libp2p 2.8.8-5b004c0c4 → 2.8.8-8e87be9e6
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 +11 -11
- package/dist/index.min.js.map +4 -4
- package/dist/src/address-manager/dns-mappings.d.ts.map +1 -1
- package/dist/src/address-manager/dns-mappings.js +5 -1
- package/dist/src/address-manager/dns-mappings.js.map +1 -1
- package/dist/src/address-manager/index.d.ts +3 -1
- package/dist/src/address-manager/index.d.ts.map +1 -1
- package/dist/src/address-manager/index.js.map +1 -1
- package/dist/src/address-manager/ip-mappings.d.ts.map +1 -1
- package/dist/src/address-manager/ip-mappings.js +5 -1
- package/dist/src/address-manager/ip-mappings.js.map +1 -1
- package/dist/src/address-manager/observed-addresses.d.ts.map +1 -1
- package/dist/src/address-manager/observed-addresses.js +5 -1
- package/dist/src/address-manager/observed-addresses.js.map +1 -1
- package/dist/src/address-manager/transport-addresses.d.ts.map +1 -1
- package/dist/src/address-manager/transport-addresses.js +5 -1
- package/dist/src/address-manager/transport-addresses.js.map +1 -1
- package/dist/src/components.d.ts +2 -1
- package/dist/src/components.d.ts.map +1 -1
- package/dist/src/components.js.map +1 -1
- package/dist/src/connection/index.d.ts.map +1 -1
- package/dist/src/connection/index.js +2 -1
- package/dist/src/connection/index.js.map +1 -1
- package/dist/src/connection-manager/connection-pruner.d.ts +2 -1
- package/dist/src/connection-manager/connection-pruner.d.ts.map +1 -1
- package/dist/src/connection-manager/connection-pruner.js.map +1 -1
- package/dist/src/connection-manager/dial-queue.d.ts.map +1 -1
- package/dist/src/connection-manager/dial-queue.js +2 -1
- package/dist/src/connection-manager/dial-queue.js.map +1 -1
- package/dist/src/connection-manager/index.d.ts +2 -1
- package/dist/src/connection-manager/index.d.ts.map +1 -1
- package/dist/src/connection-manager/index.js.map +1 -1
- package/dist/src/connection-manager/reconnect-queue.d.ts +2 -1
- package/dist/src/connection-manager/reconnect-queue.d.ts.map +1 -1
- package/dist/src/connection-manager/reconnect-queue.js.map +1 -1
- package/dist/src/connection-monitor.d.ts.map +1 -1
- package/dist/src/connection-monitor.js +2 -1
- package/dist/src/connection-monitor.js.map +1 -1
- package/dist/src/libp2p.d.ts +1 -1
- package/dist/src/libp2p.d.ts.map +1 -1
- package/dist/src/libp2p.js +6 -5
- package/dist/src/libp2p.js.map +1 -1
- package/dist/src/random-walk.d.ts +1 -1
- package/dist/src/random-walk.d.ts.map +1 -1
- package/dist/src/random-walk.js +1 -1
- package/dist/src/random-walk.js.map +1 -1
- package/dist/src/registrar.d.ts +3 -1
- package/dist/src/registrar.d.ts.map +1 -1
- package/dist/src/registrar.js +15 -2
- package/dist/src/registrar.js.map +1 -1
- package/dist/src/transport-manager.d.ts +2 -1
- package/dist/src/transport-manager.d.ts.map +1 -1
- package/dist/src/transport-manager.js +4 -1
- package/dist/src/transport-manager.js.map +1 -1
- package/dist/src/upgrader.d.ts +2 -1
- package/dist/src/upgrader.d.ts.map +1 -1
- package/dist/src/upgrader.js +20 -4
- package/dist/src/upgrader.js.map +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +11 -10
- package/src/address-manager/dns-mappings.ts +5 -1
- package/src/address-manager/index.ts +3 -1
- package/src/address-manager/ip-mappings.ts +5 -1
- package/src/address-manager/observed-addresses.ts +5 -1
- package/src/address-manager/transport-addresses.ts +5 -1
- package/src/components.ts +2 -1
- package/src/connection/index.ts +2 -1
- package/src/connection-manager/connection-pruner.ts +2 -1
- package/src/connection-manager/dial-queue.ts +2 -1
- package/src/connection-manager/index.ts +2 -1
- package/src/connection-manager/reconnect-queue.ts +2 -1
- package/src/connection-monitor.ts +2 -1
- package/src/libp2p.ts +7 -6
- package/src/random-walk.ts +1 -1
- package/src/registrar.ts +20 -3
- package/src/transport-manager.ts +6 -2
- package/src/upgrader.ts +26 -7
- package/src/version.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2P = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2P=(()=>{var lp=Object.create;var _o=Object.defineProperty;var up=Object.getOwnPropertyDescriptor;var fp=Object.getOwnPropertyNames;var dp=Object.getPrototypeOf,hp=Object.prototype.hasOwnProperty;var Cr=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Ut=(r,t)=>{for(var e in t)_o(r,e,{get:t[e],enumerable:!0})},fu=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of fp(t))!hp.call(r,o)&&o!==e&&_o(r,o,{get:()=>t[o],enumerable:!(n=up(t,o))||n.enumerable});return r};var Io=(r,t,e)=>(e=r!=null?lp(dp(r)):{},fu(t||!r||!r.__esModule?_o(e,"default",{value:r,enumerable:!0}):e,r)),pp=r=>fu(_o({},"__esModule",{value:!0}),r);var Ed=Cr(($E,Rc)=>{"use strict";var Wg=Object.prototype.hasOwnProperty,Ot="~";function Qn(){}Object.create&&(Qn.prototype=Object.create(null),new Qn().__proto__||(Ot=!1));function jg(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function xd(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new jg(e,n||r,o),i=Ot?Ot+t:t;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function ls(r,t){--r._eventsCount===0?r._events=new Qn:delete r._events[t]}function Ct(){this._events=new Qn,this._eventsCount=0}Ct.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)Wg.call(e,n)&&t.push(Ot?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Ct.prototype.listeners=function(t){var e=Ot?Ot+t:t,n=this._events[e];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Ct.prototype.listenerCount=function(t){var e=Ot?Ot+t:t,n=this._events[e];return n?n.fn?1:n.length:0};Ct.prototype.emit=function(t,e,n,o,s,i){var a=Ot?Ot+t:t;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,n),!0;case 4:return c.fn.call(c.context,e,n,o),!0;case 5:return c.fn.call(c.context,e,n,o,s),!0;case 6:return c.fn.call(c.context,e,n,o,s,i),!0}for(f=1,u=new Array(l-1);f<l;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var d=c.length,g;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(g=1,u=new Array(l-1);g<l;g++)u[g-1]=arguments[g];c[f].fn.apply(c[f].context,u)}}return!0};Ct.prototype.on=function(t,e,n){return xd(this,t,e,n,!1)};Ct.prototype.once=function(t,e,n){return xd(this,t,e,n,!0)};Ct.prototype.removeListener=function(t,e,n,o){var s=Ot?Ot+t:t;if(!this._events[s])return this;if(!e)return ls(this,s),this;var i=this._events[s];if(i.fn)i.fn===e&&(!o||i.once)&&(!n||i.context===n)&&ls(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:ls(this,s)}return this};Ct.prototype.removeAllListeners=function(t){var e;return t?(e=Ot?Ot+t:t,this._events[e]&&ls(this,e)):(this._events=new Qn,this._eventsCount=0),this};Ct.prototype.off=Ct.prototype.removeListener;Ct.prototype.addListener=Ct.prototype.on;Ct.prefixed=Ot;Ct.EventEmitter=Ct;typeof Rc<"u"&&(Rc.exports=Ct)});var Id=Cr((pv,_d)=>{_d.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 mh=Cr(uo=>{(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,g,h;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)}h=t(c),g=h[0],u=h[1],c=c.substring(u),l.push(g)}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,g;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")),g=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===g)throw new Error("empty octet");return[d,f]},r=function(){function c(l,u){var f,d,g,h;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(h=l.split("/",2),l=h[0],u=h[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(m){throw f=m,new Error("Invalid mask: "+u)}for(d=g=32;g>=0;d=--g)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(m){throw f=m,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,f,d;for(d=i(this.first),f=i(this.last),u=0;d<=f;)l(a(d),d,u),u++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),uo.ip2long=i,uo.long2ip=a,uo.Netmask=r}).call(uo)});var Vh=Cr((i3,zh)=>{function Xt(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=Xt;Xt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Xt.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Xt.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};Xt.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)};Xt.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Xt.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Xt.prototype.start=Xt.prototype.try;Xt.prototype.errors=function(){return this._errors};Xt.prototype.attempts=function(){return this._attempts};Xt.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=Cr(Ar=>{var nb=Vh();Ar.operation=function(r){var t=Ar.timeouts(r);return new nb(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=Cr((c3,$h)=>{$h.exports=Hh()});var kb={};Ut(kb,{createLibp2p:()=>Db});var du=Symbol.for("@libp2p/connection");var Wi=Symbol.for("@libp2p/content-routing");var ji=Symbol.for("@libp2p/peer-discovery");var Co=Symbol.for("@libp2p/peer-id");function Le(r){return!!r?.[Co]}var Xi=Symbol.for("@libp2p/peer-routing");var Yi="keep-alive";var Kb=Symbol.for("@libp2p/transport");var Ge;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ge||(Ge={}));var Zt=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"}},Pr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}},bn=class extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}};var Po=class extends Error{static name="ConnectionClosingError";constructor(t="The connection is closing"){super(t),this.name="ConnectionClosingError"}},Tr=class extends Error{static name="ConnectionClosedError";constructor(t="The connection is closed"){super(t),this.name="ConnectionClosedError"}};var We=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}},Lr=class extends Error{static name="InvalidPeerIdError";constructor(t="Invalid PeerID"){super(t),this.name="InvalidPeerIdError"}},De=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},To=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Lo=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},wn=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}},Do=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var ko=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},he=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var Dr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}};var kr=class extends Error{static name="LimitedConnectionError";constructor(t="Limited connection"){super(t),this.name="LimitedConnectionError"}},Ro=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(t="Too many inbound protocol streams"){super(t),this.name="TooManyInboundProtocolStreamsError"}},Mo=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(t="Too many outbound protocol streams"){super(t),this.name="TooManyOutboundProtocolStreamsError"}},ke=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var pe=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 No(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function hu(...r){let t=[];for(let e of r)No(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 pu(...r){let t=[];for(let e of r)No(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 xn=Symbol.for("@libp2p/service-capabilities"),Zi=Symbol.for("@libp2p/service-dependencies");var ra={};Ut(ra,{base58btc:()=>G,base58flickr:()=>Ep});var hw=new Uint8Array(0);function mu(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 me(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 gu(r){return new TextEncoder().encode(r)}function yu(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(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var m=0,b=0,v=0,C=h.length;v!==C&&h[v]===0;)v++,m++;for(var x=(C-v)*u+1>>>0,p=new Uint8Array(x);v!==C;){for(var w=h[v],P=0,T=x-1;(w!==0||P<b)&&T!==-1;T--,P++)w+=256*p[T]>>>0,p[T]=w%a>>>0,w=w/a>>>0;if(w!==0)throw new Error("Non-zero carry");b=P,v++}for(var D=x-b;D!==x&&p[D]===0;)D++;for(var F=c.repeat(m);D<x;++D)F+=r.charAt(p[D]);return F}function d(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var b=0,v=0;h[m]===c;)b++,m++;for(var C=(h.length-m)*l+1>>>0,x=new Uint8Array(C);h[m];){var p=e[h.charCodeAt(m)];if(p===255)return;for(var w=0,P=C-1;(p!==0||w<v)&&P!==-1;P--,w++)p+=a*x[P]>>>0,x[P]=p%256>>>0,p=p/256>>>0;if(p!==0)throw new Error("Non-zero carry");v=w,m++}if(h[m]!==" "){for(var T=C-v;T!==C&&x[T]===0;)T++;for(var D=new Uint8Array(b+(C-T)),F=b;T!==C;)D[F++]=x[T++];return D}}}function g(h){var m=d(h);if(m)return m;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:g}}var gp=mp,yp=gp,wu=yp;var Qi=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Ji=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return xu(this,t)}},ta=class{decoders;constructor(t){this.decoders=t}or(t){return xu(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 xu(r,t){return new ta({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ea=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 Qi(t,e,n),this.decoder=new Ji(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Rr({name:r,prefix:t,encode:e,decode:n}){return new ea(r,t,e,n)}function Re({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=wu(e,r);return Rr({prefix:t,name:r,encode:n,decode:s=>me(o(s))})}function bp(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=t[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|u,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function wp(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 xp(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function at({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=xp(n);return Rr({prefix:t,name:r,encode(s){return wp(s,n,e)},decode(s){return bp(s,o,e,r)}})}var G=Re({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ep=Re({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var na={};Ut(na,{base32:()=>zt,base32hex:()=>_p,base32hexpad:()=>Cp,base32hexpadupper:()=>Pp,base32hexupper:()=>Ip,base32pad:()=>Sp,base32padupper:()=>Ap,base32upper:()=>vp,base32z:()=>Tp});var zt=at({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),vp=at({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Sp=at({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ap=at({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),_p=at({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ip=at({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Cp=at({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Pp=at({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Tp=at({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var oa={};Ut(oa,{base36:()=>En,base36upper:()=>Lp});var En=Re({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Lp=Re({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Dp=Su,Eu=128,kp=127,Rp=~kp,Mp=Math.pow(2,31);function Su(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Mp;)t[e++]=r&255|Eu,r/=128;for(;r&Rp;)t[e++]=r&255|Eu,r>>>=7;return t[e]=r|0,Su.bytes=e-n+1,t}var Np=sa,Op=128,vu=127;function sa(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw sa.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&vu)<<o:(i&vu)*Math.pow(2,o),o+=7}while(i>=Op);return sa.bytes=s-n,e}var Bp=Math.pow(2,7),Fp=Math.pow(2,14),Up=Math.pow(2,21),Kp=Math.pow(2,28),qp=Math.pow(2,35),zp=Math.pow(2,42),Vp=Math.pow(2,49),Hp=Math.pow(2,56),$p=Math.pow(2,63),Gp=function(r){return r<Bp?1:r<Fp?2:r<Up?3:r<Kp?4:r<qp?5:r<zp?6:r<Vp?7:r<Hp?8:r<$p?9:10},Wp={encode:Dp,decode:Np,encodingLength:Gp},jp=Wp,vn=jp;function Sn(r,t=0){return[vn.decode(r,t),vn.decode.bytes]}function Mr(r,t,e=0){return vn.encode(r,t,e),t}function Nr(r){return vn.encodingLength(r)}function Qt(r,t){let e=t.byteLength,n=Nr(r),o=n+Nr(e),s=new Uint8Array(o+e);return Mr(r,s,0),Mr(e,s,n),s.set(t,o),new Or(r,e,t,s)}function Vt(r){let t=me(r),[e,n]=Sn(t),[o,s]=Sn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Or(e,o,i,t)}function Au(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&mu(r.bytes,e.bytes)}}var Or=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function _u(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Yp(e,ia(r),t??G.encoder);default:return Zp(e,ia(r),t??zt.encoder)}}var Iu=new WeakMap;function ia(r){let t=Iu.get(r);if(t==null){let e=new Map;return Iu.set(r,e),e}return t}var it=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!==An)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Qp)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=Qt(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&&Au(t.multihash,n.multihash)}toString(t){return _u(this,t)}toJSON(){return{"/":_u(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??Cu(n,o,s.bytes))}else if(e[Jp]===!0){let{version:n,multihash:o,code:s}=e,i=Vt(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!==An)throw new Error(`Version 0 CID must use dag-pb (code: ${An}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Cu(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,An,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=me(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 Or(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]=Sn(t.subarray(e));return e+=d,f},o=n(),s=An;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]=Xp(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 ia(s).set(n,t),s}};function Xp(r,t){switch(r[0]){case"Q":{let e=t??G;return[G.prefix,e.decode(`${G.prefix}${r}`)]}case G.prefix:{let e=t??G;return[G.prefix,e.decode(r)]}case zt.prefix:{let e=t??zt;return[zt.prefix,e.decode(r)]}case En.prefix:{let e=t??En;return[En.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 Yp(r,t,e){let{prefix:n}=e;if(n!==G.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function 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 An=112,Qp=18;function Cu(r,t,e){let n=Nr(r),o=n+Nr(t),s=new Uint8Array(o+e.byteLength);return Mr(r,s,0),Mr(t,s,n),s.set(e,o),s}var Jp=Symbol.for("@ipld/js-cid/CID");var aa={};Ut(aa,{identity:()=>Jt});var Pu=0,tm="identity",Tu=me;function em(r){return Qt(Pu,Tu(r))}var Jt={code:Pu,name:tm,encode:Tu,digest:em};function tt(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 ct(r=0){return new Uint8Array(r)}function St(r=0){return new Uint8Array(r)}function Tt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=St(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var Du=Symbol.for("@achingbrain/uint8arraylist");function Lu(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 Bo(r){return!!r?.[Du]}var Y=class r{bufs;length;[Du]=!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(Bo(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(Bo(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=Lu(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Lu(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(Bo(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 Tt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Tt(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(!Bo(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 g=this.get(f+d);if(n[d]!==g){u=Math.max(1,d-a[g]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=St(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=ct(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=ct(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=ct(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=St(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=ct(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=ct(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=ct(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=ct(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=ct(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!tt(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 ca={};Ut(ca,{base10:()=>rm});var rm=Re({prefix:"9",name:"base10",alphabet:"0123456789"});var la={};Ut(la,{base16:()=>nm,base16upper:()=>om});var nm=at({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),om=at({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ua={};Ut(ua,{base2:()=>sm});var sm=at({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var fa={};Ut(fa,{base256emoji:()=>um});var ku=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}"),im=ku.reduce((r,t,e)=>(r[e]=t,r),[]),am=ku.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function cm(r){return r.reduce((t,e)=>(t+=im[e],t),"")}function lm(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=am[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var um=Rr({prefix:"\u{1F680}",name:"base256emoji",encode:cm,decode:lm});var pa={};Ut(pa,{base64:()=>da,base64pad:()=>fm,base64url:()=>ha,base64urlpad:()=>dm});var da=at({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),fm=at({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ha=at({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),dm=at({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ma={};Ut(ma,{base8:()=>hm});var hm=at({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ga={};Ut(ga,{identity:()=>pm});var pm=Rr({prefix:"\0",name:"identity",encode:r=>yu(r),decode:r=>gu(r)});var Yw=new TextEncoder,Zw=new TextDecoder;var wa={};Ut(wa,{sha256:()=>Br,sha512:()=>ym});function ba({name:r,code:t,encode:e}){return new ya(r,t,e)}var ya=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?Qt(this.code,e):e.then(n=>Qt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Mu(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Br=ba({name:"sha2-256",code:18,encode:Mu("SHA-256")}),ym=ba({name:"sha2-512",code:19,encode:Mu("SHA-512")});var _n={...ga,...ua,...ma,...ca,...la,...na,...oa,...ra,...pa,...fa},lx={...wa,...aa};function Ou(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Nu=Ou("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),xa=Ou("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=St(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),bm={utf8:Nu,"utf-8":Nu,hex:_n.base16,latin1:xa,ascii:xa,binary:xa,..._n},Fo=bm;function L(r,t="utf8"){let e=Fo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function B(r,t="utf8"){let e=Fo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var wm=parseInt("11111",2),Ea=parseInt("10000000",2),xm=parseInt("01111111",2),Bu={0:In,1:In,2:Em,3:Am,4:_m,5:Sm,6:vm,16:In,22:In,48:In};function ge(r,t={offset:0}){let e=r[t.offset]&wm;if(t.offset++,Bu[e]!=null)return Bu[e](r,t);throw new Error("No decoder for tag "+e)}function Cn(r,t){let e=0;if((r[t.offset]&Ea)===Ea){let n=r[t.offset]&xm,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 In(r,t){Cn(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=ge(r,t);if(n===null)break;e.push(n)}return e}function Em(r,t){let e=Cn(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 vm(r,t){let e=Cn(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 Sm(r,t){return t.offset++,null}function Am(r,t){let e=Cn(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 _m(r,t){let e=Cn(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function Im(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new Y;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function Uo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=Im(r.byteLength);return new Y(Uint8Array.from([t.byteLength|Ea]),t)}function Lt(r){let t=new Y,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new Y(Uint8Array.from([2]),Uo(t),t)}function Pn(r){let t=Uint8Array.from([0]),e=new Y(t,r);return new Y(Uint8Array.from([3]),Uo(e),e)}function Fu(r){return new Y(Uint8Array.from([4]),Uo(r),r)}function te(r,t=48){let e=new Y;for(let n of r)e.append(n);return new Y(Uint8Array.from([t]),Uo(e),e)}async function Uu(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 Ku(r,t,e){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);e?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,t.subarray());return e?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function qu(r,t,e,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,e.subarray());return n?.signal?.throwIfAborted(),s}var Cm=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Pm=Uint8Array.from([6,5,43,129,4,0,34]),Tm=Uint8Array.from([6,5,43,129,4,0,35]),Lm={ext:!0,kty:"EC",crv:"P-256"},Dm={ext:!0,kty:"EC",crv:"P-384"},km={ext:!0,kty:"EC",crv:"P-521"},va=32,Sa=48,Aa=66;function _a(r){let t=ge(r);return zu(t)}function zu(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===va*2+1)return n=B(t.subarray(e,e+va),"base64url"),o=B(t.subarray(e+va),"base64url"),new je({...Lm,key_ops:["verify"],x:n,y:o});if(t.byteLength===Sa*2+1)return n=B(t.subarray(e,e+Sa),"base64url"),o=B(t.subarray(e+Sa),"base64url"),new je({...Dm,key_ops:["verify"],x:n,y:o});if(t.byteLength===Aa*2+1)return n=B(t.subarray(e,e+Aa),"base64url"),o=B(t.subarray(e+Aa),"base64url"),new je({...km,key_ops:["verify"],x:n,y:o});throw new R(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Vu(r){return te([Lt(Uint8Array.from([1])),Fu(L(r.d??"","base64url")),te([$u(r.crv)],160),te([Pn(new Y(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function Hu(r){return te([Lt(Uint8Array.from([1])),te([$u(r.crv)],160),te([Pn(new Y(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function $u(r){if(r==="P-256")return Cm;if(r==="P-384")return Pm;if(r==="P-521")return Tm;throw new R(`Invalid curve ${r}`)}async function Gu(r="P-256"){let t=await Uu(r);return new Ko(t.privateKey)}var je=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Hu(this.jwk)),this._raw}toMultihash(){return Jt.digest(Wt(this))}toCID(){return it.createV1(114,this.toMultihash())}toString(){return G.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:tt(this.raw,t.raw)}async verify(t,e,n){return qu(this.jwk,e,t,n)}},Ko=class{type="ECDSA";jwk;publicKey;_raw;constructor(t){this.jwk=t,this.publicKey=new je({crv:t.crv,ext:t.ext,key_ops:["verify"],kty:"EC",x:t.x,y:t.y})}get raw(){return this._raw==null&&(this._raw=Vu(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:tt(this.raw,t.raw)}async sign(t,e){return Ku(this.jwk,t,e)}};var Xe=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Rm(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function qo(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Ye(r,...t){if(!Rm(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 Wu(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");qo(r.outputLen),qo(r.blockLen)}function Ur(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 ju(r,t){Ye(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function ye(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function zo(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ee(r,t){return r<<32-t|r>>>t}function Xu(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Tn(r){return typeof r=="string"&&(r=Xu(r)),Ye(r),r}function Ia(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Ye(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 Fr=class{};function Ca(r){let t=n=>r().update(Tn(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Kr(r=32){if(Xe&&typeof Xe.getRandomValues=="function")return Xe.getRandomValues(new Uint8Array(r));if(Xe&&typeof Xe.randomBytes=="function")return Uint8Array.from(Xe.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 Yu(r,t,e){return r&t^~r&e}function Zu(r,t,e){return r&t^r&e^t&e}var Ln=class extends Fr{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=zo(this.buffer)}update(t){Ur(this),t=Tn(t),Ye(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=zo(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){Ur(this),ju(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,ye(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=zo(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()}},be=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var xt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Vo=BigInt(4294967295),Qu=BigInt(32);function Nm(r,t=!1){return t?{h:Number(r&Vo),l:Number(r>>Qu&Vo)}:{h:Number(r>>Qu&Vo)|0,l:Number(r&Vo)|0}}function Ju(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}=Nm(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var Pa=(r,t,e)=>r>>>e,Ta=(r,t,e)=>r<<32-e|t>>>e,Ze=(r,t,e)=>r>>>e|t<<32-e,Qe=(r,t,e)=>r<<32-e|t>>>e,Dn=(r,t,e)=>r<<64-e|t>>>e-32,kn=(r,t,e)=>r>>>e-32|t<<64-e;function ce(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var tf=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),ef=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,rf=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),nf=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,of=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),sf=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var Bm=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]),Me=new Uint32Array(64),Ho=class extends Ln{constructor(t=32){super(64,t,8,!1),this.A=be[0]|0,this.B=be[1]|0,this.C=be[2]|0,this.D=be[3]|0,this.E=be[4]|0,this.F=be[5]|0,this.G=be[6]|0,this.H=be[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)Me[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Me[f-15],g=Me[f-2],h=ee(d,7)^ee(d,18)^d>>>3,m=ee(g,17)^ee(g,19)^g>>>10;Me[f]=m+Me[f-7]+h+Me[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=ee(a,6)^ee(a,11)^ee(a,25),g=u+d+Yu(a,c,l)+Bm[f]+Me[f]|0,m=(ee(n,2)^ee(n,13)^ee(n,22))+Zu(n,o,s)|0;u=l,l=c,c=a,a=i+g|0,i=s,s=o,o=n,n=g+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){ye(Me)}destroy(){this.set(0,0,0,0,0,0,0,0),ye(this.buffer)}};var af=Ju(["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))),Fm=af[0],Um=af[1],Ne=new Uint32Array(80),Oe=new Uint32Array(80),La=class extends Ln{constructor(t=64){super(128,t,16,!1),this.Ah=xt[0]|0,this.Al=xt[1]|0,this.Bh=xt[2]|0,this.Bl=xt[3]|0,this.Ch=xt[4]|0,this.Cl=xt[5]|0,this.Dh=xt[6]|0,this.Dl=xt[7]|0,this.Eh=xt[8]|0,this.El=xt[9]|0,this.Fh=xt[10]|0,this.Fl=xt[11]|0,this.Gh=xt[12]|0,this.Gl=xt[13]|0,this.Hh=xt[14]|0,this.Hl=xt[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:g,Gl:h,Hh:m,Hl:b}=this;return[t,e,n,o,s,i,a,c,l,u,f,d,g,h,m,b]}set(t,e,n,o,s,i,a,c,l,u,f,d,g,h,m,b){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=g|0,this.Gl=h|0,this.Hh=m|0,this.Hl=b|0}process(t,e){for(let x=0;x<16;x++,e+=4)Ne[x]=t.getUint32(e),Oe[x]=t.getUint32(e+=4);for(let x=16;x<80;x++){let p=Ne[x-15]|0,w=Oe[x-15]|0,P=Ze(p,w,1)^Ze(p,w,8)^Pa(p,w,7),T=Qe(p,w,1)^Qe(p,w,8)^Ta(p,w,7),D=Ne[x-2]|0,F=Oe[x-2]|0,q=Ze(D,F,19)^Dn(D,F,61)^Pa(D,F,6),M=Qe(D,F,19)^kn(D,F,61)^Ta(D,F,6),U=rf(T,M,Oe[x-7],Oe[x-16]),O=nf(U,P,q,Ne[x-7],Ne[x-16]);Ne[x]=O|0,Oe[x]=U|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:g,Fl:h,Gh:m,Gl:b,Hh:v,Hl:C}=this;for(let x=0;x<80;x++){let p=Ze(f,d,14)^Ze(f,d,18)^Dn(f,d,41),w=Qe(f,d,14)^Qe(f,d,18)^kn(f,d,41),P=f&g^~f&m,T=d&h^~d&b,D=of(C,w,T,Um[x],Oe[x]),F=sf(D,v,p,P,Fm[x],Ne[x]),q=D|0,M=Ze(n,o,28)^Dn(n,o,34)^Dn(n,o,39),U=Qe(n,o,28)^kn(n,o,34)^kn(n,o,39),O=n&s^n&a^s&a,ht=o&i^o&c^i&c;v=m|0,C=b|0,m=g|0,b=h|0,g=f|0,h=d|0,{h:f,l:d}=ce(l|0,u|0,F|0,q|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let _=tf(q,U,ht);n=ef(_,F,M,O),o=_|0}({h:n,l:o}=ce(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ce(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ce(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ce(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=ce(this.Eh|0,this.El|0,f|0,d|0),{h:g,l:h}=ce(this.Fh|0,this.Fl|0,g|0,h|0),{h:m,l:b}=ce(this.Gh|0,this.Gl|0,m|0,b|0),{h:v,l:C}=ce(this.Hh|0,this.Hl|0,v|0,C|0),this.set(n,o,s,i,a,c,l,u,f,d,g,h,m,b,v,C)}roundClean(){ye(Ne,Oe)}destroy(){ye(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var $o=Ca(()=>new Ho);var cf=Ca(()=>new La);var Ma=BigInt(0),Ra=BigInt(1);function qr(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Na(r){if(!qr(r))throw new Error("Uint8Array expected")}function le(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}function Rn(r){let t=r.toString(16);return t.length&1?"0"+t:t}function ff(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Ma:BigInt("0x"+r)}var df=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Km=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Be(r){if(Na(r),df)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=Km[r[e]];return t}var we={_0:48,_9:57,A:65,F:70,a:97,f:102};function lf(r){if(r>=we._0&&r<=we._9)return r-we._0;if(r>=we.A&&r<=we.F)return r-(we.A-10);if(r>=we.a&&r<=we.f)return r-(we.a-10)}function Mn(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(df)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=lf(r.charCodeAt(s)),a=lf(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 xe(r){return ff(Be(r))}function Je(r){return Na(r),ff(Be(Uint8Array.from(r).reverse()))}function tr(r,t){return Mn(r.toString(16).padStart(t*2,"0"))}function zr(r,t){return tr(r,t).reverse()}function nt(r,t,e){let n;if(typeof t=="string")try{n=Mn(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(qr(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 Fe(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Na(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 Da=r=>typeof r=="bigint"&&Ma<=r;function Go(r,t,e){return Da(r)&&Da(t)&&Da(e)&&t<=r&&r<e}function Ht(r,t,e,n){if(!Go(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function hf(r){let t;for(t=0;r>Ma;r>>=Ra,t+=1);return t}var er=r=>(Ra<<BigInt(r))-Ra,ka=r=>new Uint8Array(r),uf=r=>Uint8Array.from(r);function pf(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=ka(r),o=ka(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=ka(0))=>{o=a(uf([0]),f),n=a(),f.length!==0&&(o=a(uf([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 g=n.slice();d.push(g),f+=n.length}return Fe(...d)};return(f,d)=>{i(),c(f);let g;for(;!(g=d(l()));)c();return i(),g}}var qm={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"||qr(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 Ee(r,t,e={}){let n=(o,s,i)=>{let a=qm[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 Vr(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 Dt=BigInt(0),yt=BigInt(1),rr=BigInt(2),zm=BigInt(3),gf=BigInt(4),yf=BigInt(5),bf=BigInt(8);function rt(r,t){let e=r%t;return e>=Dt?e:t+e}function ot(r,t,e){let n=r;for(;t-- >Dt;)n*=n,n%=e;return n}function Wo(r,t){if(r===Dt)throw new Error("invert: expected non-zero number");if(t<=Dt)throw new Error("invert: expected positive modulus, got "+t);let e=rt(r,t),n=t,o=Dt,s=yt,i=yt,a=Dt;for(;e!==Dt;){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!==yt)throw new Error("invert: does not exist");return rt(o,t)}function wf(r,t){let e=(r.ORDER+yt)/gf,n=r.pow(t,e);if(!r.eql(r.sqr(n),t))throw new Error("Cannot find square root");return n}function Vm(r,t){let e=(r.ORDER-yf)/bf,n=r.mul(t,rr),o=r.pow(n,e),s=r.mul(t,o),i=r.mul(r.mul(s,rr),o),a=r.mul(s,r.sub(i,r.ONE));if(!r.eql(r.sqr(a),t))throw new Error("Cannot find square root");return a}function Hm(r){if(r<BigInt(3))throw new Error("sqrt is not defined for small field");let t=r-yt,e=0;for(;t%rr===Dt;)t/=rr,e++;let n=rr,o=ve(r);for(;mf(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return wf;let s=o.pow(n,t),i=(t+yt)/rr;return function(c,l){if(c.is0(l))return l;if(mf(c,l)!==1)throw new Error("Cannot find square root");let u=e,f=c.mul(c.ONE,s),d=c.pow(l,t),g=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let h=1,m=c.sqr(d);for(;!c.eql(m,c.ONE);)if(h++,m=c.sqr(m),h===u)throw new Error("Cannot find square root");let b=yt<<BigInt(u-h-1),v=c.pow(f,b);u=h,f=c.sqr(v),d=c.mul(d,f),g=c.mul(g,v)}return g}}function $m(r){return r%gf===zm?wf:r%bf===yf?Vm:Hm(r)}var xf=(r,t)=>(rt(r,t)&yt)===yt,Gm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Oa(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Gm.reduce((n,o)=>(n[o]="function",n),t);return Ee(r,e)}function Wm(r,t,e){if(e<Dt)throw new Error("invalid exponent, negatives unsupported");if(e===Dt)return r.ONE;if(e===yt)return t;let n=r.ONE,o=t;for(;e>Dt;)e&yt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=yt;return n}function Hr(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 mf(r,t){let e=(r.ORDER-yt)/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("invalid Legendre symbol result");return o?1:s?0:-1}function Ba(r,t){t!==void 0&&qo(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function ve(r,t,e=!1,n={}){if(r<=Dt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=Ba(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:Dt,ONE:yt,create:c=>rt(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Dt<=c&&c<r},is0:c=>c===Dt,isOdd:c=>(c&yt)===yt,neg:c=>rt(-c,r),eql:(c,l)=>c===l,sqr:c=>rt(c*c,r),add:(c,l)=>rt(c+l,r),sub:(c,l)=>rt(c-l,r),mul:(c,l)=>rt(c*l,r),pow:(c,l)=>Wm(a,c,l),div:(c,l)=>rt(c*Wo(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Wo(c,r),sqrt:n.sqrt||(c=>(i||(i=$m(r)),i(a,c))),toBytes:c=>e?zr(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):xe(c)},invertBatch:c=>Hr(a,c),cmov:(c,l,u)=>u?l:c});return Object.freeze(a)}function Ef(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 Fa(r){let t=Ef(r);return t+Math.ceil(t/2)}function vf(r,t,e=!1){let n=r.length,o=Ef(t),s=Fa(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?Je(r):xe(r),a=rt(i,t-yt)+yt;return e?zr(a,o):tr(a,o)}var Sf=BigInt(0),Va=BigInt(1);function Ua(r,t){let e=t.negate();return r?e:t}function _f(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Ka(r,t){_f(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 Af(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+=Va);let l=t*n,u=l+Math.abs(a)-1,f=a===0,d=a<0,g=t%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:d,isNegF:g,offsetF:l}}function jm(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 Xm(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 qa=new WeakMap,If=new WeakMap;function za(r){return If.get(r)||1}function jo(r,t){return{constTimeNegate:Ua,hasPrecomputes(e){return za(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>Sf;)n&Va&&(o=o.add(s)),s=s.double(),n>>=Va;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=Ka(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=Ka(e,t);for(let c=0;c<a.windows;c++){let{nextN:l,offset:u,isZero:f,isNeg:d,isNegF:g,offsetF:h}=Af(o,c,a);o=l,f?i=i.add(Ua(g,n[h])):s=s.add(Ua(d,n[u]))}return{p:s,f:i}},wNAFUnsafe(e,n,o,s=r.ZERO){let i=Ka(e,t);for(let a=0;a<i.windows&&o!==Sf;a++){let{nextN:c,offset:l,isZero:u,isNeg:f}=Af(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=qa.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&qa.set(n,o(s))),s},wNAFCached(e,n,o){let s=za(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=za(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){_f(n,t),If.set(e,n),qa.delete(e)}}}function Xo(r,t,e,n){jm(e,r),Xm(n,t);let o=e.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=r.ZERO,a=hf(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=er(c),u=new Array(Number(l)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,d=i;for(let g=f;g>=0;g-=c){u.fill(i);for(let m=0;m<s;m++){let b=n[m],v=Number(b>>BigInt(g)&l);u[v]=u[v].add(e[m])}let h=i;for(let m=u.length-1,b=i;m>0;m--)b=b.add(u[m]),h=h.add(b);if(d=d.add(h),g!==0)for(let m=0;m<c;m++)d=d.double()}return d}function Nn(r){return Oa(r.Fp),Ee(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ba(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var ue=BigInt(0),kt=BigInt(1),Cf=BigInt(2),Ym=BigInt(8),Zm={zip215:!0};function Qm(r){let t=Nn(r);return Ee(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Pf(r){let t=Qm(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=Cf<<BigInt(a*8)-kt,u=e.create,f=ve(t.n,t.nBitLength);function d(S,y){let E=e.sqr(S),I=e.sqr(y),N=e.add(e.mul(t.a,E),I),K=e.add(e.ONE,e.mul(t.d,e.mul(E,I)));return e.eql(N,K)}if(!d(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let g=t.uvRatio||((S,y)=>{try{return{isValid:!0,value:e.sqrt(S*e.inv(y))}}catch{return{isValid:!1,value:ue}}}),h=t.adjustScalarBytes||(S=>S),m=t.domain||((S,y,E)=>{if(le("phflag",E),y.length||E)throw new Error("Contexts/pre-hash are not supported");return S});function b(S,y,E=!1){let I=E?kt:ue;Ht("coordinate "+S,y,I,l)}function v(S){if(!(S instanceof p))throw new Error("ExtendedPoint expected")}let C=Vr((S,y)=>{let{ex:E,ey:I,ez:N}=S,K=S.is0();y==null&&(y=K?Ym:e.inv(N));let V=u(E*y),$=u(I*y),X=u(N*y);if(K)return{x:ue,y:kt};if(X!==kt)throw new Error("invZ was invalid");return{x:V,y:$}}),x=Vr(S=>{let{a:y,d:E}=t;if(S.is0())throw new Error("bad point: ZERO");let{ex:I,ey:N,ez:K,et:V}=S,$=u(I*I),X=u(N*N),J=u(K*K),pt=u(J*J),ut=u($*y),wt=u(J*u(ut+X)),Ft=u(pt+u(E*u($*X)));if(wt!==Ft)throw new Error("bad point: equation left != right (1)");let gt=u(I*N),vt=u(K*V);if(gt!==vt)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(y,E,I,N){b("x",y),b("y",E),b("z",I,!0),b("t",N),this.ex=y,this.ey=E,this.ez=I,this.et=N,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(y){if(y instanceof p)throw new Error("extended point not allowed");let{x:E,y:I}=y||{};return b("x",E),b("y",I),new p(E,I,kt,u(E*I))}static normalizeZ(y){let E=Hr(e,y.map(I=>I.ez));return y.map((I,N)=>I.toAffine(E[N])).map(p.fromAffine)}static msm(y,E){return Xo(p,f,y,E)}_setWindowSize(y){T.setWindowSize(this,y)}assertValidity(){x(this)}equals(y){v(y);let{ex:E,ey:I,ez:N}=this,{ex:K,ey:V,ez:$}=y,X=u(E*$),J=u(K*N),pt=u(I*$),ut=u(V*N);return X===J&&pt===ut}is0(){return this.equals(p.ZERO)}negate(){return new p(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:y}=t,{ex:E,ey:I,ez:N}=this,K=u(E*E),V=u(I*I),$=u(Cf*u(N*N)),X=u(y*K),J=E+I,pt=u(u(J*J)-K-V),ut=X+V,wt=ut-$,Ft=X-V,gt=u(pt*wt),vt=u(ut*Ft),qt=u(pt*Ft),Yt=u(wt*ut);return new p(gt,vt,Yt,qt)}add(y){v(y);let{a:E,d:I}=t,{ex:N,ey:K,ez:V,et:$}=this,{ex:X,ey:J,ez:pt,et:ut}=y,wt=u(N*X),Ft=u(K*J),gt=u($*I*ut),vt=u(V*pt),qt=u((N+K)*(X+J)-wt-Ft),Yt=vt-gt,yn=vt+gt,uu=u(Ft-E*wt),sp=u(qt*Yt),ip=u(yn*uu),ap=u(qt*uu),cp=u(Yt*yn);return new p(sp,ip,cp,ap)}subtract(y){return this.add(y.negate())}wNAF(y){return T.wNAFCached(this,y,p.normalizeZ)}multiply(y){let E=y;Ht("scalar",E,kt,n);let{p:I,f:N}=this.wNAF(E);return p.normalizeZ([I,N])[0]}multiplyUnsafe(y,E=p.ZERO){let I=y;return Ht("scalar",I,ue,n),I===ue?P:this.is0()||I===kt?this:T.wNAFCachedUnsafe(this,I,p.normalizeZ,E)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return T.unsafeLadder(this,n).is0()}toAffine(y){return C(this,y)}clearCofactor(){let{h:y}=t;return y===kt?this:this.multiplyUnsafe(y)}static fromHex(y,E=!1){let{d:I,a:N}=t,K=e.BYTES;y=nt("pointHex",y,K),le("zip215",E);let V=y.slice(),$=y[K-1];V[K-1]=$&-129;let X=Je(V),J=E?l:e.ORDER;Ht("pointHex.y",X,ue,J);let pt=u(X*X),ut=u(pt-kt),wt=u(I*pt-N),{isValid:Ft,value:gt}=g(ut,wt);if(!Ft)throw new Error("Point.fromHex: invalid y coordinate");let vt=(gt&kt)===kt,qt=($&128)!==0;if(!E&>===ue&&qt)throw new Error("Point.fromHex: x=0 and x_0=1");return qt!==vt&&(gt=u(-gt)),p.fromAffine({x:gt,y:X})}static fromPrivateKey(y){let{scalar:E}=q(y);return w.multiply(E)}toRawBytes(){let{x:y,y:E}=this.toAffine(),I=zr(E,e.BYTES);return I[I.length-1]|=y&kt?128:0,I}toHex(){return Be(this.toRawBytes())}}p.BASE=new p(t.Gx,t.Gy,kt,u(t.Gx*t.Gy)),p.ZERO=new p(ue,kt,kt,ue);let{BASE:w,ZERO:P}=p,T=jo(p,a*8);function D(S){return rt(S,n)}function F(S){return D(Je(S))}function q(S){let y=e.BYTES;S=nt("private key",S,y);let E=nt("hashed private key",s(S),2*y),I=h(E.slice(0,y)),N=E.slice(y,2*y),K=F(I);return{head:I,prefix:N,scalar:K}}function M(S){let{head:y,prefix:E,scalar:I}=q(S),N=w.multiply(I),K=N.toRawBytes();return{head:y,prefix:E,scalar:I,point:N,pointBytes:K}}function U(S){return M(S).pointBytes}function O(S=Uint8Array.of(),...y){let E=Fe(...y);return F(s(m(E,nt("context",S),!!o)))}function ht(S,y,E={}){S=nt("message",S),o&&(S=o(S));let{prefix:I,scalar:N,pointBytes:K}=M(y),V=O(E.context,I,S),$=w.multiply(V).toRawBytes(),X=O(E.context,$,K,S),J=D(V+X*N);Ht("signature.s",J,ue,n);let pt=Fe($,zr(J,e.BYTES));return nt("result",pt,e.BYTES*2)}let _=Zm;function A(S,y,E,I=_){let{context:N,zip215:K}=I,V=e.BYTES;S=nt("signature",S,2*V),y=nt("message",y),E=nt("publicKey",E,V),K!==void 0&&le("zip215",K),o&&(y=o(y));let $=Je(S.slice(V,2*V)),X,J,pt;try{X=p.fromHex(E,K),J=p.fromHex(S.slice(0,V),K),pt=w.multiplyUnsafe($)}catch{return!1}if(!K&&X.isSmallOrder())return!1;let ut=O(N,J.toRawBytes(),X.toRawBytes(),y);return J.add(X.multiplyUnsafe(ut)).subtract(pt).clearCofactor().equals(p.ZERO)}return w._setWindowSize(8),{CURVE:t,getPublicKey:U,sign:ht,verify:A,ExtendedPoint:p,utils:{getExtendedPublicKey:M,randomPrivateKey:()=>i(e.BYTES),precompute(S=8,y=p.BASE){return y._setWindowSize(S),y.multiply(BigInt(3)),y}}}}var Ha=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Tf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),l1=BigInt(0),Jm=BigInt(1),Lf=BigInt(2),u1=BigInt(3),tg=BigInt(5),eg=BigInt(8);function rg(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=Ha,a=r*r%s*r%s,c=ot(a,Lf,s)*a%s,l=ot(c,Jm,s)*r%s,u=ot(l,tg,s)*l%s,f=ot(u,t,s)*u%s,d=ot(f,e,s)*f%s,g=ot(d,n,s)*d%s,h=ot(g,o,s)*g%s,m=ot(h,o,s)*g%s,b=ot(m,t,s)*u%s;return{pow_p_5_8:ot(b,Lf,s)*r%s,b2:a}}function ng(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function og(r,t){let e=Ha,n=rt(t*t*t,e),o=rt(n*n*t,e),s=rg(r*o).pow_p_5_8,i=rt(r*n*s,e),a=rt(t*i*i,e),c=i,l=rt(i*Tf,e),u=a===r,f=a===rt(-r,e),d=a===rt(-r*Tf,e);return u&&(i=c),(f||d)&&(i=l),xf(i,e)&&(i=rt(-i,e)),{isValid:u||f,value:i}}var Df=ve(Ha,void 0,!0),sg={a:Df.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Df,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:eg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:cf,randomBytes:Kr,adjustScalarBytes:ng,uvRatio:og},On=Pf(sg);var Yo=32,Zo=64,$a=32;function kf(){let r=On.utils.randomPrivateKey(),t=On.getPublicKey(r);return{privateKey:ig(r,t),publicKey:t}}function Rf(r,t){let e=r.subarray(0,$a);return On.sign(t instanceof Uint8Array?t:t.subarray(),e)}function Mf(r,t,e){return On.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}function ig(r,t){let e=new Uint8Array(Zo);for(let n=0;n<$a;n++)e[n]=r[n],e[$a+n]=t[n];return e}var Bn=class{type="Ed25519";raw;constructor(t){this.raw=Jo(t,Yo)}toMultihash(){return Jt.digest(Wt(this))}toCID(){return it.createV1(114,this.toMultihash())}toString(){return G.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:tt(this.raw,t.raw)}verify(t,e,n){return n?.signal?.throwIfAborted(),Mf(this.raw,e,t)}},Qo=class{type="Ed25519";raw;publicKey;constructor(t,e){this.raw=Jo(t,Zo),this.publicKey=new Bn(e)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:tt(this.raw,t.raw)}sign(t,e){return e?.signal?.throwIfAborted(),Rf(this.raw,t)}};function Ga(r){return r=Jo(r,Yo),new Bn(r)}async function Of(){let{privateKey:r,publicKey:t}=kf();return new Qo(r,t)}function Jo(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new R(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var ag=Math.pow(2,7),cg=Math.pow(2,14),lg=Math.pow(2,21),Wa=Math.pow(2,28),ja=Math.pow(2,35),Xa=Math.pow(2,42),Ya=Math.pow(2,49),Q=128,At=127;function mt(r){if(r<ag)return 1;if(r<cg)return 2;if(r<lg)return 3;if(r<Wa)return 4;if(r<ja)return 5;if(r<Xa)return 6;if(r<Ya)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(mt(r)){case 8:t[e++]=r&255|Q,r/=128;case 7:t[e++]=r&255|Q,r/=128;case 6:t[e++]=r&255|Q,r/=128;case 5:t[e++]=r&255|Q,r/=128;case 4:t[e++]=r&255|Q,r>>>=7;case 3:t[e++]=r&255|Q,r>>>=7;case 2:t[e++]=r&255|Q,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function ug(r,t,e=0){switch(mt(r)){case 8:t.set(e++,r&255|Q),r/=128;case 7:t.set(e++,r&255|Q),r/=128;case 6:t.set(e++,r&255|Q),r/=128;case 5:t.set(e++,r&255|Q),r/=128;case 4:t.set(e++,r&255|Q),r>>>=7;case 3:t.set(e++,r&255|Q),r>>>=7;case 2:t.set(e++,r&255|Q),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Qa(r,t){let e=r[t],n=0;if(n+=e&At,e<Q||(e=r[t+1],n+=(e&At)<<7,e<Q)||(e=r[t+2],n+=(e&At)<<14,e<Q)||(e=r[t+3],n+=(e&At)<<21,e<Q)||(e=r[t+4],n+=(e&At)*Wa,e<Q)||(e=r[t+5],n+=(e&At)*ja,e<Q)||(e=r[t+6],n+=(e&At)*Xa,e<Q)||(e=r[t+7],n+=(e&At)*Ya,e<Q))return n;throw new RangeError("Could not decode varint")}function fg(r,t){let e=r.get(t),n=0;if(n+=e&At,e<Q||(e=r.get(t+1),n+=(e&At)<<7,e<Q)||(e=r.get(t+2),n+=(e&At)<<14,e<Q)||(e=r.get(t+3),n+=(e&At)<<21,e<Q)||(e=r.get(t+4),n+=(e&At)*Wa,e<Q)||(e=r.get(t+5),n+=(e&At)*ja,e<Q)||(e=r.get(t+6),n+=(e&At)*Xa,e<Q)||(e=r.get(t+7),n+=(e&At)*Ya,e<Q))return n;throw new RangeError("Could not decode varint")}function _t(r,t,e=0){return t==null&&(t=St(mt(r))),t instanceof Uint8Array?Za(r,t,e):ug(r,t,e)}function re(r,t=0){return r instanceof Uint8Array?Qa(r,t):fg(r,t)}var Ja=new Float32Array([-0]),Ue=new Uint8Array(Ja.buffer);function Bf(r,t,e){Ja[0]=r,t[e]=Ue[0],t[e+1]=Ue[1],t[e+2]=Ue[2],t[e+3]=Ue[3]}function Ff(r,t){return Ue[0]=r[t],Ue[1]=r[t+1],Ue[2]=r[t+2],Ue[3]=r[t+3],Ja[0]}var tc=new Float64Array([-0]),It=new Uint8Array(tc.buffer);function Uf(r,t,e){tc[0]=r,t[e]=It[0],t[e+1]=It[1],t[e+2]=It[2],t[e+3]=It[3],t[e+4]=It[4],t[e+5]=It[5],t[e+6]=It[6],t[e+7]=It[7]}function Kf(r,t){return It[0]=r[t],It[1]=r[t+1],It[2]=r[t+2],It[3]=r[t+3],It[4]=r[t+4],It[5]=r[t+5],It[6]=r[t+6],It[7]=r[t+7],tc[0]}var dg=BigInt(Number.MAX_SAFE_INTEGER),hg=BigInt(Number.MIN_SAFE_INTEGER),$t=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<dg&&t>hg)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>qf&&(o=0n,++n>qf&&(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 $t(0,0);or.toBigInt=function(){return 0n};or.zzEncode=or.zzDecode=function(){return this};or.length=function(){return 1};var qf=4294967296n;function zf(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 Vf(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 ec(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 ne(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function ts(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var rc=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,ne(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 ne(this,4);return ts(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ne(this,4);return ts(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ne(this,4);let t=Ff(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw ne(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 ne(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Vf(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw ne(this,t);this.pos+=t}else do if(this.pos>=this.len)throw ne(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 $t(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 ne(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 ne(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 ne(this,8);let t=ts(this.buf,this.pos+=4),e=ts(this.buf,this.pos+=4);return new $t(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=Qa(this.buf,this.pos);return this.pos+=mt(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 nc(r){return new rc(r instanceof Uint8Array?r:r.subarray())}function Rt(r,t,e){let n=nc(r);return t.decode(n,void 0,e)}function oc(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return St(i);o+i>t&&(n=St(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var sr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function sc(){}var ac=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},pg=oc();function mg(r){return globalThis.Buffer!=null?St(r):pg(r)}var Un=class{len;head;tail;states;constructor(){this.len=0,this.head=new sr(sc,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 cc((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(es,10,$t.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=$t.fromBigInt(t);return this._push(es,e.length(),e)}uint64Number(t){return this._push(Za,mt(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=$t.fromBigInt(t).zzEncode();return this._push(es,e.length(),e)}sint64Number(t){let e=$t.fromNumber(t).zzEncode();return this._push(es,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ic,1,t?1:0)}fixed32(t){return this._push(Fn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=$t.fromBigInt(t);return this._push(Fn,4,e.lo)._push(Fn,4,e.hi)}fixed64Number(t){let e=$t.fromNumber(t);return this._push(Fn,4,e.lo)._push(Fn,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(Bf,4,t)}double(t){return this._push(Uf,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ic,1,0):this.uint32(e)._push(yg,e,t)}string(t){let e=zf(t);return e!==0?this.uint32(e)._push(ec,e,t):this._push(ic,1,0)}fork(){return this.states=new ac(this),this.head=this.tail=new sr(sc,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(sc,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=mg(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ic(r,t,e){t[e]=r&255}function gg(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var cc=class extends sr{next;constructor(t,e){super(gg,t,e),this.next=void 0}};function es(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 Fn(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 yg(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Un.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(bg,t,r),this},Un.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(wg,t,r),this});function bg(r,t,e){t.set(r,e)}function wg(r,t,e){r.length<40?ec(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(L(r),e)}function lc(){return new Un}function Mt(r,t){let e=lc();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var $r;(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"})($r||($r={}));function rs(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function uc(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 rs("enum",$r.VARINT,e,n)}function Nt(r,t){return rs("message",$r.LENGTH_DELIMITED,r,t)}var ir=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Kn=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ft;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ft||(ft={}));var fc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(fc||(fc={}));(function(r){r.codec=()=>uc(fc)})(ft||(ft={}));var fe;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ft.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=ft.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(fe||(fe={}));var dc;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ft.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=ft.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(dc||(dc={}));function Gr(r){if(isNaN(r)||r<=0)throw new R("random bytes length must be a Number bigger than 0");return Kr(r)}var qn=class extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}},zn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},ns=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Gf={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new ns("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 Ke=Gf;var Hn={};Ut(Hn,{MAX_RSA_KEY_SIZE:()=>hc,generateRSAKeyPair:()=>vc,jwkToJWKKeyPair:()=>Yf,jwkToPkcs1:()=>Sg,jwkToPkix:()=>yc,jwkToRSAPrivateKey:()=>Ec,pkcs1MessageToJwk:()=>mc,pkcs1MessageToRSAPrivateKey:()=>bc,pkcs1ToJwk:()=>vg,pkcs1ToRSAPrivateKey:()=>Xf,pkixMessageToJwk:()=>gc,pkixMessageToRSAPublicKey:()=>xc,pkixToJwk:()=>Ag,pkixToRSAPublicKey:()=>wc});var os=$o;var Wr=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=Hn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return it.createV1(114,this._multihash)}toString(){return G.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:tt(this.raw,t.raw)}verify(t,e,n){return jf(this.jwk,e,t,n)}},Vn=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=Hn.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:tt(this.raw,t.raw)}sign(t,e){return Wf(this.jwk,t,e)}};var hc=8192,pc=18,xg=1062,Eg=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function vg(r){let t=ge(r);return mc(t)}function mc(r){return{n:B(r[1],"base64url"),e:B(r[2],"base64url"),d:B(r[3],"base64url"),p:B(r[4],"base64url"),q:B(r[5],"base64url"),dp:B(r[6],"base64url"),dq:B(r[7],"base64url"),qi:B(r[8],"base64url"),kty:"RSA"}}function Sg(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 te([Lt(Uint8Array.from([0])),Lt(L(r.n,"base64url")),Lt(L(r.e,"base64url")),Lt(L(r.d,"base64url")),Lt(L(r.p,"base64url")),Lt(L(r.q,"base64url")),Lt(L(r.dp,"base64url")),Lt(L(r.dq,"base64url")),Lt(L(r.qi,"base64url"))]).subarray()}function Ag(r){let t=ge(r,{offset:0});return gc(t)}function gc(r){let t=ge(r[1],{offset:0});return{kty:"RSA",n:B(t[0],"base64url"),e:B(t[1],"base64url")}}function yc(r){if(r.n==null||r.e==null)throw new R("JWK was missing components");return te([Eg,Pn(te([Lt(L(r.n,"base64url")),Lt(L(r.e,"base64url"))]))]).subarray()}function Xf(r){let t=ge(r);return bc(t)}function bc(r){let t=mc(r);return Ec(t)}function wc(r,t){if(r.byteLength>=xg)throw new Pr("Key size is too large");let e=ge(r,{offset:0});return xc(e,r,t)}function xc(r,t,e){let n=gc(r);if(e==null){let o=os(fe.encode({Type:ft.RSA,Data:t}));e=Qt(pc,o)}return new Wr(n,e)}function Ec(r){if(Qf(r)>hc)throw new R("Key size is too large");let t=Yf(r),e=os(fe.encode({Type:ft.RSA,Data:yc(t.publicKey)})),n=Qt(pc,e);return new Vn(t.privateKey,new Wr(t.publicKey,n))}async function vc(r){if(r>hc)throw new R("Key size is too large");let t=await Zf(r),e=os(fe.encode({Type:ft.RSA,Data:yc(t.publicKey)})),n=Qt(pc,e);return new Vn(t.privateKey,new Wr(t.publicKey,n))}function Yf(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 Zf(r,t){let e=await Ke.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);t?.signal?.throwIfAborted();let n=await _g(e,t);return{privateKey:n[0],publicKey:n[1]}}async function Wf(r,t,e){let n=await Ke.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);e?.signal?.throwIfAborted();let o=await Ke.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,t instanceof Uint8Array?t:t.subarray());return e?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function jf(r,t,e,n){let o=await Ke.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ke.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),s}async function _g(r,t){if(r.privateKey==null||r.publicKey==null)throw new R("Private and public key are required");let e=await Promise.all([Ke.get().subtle.exportKey("jwk",r.privateKey),Ke.get().subtle.exportKey("jwk",r.publicKey)]);return t?.signal?.throwIfAborted(),e}function Qf(r){if(r.kty!=="RSA")throw new R("invalid key type");if(r.n==null)throw new R("invalid key modulus");return L(r.n,"base64url").length*8}var ss=class extends Fr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Wu(t);let n=Tn(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),ye(s)}update(t){return Ur(this),this.iHash.update(t),this}digestInto(t){Ur(this),Ye(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()}},Sc=(r,t,e)=>new ss(r,t).update(e).digest();Sc.create=(r,t)=>new ss(r,t);function Jf(r){r.lowS!==void 0&&le("lowS",r.lowS),r.prehash!==void 0&&le("prehash",r.prehash)}function Ig(r){let t=Nn(r);Ee(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}var Ic=class extends Error{constructor(t=""){super(t)}},Se={Err:Ic,_tlv:{encode:(r,t)=>{let{Err:e}=Se;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=Rn(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Rn(o.length/2|128):"";return Rn(r)+s+o+t},decode(r,t){let{Err:e}=Se,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}=Se;if(r<Ae)throw new t("integer: negative integers are not allowed");let e=Rn(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}=Se;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 xe(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Se,o=nt("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}=Se,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}};function Ac(r,t){return Be(tr(r,t))}var Ae=BigInt(0),bt=BigInt(1),B2=BigInt(2),_c=BigInt(3),Cg=BigInt(4);function Pg(r){let t=Ig(r),{Fp:e}=t,n=ve(t.n,t.nBitLength),o=t.toBytes||((x,p,w)=>{let P=p.toAffine();return Fe(Uint8Array.from([4]),e.toBytes(P.x),e.toBytes(P.y))}),s=t.fromBytes||(x=>{let p=x.subarray(1),w=e.fromBytes(p.subarray(0,e.BYTES)),P=e.fromBytes(p.subarray(e.BYTES,2*e.BYTES));return{x:w,y:P}});function i(x){let{a:p,b:w}=t,P=e.sqr(x),T=e.mul(P,x);return e.add(e.add(T,e.mul(x,p)),w)}function a(x,p){let w=e.sqr(p),P=i(x);return e.eql(w,P)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let c=e.mul(e.pow(t.a,_c),Cg),l=e.mul(e.sqr(t.b),BigInt(27));if(e.is0(e.add(c,l)))throw new Error("bad curve params: a or b");function u(x){return Go(x,bt,t.n)}function f(x){let{allowedPrivateKeyLengths:p,nByteLength:w,wrapPrivateKey:P,n:T}=t;if(p&&typeof x!="bigint"){if(qr(x)&&(x=Be(x)),typeof x!="string"||!p.includes(x.length))throw new Error("invalid private key");x=x.padStart(w*2,"0")}let D;try{D=typeof x=="bigint"?x:xe(nt("private key",x,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof x)}return P&&(D=rt(D,T)),Ht("private key",D,bt,T),D}function d(x){if(!(x instanceof m))throw new Error("ProjectivePoint expected")}let g=Vr((x,p)=>{let{px:w,py:P,pz:T}=x;if(e.eql(T,e.ONE))return{x:w,y:P};let D=x.is0();p==null&&(p=D?e.ONE:e.inv(T));let F=e.mul(w,p),q=e.mul(P,p),M=e.mul(T,p);if(D)return{x:e.ZERO,y:e.ZERO};if(!e.eql(M,e.ONE))throw new Error("invZ was invalid");return{x:F,y:q}}),h=Vr(x=>{if(x.is0()){if(t.allowInfinityPoint&&!e.is0(x.py))return;throw new Error("bad point: ZERO")}let{x:p,y:w}=x.toAffine();if(!e.isValid(p)||!e.isValid(w))throw new Error("bad point: x or y not FE");if(!a(p,w))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class m{constructor(p,w,P){if(p==null||!e.isValid(p))throw new Error("x required");if(w==null||!e.isValid(w)||e.is0(w))throw new Error("y required");if(P==null||!e.isValid(P))throw new Error("z required");this.px=p,this.py=w,this.pz=P,Object.freeze(this)}static fromAffine(p){let{x:w,y:P}=p||{};if(!p||!e.isValid(w)||!e.isValid(P))throw new Error("invalid affine point");if(p instanceof m)throw new Error("projective point not allowed");let T=D=>e.eql(D,e.ZERO);return T(w)&&T(P)?m.ZERO:new m(w,P,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(p){let w=Hr(e,p.map(P=>P.pz));return p.map((P,T)=>P.toAffine(w[T])).map(m.fromAffine)}static fromHex(p){let w=m.fromAffine(s(nt("pointHex",p)));return w.assertValidity(),w}static fromPrivateKey(p){return m.BASE.multiply(f(p))}static msm(p,w){return Xo(m,n,p,w)}_setWindowSize(p){C.setWindowSize(this,p)}assertValidity(){h(this)}hasEvenY(){let{y:p}=this.toAffine();if(e.isOdd)return!e.isOdd(p);throw new Error("Field doesn't support isOdd")}equals(p){d(p);let{px:w,py:P,pz:T}=this,{px:D,py:F,pz:q}=p,M=e.eql(e.mul(w,q),e.mul(D,T)),U=e.eql(e.mul(P,q),e.mul(F,T));return M&&U}negate(){return new m(this.px,e.neg(this.py),this.pz)}double(){let{a:p,b:w}=t,P=e.mul(w,_c),{px:T,py:D,pz:F}=this,q=e.ZERO,M=e.ZERO,U=e.ZERO,O=e.mul(T,T),ht=e.mul(D,D),_=e.mul(F,F),A=e.mul(T,D);return A=e.add(A,A),U=e.mul(T,F),U=e.add(U,U),q=e.mul(p,U),M=e.mul(P,_),M=e.add(q,M),q=e.sub(ht,M),M=e.add(ht,M),M=e.mul(q,M),q=e.mul(A,q),U=e.mul(P,U),_=e.mul(p,_),A=e.sub(O,_),A=e.mul(p,A),A=e.add(A,U),U=e.add(O,O),O=e.add(U,O),O=e.add(O,_),O=e.mul(O,A),M=e.add(M,O),_=e.mul(D,F),_=e.add(_,_),O=e.mul(_,A),q=e.sub(q,O),U=e.mul(_,ht),U=e.add(U,U),U=e.add(U,U),new m(q,M,U)}add(p){d(p);let{px:w,py:P,pz:T}=this,{px:D,py:F,pz:q}=p,M=e.ZERO,U=e.ZERO,O=e.ZERO,ht=t.a,_=e.mul(t.b,_c),A=e.mul(w,D),k=e.mul(P,F),S=e.mul(T,q),y=e.add(w,P),E=e.add(D,F);y=e.mul(y,E),E=e.add(A,k),y=e.sub(y,E),E=e.add(w,T);let I=e.add(D,q);return E=e.mul(E,I),I=e.add(A,S),E=e.sub(E,I),I=e.add(P,T),M=e.add(F,q),I=e.mul(I,M),M=e.add(k,S),I=e.sub(I,M),O=e.mul(ht,E),M=e.mul(_,S),O=e.add(M,O),M=e.sub(k,O),O=e.add(k,O),U=e.mul(M,O),k=e.add(A,A),k=e.add(k,A),S=e.mul(ht,S),E=e.mul(_,E),k=e.add(k,S),S=e.sub(A,S),S=e.mul(ht,S),E=e.add(E,S),A=e.mul(k,E),U=e.add(U,A),A=e.mul(I,E),M=e.mul(y,M),M=e.sub(M,A),A=e.mul(y,k),O=e.mul(I,O),O=e.add(O,A),new m(M,U,O)}subtract(p){return this.add(p.negate())}is0(){return this.equals(m.ZERO)}wNAF(p){return C.wNAFCached(this,p,m.normalizeZ)}multiplyUnsafe(p){let{endo:w,n:P}=t;Ht("scalar",p,Ae,P);let T=m.ZERO;if(p===Ae)return T;if(this.is0()||p===bt)return this;if(!w||C.hasPrecomputes(this))return C.wNAFCachedUnsafe(this,p,m.normalizeZ);let{k1neg:D,k1:F,k2neg:q,k2:M}=w.splitScalar(p),U=T,O=T,ht=this;for(;F>Ae||M>Ae;)F&bt&&(U=U.add(ht)),M&bt&&(O=O.add(ht)),ht=ht.double(),F>>=bt,M>>=bt;return D&&(U=U.negate()),q&&(O=O.negate()),O=new m(e.mul(O.px,w.beta),O.py,O.pz),U.add(O)}multiply(p){let{endo:w,n:P}=t;Ht("scalar",p,bt,P);let T,D;if(w){let{k1neg:F,k1:q,k2neg:M,k2:U}=w.splitScalar(p),{p:O,f:ht}=this.wNAF(q),{p:_,f:A}=this.wNAF(U);O=C.constTimeNegate(F,O),_=C.constTimeNegate(M,_),_=new m(e.mul(_.px,w.beta),_.py,_.pz),T=O.add(_),D=ht.add(A)}else{let{p:F,f:q}=this.wNAF(p);T=F,D=q}return m.normalizeZ([T,D])[0]}multiplyAndAddUnsafe(p,w,P){let T=m.BASE,D=(q,M)=>M===Ae||M===bt||!q.equals(T)?q.multiplyUnsafe(M):q.multiply(M),F=D(this,w).add(D(p,P));return F.is0()?void 0:F}toAffine(p){return g(this,p)}isTorsionFree(){let{h:p,isTorsionFree:w}=t;if(p===bt)return!0;if(w)return w(m,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:p,clearCofactor:w}=t;return p===bt?this:w?w(m,this):this.multiplyUnsafe(t.h)}toRawBytes(p=!0){return le("isCompressed",p),this.assertValidity(),o(m,this,p)}toHex(p=!0){return le("isCompressed",p),Be(this.toRawBytes(p))}}m.BASE=new m(t.Gx,t.Gy,e.ONE),m.ZERO=new m(e.ZERO,e.ONE,e.ZERO);let{endo:b,nBitLength:v}=t,C=jo(m,b?Math.ceil(v/2):v);return{CURVE:t,ProjectivePoint:m,normPrivateKeyToScalar:f,weierstrassEquation:i,isWithinCurveOrder:u}}function Tg(r){let t=Nn(r);return Ee(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function td(r){let t=Tg(r),{Fp:e,n,nByteLength:o,nBitLength:s}=t,i=e.BYTES+1,a=2*e.BYTES+1;function c(_){return rt(_,n)}function l(_){return Wo(_,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:d,isWithinCurveOrder:g}=Pg({...t,toBytes(_,A,k){let S=A.toAffine(),y=e.toBytes(S.x),E=Fe;return le("isCompressed",k),k?E(Uint8Array.from([A.hasEvenY()?2:3]),y):E(Uint8Array.from([4]),y,e.toBytes(S.y))},fromBytes(_){let A=_.length,k=_[0],S=_.subarray(1);if(A===i&&(k===2||k===3)){let y=xe(S);if(!Go(y,bt,e.ORDER))throw new Error("Point is not on curve");let E=d(y),I;try{I=e.sqrt(E)}catch(V){let $=V instanceof Error?": "+V.message:"";throw new Error("Point is not on curve"+$)}let N=(I&bt)===bt;return(k&1)===1!==N&&(I=e.neg(I)),{x:y,y:I}}else if(A===a&&k===4){let y=e.fromBytes(S.subarray(0,e.BYTES)),E=e.fromBytes(S.subarray(e.BYTES,2*e.BYTES));return{x:y,y:E}}else{let y=i,E=a;throw new Error("invalid Point, expected length of "+y+", or uncompressed "+E+", got "+A)}}});function h(_){let A=n>>bt;return _>A}function m(_){return h(_)?c(-_):_}let b=(_,A,k)=>xe(_.slice(A,k));class v{constructor(A,k,S){Ht("r",A,bt,n),Ht("s",k,bt,n),this.r=A,this.s=k,S!=null&&(this.recovery=S),Object.freeze(this)}static fromCompact(A){let k=o;return A=nt("compactSignature",A,k*2),new v(b(A,0,k),b(A,k,2*k))}static fromDER(A){let{r:k,s:S}=Se.toSig(nt("DER",A));return new v(k,S)}assertValidity(){}addRecoveryBit(A){return new v(this.r,this.s,A)}recoverPublicKey(A){let{r:k,s:S,recovery:y}=this,E=T(nt("msgHash",A));if(y==null||![0,1,2,3].includes(y))throw new Error("recovery id invalid");let I=y===2||y===3?k+t.n:k;if(I>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let N=(y&1)===0?"02":"03",K=u.fromHex(N+Ac(I,e.BYTES)),V=l(I),$=c(-E*V),X=c(S*V),J=u.BASE.multiplyAndAddUnsafe(K,$,X);if(!J)throw new Error("point at infinify");return J.assertValidity(),J}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Mn(this.toDERHex())}toDERHex(){return Se.hexFromSig(this)}toCompactRawBytes(){return Mn(this.toCompactHex())}toCompactHex(){let A=o;return Ac(this.r,A)+Ac(this.s,A)}}let C={isValidPrivateKey(_){try{return f(_),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let _=Fa(t.n);return vf(t.randomBytes(_),t.n)},precompute(_=8,A=u.BASE){return A._setWindowSize(_),A.multiply(BigInt(3)),A}};function x(_,A=!0){return u.fromPrivateKey(_).toRawBytes(A)}function p(_){if(typeof _=="bigint")return!1;if(_ instanceof u)return!0;let k=nt("key",_).length,S=e.BYTES,y=S+1,E=2*S+1;if(!(t.allowedPrivateKeyLengths||o===y))return k===y||k===E}function w(_,A,k=!0){if(p(_)===!0)throw new Error("first arg must be private key");if(p(A)===!1)throw new Error("second arg must be public key");return u.fromHex(A).multiply(f(_)).toRawBytes(k)}let P=t.bits2int||function(_){if(_.length>8192)throw new Error("input is too large");let A=xe(_),k=_.length*8-s;return k>0?A>>BigInt(k):A},T=t.bits2int_modN||function(_){return c(P(_))},D=er(s);function F(_){return Ht("num < 2^"+s,_,Ae,D),tr(_,o)}function q(_,A,k=M){if(["recovered","canonical"].some(ut=>ut in k))throw new Error("sign() legacy options not supported");let{hash:S,randomBytes:y}=t,{lowS:E,prehash:I,extraEntropy:N}=k;E==null&&(E=!0),_=nt("msgHash",_),Jf(k),I&&(_=nt("prehashed msgHash",S(_)));let K=T(_),V=f(A),$=[F(V),F(K)];if(N!=null&&N!==!1){let ut=N===!0?y(e.BYTES):N;$.push(nt("extraEntropy",ut))}let X=Fe(...$),J=K;function pt(ut){let wt=P(ut);if(!g(wt))return;let Ft=l(wt),gt=u.BASE.multiply(wt).toAffine(),vt=c(gt.x);if(vt===Ae)return;let qt=c(Ft*c(J+vt*V));if(qt===Ae)return;let Yt=(gt.x===vt?0:2)|Number(gt.y&bt),yn=qt;return E&&h(qt)&&(yn=m(qt),Yt^=1),new v(vt,yn,Yt)}return{seed:X,k2sig:pt}}let M={lowS:t.lowS,prehash:!1},U={lowS:t.lowS,prehash:!1};function O(_,A,k=M){let{seed:S,k2sig:y}=q(_,A,k),E=t;return pf(E.hash.outputLen,E.nByteLength,E.hmac)(S,y)}u.BASE._setWindowSize(8);function ht(_,A,k,S=U){let y=_;A=nt("msgHash",A),k=nt("publicKey",k);let{lowS:E,prehash:I,format:N}=S;if(Jf(S),"strict"in S)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 K=typeof y=="string"||qr(y),V=!K&&!N&&typeof y=="object"&&y!==null&&typeof y.r=="bigint"&&typeof y.s=="bigint";if(!K&&!V)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let $,X;try{if(V&&($=new v(y.r,y.s)),K){try{N!=="compact"&&($=v.fromDER(y))}catch(Yt){if(!(Yt instanceof Se.Err))throw Yt}!$&&N!=="der"&&($=v.fromCompact(y))}X=u.fromHex(k)}catch{return!1}if(!$||E&&$.hasHighS())return!1;I&&(A=t.hash(A));let{r:J,s:pt}=$,ut=T(A),wt=l(pt),Ft=c(ut*wt),gt=c(J*wt),vt=u.BASE.multiplyAndAddUnsafe(X,Ft,gt)?.toAffine();return vt?c(vt.x)===J:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:w,sign:O,verify:ht,ProjectivePoint:u,Signature:v,utils:C}}function Lg(r){return{hash:r,hmac:(t,...e)=>Sc(r,t,Ia(...e)),randomBytes:Kr}}function ed(r,t){let e=n=>td({...r,...Lg(n)});return{...e(t),create:e}}var od=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),rd=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Dg=BigInt(0),kg=BigInt(1),Cc=BigInt(2),nd=(r,t)=>(r+t/Cc)/t;function Rg(r){let t=od,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=ot(u,e,t)*u%t,d=ot(f,e,t)*u%t,g=ot(d,Cc,t)*l%t,h=ot(g,o,t)*g%t,m=ot(h,s,t)*h%t,b=ot(m,a,t)*m%t,v=ot(b,c,t)*b%t,C=ot(v,a,t)*m%t,x=ot(C,e,t)*u%t,p=ot(x,i,t)*h%t,w=ot(p,n,t)*l%t,P=ot(w,Cc,t);if(!Pc.eql(Pc.sqr(P),r))throw new Error("Cannot find square root");return P}var Pc=ve(od,void 0,void 0,{sqrt:Rg}),oe=ed({a:Dg,b:BigInt(7),Fp:Pc,n:rd,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=rd,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-kg*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=nd(s*r,t),c=nd(-n*r,t),l=rt(r-a*e-c*o,t),u=rt(-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}}}},$o);function Tc(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function sd(r,t,e){let n=Br.digest(t instanceof Uint8Array?t:t.subarray());if(Tc(n))return n.then(({digest:o})=>(e?.signal?.throwIfAborted(),oe.sign(o,r).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new qn(String(o))});try{return oe.sign(n.digest,r).toDERRawBytes()}catch(o){throw new qn(String(o))}}function id(r,t,e,n){let o=Br.digest(e instanceof Uint8Array?e:e.subarray());if(Tc(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),oe.verify(t,s,r))).catch(s=>{throw s.name==="AbortError"?s:new zn(String(s))});try{return n?.signal?.throwIfAborted(),oe.verify(t,o.digest,r)}catch(s){throw new zn(String(s))}}var $n=class{type="secp256k1";raw;_key;constructor(t){this._key=ld(t),this.raw=ad(this._key)}toMultihash(){return Jt.digest(Wt(this))}toCID(){return it.createV1(114,this.toMultihash())}toString(){return G.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:tt(this.raw,t.raw)}verify(t,e,n){return id(this._key,e,t,n)}},is=class{type="secp256k1";raw;publicKey;constructor(t,e){this.raw=cd(t),this.publicKey=new $n(e??ud(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:tt(this.raw,t.raw)}sign(t,e){return sd(this.raw,t,e)}};function Lc(r){return new $n(r)}async function fd(){let r=Mg();return new is(r)}function ad(r){return oe.ProjectivePoint.fromHex(r).toRawBytes(!0)}function cd(r){try{return oe.getPublicKey(r,!0),r}catch(t){throw new bn(String(t))}}function ld(r){try{return oe.ProjectivePoint.fromHex(r),r}catch(t){throw new Pr(String(t))}}function ud(r){try{return oe.getPublicKey(r,!0)}catch(t){throw new bn(String(t))}}function Mg(){return oe.utils.randomPrivateKey()}async function dd(r,t){if(r==="Ed25519")return Of();if(r==="secp256k1")return fd();if(r==="RSA")return vc(Ng(t));if(r==="ECDSA")return Gu(Og(t));throw new ke}function jr(r,t){let{Type:e,Data:n}=fe.decode(r),o=n??new Uint8Array;switch(e){case ft.RSA:return wc(o,t);case ft.Ed25519:return Ga(o);case ft.secp256k1:return Lc(o);case ft.ECDSA:return _a(o);default:throw new ke}}function hd(r){let{Type:t,Data:e}=fe.decode(r.digest),n=e??new Uint8Array;switch(t){case ft.Ed25519:return Ga(n);case ft.secp256k1:return Lc(n);case ft.ECDSA:return _a(n);default:throw new ke}}function Wt(r){return fe.encode({Type:ft[r.type],Data:r.raw})}function Ng(r){return r==null?2048:parseInt(r,10)}function Og(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 pd=Symbol.for("nodejs.util.inspect.custom"),Bg=114,Gn=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()})`}[Co]=!0;toString(){return this.string==null&&(this.string=G.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return it.createV1(Bg,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return tt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return tt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[pd](){return`PeerId(${this.toString()})`}},Wn=class extends Gn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},jn=class extends Gn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Xn=class extends Gn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Fg=2336,Yn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Jt.digest(L(this.url))}[pd](){return`PeerId(${this.url})`}[Co]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return it.createV1(Fg,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=B(t)),t.toString()===this.toString())}};var Ug=114,md=2336;function de(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Vt(G.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Zn(it.parse(r));if(t==null)throw new R('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Vt(t.decode(r))}return Xr(e)}function Dc(r){if(r.type==="Ed25519")return new jn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Xn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Wn({multihash:r.toCID().multihash,publicKey:r});throw new ke}function gd(r){return Dc(r.publicKey)}function Xr(r){if(qg(r))return new Wn({multihash:r});if(Kg(r))try{let t=hd(r);if(t.type==="Ed25519")return new jn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Xn({multihash:r,publicKey:t})}catch{let e=B(r.digest);return new Yn(new URL(e))}throw new Lo("Supplied PeerID Multihash is invalid")}function Zn(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Ug&&r.code!==md)throw new To("Supplied PeerID CID is invalid");if(r.code===md){let t=B(r.multihash.digest);return new Yn(new URL(t))}return Xr(r.multihash)}function Kg(r){return r.code===Jt.code}function qg(r){return r.code===Br.code}function Yr(r){if(typeof r!="object"||r===null)return!1;let t=Object.getPrototypeOf(r);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)}var{hasOwnProperty:bd}=Object.prototype,{propertyIsEnumerable:zg}=Object,Zr=(r,t,e)=>{Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0})},Vg=void 0,yd={concatArrays:!1,ignoreUndefined:!1},as=r=>{let t=[];for(let e in r)bd.call(r,e)&&t.push(e);if(Object.getOwnPropertySymbols){let e=Object.getOwnPropertySymbols(r);for(let n of e)zg.call(r,n)&&t.push(n)}return t};function Qr(r){return Array.isArray(r)?Hg(r):Yr(r)?$g(r):r}function Hg(r){let t=r.slice(0,0);return as(r).forEach(e=>{Zr(t,e,Qr(r[e]))}),t}function $g(r){let t=Object.getPrototypeOf(r)===null?Object.create(null):{};return as(r).forEach(e=>{Zr(t,e,Qr(r[e]))}),t}var wd=(r,t,e,n)=>(e.forEach(o=>{typeof t[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?Zr(r,o,kc(r[o],t[o],n)):Zr(r,o,Qr(t[o])))}),r),Gg=(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++)bd.call(s,a)&&(i.push(String(a)),s===r?Zr(n,o++,s[a]):Zr(n,o++,Qr(s[a])));n=wd(n,s,as(s).filter(a=>!i.includes(a)),e)}),n};function kc(r,t,e){return e.concatArrays&&Array.isArray(r)&&Array.isArray(t)?Gg(r,t,e):!Yr(t)||!Yr(r)?Qr(t):wd(r,t,as(t),e)}function cs(...r){let t=kc(Qr(yd),this!==Vg&&this||{},yd),e={_:{}};for(let n of r)if(n!==void 0){if(!Yr(n))throw new TypeError("`"+n+"` is not an Option Object");e=kc(e,{_:n},t)}return e._}var dt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Mc=Io(Ed(),1);var Jn=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Nc=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},vd=r=>globalThis.DOMException===void 0?new Nc(r):new DOMException(r),Sd=r=>{let t=r.reason===void 0?vd("This operation was aborted."):r.reason;return t instanceof Error?t:vd(t)};function Oc(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:g}=t;g.aborted&&f(Sd(g)),a=()=>{f(Sd(g))},g.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new Jn;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(g){f(g)}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(g){f(g)}})()}).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 Bc(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 to=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=Bc(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 qe=class extends Mc.default{#t;#e;#r=0;#a;#c;#p=0;#o;#l;#n;#m;#s=0;#u;#i;#g;#w=1n;timeout;constructor(t){if(super(),t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:to,...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.#b(),this.#y(),this.#l=void 0}get#A(){let t=Date.now();if(this.#o===void 0){let e=this.#p-t;if(e<0)this.#r=this.#t?this.#s:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#S()},e)),!0}return!1}#f(){if(this.#n.size===0)return this.#o&&clearInterval(this.#o),this.#o=void 0,this.emit("empty"),this.#s===0&&this.emit("idle"),!1;if(!this.#i){let t=!this.#A;if(this.#x&&this.#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.#b()},this.#c),this.#p=Date.now()+this.#c)}#b(){this.#r===0&&this.#s===0&&this.#o&&(clearInterval(this.#o),this.#o=void 0),this.#r=this.#t?this.#s:0,this.#d()}#d(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#u=t,this.#d()}async#_(t){return new Promise((e,n)=>{t.addEventListener("abort",()=>{n(t.reason)},{once:!0})})}setPriority(t,e){this.#n.setPriority(t,e)}async add(t,e={}){return e.id??=(this.#w++).toString(),e={timeout:this.timeout,throwOnTimeout:this.#g,...e},new Promise((n,o)=>{this.#n.enqueue(async()=>{this.#s++,this.#r++;try{e.signal?.throwIfAborted();let s=t({signal:e.signal});e.timeout&&(s=Oc(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 Jn&&!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 us(r){let t=[Gt.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var Fc=60;function fs(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:Gt[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:Gt[t.type],TTL:t.TTL??t.ttl??Fc,data:t.data instanceof Uint8Array?B(t.data):t.data}))}}var Xg=4;function Uc(r,t={}){let e=new qe({concurrency:t.queryConcurrency??Xg});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),us(o.types).forEach(a=>{s.append("type",Gt[a])}),o.onProgress?.(new dt("dns:query",{detail:n}));let i=await e.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=fs(await a.json());return o.onProgress?.(new dt("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function Ad(){return[Uc("https://cloudflare-dns.com/dns-query"),Uc("https://dns.google/resolve")]}var Cd=Io(Id(),1);var Kc=class{lru;constructor(t){this.lru=(0,Cd.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 fs({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:Gt[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??Fc)*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 Pd(r){return new Kc(r)}var Yg=1e3,ds=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=Pd(t.cacheSize??Yg),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["."]=Ad())}async query(t,e={}){let n=us(e.types),o=e.cached!==!1?this.cache.get(t,n):void 0;if(o!=null)return e.onProgress?.(new dt("dns:cache",{detail:o})),o;let s=`${t.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(e.signal?.aborted===!0)break;try{let l=await c(t,{...e,types:n});for(let u of l.Answer)this.cache.add(t,u);return l}catch(l){a.push(l),e.onProgress?.(new dt("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${t} ${n} failed`)}};var Gt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Gt||(Gt={}));function Td(r={}){return new ds(r)}var hs=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 Ld=45,Zg=15,Jr=new hs;function ps(r){if(!(r.length>Zg))return Jr.new(r).parseWith(()=>Jr.readIPv4Addr())}function ms(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ld))return Jr.new(r).parseWith(()=>Jr.readIPv6Addr())}function ar(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Ld)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 Dd(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 kd(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 qc(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 Rd(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 Md(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,kv=parseInt("0xFFFF",16),Qg=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function eo(r,t){t.length===lr&&r.length===cr&&Dd(t,0,11)&&(t=t.slice(12)),t.length===cr&&r.length===lr&&kd(r,Qg,0,11)&&(r=r.slice(12));let e=r.length;if(e!=t.length)throw new Error("Failed to mask ip");let n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=r[o]&t[o];return n}function Nd(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 zc(r){let[t,e]=r.split("/");if(!t||!e)throw new Error("Failed to parse given CIDR: "+r);let n=cr,o=ps(t);if(o==null&&(n=lr,o=ms(t),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(e,10);if(Number.isNaN(s)||String(s).length!==e.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=Vc(s,8*n);return{network:eo(o,i),mask:i}}function Vc(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 tn=class{constructor(t,e){if(e==null)({network:this.network,mask:this.mask}=zc(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=Vc(o,8*n.length);this.network=eo(n,this.mask)}}contains(t){return Nd({network:this.network,mask:this.mask},t)}toString(){let t=Rd(this.mask),e=t!==-1?String(t):Md(this.mask);return qc(this.network)+"/"+e}};function se(r){return!!ps(r)}function en(r){return!!ms(r)}function gs(r){return!!ar(r)}var Od=se,Jg=en,Hc=function(r){let t=0;if(r=r.toString().trim(),Od(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Jg(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Od(e[n]),i;s&&(i=Hc(e[n]),e[n]=B(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,B(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let s=parseInt(e[n],16);o[t++]=s>>8&255,o[t++]=s&255}return o}throw new Error("invalid ip address")},Bd=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 rn={},$c={},e0=[[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"]];e0.forEach(r=>{let t=r0(...r);$c[t.code]=t,rn[t.name]=t});function r0(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function W(r){if(typeof r=="number"){if($c[r]!=null)return $c[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(rn[r]!=null)return rn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var n0=W("ip4"),o0=W("ip6"),s0=W("ipcidr");function Xc(r,t){switch(W(r).code){case 4:case 41:return a0(t);case 42:return jc(t);case 43:return B(t,"base10");case 6:case 273:case 33:case 132:return Kd(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return jc(t);case 421:return f0(t);case 444:return Ud(t);case 445:return Ud(t);case 466:return u0(t);case 481:return globalThis.encodeURIComponent(jc(t));default:return B(t,"base16")}}function Yc(r,t){switch(W(r).code){case 4:return Fd(t);case 41:return Fd(t);case 42:return Wc(t);case 43:return L(t,"base10");case 6:case 273:case 33:case 132:return Qc(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Wc(t);case 421:return c0(t);case 444:return d0(t);case 445:return h0(t);case 466:return l0(t);case 481:return Wc(globalThis.decodeURIComponent(t));default:return L(t,"base16")}}function Zc(r){let t,e;if(r.stringTuples().forEach(([n,o])=>{(n===n0.code||n===o0.code)&&(e=o),n===s0.code&&(t=o)}),t==null||e==null)throw new Error("Invalid multiaddr");return new tn(e,t)}var Gc=Object.values(_n).map(r=>r.decoder),i0=function(){let r=Gc[0].or(Gc[1]);return Gc.slice(2).forEach(t=>r=r.or(t)),r}();function Fd(r){if(!gs(r))throw new Error("invalid ip address");return Hc(r)}function a0(r){let t=Bd(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!gs(t))throw new Error("invalid ip address");return t}function Qc(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Kd(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Wc(r){let t=L(r),e=Uint8Array.from(_t(t.length));return Tt([e,t],e.length+t.length)}function jc(r){let t=re(r);if(r=r.slice(mt(t)),r.length!==t)throw new Error("inconsistent lengths");return B(r)}function c0(r){let t;r[0]==="Q"||r[0]==="1"?t=Vt(G.decode(`z${r}`)).bytes:t=it.parse(r).multihash.bytes;let e=Uint8Array.from(_t(t.length));return Tt([e,t],e.length+t.length)}function l0(r){let t=i0.decode(r),e=Uint8Array.from(_t(t.length));return Tt([e,t],e.length+t.length)}function u0(r){let t=re(r),e=r.slice(mt(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+B(e,"base64url")}function f0(r){let t=re(r),e=r.slice(mt(t));if(e.length!==t)throw new Error("inconsistent lengths");return B(e,"base58btc")}function d0(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=zt.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=Qc(n);return Tt([e,o],e.length+o.length)}function h0(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=zt.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=Qc(n);return Tt([e,o],e.length+o.length)}function Ud(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=B(t,"base32"),o=Kd(e);return`${n}:${o}`}function qd(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=W(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw new ys("invalid address: "+r);if(a.path===!0){n=Jc(o.slice(s).join("/")),t.push([a.code,Yc(a.code,n)]),e.push([a.code,n]);break}let c=Yc(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Xc(a.code,c)])}return{string:zd(e),bytes:bs(t),tuples:t,stringTuples:e,path:n}}function tl(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=re(r,o),i=mt(s),a=W(s),c=p0(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 ys("Invalid address Uint8Array: "+B(r,"base16"));t.push([s,l]);let u=Xc(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:zd(e),tuples:t,stringTuples:e,path:n}}function zd(r){let t=[];return r.map(e=>{let n=W(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Jc(t.join("/"))}function bs(r){return Tt(r.map(t=>{let e=W(t[0]),n=Uint8Array.from(_t(e.code));return t.length>1&&t[1]!=null&&(n=Tt([n,t[1]])),n}))}function p0(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=re(t instanceof Uint8Array?t:Uint8Array.from(t));return e+mt(e)}}function Jc(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var ys=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var m0=Symbol.for("nodejs.util.inspect.custom"),rl=Symbol.for("@multiformats/js-multiaddr/multiaddr"),g0=[W("dns").code,W("dns4").code,W("dns6").code,W("dnsaddr").code],el=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},ws=class r{bytes;#t;#e;#r;#a;[rl]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=tl(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=qd(t)}else if(ze(t))e=tl(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=W("tcp"),a=W("udp"),c=W("ip4"),l=W("ip6"),u=W("dns6"),f=W("ip6zone");for(let[g,h]of this.stringTuples())g===f.code&&(s=`%${h??""}`),g0.includes(g)&&(e=i.name==="tcp"?"tcp":"udp",o=443,n=`${h??""}${s}`,t=g===u.code?6:4),(g===i.code||g===a.code)&&(e=W(g).name==="tcp"?"tcp":"udp",o=parseInt(h??"")),(g===c.code||g===l.code)&&(e=W(g).name==="tcp"?"tcp":"udp",n=`${h??""}${s}`,t=g===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({},W(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>W(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(bs(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===rn.p2p.code&&t.push([n,o]),n===rn["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?B(G.decode(`z${n}`),"base58btc"):B(it.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(t){return tt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=nn.get(e.name);if(n==null)throw new el(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>j(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[m0](){return`Multiaddr(${this.#t})`}};var nn=new Map;function ze(r){return!!r?.[rl]}function j(r){return new ws(r)}var y0=32,{code:b0}=W("dnsaddr"),nl=class extends Error{constructor(t="Max recursive depth reached"){super(t),this.name="RecursionLimitError"}},ur=async function(t,e={}){let n=e.maxRecursiveDepth??y0;if(n===0)throw new nl("Max recursive depth reached");let[,o]=t.stringTuples().find(([l])=>l===b0)??[],i=await(e?.dns??Td()).query(`_dnsaddr.${o}`,{signal:e?.signal,types:[Gt.TXT]}),a=t.getPeerId(),c=[];for(let l of i.Answer){let u=l.data.replace(/["']/g,"").trim().split("=")[1];if(u==null||a!=null&&!u.includes(a))continue;let f=j(u);if(u.startsWith("/dnsaddr")){let d=await f.resolve({...e,maxRecursiveDepth:n-1});c.push(...d.map(g=>g.toString()))}else c.push(f.toString())}return c};var w0={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:ur}},transportManager:{faultTolerance:Ge.FATAL_ALL}};async function Vd(r){let t=cs(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 x0(r,t){try{if(typeof r=="string"&&r.length>0)return E0(r);if(typeof r=="number"&&isFinite(r))return t?.long?S0(r):v0(r);throw new Error("Value is not a string or number.")}catch(e){let n=A0(e)?`${e.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function E0(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 Es=x0;function v0(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 S0(r){let t=Math.abs(r);return t>=864e5?xs(r,t,864e5,"day"):t>=36e5?xs(r,t,36e5,"hour"):t>=6e4?xs(r,t,6e4,"minute"):t>=1e3?xs(r,t,1e3,"second"):`${r} ms`}function xs(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function A0(r){return typeof r=="object"&&r!==null&&"message"in r}function ol(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=o,e.enabled=i,e.humanize=Es,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,g,h;function m(...b){if(!m.enabled)return;let v=m,C=Number(new Date),x=C-(f||C);v.diff=x,v.prev=f,v.curr=C,f=C,b[0]=e.coerce(b[0]),typeof b[0]!="string"&&b.unshift("%O");let p=0;b[0]=b[0].replace(/%([a-zA-Z%])/g,(P,T)=>{if(P==="%%")return"%";p++;let D=e.formatters[T];if(typeof D=="function"){let F=b[p];P=D.call(v,F),b.splice(p,1),p--}return P}),e.formatArgs.call(v,b),(v.log||e.log).apply(v,b)}return m.namespace=u,m.useColors=e.useColors(),m.color=e.selectColor(u),m.extend=n,m.destroy=e.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(g!==e.namespaces&&(g=e.namespaces,h=e.enabled(u)),h),set:b=>{d=b}}),typeof e.init=="function"&&e.init(m),m}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,]+/),g=d.length;for(f=0;f<g;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 vs=D0(),_0=["#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 I0(){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 C0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Es(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 P0=console.debug??console.log??(()=>{});function T0(r){try{r?vs?.setItem("debug",r):vs?.removeItem("debug")}catch{}}function L0(){let r;try{r=vs?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function D0(){try{return localStorage}catch{}}function k0(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var Hd=ol({formatArgs:C0,save:T0,load:L0,useColors:I0,setupFormatters:k0,colors:_0,storage:vs,log:P0});var Kt=Hd;Kt.formatters.b=r=>r==null?"undefined":G.baseEncode(r);Kt.formatters.t=r=>r==null?"undefined":zt.baseEncode(r);Kt.formatters.m=r=>r==null?"undefined":da.baseEncode(r);Kt.formatters.p=r=>r==null?"undefined":r.toString();Kt.formatters.c=r=>r==null?"undefined":r.toString();Kt.formatters.k=r=>r==null?"undefined":r.toString();Kt.formatters.a=r=>r==null?"undefined":r.toString();Kt.formatters.e=r=>r==null?"undefined":$d(r.stack)??$d(r.message)??r.toString();function R0(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 Ss(){return{forComponent(r){return M0(r)}}}function M0(r){let t=R0(`${r}:trace`);return Kt.enabled(`${r}:trace`)&&Kt.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=Kt(`${r}:trace`)),Object.assign(Kt(r),{error:Kt(`${r}:error`),trace:t})}function $d(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 As(r){let t=Vt(G.decode(`z${r}`));return Xr(t)}var _e=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=As(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=As(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return fr(this.set.values(),t=>As(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 sl={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Gd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Wd=new globalThis.TextEncoder;function N0(r,t){let e=sl[t],n=Gd[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function O0(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=sl[t],o=Gd[t],s=r;for(;s.length>0;){let i=Wd.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 il(r,{size:t=32,utf8Buffer:e}={}){if(!sl[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 O0(r,t,e);r=Wd.encode(r)}return N0(r,t)}var ro={hash:r=>Number(il(r,{size:32})),hashV:(r,t)=>B0(ro.hash(r,t))};function B0(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),L(t,"base16")}var al=64,ie=class{fp;h;seed;constructor(t,e,n,o=2){if(o>al)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=ct(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?tt(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 ie))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof ie))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 ie))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 ie))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var F0=500,no=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??ro,this.seed=t.seed??hr(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=L(t));let e=new ie(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<F0;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=L(t));let e=new ie(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=L(t));let e=new ie(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}},U0={1:.5,2:.84,4:.95,8:.98};function K0(r=.001){return r>.002?2:r>1e-5?4:8}function jd(r,t=.001){let e=K0(t),n=U0[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),al);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var _s=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??ro,this.seed=t.seed??hr(0,Math.pow(2,10)),this.filterSeries=[new no({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=L(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 no({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=L(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=L(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 oo(r,t=.001,e){return new _s({...jd(r,t),...e??{}})}var so;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&e.payload.byteLength>0&&(n.uint32(26),n.bytes(e.payload)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={publicKey:ct(0),payloadType:ct(0),payload:ct(0),signature:ct(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.payloadType=e.bytes();break}case 3:{s.payload=e.bytes();break}case 5:{s.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(so||(so={}));var Is=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var on=class r{static createFromProtobuf=t=>{let e=so.decode(t),n=jr(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e,n)=>{if(e==null)throw new Error("Missing private key");let o=t.domain,s=t.codec,i=t.marshal(),a=Xd(o,s,i),c=await e.sign(a.subarray(),n);return new r({publicKey:e.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(t,e,n)=>{let o=r.createFromProtobuf(t);if(!await o.validate(e,n))throw new Is("Envelope signature is not valid for the given domain");return o};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=so.encode({publicKey:Wt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return t==null?!1:tt(this.marshal(),t.marshal())}async validate(t,e){let n=Xd(t,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,e)}},Xd=(r,t,e)=>{let n=L(r),o=_t(n.byteLength),s=_t(t.length),i=_t(e.length);return new Y(o,n,s,t,i,e)};function Yd(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",Qd=Uint8Array.from([3,1]);var io;(function(r){let t;(function(n){let o;n.codec=()=>(o==null&&(o=Nt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:ct(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(u&7);break}}}return c})),o),n.encode=s=>Mt(s,n.codec()),n.decode=(s,i)=>Rt(s,n.codec(),i)})(t=r.AddressInfo||(r.AddressInfo={}));let e;r.codec=()=>(e==null&&(e=Nt((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o,s={})=>{let i={peerId:ct(0),seq:0n,addresses:[]},a=o==null?n.len:n.pos+o;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new 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)=>Rt(n,r.codec(),o)})(io||(io={}));var mr=class r{static createFromProtobuf=t=>{let e=io.decode(t),n=Xr(Vt(e.peerId)),o=(e.addresses??[]).map(i=>j(i.multiaddr)),s=e.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Zd;static CODEC=Qd;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=io.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||!Yd(this.multiaddrs,t.multiaddrs))}};function q0(r){return r[Symbol.asyncIterator]!=null}function z0(r){if(q0(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 ao=z0;var sn=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};var Ve={},an=r=>{r.addEventListener("message",t=>{an.dispatchEvent("message",r,t)}),r.port!=null&&r.port.addEventListener("message",t=>{an.dispatchEvent("message",r,t)})};an.addEventListener=(r,t)=>{Ve[r]==null&&(Ve[r]=[]),Ve[r].push(t)};an.removeEventListener=(r,t)=>{Ve[r]!=null&&(Ve[r]=Ve[r].filter(e=>e===t))};an.dispatchEvent=function(r,t,e){Ve[r]!=null&&Ve[r].forEach(n=>n(t,e))};var cl=an;var ll="lock:worker:request-read",ul="lock:worker:abort-read-request",fl="lock:worker:release-read",dl="lock:master:grant-read",hl="lock:worker:request-write",pl="lock:worker:abort-write-request",ml="lock:worker:release-write",gl="lock:master:grant-write";var Jd=(r=10)=>Math.random().toString().substring(2,r+2);var th=(r,t,e,n,o,s,i)=>(a,c)=>{if(c.data==null)return;let l={type:c.data.type,name:c.data.name,identifier:c.data.identifier};c.data.type===n&&r.dispatchEvent(new MessageEvent(t,{data:{name:l.name,handler:async()=>{a.postMessage({type:i,name:l.name,identifier:l.identifier}),await new Promise(u=>{let f=d=>{if(d?.data==null)return;let g={type:d.data.type,name:d.data.name,identifier:d.data.identifier};g.type===s&&g.identifier===l.identifier&&(a.removeEventListener("message",f),u())};a.addEventListener("message",f)})}}})),l.type===o&&(a.postMessage({type:o,name:l.name,identifier:l.identifier}),r.dispatchEvent(new MessageEvent(e,{data:{name:l.name}})))},eh=(r,t,e,n,o)=>async s=>{s?.signal?.throwIfAborted();let i=Jd();return globalThis.postMessage({type:t,identifier:i,name:r}),new Promise((a,c)=>{let l=()=>{process.send?.({type:e,identifier:i,name:r}),c(new sn)};s?.signal?.addEventListener("abort",l,{once:!0});let u=f=>{if(f?.data==null)return;let d={type:f.data.type,identifier:f.data.identifier};d.type===n&&d.identifier===i&&(globalThis.removeEventListener("message",u),s?.signal?.removeEventListener("abort",l),a(()=>{globalThis.postMessage({type:o,identifier:i,name:r})}))};globalThis.addEventListener("message",u)})},V0={singleProcess:!1},rh=r=>{if(r=Object.assign({},V0,r),!!globalThis.document||r.singleProcess){let e=new EventTarget;return cl.addEventListener("message",th(e,"requestReadLock","abortReadLockRequest",ll,ul,fl,dl)),cl.addEventListener("message",th(e,"requestWriteLock","abortWriteLockRequest",hl,pl,ml,gl)),e}return{isWorker:!0,readLock:e=>eh(e,ll,ul,dl,fl),writeLock:e=>eh(e,hl,pl,gl,ml)}};var gr={},jt;async function yl(r,t){let e,n,o=new Promise((i,a)=>{e=i,n=a}),s=()=>{n(new sn)};return t?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{e(()=>{t?.signal?.removeEventListener("abort",s),i()})})},{signal:t?.signal}).catch(i=>{n(i)}),o}var H0=(r,t)=>{if(jt.isWorker===!0)return{readLock:jt.readLock(r,t),writeLock:jt.writeLock(r,t)};let e=new qe({concurrency:1}),n;return{async readLock(o){if(n!=null)return yl(n,o);n=new qe({concurrency:t.concurrency,autoStart:!1});let s=n,i=yl(n,o);return e.add(async()=>{s.start(),await s.onIdle().then(()=>{n===s&&(n=null)})}),i},async writeLock(o){return n=null,yl(e,o)}}},$0={name:"lock",concurrency:1/0,singleProcess:!1};function bl(r){let t=Object.assign({},$0,r);return jt==null&&(jt=rh(t),jt.isWorker!==!0&&(jt.addEventListener("requestReadLock",e=>{let n=e.data.name;if(gr[n]==null)return;let o=new AbortController,s=i=>{i.data.name===n&&o.abort()};jt.addEventListener("abortReadLockRequest",s),gr[n].readLock({signal:o.signal}).then(async i=>e.data.handler().finally(()=>{i()})).finally(()=>{jt.removeEventListener("abortReadLockRequest",s)})}),jt.addEventListener("requestWriteLock",async e=>{let n=e.data.name;if(gr[n]==null)return;let o=new AbortController,s=i=>{i.data.name===n&&o.abort()};jt.addEventListener("abortWriteLockRequest",s),gr[e.data.name].writeLock({signal:o.signal}).then(async i=>e.data.handler().finally(()=>{i()})).finally(()=>{jt.removeEventListener("abortWriteLockRequest",s)})}))),gr[t.name]==null&&(gr[t.name]=H0(t.name,t)),gr[t.name]}var Ie;(function(r){let t;(function(o){let s;o.codec=()=>(s==null&&(s=Nt((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:"",value:ct(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(f&7);break}}}return l})),s),o.encode=i=>Mt(i,o.codec()),o.decode=(i,a)=>Rt(i,o.codec(),a)})(t=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let e;(function(o){let s;o.codec=()=>(s==null&&(s=Nt((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Ps.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=Ps.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return l})),s),o.encode=i=>Mt(i,o.codec()),o.decode=(i,a)=>Rt(i,o.codec(),a)})(e=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Nt((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Cs.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(Cs.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 Kn('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new Kn('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(u.key,u.value);break}case 8:{a.updated=o.uint64Number();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Mt(o,r.codec()),r.decode=(o,s)=>Rt(o,r.codec(),s)})(Ie||(Ie={}));var Cs;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.multiaddr!=null&&e.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(e.multiaddr)),e.isCertified!=null&&(n.uint32(16),n.bool(e.isCertified)),e.observed!=null&&(n.uint32(24),n.uint64Number(e.observed)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={multiaddr:ct(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.multiaddr=e.bytes();break}case 2:{s.isCertified=e.bool();break}case 3:{s.observed=e.uint64Number();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(Cs||(Cs={}));var Ps;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.value!=null&&e.value!==0&&(n.uint32(8),n.uint32(e.value)),e.expiry!=null&&(n.uint32(16),n.uint64(e.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={value:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.value=e.uint32();break}case 2:{s.expiry=e.uint64();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(Ps||(Ps={}));function G0(r,t){if(r.publicKey!=null||t.publicKey==null)return r;let e;if(r.type==="RSA"){let o=G.decode(`z${r}`);e=Vt(o)}let n=jr(t.publicKey,e);return Dc(n)}function Ts(r,t,e){let n=Ie.decode(t);return Ls(r,n,e)}function Ls(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:G0(r,t),addresses:t.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-e).map(({multiaddr:s,isCertified:i})=>({multiaddr:j(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}function nh(r,t){return W0(r.addresses,t.addresses)&&j0(r.protocols,t.protocols)&&X0(r.publicKey,t.publicKey)&&Y0(r.peerRecordEnvelope,t.peerRecordEnvelope)&&Z0(r.metadata,t.metadata)&&Q0(r.tags,t.tags)}function W0(r,t){return sh(r,t,(e,n)=>!(e.isCertified!==n.isCertified||!tt(e.multiaddr,n.multiaddr)))}function j0(r,t){return sh(r,t,(e,n)=>e===n)}function X0(r,t){return oh(r,t)}function Y0(r,t){return oh(r,t)}function Z0(r,t){return ih(r,t,(e,n)=>tt(e,n))}function Q0(r,t){return ih(r,t,(e,n)=>e.value===n.value&&e.expiry===n.expiry)}function oh(r,t){return r==null&&t==null?!0:r!=null&&t!=null?tt(r,t):!1}function sh(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 ih(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 Ce="/",ah=new TextEncoder().encode(Ce),Ds=ah[0],yr=class r{_buf;constructor(t,e){if(typeof t=="string")this._buf=L(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]!==Ds)throw new Error("Invalid key")}toString(t="utf8"){return B(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(Ce))}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=ah),this._buf[0]!==Ds){let t=new Uint8Array(this._buf.byteLength+1);t.fill(Ds,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ds;)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(Ce).slice(1)}type(){return J0(this.baseNamespace())}name(){return ty(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(Ce)||(t+=Ce),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(Ce):new r(t.slice(0,-1).join(Ce))}child(t){return this.toString()===Ce?t:t.toString()===Ce?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(),...ey(t.map(e=>e.namespaces()))])}};function J0(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function ty(r){let t=r.split(":");return t[t.length-1]}function ey(r){return[].concat(...r)}var wl="/peers/";function co(r){if(!Le(r)||r.type==null)throw new R("Invalid PeerId");let t=r.toCID().toString();return new yr(`${wl}${t}`)}async function ch(r,t,e,n,o){let s=new Map;for(let i of e){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=j(i.multiaddr)),!ze(i.multiaddr))throw new R("Multiaddr was invalid");if(!await t(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=s.get(c);l!=null?i.isCertified=l.isCertified||a:s.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...s.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getPeerId();return r.equals(c)&&(a=a.decapsulate(j(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function Rs(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=ks(d,{validate:lh})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);c=ks(d,{validate:uh,map:fh})}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[g,h]of d)h==null?a.delete(g):a.set(g,h);a=ks([...a.entries()],{validate:lh})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),g=new Map(c);for(let[h,m]of d)m==null?g.delete(h):g.set(h,m);c=ks([...g.entries()],{validate:uh,map:fh})}t.peerRecordEnvelope!=null&&(l=t.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=Wt(o.id.publicKey):t.publicKey!=null?u=Wt(t.publicKey):r.publicKey!=null&&(u=Wt(r.publicKey));let f={addresses:await ch(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((d,g)=>d.localeCompare(g)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(g=>tt(g.multiaddr,g.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function ks(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 lh(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 uh(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 fh(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 dh(r){let t=r.toString().split("/")[2],e=it.parse(t,zt);return Zn(e)}function xl(r,t,e){let n=dh(r);return Ts(n,t,e)}function ry(r,t){return{prefix:wl,filters:(r.filters??[]).map(e=>({key:n,value:o})=>e(xl(n,o,t))),orders:(r.orders??[]).map(e=>(n,o)=>e(xl(n.key,n.value,t),xl(o.key,o.value,t)))}}var Ms=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=bl({name:"peer-store",singleProcess:!0}),this.maxAddressAge=e.maxAddressAge??36e5,this.maxPeerAge=e.maxPeerAge??216e5}async has(t,e){try{return await this.load(t,e),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(t,e){this.peerId.equals(t)||await this.datastore.delete(co(t),e)}async load(t,e){let n=co(t),o=await this.datastore.get(n,e),s=Ie.decode(o);if(this.#r(t,s))throw await this.datastore.delete(n,e),new We;return Ls(t,s,this.peerId.equals(t)?1/0:this.maxAddressAge)}async save(t,e,n){let o=await this.#t(t,n),s=await Rs(t,e,"patch",{...n,addressFilter:this.addressFilter});return this.#e(t,s,o)}async patch(t,e,n){let o=await this.#t(t,n),s=await Rs(t,e,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#e(t,s,o)}async merge(t,e,n){let o=await this.#t(t,n),s=await Rs(t,e,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#e(t,s,o)}async*all(t){for await(let{key:e,value:n}of this.datastore.query(ry(t??{},this.maxAddressAge),t)){let o=dh(e);if(o.equals(this.peerId))continue;let s=Ie.decode(n);if(this.#r(o,s)){await this.datastore.delete(e,t);continue}yield Ls(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#t(t,e){try{let n=co(t),o=await this.datastore.get(n,e),s=Ie.decode(o);if(this.#r(t,s))throw await this.datastore.delete(n,e),new We;return{peerPB:s,peer:Ts(t,o,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#e(t,e,n,o){e.updated=Date.now();let s=Ie.encode(e);return await this.datastore.put(co(t),s,o),{peer:Ts(t,s,this.maxAddressAge),previous:n?.peer,updated:n==null||!nh(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 El=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 Ms(t,e)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(t,e){let n=await this.store.lock.readLock(e);try{for await(let o of this.store.all(e))t(o)}finally{n()}}async all(t){let e=await this.store.lock.readLock(t);try{return await ao(this.store.all(t))}finally{e()}}async delete(t,e){let n=await this.store.lock.writeLock(e);try{await this.store.delete(t,e)}finally{n()}}async has(t,e){let n=await this.store.lock.readLock(e);try{return await this.store.has(t,e)}finally{this.log.trace("has release read lock"),n()}}async get(t,e){let n=await this.store.lock.readLock(e);try{return await this.store.load(t,e)}finally{n()}}async getInfo(t,e){let n=await this.get(t,e);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(t,e,n){let o=await this.store.lock.writeLock(n);try{let s=await this.store.save(t,e,n);return this.#t(t,s),s.peer}finally{o()}}async patch(t,e,n){let o=await this.store.lock.writeLock(n);try{let s=await this.store.patch(t,e,n);return this.#t(t,s),s.peer}finally{o()}}async merge(t,e,n){let o=await this.store.lock.writeLock(n);try{let s=await this.store.merge(t,e,n);return this.#t(t,s),s.peer}finally{o()}}async consumePeerRecord(t,e,n){let o=Le(e)?e:Le(e?.expectedPeer)?e.expectedPeer:void 0,s=Le(e)||e===void 0?n:e,i=await on.openAndCertify(t,mr.DOMAIN,s),a=Zn(i.publicKey.toCID());if(o?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",o,a),!1;let c=mr.createFromProtobuf(i.payload),l;try{l=await this.get(a,s)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=on.createFromProtobuf(l.peerRecordEnvelope),f=mr.createFromProtobuf(u.payload);if(f.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:t,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},s),!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 hh(r,t={}){return new El(r,t)}var Ns=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 ny(r){return r[Symbol.asyncIterator]!=null}function oy(r){if(ny(r))return(async()=>{for await(let t of r);})();for(let t of r);}var vl=oy;function sy(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 ph=sy;function iy(r){return r[Symbol.asyncIterator]!=null}function ay(r,t){let e=0;if(iy(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=ph(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 br=ay;function cy(r){return r[Symbol.asyncIterator]!=null}function ly(r,t){return cy(r)?async function*(){yield*(await ao(r)).sort(t)}():function*(){yield*ao(r).sort(t)}()}var Sl=ly;function uy(r){return r[Symbol.asyncIterator]!=null}function fy(r,t){return uy(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 Al=fy;var Os=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 vl(this.putMany(t,n)),t=[],await vl(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=br(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>br(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>Sl(o,s),n)),t.offset!=null){let o=0,s=t.offset;n=br(n,()=>o++>=s)}return t.limit!=null&&(n=Al(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=br(n,s=>s.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>br(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>Sl(o,s),n)),t.offset!=null){let o=t.offset,s=0;n=br(n,()=>s++>=o)}return t.limit!=null&&(n=Al(n,t.limit)),n}};var Bs=class extends Os{data;constructor(){super(),this.data=new Map}put(t,e,n){return n?.signal?.throwIfAborted(),this.data.set(t.toString(),e),t}get(t,e){e?.signal?.throwIfAborted();let n=this.data.get(t.toString());if(n==null)throw new Ns;return n}has(t,e){return e?.signal?.throwIfAborted(),this.data.has(t.toString())}delete(t,e){e?.signal?.throwIfAborted(),this.data.delete(t.toString())}*_all(t,e){e?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new yr(n),value:o},e?.signal?.throwIfAborted()}*_allKeys(t,e){e?.signal?.throwIfAborted();for(let n of this.data.keys())yield new yr(n),e?.signal?.throwIfAborted()}};function lo(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=Io(mh(),1),dy=["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"],hy=dy.map(r=>new gh.Netmask(r));function _l(r){for(let t of hy)if(t.contains(r))return!0;return!1}function py(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function my(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 _l(o)}function gy(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function yy(r){let t=r.split(":"),e=t[t.length-1];return _l(e)}function by(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 He(r){return se(r)?_l(r):py(r)?my(r):gy(r)?yy(r):en(r)?by(r):void 0}var wy=r=>r.toString().split("/").slice(1),cn=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),z=r=>({match:t=>cn(e=>e===r).match(t),pattern:r}),wr=()=>({match:r=>cn(t=>typeof t=="string").match(r),pattern:"{string}"}),ln=()=>({match:r=>cn(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),et=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{G.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),fo=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{ha.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Z=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Pt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),H=(...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 st(...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 xy=et(),yh=st(xy),Us=H(z("dns4"),wr()),Ks=H(z("dns6"),wr()),qs=H(z("dnsaddr"),wr()),Cl=H(z("dns"),wr()),$6=st(Us,Z(et())),G6=st(Ks,Z(et())),W6=st(qs,Z(et())),j6=st(Pt(Cl,qs,Us,Ks),Z(et())),bh=H(z("ip4"),cn(se)),wh=H(z("ip6"),cn(en)),Pl=Pt(bh,wh),Pe=Pt(Pl,Cl,Us,Ks,qs),X6=st(Pt(Pl,H(Pt(Cl,qs,Us,Ks),Z(et())))),Tl=st(bh),Ll=st(wh),Y6=st(Pl),Dl=H(Pe,z("tcp"),ln()),ho=H(Pe,z("udp"),ln()),po=st(H(Dl,Z(et()))),Z6=st(ho),kl=H(ho,z("quic"),Z(et())),zs=H(ho,z("quic-v1"),Z(et())),Ey=Pt(kl,zs),Q6=st(kl),xh=st(zs),Il=Pt(Pe,Dl,ho,kl,zs),Eh=Pt(H(Il,z("ws"),Z(et()))),xr=st(Eh),vh=Pt(H(Il,z("wss"),Z(et())),H(Il,z("tls"),Z(H(z("sni"),wr())),z("ws"),Z(et()))),mo=st(vh),Sh=H(ho,z("webrtc-direct"),Z(fo()),Z(fo()),Z(et())),Rl=st(Sh),Ah=H(zs,z("webtransport"),Z(fo()),Z(fo()),Z(et())),Ml=st(Ah),Fs=Pt(Eh,vh,H(Dl,Z(et())),H(Ey,Z(et())),H(Pe,Z(et())),Sh,Ah,et()),J6=st(Fs),vy=H(Fs,z("p2p-circuit"),et()),go=st(vy),Sy=Pt(H(Fs,z("p2p-circuit"),z("webrtc"),Z(et())),H(Fs,z("webrtc"),Z(et())),H(z("webrtc"),Z(et()))),Nl=st(Sy),Ay=Pt(H(Pe,z("tcp"),ln(),z("http"),Z(et())),H(Pe,z("http"),Z(et()))),t4=st(Ay),_y=Pt(H(Pe,z("tcp"),Pt(H(z("443"),z("http")),H(ln(),z("https")),H(ln(),z("tls"),z("http"))),Z(et())),H(Pe,z("tls"),z("http"),Z(et())),H(Pe,z("https"),Z(et()))),e4=st(_y),Iy=Pt(H(z("memory"),wr(),Z(et()))),r4=st(Iy);var _h=864e13;var Cy=448,Ol=449,Py=53,Ty=54,Ly=55,Dy=56,Vs=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=He(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:j(`/${s.map(u=>[W(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]===Cy&&t[n+1]?.[0]!==Ol)return t.splice(n+1,0,[Ol,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]===Ol||e[0]===Py||e[0]===Ty||e[0]===Ly||e[0]===Dy)return e[1]}};var Bl=4,Fl=41,Ul=6,ky=273,Hs=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:se(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]===Ul?"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]===Bl||o[0][0]===Fl)&&o[1][0]===Ul?s=`${o[0][1]}-${o[1][1]}-tcp`:(o[0][0]===Bl||o[0][0]===Fl)&&o[1][0]===ky&&(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?Bl:Fl,o[0][1]=a.externalIp,o[1][1]=`${a.externalPort}`,e.push({multiaddr:j(`/${o.map(c=>[W(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]===Ul?"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 $s(r){try{let[[t]]=r.stringTuples();return t===4||t===41}catch{}return!1}function Er(r){try{if(!$s(r))return!1;let[[,t]]=r.stringTuples();return t==null?!1:He(t)??!1}catch{}return!0}var Ry={maxObservedAddresses:10},Gs=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}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:j(t),verified:e.verified,type:"observed",expires:e.expires,lastVerified:e.lastVerified}))}remove(t){let e=this.addresses.get(t.toString())?.verified??!1;return this.log("removing observed address %a",t),this.addresses.delete(t.toString()),e}confirm(t,e){let n=t.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+e,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+e,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var My=[4,41,53,54,55,56];function Kl(r){try{let[[t]]=r.stringTuples();return My.includes(t)}catch{}return!1}var Ny={maxObservedAddresses:10},Ws=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??Ny.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:!Kl(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(Kl(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},Oy=r=>r;function ql(r,t){let e=r.getPeerId();return e!=null&&de(e).equals(t)&&(r=r.decapsulate(j(`/p2p/${t.toString()}`))),r}var js=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 Gs(t,e),this.dnsMappings=new Vs(t,e),this.ipMappings=new Hs(t,e),this.transportAddresses=new Ws(t,e),this.announceFilter=e.announceFilter??Oy,this.observedAddressFilter=oo(1024),this.addressVerificationTTL=e.addressVerificationTTL??Ph.addressVerificationTTL,this.addressVerificationRetry=e.addressVerificationRetry??Ph.addressVerificationRetry,this._updatePeerStoreAddresses=lo(this._updatePeerStoreAddresses.bind(this),1e3),t.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),t.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let t=this.getAddresses().map(e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate(`/p2p/${this.components.peerId.toString()}`):e);this.components.peerStore.patch(this.components.peerId,{multiaddrs:t}).catch(e=>{this.log.error("error updating addresses",e)})}getListenAddrs(){return Array.from(this.listen).map(t=>j(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>j(t))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(t=>j(t))}getObservedAddrs(){return this.observed.getAll().map(t=>t.multiaddr)}addObservedAddr(t){let e=t.stringTuples(),n=`${e[0][1]}:${e[1][1]}`;this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),t=ql(t,this.components.peerId),!this.ipMappings.has(t)&&(this.dnsMappings.has(t)||this.observed.add(t)))}confirmObservedAddr(t,e){t=ql(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=ql(t,this.components.peerId);let n=!1;this.observed.has(t)&&!this.observed.remove(t)&&n&&(n=!1),this.transportAddresses.has(t)&&!this.transportAddresses.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(t)&&!this.dnsMappings.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(t)&&!this.ipMappings.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let t=new Set,e=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return t.has(o)?!1:(t.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(e.map(n=>{let o=j(n);return o.protos().pop()?.path===!0||o.getPeerId()===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let t=this.getAnnounceAddrs();if(t.length>0)return this.components.transportManager.getListeners().forEach(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(j(`/dns/${t}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.add(t,e,n,o,s),this.observed.removePrefixed(`/ip${se(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.remove(j(`/ip${se(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"||He(e.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>xr.exactMatch(s)||mo.exactMatch(s),s=>po.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 Xs=class extends Error{constructor(t="Missing service"){super(t),this.name="MissingServiceError"}},Ys=class extends Error{constructor(t="Unmet service dependencies"){super(t),this.name="UnmetServiceDependenciesError"}},un=class extends Error{constructor(t="No content routers available"){super(t),this.name="NoContentRoutersError"}},yo=class extends Error{constructor(t="No peer routers available"){super(t),this.name="NoPeerRoutersError"}},Zs=class extends Error{constructor(t="Should not try to find self"){super(t),this.name="QueriedForSelfError"}},Qs=class extends Error{constructor(t="Unhandled protocol error"){super(t),this.name="UnhandledProtocolError"}},Js=class extends Error{constructor(t="Duplicate protocol handler error"){super(t),this.name="DuplicateProtocolHandlerError"}},bo=class extends Error{constructor(t="Dial denied error"){super(t),this.name="DialDeniedError"}},ti=class extends Error{constructor(t="No transport was configured to listen on this address"){super(t),this.name="UnsupportedListenAddressError"}},ei=class extends Error{constructor(t="Configured listen addresses could not be listened on"){super(t),this.name="UnsupportedListenAddressesError"}},ri=class extends Error{constructor(t="No valid addresses"){super(t),this.name="NoValidAddressesError"}},ni=class extends Error{constructor(t="Connection intercepted"){super(t),this.name="ConnectionInterceptedError"}},oi=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"}},si=class extends Error{constructor(t="Transport unavailable"){super(t),this.name="TransportUnavailableError"}};var zl=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=Ss())}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(e=>No(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")}},Fy=["metrics","connectionProtector","dns"],Uy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Lh(r={}){let t=new zl(r);return new Proxy(t,{get(n,o,s){if(typeof o=="string"&&!Uy.includes(o)){let i=t.components[o];if(i==null&&!Fy.includes(o))throw new Xs(`${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 Ky(e))t[n]=!0;for(let e of Object.values(r.components))for(let n of qy(e))if(t[n]!==!0)throw new Ys(`Service "${zy(e)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Ky(r){return Array.isArray(r?.[xn])?r[xn]:[]}function qy(r){return Array.isArray(r?.[Zi])?r[Zi]:[]}function zy(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var Vy=4,Hy=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]===Vy||e[0][0]===Hy?!!He(`${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 Rh=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},$y=new WeakMap;function Gy({clearTimeout:r,setTimeout:t}={}){return(e,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Rh());let s,i,a,c=r??clearTimeout,l=()=>{c(s),a(Rh())},u=()=>{o&&o.removeEventListener("abort",l)},f=new Promise((d,g)=>{i=()=>{u(),d(n)},a=g,s=(t??setTimeout)(i,e)});return o&&o.addEventListener("abort",l,{once:!0}),$y.set(f,()=>{c(s),s=null,i()}),f}}var Wy=Gy(),Mh=Wy;var ii=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}},ai=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var ci=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(t={}){this.points=t.points??4,this.duration=t.duration??1,this.blockDuration=t.blockDuration??0,this.execEvenly=t.execEvenly??!1,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=t.keyPrefix??"rlflx",this.memoryStorage=new Vl}async consume(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+e&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new ii("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 Mh(a)}return i}penalty(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(t,e){let n=e*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(t),o,e),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(t,e,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(t),e,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:e,isFirstInDuration:!1}}get(t){let e=this.memoryStorage.get(this.getKey(t));return e!=null&&(e.remainingPoints=Math.max(this.points-e.consumedPoints,0)),e}delete(t){this.memoryStorage.delete(this.getKey(t))}_getKeySecDuration(t){return t?.customDuration!=null&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return t.substring(this.keyPrefix.length)}},Vl=class{storage;constructor(){this.storage=new Map}incrby(t,e,n){let o=this.storage.get(t);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=e,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(t,e,n)}return this.set(t,e,n)}set(t,e,n){let o=n*1e3,s=this.storage.get(t);s!=null&&clearTimeout(s.timeoutId);let i={value:e,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(t,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(t)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(t){let e=this.storage.get(t);if(e!=null)return{remainingPoints:0,msBeforeNext:e.expiresAt!=null?e.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:e.value,isFirstInDuration:!1}}delete(t){let e=this.storage.get(t);return e!=null?(e.timeoutId!=null&&clearTimeout(e.timeoutId),this.storage.delete(t),!0):!1}};function li(r){if(Le(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:de(n),t.forEach(o=>{if(!ze(o))throw new De("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=de(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 jy=["/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??jy;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 ui=100,fi=50;async function Fh(r,t){let e=!1;for(let o of nn.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 wo(r){try{let t;if(typeof r=="string"?t=j(r):t=r,!t.protoNames().includes("ipcidr")){let n=t.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(n)}return Zc(t)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var Xy={maxConnections:ui,allow:[]},di=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(t,e={}){this.maxConnections=e.maxConnections??Xy.maxConnections,this.allow=(e.allow??[]).map(n=>wo(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 _e;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 lt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var hi=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}},fn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new hi(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 hi(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 Hl=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 Yy(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 Yy(r,t){t=t??{};let e=t.onEnd,n=new fn,o,s,i,a=lt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((b,v)=>{s=C=>{s=null,n.push(C);try{b(r(n))}catch(x){v(x)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=lt()})}},l=b=>s!=null?s(b):(n.push(b),o),u=b=>(n=new fn,s!=null?s({error:b}):(n.push({error:b}),o)),f=b=>{if(i)return o;if(t?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:b})},d=b=>i?o:(i=!0,b!=null?u(b):l({done:!0})),g=()=>(n=new fn,d(),{done:!0}),h=b=>(d(b),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:g,throw:h,push:f,end:d,get readableLength(){return n.size},onEmpty:async b=>{let v=b?.signal;if(v?.throwIfAborted(),n.isEmpty())return;let C,x;v!=null&&(C=new Promise((p,w)=>{x=()=>{w(new Hl)},v.addEventListener("abort",x)}));try{await Promise.race([a.promise,C])}finally{x!=null&&v!=null&&v?.removeEventListener("abort",x)}}},e==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(b){return m.throw(b),e!=null&&(e(b),e=void 0),{done:!0}},return(){return m.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(b){return m.end(b),e!=null&&(e(b),e=void 0),o},get readableLength(){return m.readableLength},onEmpty:b=>m.onEmpty(b)},o}var $l=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 dn(r,t,e,n){let o=new $l(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 pi=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function Bt(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new pi(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new pi(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 mi=class{deferred;signal;constructor(t){this.signal=t,this.deferred=lt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Zt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Zy(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var gi=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 Zt),this.cleanup())}async join(t={}){let e=new mi(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await Bt(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var pn=class extends pe{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=[],this.emitEmpty=lo(this.emitEmpty.bind(this),1),this.emitIdle=lo(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!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 ai;let n=new gi(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 Zt)}),this.clear()}async onEmpty(t){this.size!==0&&await dn(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await dn(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await dn(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 Zt("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 yi=class extends pn{constructor(t={}){super({...t,sort:(e,n)=>e.options.priority>n.options.priority?-1:e.options.priority<n.options.priority?1:0})}};function Te(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 Gl(r){if(!$s(r))return!1;let{address:t}=r.nodeAddress();return Kh(t)}function Qy(r,t){let e=po.exactMatch(r.multiaddr),n=po.exactMatch(t.multiaddr);if(e&&!n)return-1;if(!e&&n)return 1;let o=mo.exactMatch(r.multiaddr),s=mo.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=Nl.exactMatch(r.multiaddr),l=Nl.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=Rl.exactMatch(r.multiaddr),f=Rl.exactMatch(t.multiaddr);if(u&&!f)return-1;if(!u&&f)return 1;let d=Ml.exactMatch(r.multiaddr),g=Ml.exactMatch(t.multiaddr);return d&&!g?-1:!d&&g?1:0}function Jy(r,t){let e=Gl(r.multiaddr),n=Gl(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function tb(r,t){let e=Er(r.multiaddr),n=Er(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function eb(r,t){return r.isCertified&&!t.isCertified?-1:!r.isCertified&&t.isCertified?1:0}function rb(r,t){let e=go.exactMatch(r.multiaddr),n=go.exactMatch(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function qh(r){return r.sort(Qy).sort(eb).sort(rb).sort(tb).sort(Jy)}var bi={maxParallelDials:fi,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:ur}},wi=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(t,e={}){this.addressSorter=e.addressSorter,this.maxPeerAddrsToDial=e.maxPeerAddrsToDial??bi.maxPeerAddrsToDial,this.maxDialQueueLength=e.maxDialQueueLength??bi.maxDialQueueLength,this.dialTimeout=e.dialTimeout??bi.dialTimeout,this.connections=e.connections??new _e,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??{}))nn.set(n,o);this.queue=new yi({concurrency:e.maxParallelDials??bi.maxParallelDials,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("error",n=>{n.detail?.name!==Zt.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}=li(t),s=Array.from(this.connections.values()).flat().find(a=>e.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s?.status==="open")return this.log("already connected to %a",s.remoteAddr),e.onProgress?.(new dt("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of o)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return e.onProgress?.(new dt("dial-queue:already-in-dial-queue")),i.join(e)}if(this.queue.size>=this.maxDialQueueLength)throw new Dr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),e.onProgress?.(new dt("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new dt("dial-queue:start-dial"));let c=Te([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:n,priority:e.priority??Yl,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 g of d){if(s.has(g.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",g.multiaddr,n);continue}u.push(g)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(g=>g.multiaddr.toString())),t?.onProgress?.(new dt("dial-queue:calculated-addresses",u));for(let g of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,t.peerId),new Dr("Peer had more than maxPeerAddrsToDial");a++;try{let h=await this.components.transportManager.dial(g.multiaddr,{...t,signal:e});this.log("dial to %a succeeded",g.multiaddr);try{await this.components.peerStore.merge(h.remotePeer,{multiaddrs:[h.remoteAddr],metadata:{[Bh]:L(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p",n,m)}return h}catch(h){if(this.log.error("dial failed to %a",g.multiaddr,h),s.add(g.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[Oh]:L(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p",n,m)}if(e.aborted)throw new ko(h.message);l.push(h)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(t,e=new Set,n={}){let o=[...e].map(f=>({multiaddr:j(f),isCertified:!1}));if(t!=null){if(this.components.peerId.equals(t))throw new Dr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(t)===!0)throw new bo("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(g=>({multiaddr:g,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(),g=a.get(d);if(g!=null){g.isCertified=g.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new ri("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 bo("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=>!go.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var xi=class extends pn{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var jh=Io(Gh(),1);var ob=Object.prototype.toString,sb=r=>ob.call(r)==="[object Error]",ib=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 Zl(r){return r&&sb(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:ib.has(r.message):!1}var Ql=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}},Wh=(r,t,e)=>{let n=e.retries-(t-1);return r.attemptNumber=t,r.retriesLeft=n,r};async function Jl(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 Ql)throw c.originalError;if(c instanceof TypeError&&!Zl(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 Ei=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 xi({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 Jl(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(Yi)&&(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(Yi))return!0;return!1}var Yl=50,tu={maxConnections:ui,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},vi=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??tu.maxConnections,this.maxConnections<1)throw new R("Connection Manager maxConnections must be greater than 0");this.connections=new _e,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=>wo(n)),this.deny=(e.deny??[]).map(n=>wo(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=e.maxIncomingPendingConnections??tu.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new ci({points:e.inboundConnectionThreshold??tu.inboundConnectionThreshold,duration:1}),this.connectionPruner=new di({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{maxConnections:this.maxConnections,allow:e.allow?.map(n=>j(n))}),this.dialQueue=new wi(t,{addressSorter:e.addressSorter,maxParallelDials:e.maxParallelDials??fi,maxDialQueueLength:e.maxDialQueueLength??500,maxPeerAddrsToDial:e.maxPeerAddrsToDial??25,dialTimeout:e.dialTimeout??1e4,resolvers:e.resolvers??{dnsaddr:ur},connections:this.connections}),this.reconnectQueue=new Ei({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 hu(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 pu(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 he("Not started");this.outboundPendingConnections++;try{e.signal?.throwIfAborted();let{peerId:n}=li(t);if(this.peerId.equals(n))throw new Lr("Can not dial self");if(n!=null&&e.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),e.onProgress?.(new dt("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(t,{...e,priority:e.priority??Yl});if(o.status!=="open")throw new Tr("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 De("Duplicate multiaddr connection")),a;return i||s.push(o),o}finally{this.outboundPendingConnections--}}async closeConnections(t,e={}){let n=this.connections.get(t)??[];await Promise.all(n.map(async o=>{try{await o.close(e)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(t){if(this.deny.some(o=>o.contains(t.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",t.remoteAddr),!1;if(this.allow.some(o=>o.contains(t.remoteAddr.nodeAddress().address)))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",t.remoteAddr),!1;if(t.remoteAddr.isThinWaistAddress()){let o=t.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",t.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",t.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let t={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(e=>({id:e.id,status:t[e.status],peerId:e.options.peerId,multiaddrs:[...e.options.multiaddrs].map(n=>j(n))}))}async isDialable(t,e={}){return this.dialQueue.isDialable(t,e)}};var mn=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 lb=1.2,ub=2,fb=5e3,Si=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(t={}){this.success=new mn(t.interval??5e3),this.failure=new mn(t.interval??5e3),this.next=new mn(t.interval??5e3),this.failureMultiplier=t.failureMultiplier??ub,this.timeoutMultiplier=t.timeoutMultiplier??lb,this.minTimeout=t.minTimeout??fb,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=Te([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 eu=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=lt(),this.haveNext=lt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=lt(),t}async throw(t){return this.ended=!0,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=lt(),await Bt(this.readNext.promise,e?.signal,e)}};function Ai(){return new eu}var _i=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Ii(r,t){let e=Ai();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 Y;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:l}=await Bt(n.next(),i?.signal);return c===!0?null:l}for(;o.byteLength<i.bytes;){let{value:c,done:l}=await Bt(n.next(),i?.signal);if(l===!0)throw new _i("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 db=1e4,hb="1.0.0",pb="ping",mb="ipfs",Yh=32,gb=!0,Ci=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(t,e={}){this.components=t,this.protocol=`/${e.protocolPrefix??mb}/${pb}/${hb}`,this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=e.pingInterval??db,this.abortConnectionOnPingFailure=e.abortConnectionOnPingFailure??gb,this.timeout=new Si({...e.pingTimeout??{},metrics:t.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[xn]=["@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=Ii(o);e=Date.now(),await Promise.all([s.write(Gr(Yh),{signal:n}),s.read({bytes:Yh,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 yb(r){return r[Symbol.asyncIterator]!=null}async function bb(r,t,e){try{await Promise.all(r.map(async n=>{for await(let o of n)await t.push(o,{signal:e}),e.throwIfAborted()})),await t.end(void 0,{signal:e})}catch(n){await t.end(n,{signal:e}).catch(()=>{})}}async function*wb(r){let t=new AbortController,e=Ai();bb(r,e,t.signal).catch(()=>{});try{yield*e}finally{t.abort()}}function*xb(r){for(let t of r)yield*t}function Eb(...r){let t=[];for(let e of r)yb(e)||t.push(e);return t.length===r.length?xb(t):wb(r)}var xo=Eb;var Pi=class{routers;started;components;constructor(t,e){this.routers=e.routers??[],this.started=!1,this.components=t,this.findProviders=t.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=t.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=t.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=t.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:B(n,"base36")})})??this.put,this.get=t.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:B(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(t,e={}){if(this.routers.length===0)throw new un("No content routers available");let n=this,o=new dr;for await(let s of xo(...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},e),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(t,e={}){if(this.routers.length===0)throw new un("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 un("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 he;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 he;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(t,e)))}};var Ti=globalThis.CustomEvent??Event;async function*ru(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered??!1,o=new EventTarget,s=[],i=lt(),a=lt(),c=!1,l,u=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let h of r){if(s.length===e&&(i=lt(),await i.promise),u)break;let m={done:!1};s.push(m),h().then(b=>{m.done=!0,m.ok=!0,m.value=b,o.dispatchEvent(new Ti("task-complete"))},b=>{m.done=!0,m.err=b,o.dispatchEvent(new Ti("task-complete"))})}c=!0,o.dispatchEvent(new Ti("task-complete"))}catch(h){l=h,o.dispatchEvent(new Ti("task-complete"))}});function f(){return n?s[0]?.done:!!s.find(h=>h.done)}function*d(){for(;s.length>0&&s[0].done;){let h=s[0];if(s.shift(),h.ok)yield h.value;else throw u=!0,i.resolve(),h.err;i.resolve()}}function*g(){for(;f();)for(let h=0;h<s.length;h++)if(s[h].done){let m=s[h];if(s.splice(h,1),h--,m.ok)yield m.value;else throw u=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(f()||(a=lt(),await a.promise),l!=null||(n?yield*d():yield*g(),l!=null))throw l;if(c&&s.length===0)break}}var Li=class{log;peerId;peerStore;routers;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-routing"),this.peerId=t.peerId,this.peerStore=t.peerStore,this.routers=e.routers??[],this.findPeer=t.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=t.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:B(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(t,e){if(this.routers.length===0)throw new yo("No peer routers available");if(t.toString()===this.peerId.toString())throw new Zs("Should not try to find self");let n=this,o=xo(...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},e),s;throw new We}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new yo("No peer routers available");let n=this,o=oo(1024);for await(let s of ru(async function*(){let i=xo(...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},e),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var Di=class extends pe{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=Te([this.shutdownController.signal,t?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=lt(),yield(await dn(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=Te([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=Gr(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:t}))t.aborted&&this.log("aborting walk"),t.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Bt(this.needNext.promise,t)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-e),this.walking=!1})}};var nu=32,ou=64,ki=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 Qs(`No handler registered for protocol ${t}`);return e}getTopologies(t){let e=this.topologies.get(t);return e==null?[]:[...e.values()]}async handle(t,e,n){if(this.handlers.has(t)&&n?.force!==!0)throw new Js(`Handler already registered for protocol ${t}`);let o=cs.bind({ignoreUndefined:!0})({maxInboundStreams:nu,maxOutboundStreams:ou},n);this.handlers.set(t,{handler:e,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[t]},n)}async unhandle(t,e){(Array.isArray(t)?t:[t]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},e)}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,n={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(e,n).then(o=>{for(let s of o.protocols){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(e)!==!1&&(a.filter?.remove(e),a.onDisconnect?.(e))}}).catch(o=>{o.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",e,o)})}_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 su=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Zh(r){let{name:t,metrics:e}=r,n;return e!=null?n=new su({name:t,metrics:e}):n=new Map,n}var Ri=class{log;components;transports;listeners;faultTolerance;started;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:transports"),this.components=t,this.started=!1,this.transports=new Map,this.listeners=Zh({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=e.faultTolerance??Ge.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(t){let e=t[Symbol.toStringTag];if(e==null)throw new R("Transport must have a valid tag");if(this.transports.has(e))throw new R(`There is already a transport with the tag ${e}`);this.log("adding transport %s",e),this.transports.set(e,t),this.listeners.has(e)||this.listeners.set(e,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let t=this.components.addressManager.getListenAddrs();await this.listen(t)}async stop(){let t=[];for(let[e,n]of this.listeners)for(this.log("closing listeners for %s",e);n.length>0;){let o=n.pop();o!=null&&t.push(o.close())}await Promise.all(t),this.log("all listeners closed");for(let e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(t,e){let n=this.dialTransportForMultiaddr(t);if(n==null)throw new si(`No transport available for address ${String(t)}`);return e?.onProgress?.(new dt("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(t,{...e,upgrader:this.components.upgrader})}getAddrs(){let t=[];for(let e of this.listeners.values())for(let n of e)t=[...t,...n.getAddrs()];return t}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(t){for(let e of this.transports.values())if(e.dialFilter([t]).length>0)return e}listenTransportForMultiaddr(t){for(let e of this.transports.values())if(e.listenFilter([t]).length>0)return e}async listen(t){if(!this.isStarted())throw new he("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 ti)});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})}),Tl.matches(c)?e.ipv4.attempts++:Ll.matches(c)&&e.ipv6.attempts++,n.push(l.listen(c).then(()=>{e.errors.delete(c.toString()),Tl.matches(c)&&e.ipv4.success++,Ll.matches(c)&&e.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),e.errors.set(c.toString(),f),f}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(e)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===Ge.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new ei(`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 Ep=Object.create;var To=Object.defineProperty;var vp=Object.getOwnPropertyDescriptor;var Ap=Object.getOwnPropertyNames;var Sp=Object.getPrototypeOf,_p=Object.prototype.hasOwnProperty;var Cr=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Kt=(r,t)=>{for(var e in t)To(r,e,{get:t[e],enumerable:!0})},vu=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ap(t))!_p.call(r,o)&&o!==e&&To(r,o,{get:()=>t[o],enumerable:!(n=vp(t,o))||n.enumerable});return r};var Po=(r,t,e)=>(e=r!=null?Ep(Sp(r)):{},vu(t||!r||!r.__esModule?To(e,"default",{value:r,enumerable:!0}):e,r)),Ip=r=>vu(To({},"__esModule",{value:!0}),r);var kd=Cr((dv,Xc)=>{"use strict";var l0=Object.prototype.hasOwnProperty,Ft="~";function Qn(){}Object.create&&(Qn.prototype=Object.create(null),new Qn().__proto__||(Ft=!1));function u0(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function Rd(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new u0(e,n||r,o),i=Ft?Ft+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 fs(r,t){--r._eventsCount===0?r._events=new Qn:delete r._events[t]}function Tt(){this._events=new Qn,this._eventsCount=0}Tt.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)l0.call(e,n)&&t.push(Ft?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Tt.prototype.listeners=function(t){var e=Ft?Ft+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};Tt.prototype.listenerCount=function(t){var e=Ft?Ft+t:t,n=this._events[e];return n?n.fn?1:n.length:0};Tt.prototype.emit=function(t,e,n,o,s,i){var a=Ft?Ft+t:t;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,f;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,n),!0;case 4:return c.fn.call(c.context,e,n,o),!0;case 5:return c.fn.call(c.context,e,n,o,s),!0;case 6:return c.fn.call(c.context,e,n,o,s,i),!0}for(f=1,l=new Array(u-1);f<u;f++)l[f-1]=arguments[f];c.fn.apply(c.context,l)}else{var d=c.length,m;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(t,c[f].fn,void 0,!0),u){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,e);break;case 3:c[f].fn.call(c[f].context,e,n);break;case 4:c[f].fn.call(c[f].context,e,n,o);break;default:if(!l)for(m=1,l=new Array(u-1);m<u;m++)l[m-1]=arguments[m];c[f].fn.apply(c[f].context,l)}}return!0};Tt.prototype.on=function(t,e,n){return Rd(this,t,e,n,!1)};Tt.prototype.once=function(t,e,n){return Rd(this,t,e,n,!0)};Tt.prototype.removeListener=function(t,e,n,o){var s=Ft?Ft+t:t;if(!this._events[s])return this;if(!e)return fs(this,s),this;var i=this._events[s];if(i.fn)i.fn===e&&(!o||i.once)&&(!n||i.context===n)&&fs(this,s);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==e||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:fs(this,s)}return this};Tt.prototype.removeAllListeners=function(t){var e;return t?(e=Ft?Ft+t:t,this._events[e]&&fs(this,e)):(this._events=new Qn,this._eventsCount=0),this};Tt.prototype.off=Tt.prototype.removeListener;Tt.prototype.addListener=Tt.prototype.on;Tt.prefixed=Ft;Tt.EventEmitter=Tt;typeof Xc<"u"&&(Xc.exports=Tt)});var Fd=Cr((Ov,Bd)=>{Bd.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 Ph=Cr(po=>{(function(){var r,t,e,n,o,s,i,a;a=function(c){var u,l,f,d;return u=(c&255<<24)>>>24,l=(c&255<<16)>>>16,f=(c&65280)>>>8,d=c&255,[u,l,f,d].join(".")},i=function(c){var u,l,f,d,m,h;for(u=[],f=d=0;d<=3&&c.length!==0;f=++d){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}h=t(c),m=h[0],l=h[1],c=c.substring(l),u.push(m)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),s=e("a"),o=e("A"),t=function(c){var u,l,f,d,m;for(d=0,u=10,l="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,u=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,u=8,l="7")),m=f;f<c.length;){if("0"<=c[f]&&c[f]<=l)d=d*u+(e(c[f])-n)>>>0;else if(u===16)if("a"<=c[f]&&c[f]<="f")d=d*u+(10+e(c[f])-s)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*u+(10+e(c[f])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===m)throw new Error("empty octet");return[d,f]},r=function(){function c(u,l){var f,d,m,h;if(typeof u!="string")throw new Error("Missing `net' parameter");if(l||(h=u.split("/",2),u=h[0],l=h[1]),l||(l=32),typeof l=="string"&&l.indexOf(".")>-1){try{this.maskLong=i(l)}catch(g){throw f=g,new Error("Invalid mask: "+l)}for(d=m=32;m>=0;d=--m)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(l||l===0)this.bitmask=parseInt(l,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(g){throw f=g,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+l);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(i(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var l,f,d;for(d=i(this.first),f=i(this.last),l=0;d<=f;)u(a(d),d,l),l++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),po.ip2long=i,po.long2ip=a,po.Netmask=r}).call(po)});var rp=Cr((a3,ep)=>{function Zt(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))}ep.exports=Zt;Zt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Zt.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Zt.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};Zt.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)};Zt.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Zt.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Zt.prototype.start=Zt.prototype.try;Zt.prototype.errors=function(){return this._errors};Zt.prototype.attempts=function(){return this._attempts};Zt.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 np=Cr(Sr=>{var wb=rp();Sr.operation=function(r){var t=Sr.timeouts(r);return new wb(t,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Sr.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};Sr.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};Sr.wrap=function(r,t,e){if(t instanceof Array&&(e=t,t=null),!e){e=[];for(var n in r)typeof r[n]=="function"&&e.push(n)}for(var o=0;o<e.length;o++){var s=e[o],i=r[s];r[s]=function(c){var u=Sr.operation(t),l=Array.prototype.slice.call(arguments,1),f=l.pop();l.push(function(d){u.retry(d)||(d&&(arguments[0]=u.mainError()),f.apply(this,arguments))}),u.attempt(function(){c.apply(r,l)})}.bind(r,i),r[s].options=t}}});var sp=Cr((l3,op)=>{op.exports=np()});var Zb={};Kt(Zb,{createLibp2p:()=>Yb});var Au=Symbol.for("@libp2p/connection");var ua=Symbol.for("@libp2p/content-routing");var fa=Symbol.for("@libp2p/peer-discovery");var Lo=Symbol.for("@libp2p/peer-id");function ke(r){return!!r?.[Lo]}var da=Symbol.for("@libp2p/peer-routing");var ha="keep-alive";var sw=Symbol.for("@libp2p/transport");var We;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(We||(We={}));var Jt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var k=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Tr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}},yn=class extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}};var Do=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"}},Lr=class extends Error{static name="InvalidPeerIdError";constructor(t="Invalid PeerID"){super(t),this.name="InvalidPeerIdError"}},Me=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},Ro=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},ko=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},bn=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}},Mo=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var Oo=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},ye=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var Dr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}};var Rr=class extends Error{static name="LimitedConnectionError";constructor(t="Limited connection"){super(t),this.name="LimitedConnectionError"}},No=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(t="Too many inbound protocol streams"){super(t),this.name="TooManyInboundProtocolStreamsError"}},Bo=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(t="Too many outbound protocol streams"){super(t),this.name="TooManyOutboundProtocolStreamsError"}},Oe=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Ht=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 Fo(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Su(...r){let t=[];for(let e of r)Fo(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 _u(...r){let t=[];for(let e of r)Fo(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 wn=Symbol.for("@libp2p/service-capabilities"),pa=Symbol.for("@libp2p/service-dependencies");var wa={};Kt(wa,{base58btc:()=>j,base58flickr:()=>kp});var Dw=new Uint8Array(0);function Iu(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 be(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 Cu(r){return new TextEncoder().encode(r)}function Tu(r){return new TextDecoder().decode(r)}function Cp(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var g=0,b=0,v=0,C=h.length;v!==C&&h[v]===0;)v++,g++;for(var x=(C-v)*l+1>>>0,p=new Uint8Array(x);v!==C;){for(var w=h[v],T=0,P=x-1;(w!==0||T<b)&&P!==-1;P--,T++)w+=256*p[P]>>>0,p[P]=w%a>>>0,w=w/a>>>0;if(w!==0)throw new Error("Non-zero carry");b=T,v++}for(var D=x-b;D!==x&&p[D]===0;)D++;for(var F=c.repeat(g);D<x;++D)F+=r.charAt(p[D]);return F}function d(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var g=0;if(h[g]!==" "){for(var b=0,v=0;h[g]===c;)b++,g++;for(var C=(h.length-g)*u+1>>>0,x=new Uint8Array(C);h[g];){var p=e[h.charCodeAt(g)];if(p===255)return;for(var w=0,T=C-1;(p!==0||w<v)&&T!==-1;T--,w++)p+=a*x[T]>>>0,x[T]=p%256>>>0,p=p/256>>>0;if(p!==0)throw new Error("Non-zero carry");v=w,g++}if(h[g]!==" "){for(var P=C-v;P!==C&&x[P]===0;)P++;for(var D=new Uint8Array(b+(C-P)),F=b;P!==C;)D[F++]=x[P++];return D}}}function m(h){var g=d(h);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:m}}var Tp=Cp,Pp=Tp,Lu=Pp;var ma=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")}},ga=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 Du(this,t)}},ya=class{decoders;constructor(t){this.decoders=t}or(t){return Du(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 Du(r,t){return new ya({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ba=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 ma(t,e,n),this.decoder=new ga(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 ba(r,t,e,n)}function Ne({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Lu(e,r);return kr({prefix:t,name:r,encode:n,decode:s=>be(o(s))})}function Lp(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let l=t[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|l,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Dp(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 Rp(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function at({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=Rp(n);return kr({prefix:t,name:r,encode(s){return Dp(s,n,e)},decode(s){return Lp(s,o,e,r)}})}var j=Ne({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),kp=Ne({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var xa={};Kt(xa,{base32:()=>$t,base32hex:()=>Bp,base32hexpad:()=>Up,base32hexpadupper:()=>Kp,base32hexupper:()=>Fp,base32pad:()=>Op,base32padupper:()=>Np,base32upper:()=>Mp,base32z:()=>qp});var $t=at({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Mp=at({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Op=at({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Np=at({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Bp=at({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Fp=at({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Up=at({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Kp=at({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),qp=at({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ea={};Kt(Ea,{base36:()=>xn,base36upper:()=>zp});var xn=Ne({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),zp=Ne({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Vp=Mu,Ru=128,Hp=127,$p=~Hp,Wp=Math.pow(2,31);function Mu(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Wp;)t[e++]=r&255|Ru,r/=128;for(;r&$p;)t[e++]=r&255|Ru,r>>>=7;return t[e]=r|0,Mu.bytes=e-n+1,t}var Gp=va,jp=128,ku=127;function va(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw va.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&ku)<<o:(i&ku)*Math.pow(2,o),o+=7}while(i>=jp);return va.bytes=s-n,e}var Xp=Math.pow(2,7),Yp=Math.pow(2,14),Zp=Math.pow(2,21),Qp=Math.pow(2,28),Jp=Math.pow(2,35),tm=Math.pow(2,42),em=Math.pow(2,49),rm=Math.pow(2,56),nm=Math.pow(2,63),om=function(r){return r<Xp?1:r<Yp?2:r<Zp?3:r<Qp?4:r<Jp?5:r<tm?6:r<em?7:r<rm?8:r<nm?9:10},sm={encode:Vp,decode:Gp,encodingLength:om},im=sm,En=im;function vn(r,t=0){return[En.decode(r,t),En.decode.bytes]}function Mr(r,t,e=0){return En.encode(r,t,e),t}function Or(r){return En.encodingLength(r)}function te(r,t){let e=t.byteLength,n=Or(r),o=n+Or(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 ee(r){let t=be(r),[e,n]=vn(t),[o,s]=vn(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 Ou(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Iu(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 Nu(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return cm(e,Aa(r),t??j.encoder);default:return lm(e,Aa(r),t??$t.encoder)}}var Bu=new WeakMap;function Aa(r){let t=Bu.get(r);if(t==null){let e=new Map;return Bu.set(r,e),e}return t}var it=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!==An)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==um)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=te(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&&Ou(t.multihash,n.multihash)}toString(t){return Nu(this,t)}toJSON(){return{"/":Nu(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??Fu(n,o,s.bytes))}else if(e[fm]===!0){let{version:n,multihash:o,code:s}=e,i=ee(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!==An)throw new Error(`Version 0 CID must use dag-pb (code: ${An}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Fu(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,An,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=be(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]=vn(t.subarray(e));return e+=d,f},o=n(),s=An;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),u=e+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(t,e){let[n,o]=am(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 Aa(s).set(n,t),s}};function am(r,t){switch(r[0]){case"Q":{let e=t??j;return[j.prefix,e.decode(`${j.prefix}${r}`)]}case j.prefix:{let e=t??j;return[j.prefix,e.decode(r)]}case $t.prefix:{let e=t??$t;return[$t.prefix,e.decode(r)]}case xn.prefix:{let e=t??xn;return[xn.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 cm(r,t,e){let{prefix:n}=e;if(n!==j.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 lm(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 An=112,um=18;function Fu(r,t,e){let n=Or(r),o=n+Or(t),s=new Uint8Array(o+e.byteLength);return Mr(r,s,0),Mr(t,s,n),s.set(e,o),s}var fm=Symbol.for("@ipld/js-cid/CID");var Sa={};Kt(Sa,{identity:()=>re});var Uu=0,dm="identity",Ku=be;function hm(r){return te(Uu,Ku(r))}var re={code:Uu,name:dm,encode:Ku,digest:hm};function tt(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 ct(r=0){return new Uint8Array(r)}function St(r=0){return new Uint8Array(r)}function Dt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=St(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var zu=Symbol.for("@achingbrain/uint8arraylist");function qu(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 Ko(r){return!!r?.[zu]}var Y=class r{bufs;length;[zu]=!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(Ko(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(Ko(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=qu(this.bufs,t);return e.buf[e.index]}set(t,e){let n=qu(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(Ko(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Dt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Dt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let u=t>=a&&t<c,l=e>a&&e<=c;if(u&&l){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(l){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Ko(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=e;f<=c;f+=l){l=0;for(let d=u;d>=0;d--){let m=this.get(f+d);if(n[d]!==m){l=Math.max(1,d-a[m]);break}}if(l===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=St(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=ct(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=ct(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=ct(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=St(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=ct(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=ct(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=ct(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=ct(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=ct(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!tt(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 _a={};Kt(_a,{base10:()=>pm});var pm=Ne({prefix:"9",name:"base10",alphabet:"0123456789"});var Ia={};Kt(Ia,{base16:()=>mm,base16upper:()=>gm});var mm=at({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),gm=at({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ca={};Kt(Ca,{base2:()=>ym});var ym=at({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ta={};Kt(Ta,{base256emoji:()=>vm});var Vu=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}"),bm=Vu.reduce((r,t,e)=>(r[e]=t,r),[]),wm=Vu.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function xm(r){return r.reduce((t,e)=>(t+=bm[e],t),"")}function Em(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=wm[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var vm=kr({prefix:"\u{1F680}",name:"base256emoji",encode:xm,decode:Em});var Da={};Kt(Da,{base64:()=>Pa,base64pad:()=>Am,base64url:()=>La,base64urlpad:()=>Sm});var Pa=at({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Am=at({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),La=at({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Sm=at({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ra={};Kt(Ra,{base8:()=>_m});var _m=at({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ka={};Kt(ka,{identity:()=>Im});var Im=kr({prefix:"\0",name:"identity",encode:r=>Tu(r),decode:r=>Cu(r)});var px=new TextEncoder,mx=new TextDecoder;var Na={};Kt(Na,{sha256:()=>Br,sha512:()=>Pm});function Oa({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?te(this.code,e):e.then(n=>te(this.code,n))}else throw Error("Unknown type, must be binary type")}};function $u(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Br=Oa({name:"sha2-256",code:18,encode:$u("SHA-256")}),Pm=Oa({name:"sha2-512",code:19,encode:$u("SHA-512")});var Sn={...ka,...Ca,...Ra,..._a,...Ia,...xa,...Ea,...wa,...Da,...Ta},Cx={...Na,...Sa};function Gu(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Wu=Gu("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ba=Gu("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=St(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Lm={utf8:Wu,"utf-8":Wu,hex:Sn.base16,latin1:Ba,ascii:Ba,binary:Ba,...Sn},qo=Lm;function L(r,t="utf8"){let e=qo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function M(r,t="utf8"){let e=qo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Dm=parseInt("11111",2),Fa=parseInt("10000000",2),Rm=parseInt("01111111",2),ju={0:_n,1:_n,2:km,3:Nm,4:Bm,5:Om,6:Mm,16:_n,22:_n,48:_n};function xe(r,t={offset:0}){let e=r[t.offset]&Dm;if(t.offset++,ju[e]!=null)return ju[e](r,t);throw new Error("No decoder for tag "+e)}function In(r,t){let e=0;if((r[t.offset]&Fa)===Fa){let n=r[t.offset]&Rm,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 _n(r,t){In(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=xe(r,t);if(n===null)break;e.push(n)}return e}function km(r,t){let e=In(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 Mm(r,t){let e=In(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 u=r[t.offset];if(t.offset++,c.push(u&127),u<128){c.reverse();let l=0;for(let f=0;f<c.length;f++)l+=c[f]<<f*7;a+=`.${l}`,c=[]}}return a}function Om(r,t){return t.offset++,null}function Nm(r,t){let e=In(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 Bm(r,t){let e=In(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function Fm(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new Y;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function zo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=Fm(r.byteLength);return new Y(Uint8Array.from([t.byteLength|Fa]),t)}function Rt(r){let t=new Y,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new Y(Uint8Array.from([2]),zo(t),t)}function Cn(r){let t=Uint8Array.from([0]),e=new Y(t,r);return new Y(Uint8Array.from([3]),zo(e),e)}function Xu(r){return new Y(Uint8Array.from([4]),zo(r),r)}function ne(r,t=48){let e=new Y;for(let n of r)e.append(n);return new Y(Uint8Array.from([t]),zo(e),e)}async function Yu(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 Zu(r,t,e){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);e?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,t.subarray());return e?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Qu(r,t,e,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,e.subarray());return n?.signal?.throwIfAborted(),s}var Um=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Km=Uint8Array.from([6,5,43,129,4,0,34]),qm=Uint8Array.from([6,5,43,129,4,0,35]),zm={ext:!0,kty:"EC",crv:"P-256"},Vm={ext:!0,kty:"EC",crv:"P-384"},Hm={ext:!0,kty:"EC",crv:"P-521"},Ua=32,Ka=48,qa=66;function za(r){let t=xe(r);return Ju(t)}function Ju(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Ua*2+1)return n=M(t.subarray(e,e+Ua),"base64url"),o=M(t.subarray(e+Ua),"base64url"),new je({...zm,key_ops:["verify"],x:n,y:o});if(t.byteLength===Ka*2+1)return n=M(t.subarray(e,e+Ka),"base64url"),o=M(t.subarray(e+Ka),"base64url"),new je({...Vm,key_ops:["verify"],x:n,y:o});if(t.byteLength===qa*2+1)return n=M(t.subarray(e,e+qa),"base64url"),o=M(t.subarray(e+qa),"base64url"),new je({...Hm,key_ops:["verify"],x:n,y:o});throw new k(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function tf(r){return ne([Rt(Uint8Array.from([1])),Xu(L(r.d??"","base64url")),ne([rf(r.crv)],160),ne([Cn(new Y(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function ef(r){return ne([Rt(Uint8Array.from([1])),ne([rf(r.crv)],160),ne([Cn(new Y(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function rf(r){if(r==="P-256")return Um;if(r==="P-384")return Km;if(r==="P-521")return qm;throw new k(`Invalid curve ${r}`)}async function nf(r="P-256"){let t=await Yu(r);return new Vo(t.privateKey)}var je=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=ef(this.jwk)),this._raw}toMultihash(){return re.digest(Xt(this))}toCID(){return it.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:tt(this.raw,t.raw)}async verify(t,e,n){return Qu(this.jwk,e,t,n)}},Vo=class{type="ECDSA";jwk;publicKey;_raw;constructor(t){this.jwk=t,this.publicKey=new je({crv:t.crv,ext:t.ext,key_ops:["verify"],kty:"EC",x:t.x,y:t.y})}get raw(){return this._raw==null&&(this._raw=tf(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:tt(this.raw,t.raw)}async sign(t,e){return Zu(this.jwk,t,e)}};var Xe=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function $m(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ho(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Ye(r,...t){if(!$m(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 of(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Ho(r.outputLen),Ho(r.blockLen)}function Ur(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 sf(r,t){Ye(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function Ee(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function $o(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function oe(r,t){return r<<32-t|r>>>t}function af(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Tn(r){return typeof r=="string"&&(r=af(r)),Ye(r),r}function Va(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Ye(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 Fr=class{};function Ha(r){let t=n=>r().update(Tn(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Kr(r=32){if(Xe&&typeof Xe.getRandomValues=="function")return Xe.getRandomValues(new Uint8Array(r));if(Xe&&typeof Xe.randomBytes=="function")return Uint8Array.from(Xe.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function Wm(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,u=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+u,a,n)}function cf(r,t,e){return r&t^~r&e}function lf(r,t,e){return r&t^r&e^t&e}var Pn=class extends Fr{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=$o(this.buffer)}update(t){Ur(this),t=Tn(t),Ye(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=$o(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Ur(this),sf(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,Ee(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;Wm(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=$o(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ve=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var xt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Wo=BigInt(4294967295),uf=BigInt(32);function Gm(r,t=!1){return t?{h:Number(r&Wo),l:Number(r>>uf&Wo)}:{h:Number(r>>uf&Wo)|0,l:Number(r&Wo)|0}}function ff(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}=Gm(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var $a=(r,t,e)=>r>>>e,Wa=(r,t,e)=>r<<32-e|t>>>e,Ze=(r,t,e)=>r>>>e|t<<32-e,Qe=(r,t,e)=>r<<32-e|t>>>e,Ln=(r,t,e)=>r<<64-e|t>>>e-32,Dn=(r,t,e)=>r>>>e-32|t<<64-e;function fe(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var df=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),hf=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,pf=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),mf=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,gf=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),yf=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var Xm=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]),Be=new Uint32Array(64),Go=class extends Pn{constructor(t=32){super(64,t,8,!1),this.A=ve[0]|0,this.B=ve[1]|0,this.C=ve[2]|0,this.D=ve[3]|0,this.E=ve[4]|0,this.F=ve[5]|0,this.G=ve[6]|0,this.H=ve[7]|0}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)Be[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Be[f-15],m=Be[f-2],h=oe(d,7)^oe(d,18)^d>>>3,g=oe(m,17)^oe(m,19)^m>>>10;Be[f]=g+Be[f-7]+h+Be[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let d=oe(a,6)^oe(a,11)^oe(a,25),m=l+d+cf(a,c,u)+Xm[f]+Be[f]|0,g=(oe(n,2)^oe(n,13)^oe(n,22))+lf(n,o,s)|0;l=u,u=c,c=a,a=i+m|0,i=s,s=o,o=n,n=m+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,u,l)}roundClean(){Ee(Be)}destroy(){this.set(0,0,0,0,0,0,0,0),Ee(this.buffer)}};var bf=ff(["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))),Ym=bf[0],Zm=bf[1],Fe=new Uint32Array(80),Ue=new Uint32Array(80),Ga=class extends Pn{constructor(t=64){super(128,t,16,!1),this.Ah=xt[0]|0,this.Al=xt[1]|0,this.Bh=xt[2]|0,this.Bl=xt[3]|0,this.Ch=xt[4]|0,this.Cl=xt[5]|0,this.Dh=xt[6]|0,this.Dl=xt[7]|0,this.Eh=xt[8]|0,this.El=xt[9]|0,this.Fh=xt[10]|0,this.Fl=xt[11]|0,this.Gh=xt[12]|0,this.Gl=xt[13]|0,this.Hh=xt[14]|0,this.Hl=xt[15]|0}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:d,Gh:m,Gl:h,Hh:g,Hl:b}=this;return[t,e,n,o,s,i,a,c,u,l,f,d,m,h,g,b]}set(t,e,n,o,s,i,a,c,u,l,f,d,m,h,g,b){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=d|0,this.Gh=m|0,this.Gl=h|0,this.Hh=g|0,this.Hl=b|0}process(t,e){for(let x=0;x<16;x++,e+=4)Fe[x]=t.getUint32(e),Ue[x]=t.getUint32(e+=4);for(let x=16;x<80;x++){let p=Fe[x-15]|0,w=Ue[x-15]|0,T=Ze(p,w,1)^Ze(p,w,8)^$a(p,w,7),P=Qe(p,w,1)^Qe(p,w,8)^Wa(p,w,7),D=Fe[x-2]|0,F=Ue[x-2]|0,q=Ze(D,F,19)^Ln(D,F,61)^$a(D,F,6),O=Qe(D,F,19)^Dn(D,F,61)^Wa(D,F,6),U=pf(P,O,Ue[x-7],Ue[x-16]),B=mf(U,T,q,Fe[x-7],Fe[x-16]);Fe[x]=B|0,Ue[x]=U|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:m,Fl:h,Gh:g,Gl:b,Hh:v,Hl:C}=this;for(let x=0;x<80;x++){let p=Ze(f,d,14)^Ze(f,d,18)^Ln(f,d,41),w=Qe(f,d,14)^Qe(f,d,18)^Dn(f,d,41),T=f&m^~f&g,P=d&h^~d&b,D=gf(C,w,P,Zm[x],Ue[x]),F=yf(D,v,p,T,Ym[x],Fe[x]),q=D|0,O=Ze(n,o,28)^Ln(n,o,34)^Ln(n,o,39),U=Qe(n,o,28)^Dn(n,o,34)^Dn(n,o,39),B=n&s^n&a^s&a,ht=o&i^o&c^i&c;v=g|0,C=b|0,g=m|0,b=h|0,m=f|0,h=d|0,{h:f,l:d}=fe(u|0,l|0,F|0,q|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let _=df(q,U,ht);n=hf(_,F,O,B),o=_|0}({h:n,l:o}=fe(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=fe(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=fe(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=fe(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=fe(this.Eh|0,this.El|0,f|0,d|0),{h:m,l:h}=fe(this.Fh|0,this.Fl|0,m|0,h|0),{h:g,l:b}=fe(this.Gh|0,this.Gl|0,g|0,b|0),{h:v,l:C}=fe(this.Hh|0,this.Hl|0,v|0,C|0),this.set(n,o,s,i,a,c,u,l,f,d,m,h,g,b,v,C)}roundClean(){Ee(Fe,Ue)}destroy(){Ee(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var jo=Ha(()=>new Go);var wf=Ha(()=>new Ga);var Za=BigInt(0),Ya=BigInt(1);function qr(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Qa(r){if(!qr(r))throw new Error("Uint8Array expected")}function de(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}function Rn(r){let t=r.toString(16);return t.length&1?"0"+t:t}function vf(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Za:BigInt("0x"+r)}var Af=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qm=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Ke(r){if(Qa(r),Af)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=Qm[r[e]];return t}var Ae={_0:48,_9:57,A:65,F:70,a:97,f:102};function xf(r){if(r>=Ae._0&&r<=Ae._9)return r-Ae._0;if(r>=Ae.A&&r<=Ae.F)return r-(Ae.A-10);if(r>=Ae.a&&r<=Ae.f)return r-(Ae.a-10)}function kn(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Af)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=xf(r.charCodeAt(s)),a=xf(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 Se(r){return vf(Ke(r))}function Je(r){return Qa(r),vf(Ke(Uint8Array.from(r).reverse()))}function tr(r,t){return kn(r.toString(16).padStart(t*2,"0"))}function zr(r,t){return tr(r,t).reverse()}function nt(r,t,e){let n;if(typeof t=="string")try{n=kn(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(qr(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 qe(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Qa(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 ja=r=>typeof r=="bigint"&&Za<=r;function Xo(r,t,e){return ja(r)&&ja(t)&&ja(e)&&t<=r&&r<e}function Wt(r,t,e,n){if(!Xo(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Sf(r){let t;for(t=0;r>Za;r>>=Ya,t+=1);return t}var er=r=>(Ya<<BigInt(r))-Ya,Xa=r=>new Uint8Array(r),Ef=r=>Uint8Array.from(r);function _f(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=Xa(r),o=Xa(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=Xa(0))=>{o=a(Ef([0]),f),n=a(),f.length!==0&&(o=a(Ef([1]),f),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<t;){n=a();let m=n.slice();d.push(m),f+=n.length}return qe(...d)};return(f,d)=>{i(),c(f);let m;for(;!(m=d(u()));)c();return i(),m}}var Jm={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"||qr(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 _e(r,t,e={}){let n=(o,s,i)=>{let a=Jm[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 Vr(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 kt=BigInt(0),yt=BigInt(1),rr=BigInt(2),tg=BigInt(3),Cf=BigInt(4),Tf=BigInt(5),Pf=BigInt(8);function rt(r,t){let e=r%t;return e>=kt?e:t+e}function ot(r,t,e){let n=r;for(;t-- >kt;)n*=n,n%=e;return n}function Yo(r,t){if(r===kt)throw new Error("invert: expected non-zero number");if(t<=kt)throw new Error("invert: expected positive modulus, got "+t);let e=rt(r,t),n=t,o=kt,s=yt,i=yt,a=kt;for(;e!==kt;){let u=n/e,l=n%e,f=o-i*u,d=s-a*u;n=e,e=l,o=i,s=a,i=f,a=d}if(n!==yt)throw new Error("invert: does not exist");return rt(o,t)}function Lf(r,t){let e=(r.ORDER+yt)/Cf,n=r.pow(t,e);if(!r.eql(r.sqr(n),t))throw new Error("Cannot find square root");return n}function eg(r,t){let e=(r.ORDER-Tf)/Pf,n=r.mul(t,rr),o=r.pow(n,e),s=r.mul(t,o),i=r.mul(r.mul(s,rr),o),a=r.mul(s,r.sub(i,r.ONE));if(!r.eql(r.sqr(a),t))throw new Error("Cannot find square root");return a}function rg(r){if(r<BigInt(3))throw new Error("sqrt is not defined for small field");let t=r-yt,e=0;for(;t%rr===kt;)t/=rr,e++;let n=rr,o=Ie(r);for(;If(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return Lf;let s=o.pow(n,t),i=(t+yt)/rr;return function(c,u){if(c.is0(u))return u;if(If(c,u)!==1)throw new Error("Cannot find square root");let l=e,f=c.mul(c.ONE,s),d=c.pow(u,t),m=c.pow(u,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let h=1,g=c.sqr(d);for(;!c.eql(g,c.ONE);)if(h++,g=c.sqr(g),h===l)throw new Error("Cannot find square root");let b=yt<<BigInt(l-h-1),v=c.pow(f,b);l=h,f=c.sqr(v),d=c.mul(d,f),m=c.mul(m,v)}return m}}function ng(r){return r%Cf===tg?Lf:r%Pf===Tf?eg:rg(r)}var Df=(r,t)=>(rt(r,t)&yt)===yt,og=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ja(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=og.reduce((n,o)=>(n[o]="function",n),t);return _e(r,e)}function sg(r,t,e){if(e<kt)throw new Error("invalid exponent, negatives unsupported");if(e===kt)return r.ONE;if(e===yt)return t;let n=r.ONE,o=t;for(;e>kt;)e&yt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=yt;return n}function Hr(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 If(r,t){let e=(r.ORDER-yt)/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("invalid Legendre symbol result");return o?1:s?0:-1}function tc(r,t){t!==void 0&&Ho(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Ie(r,t,e=!1,n={}){if(r<=kt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=tc(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:kt,ONE:yt,create:c=>rt(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return kt<=c&&c<r},is0:c=>c===kt,isOdd:c=>(c&yt)===yt,neg:c=>rt(-c,r),eql:(c,u)=>c===u,sqr:c=>rt(c*c,r),add:(c,u)=>rt(c+u,r),sub:(c,u)=>rt(c-u,r),mul:(c,u)=>rt(c*u,r),pow:(c,u)=>sg(a,c,u),div:(c,u)=>rt(c*Yo(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Yo(c,r),sqrt:n.sqrt||(c=>(i||(i=ng(r)),i(a,c))),toBytes:c=>e?zr(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):Se(c)},invertBatch:c=>Hr(a,c),cmov:(c,u,l)=>l?u:c});return Object.freeze(a)}function Rf(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 ec(r){let t=Rf(r);return t+Math.ceil(t/2)}function kf(r,t,e=!1){let n=r.length,o=Rf(t),s=ec(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?Je(r):Se(r),a=rt(i,t-yt)+yt;return e?zr(a,o):tr(a,o)}var Mf=BigInt(0),ic=BigInt(1);function rc(r,t){let e=t.negate();return r?e:t}function Nf(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function nc(r,t){Nf(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 Of(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+=ic);let u=t*n,l=u+Math.abs(a)-1,f=a===0,d=a<0,m=t%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:d,isNegF:m,offsetF:u}}function ig(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 ag(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 oc=new WeakMap,Bf=new WeakMap;function sc(r){return Bf.get(r)||1}function Zo(r,t){return{constTimeNegate:rc,hasPrecomputes(e){return sc(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>Mf;)n&ic&&(o=o.add(s)),s=s.double(),n>>=ic;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=nc(n,t),i=[],a=e,c=a;for(let u=0;u<o;u++){c=a,i.push(c);for(let l=1;l<s;l++)c=c.add(a),i.push(c);a=c.double()}return i},wNAF(e,n,o){let s=r.ZERO,i=r.BASE,a=nc(e,t);for(let c=0;c<a.windows;c++){let{nextN:u,offset:l,isZero:f,isNeg:d,isNegF:m,offsetF:h}=Of(o,c,a);o=u,f?i=i.add(rc(m,n[h])):s=s.add(rc(d,n[l]))}return{p:s,f:i}},wNAFUnsafe(e,n,o,s=r.ZERO){let i=nc(e,t);for(let a=0;a<i.windows&&o!==Mf;a++){let{nextN:c,offset:u,isZero:l,isNeg:f}=Of(o,a,i);if(o=c,!l){let d=n[u];s=s.add(f?d.negate():d)}}return s},getPrecomputes(e,n,o){let s=oc.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&oc.set(n,o(s))),s},wNAFCached(e,n,o){let s=sc(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=sc(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){Nf(n,t),Bf.set(e,n),oc.delete(e)}}}function Qo(r,t,e,n){ig(e,r),ag(n,t);let o=e.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=r.ZERO,a=Sf(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=er(c),l=new Array(Number(u)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,d=i;for(let m=f;m>=0;m-=c){l.fill(i);for(let g=0;g<s;g++){let b=n[g],v=Number(b>>BigInt(m)&u);l[v]=l[v].add(e[g])}let h=i;for(let g=l.length-1,b=i;g>0;g--)b=b.add(l[g]),h=h.add(b);if(d=d.add(h),m!==0)for(let g=0;g<c;g++)d=d.double()}return d}function Mn(r){return Ja(r.Fp),_e(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...tc(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var he=BigInt(0),Mt=BigInt(1),Ff=BigInt(2),cg=BigInt(8),lg={zip215:!0};function ug(r){let t=Mn(r);return _e(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Uf(r){let t=ug(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,u=Ff<<BigInt(a*8)-Mt,l=e.create,f=Ie(t.n,t.nBitLength);function d(A,y){let E=e.sqr(A),I=e.sqr(y),N=e.add(e.mul(t.a,E),I),K=e.add(e.ONE,e.mul(t.d,e.mul(E,I)));return e.eql(N,K)}if(!d(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let m=t.uvRatio||((A,y)=>{try{return{isValid:!0,value:e.sqrt(A*e.inv(y))}}catch{return{isValid:!1,value:he}}}),h=t.adjustScalarBytes||(A=>A),g=t.domain||((A,y,E)=>{if(de("phflag",E),y.length||E)throw new Error("Contexts/pre-hash are not supported");return A});function b(A,y,E=!1){let I=E?Mt:he;Wt("coordinate "+A,y,I,u)}function v(A){if(!(A instanceof p))throw new Error("ExtendedPoint expected")}let C=Vr((A,y)=>{let{ex:E,ey:I,ez:N}=A,K=A.is0();y==null&&(y=K?cg:e.inv(N));let V=l(E*y),$=l(I*y),X=l(N*y);if(K)return{x:he,y:Mt};if(X!==Mt)throw new Error("invZ was invalid");return{x:V,y:$}}),x=Vr(A=>{let{a:y,d:E}=t;if(A.is0())throw new Error("bad point: ZERO");let{ex:I,ey:N,ez:K,et:V}=A,$=l(I*I),X=l(N*N),J=l(K*K),pt=l(J*J),ut=l($*y),wt=l(J*l(ut+X)),Ut=l(pt+l(E*l($*X)));if(wt!==Ut)throw new Error("bad point: equation left != right (1)");let gt=l(I*N),At=l(K*V);if(gt!==At)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(y,E,I,N){b("x",y),b("y",E),b("z",I,!0),b("t",N),this.ex=y,this.ey=E,this.ez=I,this.et=N,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(y){if(y instanceof p)throw new Error("extended point not allowed");let{x:E,y:I}=y||{};return b("x",E),b("y",I),new p(E,I,Mt,l(E*I))}static normalizeZ(y){let E=Hr(e,y.map(I=>I.ez));return y.map((I,N)=>I.toAffine(E[N])).map(p.fromAffine)}static msm(y,E){return Qo(p,f,y,E)}_setWindowSize(y){P.setWindowSize(this,y)}assertValidity(){x(this)}equals(y){v(y);let{ex:E,ey:I,ez:N}=this,{ex:K,ey:V,ez:$}=y,X=l(E*$),J=l(K*N),pt=l(I*$),ut=l(V*N);return X===J&&pt===ut}is0(){return this.equals(p.ZERO)}negate(){return new p(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){let{a:y}=t,{ex:E,ey:I,ez:N}=this,K=l(E*E),V=l(I*I),$=l(Ff*l(N*N)),X=l(y*K),J=E+I,pt=l(l(J*J)-K-V),ut=X+V,wt=ut-$,Ut=X-V,gt=l(pt*wt),At=l(ut*Ut),Vt=l(pt*Ut),Qt=l(wt*ut);return new p(gt,At,Qt,Vt)}add(y){v(y);let{a:E,d:I}=t,{ex:N,ey:K,ez:V,et:$}=this,{ex:X,ey:J,ez:pt,et:ut}=y,wt=l(N*X),Ut=l(K*J),gt=l($*I*ut),At=l(V*pt),Vt=l((N+K)*(X+J)-wt-Ut),Qt=At-gt,gn=At+gt,Eu=l(Ut-E*wt),yp=l(Vt*Qt),bp=l(gn*Eu),wp=l(Vt*Eu),xp=l(Qt*gn);return new p(yp,bp,xp,wp)}subtract(y){return this.add(y.negate())}wNAF(y){return P.wNAFCached(this,y,p.normalizeZ)}multiply(y){let E=y;Wt("scalar",E,Mt,n);let{p:I,f:N}=this.wNAF(E);return p.normalizeZ([I,N])[0]}multiplyUnsafe(y,E=p.ZERO){let I=y;return Wt("scalar",I,he,n),I===he?T:this.is0()||I===Mt?this:P.wNAFCachedUnsafe(this,I,p.normalizeZ,E)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return P.unsafeLadder(this,n).is0()}toAffine(y){return C(this,y)}clearCofactor(){let{h:y}=t;return y===Mt?this:this.multiplyUnsafe(y)}static fromHex(y,E=!1){let{d:I,a:N}=t,K=e.BYTES;y=nt("pointHex",y,K),de("zip215",E);let V=y.slice(),$=y[K-1];V[K-1]=$&-129;let X=Je(V),J=E?u:e.ORDER;Wt("pointHex.y",X,he,J);let pt=l(X*X),ut=l(pt-Mt),wt=l(I*pt-N),{isValid:Ut,value:gt}=m(ut,wt);if(!Ut)throw new Error("Point.fromHex: invalid y coordinate");let At=(gt&Mt)===Mt,Vt=($&128)!==0;if(!E&>===he&&Vt)throw new Error("Point.fromHex: x=0 and x_0=1");return Vt!==At&&(gt=l(-gt)),p.fromAffine({x:gt,y:X})}static fromPrivateKey(y){let{scalar:E}=q(y);return w.multiply(E)}toRawBytes(){let{x:y,y:E}=this.toAffine(),I=zr(E,e.BYTES);return I[I.length-1]|=y&Mt?128:0,I}toHex(){return Ke(this.toRawBytes())}}p.BASE=new p(t.Gx,t.Gy,Mt,l(t.Gx*t.Gy)),p.ZERO=new p(he,Mt,Mt,he);let{BASE:w,ZERO:T}=p,P=Zo(p,a*8);function D(A){return rt(A,n)}function F(A){return D(Je(A))}function q(A){let y=e.BYTES;A=nt("private key",A,y);let E=nt("hashed private key",s(A),2*y),I=h(E.slice(0,y)),N=E.slice(y,2*y),K=F(I);return{head:I,prefix:N,scalar:K}}function O(A){let{head:y,prefix:E,scalar:I}=q(A),N=w.multiply(I),K=N.toRawBytes();return{head:y,prefix:E,scalar:I,point:N,pointBytes:K}}function U(A){return O(A).pointBytes}function B(A=Uint8Array.of(),...y){let E=qe(...y);return F(s(g(E,nt("context",A),!!o)))}function ht(A,y,E={}){A=nt("message",A),o&&(A=o(A));let{prefix:I,scalar:N,pointBytes:K}=O(y),V=B(E.context,I,A),$=w.multiply(V).toRawBytes(),X=B(E.context,$,K,A),J=D(V+X*N);Wt("signature.s",J,he,n);let pt=qe($,zr(J,e.BYTES));return nt("result",pt,e.BYTES*2)}let _=lg;function S(A,y,E,I=_){let{context:N,zip215:K}=I,V=e.BYTES;A=nt("signature",A,2*V),y=nt("message",y),E=nt("publicKey",E,V),K!==void 0&&de("zip215",K),o&&(y=o(y));let $=Je(A.slice(V,2*V)),X,J,pt;try{X=p.fromHex(E,K),J=p.fromHex(A.slice(0,V),K),pt=w.multiplyUnsafe($)}catch{return!1}if(!K&&X.isSmallOrder())return!1;let ut=B(N,J.toRawBytes(),X.toRawBytes(),y);return J.add(X.multiplyUnsafe(ut)).subtract(pt).clearCofactor().equals(p.ZERO)}return w._setWindowSize(8),{CURVE:t,getPublicKey:U,sign:ht,verify:S,ExtendedPoint:p,utils:{getExtendedPublicKey:O,randomPrivateKey:()=>i(e.BYTES),precompute(A=8,y=p.BASE){return y._setWindowSize(A),y.multiply(BigInt(3)),y}}}}var ac=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Kf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),C1=BigInt(0),fg=BigInt(1),qf=BigInt(2),T1=BigInt(3),dg=BigInt(5),hg=BigInt(8);function pg(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=ac,a=r*r%s*r%s,c=ot(a,qf,s)*a%s,u=ot(c,fg,s)*r%s,l=ot(u,dg,s)*u%s,f=ot(l,t,s)*l%s,d=ot(f,e,s)*f%s,m=ot(d,n,s)*d%s,h=ot(m,o,s)*m%s,g=ot(h,o,s)*m%s,b=ot(g,t,s)*l%s;return{pow_p_5_8:ot(b,qf,s)*r%s,b2:a}}function mg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function gg(r,t){let e=ac,n=rt(t*t*t,e),o=rt(n*n*t,e),s=pg(r*o).pow_p_5_8,i=rt(r*n*s,e),a=rt(t*i*i,e),c=i,u=rt(i*Kf,e),l=a===r,f=a===rt(-r,e),d=a===rt(-r*Kf,e);return l&&(i=c),(f||d)&&(i=u),Df(i,e)&&(i=rt(-i,e)),{isValid:l||f,value:i}}var zf=Ie(ac,void 0,!0),yg={a:zf.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:zf,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:hg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:wf,randomBytes:Kr,adjustScalarBytes:mg,uvRatio:gg},On=Uf(yg);var Nn=class extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}},Bn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},Jo=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Vf={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new Jo("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 qt=Vf;var ts=32,Fn=64,cc=32;var $r,Hf=(async()=>{try{return await qt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function $f(){let r=On.utils.randomPrivateKey(),t=On.getPublicKey(r);return{privateKey:vg(r,t),publicKey:t}}async function bg(r,t){let e;r.length===Fn?e=r.subarray(0,32):e=r;let n={crv:"Ed25519",kty:"OKP",x:M(r.subarray(32),"base64url"),d:M(e,"base64url"),ext:!0,key_ops:["sign"]},o=await qt.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await qt.get().subtle.sign({name:"Ed25519"},o,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(s,0,s.byteLength)}function wg(r,t){let e=r.subarray(0,cc);return On.sign(t instanceof Uint8Array?t:t.subarray(),e)}async function Wf(r,t){return $r==null&&($r=await Hf),$r?bg(r,t):wg(r,t)}async function xg(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await qt.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await qt.get().subtle.verify({name:"Ed25519"},n,t,e instanceof Uint8Array?e:e.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Eg(r,t,e){return On.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function Gf(r,t,e){return $r==null&&($r=await Hf),$r?xg(r,t,e):Eg(r,t,e)}function vg(r,t){let e=new Uint8Array(Fn);for(let n=0;n<cc;n++)e[n]=r[n],e[cc+n]=t[n];return e}function Wr(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Un=class{type="Ed25519";raw;constructor(t){this.raw=rs(t,ts)}toMultihash(){return re.digest(Xt(this))}toCID(){return it.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:tt(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=Gf(this.raw,e,t);return Wr(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},es=class{type="Ed25519";raw;publicKey;constructor(t,e){this.raw=rs(t,Fn),this.publicKey=new Un(e)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:tt(this.raw,t.raw)}sign(t,e){e?.signal?.throwIfAborted();let n=Wf(this.raw,t);return Wr(n)?n.then(o=>(e?.signal?.throwIfAborted(),o)):(e?.signal?.throwIfAborted(),n)}};function lc(r){return r=rs(r,ts),new Un(r)}async function Xf(){let{privateKey:r,publicKey:t}=$f();return new es(r,t)}function rs(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new k(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Ag=Math.pow(2,7),Sg=Math.pow(2,14),_g=Math.pow(2,21),uc=Math.pow(2,28),fc=Math.pow(2,35),dc=Math.pow(2,42),hc=Math.pow(2,49),Q=128,_t=127;function mt(r){if(r<Ag)return 1;if(r<Sg)return 2;if(r<_g)return 3;if(r<uc)return 4;if(r<fc)return 5;if(r<dc)return 6;if(r<hc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function pc(r,t,e=0){switch(mt(r)){case 8:t[e++]=r&255|Q,r/=128;case 7:t[e++]=r&255|Q,r/=128;case 6:t[e++]=r&255|Q,r/=128;case 5:t[e++]=r&255|Q,r/=128;case 4:t[e++]=r&255|Q,r>>>=7;case 3:t[e++]=r&255|Q,r>>>=7;case 2:t[e++]=r&255|Q,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Ig(r,t,e=0){switch(mt(r)){case 8:t.set(e++,r&255|Q),r/=128;case 7:t.set(e++,r&255|Q),r/=128;case 6:t.set(e++,r&255|Q),r/=128;case 5:t.set(e++,r&255|Q),r/=128;case 4:t.set(e++,r&255|Q),r>>>=7;case 3:t.set(e++,r&255|Q),r>>>=7;case 2:t.set(e++,r&255|Q),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function mc(r,t){let e=r[t],n=0;if(n+=e&_t,e<Q||(e=r[t+1],n+=(e&_t)<<7,e<Q)||(e=r[t+2],n+=(e&_t)<<14,e<Q)||(e=r[t+3],n+=(e&_t)<<21,e<Q)||(e=r[t+4],n+=(e&_t)*uc,e<Q)||(e=r[t+5],n+=(e&_t)*fc,e<Q)||(e=r[t+6],n+=(e&_t)*dc,e<Q)||(e=r[t+7],n+=(e&_t)*hc,e<Q))return n;throw new RangeError("Could not decode varint")}function Cg(r,t){let e=r.get(t),n=0;if(n+=e&_t,e<Q||(e=r.get(t+1),n+=(e&_t)<<7,e<Q)||(e=r.get(t+2),n+=(e&_t)<<14,e<Q)||(e=r.get(t+3),n+=(e&_t)<<21,e<Q)||(e=r.get(t+4),n+=(e&_t)*uc,e<Q)||(e=r.get(t+5),n+=(e&_t)*fc,e<Q)||(e=r.get(t+6),n+=(e&_t)*dc,e<Q)||(e=r.get(t+7),n+=(e&_t)*hc,e<Q))return n;throw new RangeError("Could not decode varint")}function It(r,t,e=0){return t==null&&(t=St(mt(r))),t instanceof Uint8Array?pc(r,t,e):Ig(r,t,e)}function se(r,t=0){return r instanceof Uint8Array?mc(r,t):Cg(r,t)}var gc=new Float32Array([-0]),ze=new Uint8Array(gc.buffer);function Yf(r,t,e){gc[0]=r,t[e]=ze[0],t[e+1]=ze[1],t[e+2]=ze[2],t[e+3]=ze[3]}function Zf(r,t){return ze[0]=r[t],ze[1]=r[t+1],ze[2]=r[t+2],ze[3]=r[t+3],gc[0]}var yc=new Float64Array([-0]),Ct=new Uint8Array(yc.buffer);function Qf(r,t,e){yc[0]=r,t[e]=Ct[0],t[e+1]=Ct[1],t[e+2]=Ct[2],t[e+3]=Ct[3],t[e+4]=Ct[4],t[e+5]=Ct[5],t[e+6]=Ct[6],t[e+7]=Ct[7]}function Jf(r,t){return Ct[0]=r[t],Ct[1]=r[t+1],Ct[2]=r[t+2],Ct[3]=r[t+3],Ct[4]=r[t+4],Ct[5]=r[t+5],Ct[6]=r[t+6],Ct[7]=r[t+7],yc[0]}var Tg=BigInt(Number.MAX_SAFE_INTEGER),Pg=BigInt(Number.MIN_SAFE_INTEGER),Gt=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<Tg&&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>td&&(o=0n,++n>td&&(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 Gt(0,0);or.toBigInt=function(){return 0n};or.zzEncode=or.zzDecode=function(){return this};or.length=function(){return 1};var td=4294967296n;function ed(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 rd(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 bc(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 ie(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function ns(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var wc=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,ie(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 ie(this,4);return ns(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ie(this,4);return ns(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ie(this,4);let t=Zf(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw ie(this,4);let t=Jf(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 ie(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return rd(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw ie(this,t);this.pos+=t}else do if(this.pos>=this.len)throw ie(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 Gt(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 ie(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 ie(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 ie(this,8);let t=ns(this.buf,this.pos+=4),e=ns(this.buf,this.pos+=4);return new Gt(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=mc(this.buf,this.pos);return this.pos+=mt(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 xc(r){return new wc(r instanceof Uint8Array?r:r.subarray())}function Ot(r,t,e){let n=xc(r);return t.decode(n,void 0,e)}function Ec(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return St(i);o+i>t&&(n=St(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var sr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function vc(){}var Sc=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Lg=Ec();function Dg(r){return globalThis.Buffer!=null?St(r):Lg(r)}var qn=class{len;head;tail;states;constructor(){this.len=0,this.head=new sr(vc,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 _c((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(os,10,Gt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Gt.fromBigInt(t);return this._push(os,e.length(),e)}uint64Number(t){return this._push(pc,mt(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=Gt.fromBigInt(t).zzEncode();return this._push(os,e.length(),e)}sint64Number(t){let e=Gt.fromNumber(t).zzEncode();return this._push(os,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Ac,1,t?1:0)}fixed32(t){return this._push(Kn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Gt.fromBigInt(t);return this._push(Kn,4,e.lo)._push(Kn,4,e.hi)}fixed64Number(t){let e=Gt.fromNumber(t);return this._push(Kn,4,e.lo)._push(Kn,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Yf,4,t)}double(t){return this._push(Qf,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Ac,1,0):this.uint32(e)._push(kg,e,t)}string(t){let e=ed(t);return e!==0?this.uint32(e)._push(bc,e,t):this._push(Ac,1,0)}fork(){return this.states=new Sc(this),this.head=this.tail=new sr(vc,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new sr(vc,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=Dg(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Ac(r,t,e){t[e]=r&255}function Rg(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var _c=class extends sr{next;constructor(t,e){super(Rg,t,e),this.next=void 0}};function os(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 Kn(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 kg(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(qn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Mg,t,r),this},qn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Og,t,r),this});function Mg(r,t,e){t.set(r,e)}function Og(r,t,e){r.length<40?bc(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(L(r),e)}function Ic(){return new qn}function Nt(r,t){let e=Ic();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Gr;(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"})(Gr||(Gr={}));function ss(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Cc(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 ss("enum",Gr.VARINT,e,n)}function Bt(r,t){return ss("message",Gr.LENGTH_DELIMITED,r,t)}var ir=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},zn=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ft;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ft||(ft={}));var Tc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Tc||(Tc={}));(function(r){r.codec=()=>Cc(Tc)})(ft||(ft={}));var pe;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ft.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=ft.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Nt(e,r.codec()),r.decode=(e,n)=>Ot(e,r.codec(),n)})(pe||(pe={}));var Pc;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ft.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=ft.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Nt(e,r.codec()),r.decode=(e,n)=>Ot(e,r.codec(),n)})(Pc||(Pc={}));function jr(r){if(isNaN(r)||r<=0)throw new k("random bytes length must be a Number bigger than 0");return Kr(r)}var Hn={};Kt(Hn,{MAX_RSA_KEY_SIZE:()=>Lc,generateRSAKeyPair:()=>Uc,jwkToJWKKeyPair:()=>cd,jwkToPkcs1:()=>Ug,jwkToPkix:()=>Mc,jwkToRSAPrivateKey:()=>Fc,pkcs1MessageToJwk:()=>Rc,pkcs1MessageToRSAPrivateKey:()=>Oc,pkcs1ToJwk:()=>Fg,pkcs1ToRSAPrivateKey:()=>ad,pkixMessageToJwk:()=>kc,pkixMessageToRSAPublicKey:()=>Bc,pkixToJwk:()=>Kg,pkixToRSAPublicKey:()=>Nc});var is=jo;var Xr=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=Hn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return it.createV1(114,this._multihash)}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:tt(this.raw,t.raw)}verify(t,e,n){return id(this.jwk,e,t,n)}},Vn=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=Hn.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:tt(this.raw,t.raw)}sign(t,e){return sd(this.jwk,t,e)}};var Lc=8192,Dc=18,Ng=1062,Bg=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Fg(r){let t=xe(r);return Rc(t)}function Rc(r){return{n:M(r[1],"base64url"),e:M(r[2],"base64url"),d:M(r[3],"base64url"),p:M(r[4],"base64url"),q:M(r[5],"base64url"),dp:M(r[6],"base64url"),dq:M(r[7],"base64url"),qi:M(r[8],"base64url"),kty:"RSA"}}function Ug(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 k("JWK was missing components");return ne([Rt(Uint8Array.from([0])),Rt(L(r.n,"base64url")),Rt(L(r.e,"base64url")),Rt(L(r.d,"base64url")),Rt(L(r.p,"base64url")),Rt(L(r.q,"base64url")),Rt(L(r.dp,"base64url")),Rt(L(r.dq,"base64url")),Rt(L(r.qi,"base64url"))]).subarray()}function Kg(r){let t=xe(r,{offset:0});return kc(t)}function kc(r){let t=xe(r[1],{offset:0});return{kty:"RSA",n:M(t[0],"base64url"),e:M(t[1],"base64url")}}function Mc(r){if(r.n==null||r.e==null)throw new k("JWK was missing components");return ne([Bg,Cn(ne([Rt(L(r.n,"base64url")),Rt(L(r.e,"base64url"))]))]).subarray()}function ad(r){let t=xe(r);return Oc(t)}function Oc(r){let t=Rc(r);return Fc(t)}function Nc(r,t){if(r.byteLength>=Ng)throw new Tr("Key size is too large");let e=xe(r,{offset:0});return Bc(e,r,t)}function Bc(r,t,e){let n=kc(r);if(e==null){let o=is(pe.encode({Type:ft.RSA,Data:t}));e=te(Dc,o)}return new Xr(n,e)}function Fc(r){if(ud(r)>Lc)throw new k("Key size is too large");let t=cd(r),e=is(pe.encode({Type:ft.RSA,Data:Mc(t.publicKey)})),n=te(Dc,e);return new Vn(t.privateKey,new Xr(t.publicKey,n))}async function Uc(r){if(r>Lc)throw new k("Key size is too large");let t=await ld(r),e=is(pe.encode({Type:ft.RSA,Data:Mc(t.publicKey)})),n=te(Dc,e);return new Vn(t.privateKey,new Xr(t.publicKey,n))}function cd(r){if(r==null)throw new k("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function ld(r,t){let e=await qt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);t?.signal?.throwIfAborted();let n=await qg(e,t);return{privateKey:n[0],publicKey:n[1]}}async function sd(r,t,e){let n=await qt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);e?.signal?.throwIfAborted();let o=await qt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,t instanceof Uint8Array?t:t.subarray());return e?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function id(r,t,e,n){let o=await qt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await qt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),s}async function qg(r,t){if(r.privateKey==null||r.publicKey==null)throw new k("Private and public key are required");let e=await Promise.all([qt.get().subtle.exportKey("jwk",r.privateKey),qt.get().subtle.exportKey("jwk",r.publicKey)]);return t?.signal?.throwIfAborted(),e}function ud(r){if(r.kty!=="RSA")throw new k("invalid key type");if(r.n==null)throw new k("invalid key modulus");return L(r.n,"base64url").length*8}var as=class extends Fr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,of(t);let n=Tn(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),Ee(s)}update(t){return Ur(this),this.iHash.update(t),this}digestInto(t){Ur(this),Ye(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()}},Kc=(r,t,e)=>new as(r,t).update(e).digest();Kc.create=(r,t)=>new as(r,t);function fd(r){r.lowS!==void 0&&de("lowS",r.lowS),r.prehash!==void 0&&de("prehash",r.prehash)}function zg(r){let t=Mn(r);_e(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}var Vc=class extends Error{constructor(t=""){super(t)}},Ce={Err:Vc,_tlv:{encode:(r,t)=>{let{Err:e}=Ce;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=Rn(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Rn(o.length/2|128):"";return Rn(r)+s+o+t},decode(r,t){let{Err:e}=Ce,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new e("tlv.decode: length bytes not complete");if(u[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let l of u)i=i<<8|l;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=Ce;if(r<Te)throw new t("integer: negative integers are not allowed");let e=Rn(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}=Ce;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 Se(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Ce,o=nt("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:u,l}=n.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(u)}},hexFromSig(r){let{_tlv:t,_int:e}=Ce,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}};function qc(r,t){return Ke(tr(r,t))}var Te=BigInt(0),bt=BigInt(1),a2=BigInt(2),zc=BigInt(3),Vg=BigInt(4);function Hg(r){let t=zg(r),{Fp:e}=t,n=Ie(t.n,t.nBitLength),o=t.toBytes||((x,p,w)=>{let T=p.toAffine();return qe(Uint8Array.from([4]),e.toBytes(T.x),e.toBytes(T.y))}),s=t.fromBytes||(x=>{let p=x.subarray(1),w=e.fromBytes(p.subarray(0,e.BYTES)),T=e.fromBytes(p.subarray(e.BYTES,2*e.BYTES));return{x:w,y:T}});function i(x){let{a:p,b:w}=t,T=e.sqr(x),P=e.mul(T,x);return e.add(e.add(P,e.mul(x,p)),w)}function a(x,p){let w=e.sqr(p),T=i(x);return e.eql(w,T)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let c=e.mul(e.pow(t.a,zc),Vg),u=e.mul(e.sqr(t.b),BigInt(27));if(e.is0(e.add(c,u)))throw new Error("bad curve params: a or b");function l(x){return Xo(x,bt,t.n)}function f(x){let{allowedPrivateKeyLengths:p,nByteLength:w,wrapPrivateKey:T,n:P}=t;if(p&&typeof x!="bigint"){if(qr(x)&&(x=Ke(x)),typeof x!="string"||!p.includes(x.length))throw new Error("invalid private key");x=x.padStart(w*2,"0")}let D;try{D=typeof x=="bigint"?x:Se(nt("private key",x,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof x)}return T&&(D=rt(D,P)),Wt("private key",D,bt,P),D}function d(x){if(!(x instanceof g))throw new Error("ProjectivePoint expected")}let m=Vr((x,p)=>{let{px:w,py:T,pz:P}=x;if(e.eql(P,e.ONE))return{x:w,y:T};let D=x.is0();p==null&&(p=D?e.ONE:e.inv(P));let F=e.mul(w,p),q=e.mul(T,p),O=e.mul(P,p);if(D)return{x:e.ZERO,y:e.ZERO};if(!e.eql(O,e.ONE))throw new Error("invZ was invalid");return{x:F,y:q}}),h=Vr(x=>{if(x.is0()){if(t.allowInfinityPoint&&!e.is0(x.py))return;throw new Error("bad point: ZERO")}let{x:p,y:w}=x.toAffine();if(!e.isValid(p)||!e.isValid(w))throw new Error("bad point: x or y not FE");if(!a(p,w))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(p,w,T){if(p==null||!e.isValid(p))throw new Error("x required");if(w==null||!e.isValid(w)||e.is0(w))throw new Error("y required");if(T==null||!e.isValid(T))throw new Error("z required");this.px=p,this.py=w,this.pz=T,Object.freeze(this)}static fromAffine(p){let{x:w,y:T}=p||{};if(!p||!e.isValid(w)||!e.isValid(T))throw new Error("invalid affine point");if(p instanceof g)throw new Error("projective point not allowed");let P=D=>e.eql(D,e.ZERO);return P(w)&&P(T)?g.ZERO:new g(w,T,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(p){let w=Hr(e,p.map(T=>T.pz));return p.map((T,P)=>T.toAffine(w[P])).map(g.fromAffine)}static fromHex(p){let w=g.fromAffine(s(nt("pointHex",p)));return w.assertValidity(),w}static fromPrivateKey(p){return g.BASE.multiply(f(p))}static msm(p,w){return Qo(g,n,p,w)}_setWindowSize(p){C.setWindowSize(this,p)}assertValidity(){h(this)}hasEvenY(){let{y:p}=this.toAffine();if(e.isOdd)return!e.isOdd(p);throw new Error("Field doesn't support isOdd")}equals(p){d(p);let{px:w,py:T,pz:P}=this,{px:D,py:F,pz:q}=p,O=e.eql(e.mul(w,q),e.mul(D,P)),U=e.eql(e.mul(T,q),e.mul(F,P));return O&&U}negate(){return new g(this.px,e.neg(this.py),this.pz)}double(){let{a:p,b:w}=t,T=e.mul(w,zc),{px:P,py:D,pz:F}=this,q=e.ZERO,O=e.ZERO,U=e.ZERO,B=e.mul(P,P),ht=e.mul(D,D),_=e.mul(F,F),S=e.mul(P,D);return S=e.add(S,S),U=e.mul(P,F),U=e.add(U,U),q=e.mul(p,U),O=e.mul(T,_),O=e.add(q,O),q=e.sub(ht,O),O=e.add(ht,O),O=e.mul(q,O),q=e.mul(S,q),U=e.mul(T,U),_=e.mul(p,_),S=e.sub(B,_),S=e.mul(p,S),S=e.add(S,U),U=e.add(B,B),B=e.add(U,B),B=e.add(B,_),B=e.mul(B,S),O=e.add(O,B),_=e.mul(D,F),_=e.add(_,_),B=e.mul(_,S),q=e.sub(q,B),U=e.mul(_,ht),U=e.add(U,U),U=e.add(U,U),new g(q,O,U)}add(p){d(p);let{px:w,py:T,pz:P}=this,{px:D,py:F,pz:q}=p,O=e.ZERO,U=e.ZERO,B=e.ZERO,ht=t.a,_=e.mul(t.b,zc),S=e.mul(w,D),R=e.mul(T,F),A=e.mul(P,q),y=e.add(w,T),E=e.add(D,F);y=e.mul(y,E),E=e.add(S,R),y=e.sub(y,E),E=e.add(w,P);let I=e.add(D,q);return E=e.mul(E,I),I=e.add(S,A),E=e.sub(E,I),I=e.add(T,P),O=e.add(F,q),I=e.mul(I,O),O=e.add(R,A),I=e.sub(I,O),B=e.mul(ht,E),O=e.mul(_,A),B=e.add(O,B),O=e.sub(R,B),B=e.add(R,B),U=e.mul(O,B),R=e.add(S,S),R=e.add(R,S),A=e.mul(ht,A),E=e.mul(_,E),R=e.add(R,A),A=e.sub(S,A),A=e.mul(ht,A),E=e.add(E,A),S=e.mul(R,E),U=e.add(U,S),S=e.mul(I,E),O=e.mul(y,O),O=e.sub(O,S),S=e.mul(y,R),B=e.mul(I,B),B=e.add(B,S),new g(O,U,B)}subtract(p){return this.add(p.negate())}is0(){return this.equals(g.ZERO)}wNAF(p){return C.wNAFCached(this,p,g.normalizeZ)}multiplyUnsafe(p){let{endo:w,n:T}=t;Wt("scalar",p,Te,T);let P=g.ZERO;if(p===Te)return P;if(this.is0()||p===bt)return this;if(!w||C.hasPrecomputes(this))return C.wNAFCachedUnsafe(this,p,g.normalizeZ);let{k1neg:D,k1:F,k2neg:q,k2:O}=w.splitScalar(p),U=P,B=P,ht=this;for(;F>Te||O>Te;)F&bt&&(U=U.add(ht)),O&bt&&(B=B.add(ht)),ht=ht.double(),F>>=bt,O>>=bt;return D&&(U=U.negate()),q&&(B=B.negate()),B=new g(e.mul(B.px,w.beta),B.py,B.pz),U.add(B)}multiply(p){let{endo:w,n:T}=t;Wt("scalar",p,bt,T);let P,D;if(w){let{k1neg:F,k1:q,k2neg:O,k2:U}=w.splitScalar(p),{p:B,f:ht}=this.wNAF(q),{p:_,f:S}=this.wNAF(U);B=C.constTimeNegate(F,B),_=C.constTimeNegate(O,_),_=new g(e.mul(_.px,w.beta),_.py,_.pz),P=B.add(_),D=ht.add(S)}else{let{p:F,f:q}=this.wNAF(p);P=F,D=q}return g.normalizeZ([P,D])[0]}multiplyAndAddUnsafe(p,w,T){let P=g.BASE,D=(q,O)=>O===Te||O===bt||!q.equals(P)?q.multiplyUnsafe(O):q.multiply(O),F=D(this,w).add(D(p,T));return F.is0()?void 0:F}toAffine(p){return m(this,p)}isTorsionFree(){let{h:p,isTorsionFree:w}=t;if(p===bt)return!0;if(w)return w(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:p,clearCofactor:w}=t;return p===bt?this:w?w(g,this):this.multiplyUnsafe(t.h)}toRawBytes(p=!0){return de("isCompressed",p),this.assertValidity(),o(g,this,p)}toHex(p=!0){return de("isCompressed",p),Ke(this.toRawBytes(p))}}g.BASE=new g(t.Gx,t.Gy,e.ONE),g.ZERO=new g(e.ZERO,e.ONE,e.ZERO);let{endo:b,nBitLength:v}=t,C=Zo(g,b?Math.ceil(v/2):v);return{CURVE:t,ProjectivePoint:g,normPrivateKeyToScalar:f,weierstrassEquation:i,isWithinCurveOrder:l}}function $g(r){let t=Mn(r);return _e(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function dd(r){let t=$g(r),{Fp:e,n,nByteLength:o,nBitLength:s}=t,i=e.BYTES+1,a=2*e.BYTES+1;function c(_){return rt(_,n)}function u(_){return Yo(_,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:f,weierstrassEquation:d,isWithinCurveOrder:m}=Hg({...t,toBytes(_,S,R){let A=S.toAffine(),y=e.toBytes(A.x),E=qe;return de("isCompressed",R),R?E(Uint8Array.from([S.hasEvenY()?2:3]),y):E(Uint8Array.from([4]),y,e.toBytes(A.y))},fromBytes(_){let S=_.length,R=_[0],A=_.subarray(1);if(S===i&&(R===2||R===3)){let y=Se(A);if(!Xo(y,bt,e.ORDER))throw new Error("Point is not on curve");let E=d(y),I;try{I=e.sqrt(E)}catch(V){let $=V instanceof Error?": "+V.message:"";throw new Error("Point is not on curve"+$)}let N=(I&bt)===bt;return(R&1)===1!==N&&(I=e.neg(I)),{x:y,y:I}}else if(S===a&&R===4){let y=e.fromBytes(A.subarray(0,e.BYTES)),E=e.fromBytes(A.subarray(e.BYTES,2*e.BYTES));return{x:y,y:E}}else{let y=i,E=a;throw new Error("invalid Point, expected length of "+y+", or uncompressed "+E+", got "+S)}}});function h(_){let S=n>>bt;return _>S}function g(_){return h(_)?c(-_):_}let b=(_,S,R)=>Se(_.slice(S,R));class v{constructor(S,R,A){Wt("r",S,bt,n),Wt("s",R,bt,n),this.r=S,this.s=R,A!=null&&(this.recovery=A),Object.freeze(this)}static fromCompact(S){let R=o;return S=nt("compactSignature",S,R*2),new v(b(S,0,R),b(S,R,2*R))}static fromDER(S){let{r:R,s:A}=Ce.toSig(nt("DER",S));return new v(R,A)}assertValidity(){}addRecoveryBit(S){return new v(this.r,this.s,S)}recoverPublicKey(S){let{r:R,s:A,recovery:y}=this,E=P(nt("msgHash",S));if(y==null||![0,1,2,3].includes(y))throw new Error("recovery id invalid");let I=y===2||y===3?R+t.n:R;if(I>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let N=(y&1)===0?"02":"03",K=l.fromHex(N+qc(I,e.BYTES)),V=u(I),$=c(-E*V),X=c(A*V),J=l.BASE.multiplyAndAddUnsafe(K,$,X);if(!J)throw new Error("point at infinify");return J.assertValidity(),J}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return kn(this.toDERHex())}toDERHex(){return Ce.hexFromSig(this)}toCompactRawBytes(){return kn(this.toCompactHex())}toCompactHex(){let S=o;return qc(this.r,S)+qc(this.s,S)}}let C={isValidPrivateKey(_){try{return f(_),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let _=ec(t.n);return kf(t.randomBytes(_),t.n)},precompute(_=8,S=l.BASE){return S._setWindowSize(_),S.multiply(BigInt(3)),S}};function x(_,S=!0){return l.fromPrivateKey(_).toRawBytes(S)}function p(_){if(typeof _=="bigint")return!1;if(_ instanceof l)return!0;let R=nt("key",_).length,A=e.BYTES,y=A+1,E=2*A+1;if(!(t.allowedPrivateKeyLengths||o===y))return R===y||R===E}function w(_,S,R=!0){if(p(_)===!0)throw new Error("first arg must be private key");if(p(S)===!1)throw new Error("second arg must be public key");return l.fromHex(S).multiply(f(_)).toRawBytes(R)}let T=t.bits2int||function(_){if(_.length>8192)throw new Error("input is too large");let S=Se(_),R=_.length*8-s;return R>0?S>>BigInt(R):S},P=t.bits2int_modN||function(_){return c(T(_))},D=er(s);function F(_){return Wt("num < 2^"+s,_,Te,D),tr(_,o)}function q(_,S,R=O){if(["recovered","canonical"].some(ut=>ut in R))throw new Error("sign() legacy options not supported");let{hash:A,randomBytes:y}=t,{lowS:E,prehash:I,extraEntropy:N}=R;E==null&&(E=!0),_=nt("msgHash",_),fd(R),I&&(_=nt("prehashed msgHash",A(_)));let K=P(_),V=f(S),$=[F(V),F(K)];if(N!=null&&N!==!1){let ut=N===!0?y(e.BYTES):N;$.push(nt("extraEntropy",ut))}let X=qe(...$),J=K;function pt(ut){let wt=T(ut);if(!m(wt))return;let Ut=u(wt),gt=l.BASE.multiply(wt).toAffine(),At=c(gt.x);if(At===Te)return;let Vt=c(Ut*c(J+At*V));if(Vt===Te)return;let Qt=(gt.x===At?0:2)|Number(gt.y&bt),gn=Vt;return E&&h(Vt)&&(gn=g(Vt),Qt^=1),new v(At,gn,Qt)}return{seed:X,k2sig:pt}}let O={lowS:t.lowS,prehash:!1},U={lowS:t.lowS,prehash:!1};function B(_,S,R=O){let{seed:A,k2sig:y}=q(_,S,R),E=t;return _f(E.hash.outputLen,E.nByteLength,E.hmac)(A,y)}l.BASE._setWindowSize(8);function ht(_,S,R,A=U){let y=_;S=nt("msgHash",S),R=nt("publicKey",R);let{lowS:E,prehash:I,format:N}=A;if(fd(A),"strict"in A)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 K=typeof y=="string"||qr(y),V=!K&&!N&&typeof y=="object"&&y!==null&&typeof y.r=="bigint"&&typeof y.s=="bigint";if(!K&&!V)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let $,X;try{if(V&&($=new v(y.r,y.s)),K){try{N!=="compact"&&($=v.fromDER(y))}catch(Qt){if(!(Qt instanceof Ce.Err))throw Qt}!$&&N!=="der"&&($=v.fromCompact(y))}X=l.fromHex(R)}catch{return!1}if(!$||E&&$.hasHighS())return!1;I&&(S=t.hash(S));let{r:J,s:pt}=$,ut=P(S),wt=u(pt),Ut=c(ut*wt),gt=c(J*wt),At=l.BASE.multiplyAndAddUnsafe(X,Ut,gt)?.toAffine();return At?c(At.x)===J:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:w,sign:B,verify:ht,ProjectivePoint:l,Signature:v,utils:C}}function Wg(r){return{hash:r,hmac:(t,...e)=>Kc(r,t,Va(...e)),randomBytes:Kr}}function hd(r,t){let e=n=>dd({...r,...Wg(n)});return{...e(t),create:e}}var gd=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),pd=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Gg=BigInt(0),jg=BigInt(1),Hc=BigInt(2),md=(r,t)=>(r+t/Hc)/t;function Xg(r){let t=gd,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%t,l=u*u*r%t,f=ot(l,e,t)*l%t,d=ot(f,e,t)*l%t,m=ot(d,Hc,t)*u%t,h=ot(m,o,t)*m%t,g=ot(h,s,t)*h%t,b=ot(g,a,t)*g%t,v=ot(b,c,t)*b%t,C=ot(v,a,t)*g%t,x=ot(C,e,t)*l%t,p=ot(x,i,t)*h%t,w=ot(p,n,t)*u%t,T=ot(w,Hc,t);if(!$c.eql($c.sqr(T),r))throw new Error("Cannot find square root");return T}var $c=Ie(gd,void 0,void 0,{sqrt:Xg}),ae=hd({a:Gg,b:BigInt(7),Fp:$c,n:pd,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=pd,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-jg*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=md(s*r,t),c=md(-n*r,t),u=rt(r-a*e-c*o,t),l=rt(-a*n-c*s,t),f=u>i,d=l>i;if(f&&(u=t-u),d&&(l=t-l),u>i||l>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:u,k2neg:d,k2:l}}}},jo);function yd(r,t,e){let n=Br.digest(t instanceof Uint8Array?t:t.subarray());if(Wr(n))return n.then(({digest:o})=>(e?.signal?.throwIfAborted(),ae.sign(o,r).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new Nn(String(o))});try{return ae.sign(n.digest,r).toDERRawBytes()}catch(o){throw new Nn(String(o))}}function bd(r,t,e,n){let o=Br.digest(e instanceof Uint8Array?e:e.subarray());if(Wr(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),ae.verify(t,s,r))).catch(s=>{throw s.name==="AbortError"?s:new Bn(String(s))});try{return n?.signal?.throwIfAborted(),ae.verify(t,o.digest,r)}catch(s){throw new Bn(String(s))}}var $n=class{type="secp256k1";raw;_key;constructor(t){this._key=Ed(t),this.raw=wd(this._key)}toMultihash(){return re.digest(Xt(this))}toCID(){return it.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:tt(this.raw,t.raw)}verify(t,e,n){return bd(this._key,e,t,n)}},cs=class{type="secp256k1";raw;publicKey;constructor(t,e){this.raw=xd(t),this.publicKey=new $n(e??vd(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:tt(this.raw,t.raw)}sign(t,e){return yd(this.raw,t,e)}};function Wc(r){return new $n(r)}async function Ad(){let r=Yg();return new cs(r)}function wd(r){return ae.ProjectivePoint.fromHex(r).toRawBytes(!0)}function xd(r){try{return ae.getPublicKey(r,!0),r}catch(t){throw new yn(String(t))}}function Ed(r){try{return ae.ProjectivePoint.fromHex(r),r}catch(t){throw new Tr(String(t))}}function vd(r){try{return ae.getPublicKey(r,!0)}catch(t){throw new yn(String(t))}}function Yg(){return ae.utils.randomPrivateKey()}async function Sd(r,t){if(r==="Ed25519")return Xf();if(r==="secp256k1")return Ad();if(r==="RSA")return Uc(Zg(t));if(r==="ECDSA")return nf(Qg(t));throw new Oe}function Yr(r,t){let{Type:e,Data:n}=pe.decode(r),o=n??new Uint8Array;switch(e){case ft.RSA:return Nc(o,t);case ft.Ed25519:return lc(o);case ft.secp256k1:return Wc(o);case ft.ECDSA:return za(o);default:throw new Oe}}function _d(r){let{Type:t,Data:e}=pe.decode(r.digest),n=e??new Uint8Array;switch(t){case ft.Ed25519:return lc(n);case ft.secp256k1:return Wc(n);case ft.ECDSA:return za(n);default:throw new Oe}}function Xt(r){return pe.encode({Type:ft[r.type],Data:r.raw})}function Zg(r){return r==null?2048:parseInt(r,10)}function Qg(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 k("Unsupported curve, should be P-256, P-384 or P-521")}var Id=Symbol.for("nodejs.util.inspect.custom"),Jg=114,Wn=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()})`}[Lo]=!0;toString(){return this.string==null&&(this.string=j.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return it.createV1(Jg,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return tt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return tt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Id](){return`PeerId(${this.toString()})`}},Gn=class extends Wn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},jn=class extends Wn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Xn=class extends Wn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},t0=2336,Yn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=re.digest(L(this.url))}[Id](){return`PeerId(${this.url})`}[Lo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return it.createV1(t0,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=M(t)),t.toString()===this.toString())}};var e0=114,Cd=2336;function me(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=ee(j.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Zn(it.parse(r));if(t==null)throw new k('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=ee(t.decode(r))}return Zr(e)}function Gc(r){if(r.type==="Ed25519")return new jn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Xn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Gn({multihash:r.toCID().multihash,publicKey:r});throw new Oe}function Td(r){return Gc(r.publicKey)}function Zr(r){if(n0(r))return new Gn({multihash:r});if(r0(r))try{let t=_d(r);if(t.type==="Ed25519")return new jn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Xn({multihash:r,publicKey:t})}catch{let e=M(r.digest);return new Yn(new URL(e))}throw new ko("Supplied PeerID Multihash is invalid")}function Zn(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==e0&&r.code!==Cd)throw new Ro("Supplied PeerID CID is invalid");if(r.code===Cd){let t=M(r.multihash.digest);return new Yn(new URL(t))}return Zr(r.multihash)}function r0(r){return r.code===re.code}function n0(r){return r.code===Br.code}function Qr(r){if(typeof r!="object"||r===null)return!1;let t=Object.getPrototypeOf(r);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)}var{hasOwnProperty:Ld}=Object.prototype,{propertyIsEnumerable:o0}=Object,Jr=(r,t,e)=>{Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0})},s0=void 0,Pd={concatArrays:!1,ignoreUndefined:!1},ls=r=>{let t=[];for(let e in r)Ld.call(r,e)&&t.push(e);if(Object.getOwnPropertySymbols){let e=Object.getOwnPropertySymbols(r);for(let n of e)o0.call(r,n)&&t.push(n)}return t};function tn(r){return Array.isArray(r)?i0(r):Qr(r)?a0(r):r}function i0(r){let t=r.slice(0,0);return ls(r).forEach(e=>{Jr(t,e,tn(r[e]))}),t}function a0(r){let t=Object.getPrototypeOf(r)===null?Object.create(null):{};return ls(r).forEach(e=>{Jr(t,e,tn(r[e]))}),t}var Dd=(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),c0=(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++)Ld.call(s,a)&&(i.push(String(a)),s===r?Jr(n,o++,s[a]):Jr(n,o++,tn(s[a])));n=Dd(n,s,ls(s).filter(a=>!i.includes(a)),e)}),n};function jc(r,t,e){return e.concatArrays&&Array.isArray(r)&&Array.isArray(t)?c0(r,t,e):!Qr(t)||!Qr(r)?tn(t):Dd(r,t,ls(t),e)}function us(...r){let t=jc(tn(Pd),this!==s0&&this||{},Pd),e={_:{}};for(let n of r)if(n!==void 0){if(!Qr(n))throw new TypeError("`"+n+"` is not an Option Object");e=jc(e,{_:n},t)}return e._}var dt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Yc=Po(kd(),1);var Jn=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Zc=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Md=r=>globalThis.DOMException===void 0?new Zc(r):new DOMException(r),Od=r=>{let t=r.reason===void 0?Md("This operation was aborted."):r.reason;return t instanceof Error?t:Md(t)};function Qc(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,a,u=new Promise((l,f)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:m}=t;m.aborted&&f(Od(m)),a=()=>{f(Od(m))},m.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(l,f);return}let d=new Jn;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(m){f(m)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?f(o):(d.message=o??`Promise timed out after ${e} milliseconds`,f(d))},e),(async()=>{try{l(await r)}catch(m){f(m)}})()}).finally(()=>{u.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return u.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},u}function Jc(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 to=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=Jc(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 eo=class extends Yc.default{#t;#e;#r=0;#a;#c;#p=0;#o;#l;#n;#m;#s=0;#u;#i;#g;#w=1n;timeout;constructor(t){if(super(),t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:to,...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")}#A(){this.#b(),this.#y(),this.#l=void 0}get#S(){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.#A()},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.#S;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.#b()},this.#c),this.#p=Date.now()+this.#c)}#b(){this.#r===0&&this.#s===0&&this.#o&&(clearInterval(this.#o),this.#o=void 0),this.#r=this.#t?this.#s:0,this.#d()}#d(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#u=t,this.#d()}async#_(t){return new Promise((e,n)=>{t.addEventListener("abort",()=>{n(t.reason)},{once:!0})})}setPriority(t,e){this.#n.setPriority(t,e)}async add(t,e={}){return e.id??=(this.#w++).toString(),e={timeout:this.timeout,throwOnTimeout:this.#g,...e},new Promise((n,o)=>{this.#n.enqueue(async()=>{this.#s++,this.#r++;try{e.signal?.throwIfAborted();let s=t({signal:e.signal});e.timeout&&(s=Qc(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 Jn&&!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 ds(r){let t=[jt.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var tl=60;function hs(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:jt[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:jt[t.type],TTL:t.TTL??t.ttl??tl,data:t.data instanceof Uint8Array?M(t.data):t.data}))}}var f0=4;function el(r,t={}){let e=new eo({concurrency:t.queryConcurrency??f0});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),ds(o.types).forEach(a=>{s.append("type",jt[a])}),o.onProgress?.(new dt("dns:query",{detail:n}));let i=await e.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=hs(await a.json());return o.onProgress?.(new dt("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function Nd(){return[el("https://cloudflare-dns.com/dns-query"),el("https://dns.google/resolve")]}var Ud=Po(Fd(),1);var rl=class{lru;constructor(t){this.lru=(0,Ud.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 hs({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:jt[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??tl)*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 Kd(r){return new rl(r)}var d0=1e3,ps=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=Kd(t.cacheSize??d0),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["."]=Nd())}async query(t,e={}){let n=ds(e.types),o=e.cached!==!1?this.cache.get(t,n):void 0;if(o!=null)return e.onProgress?.(new dt("dns:cache",{detail:o})),o;let s=`${t.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(e.signal?.aborted===!0)break;try{let u=await c(t,{...e,types:n});for(let l of u.Answer)this.cache.add(t,l);return u}catch(u){a.push(u),e.onProgress?.(new dt("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${t} ${n} failed`)}};var jt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(jt||(jt={}));function qd(r={}){return new ps(r)}var ms=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});if(l===void 0)break;if(s*=t,s+=l,s>u||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var zd=45,h0=15,en=new ms;function gs(r){if(!(r.length>h0))return en.new(r).parseWith(()=>en.readIPv4Addr())}function ys(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>zd))return en.new(r).parseWith(()=>en.readIPv6Addr())}function ar(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>zd)return;let e=en.new(r).parseWith(()=>en.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 Vd(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 Hd(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 nl(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 $d(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 Wd(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,Jv=parseInt("0xFFFF",16),p0=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function ro(r,t){t.length===lr&&r.length===cr&&Vd(t,0,11)&&(t=t.slice(12)),t.length===cr&&r.length===lr&&Hd(r,p0,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 Gd(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 ol(r){let[t,e]=r.split("/");if(!t||!e)throw new Error("Failed to parse given CIDR: "+r);let n=cr,o=gs(t);if(o==null&&(n=lr,o=ys(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=sl(s,8*n);return{network:ro(o,i),mask:i}}function sl(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 rn=class{constructor(t,e){if(e==null)({network:this.network,mask:this.mask}=ol(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=sl(o,8*n.length);this.network=ro(n,this.mask)}}contains(t){return Gd({network:this.network,mask:this.mask},t)}toString(){let t=$d(this.mask),e=t!==-1?String(t):Wd(this.mask);return nl(this.network)+"/"+e}};function ce(r){return!!gs(r)}function nn(r){return!!ys(r)}function bs(r){return!!ar(r)}var jd=ce,m0=nn,il=function(r){let t=0;if(r=r.toString().trim(),jd(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(m0(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=jd(e[n]),i;s&&(i=il(e[n]),e[n]=M(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,M(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let s=parseInt(e[n],16);o[t++]=s>>8&255,o[t++]=s&255}return o}throw new Error("invalid ip address")},Xd=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 on={},al={},y0=[[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"]];y0.forEach(r=>{let t=b0(...r);al[t.code]=t,on[t.name]=t});function b0(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function W(r){if(typeof r=="number"){if(al[r]!=null)return al[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(on[r]!=null)return on[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var w0=W("ip4"),x0=W("ip6"),E0=W("ipcidr");function fl(r,t){switch(W(r).code){case 4:case 41:return A0(t);case 42:return ul(t);case 43:return M(t,"base10");case 6:case 273:case 33:case 132:return Qd(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ul(t);case 421:return C0(t);case 444:return Zd(t);case 445:return Zd(t);case 466:return I0(t);case 481:return globalThis.encodeURIComponent(ul(t));default:return M(t,"base16")}}function dl(r,t){switch(W(r).code){case 4:return Yd(t);case 41:return Yd(t);case 42:return ll(t);case 43:return L(t,"base10");case 6:case 273:case 33:case 132:return pl(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ll(t);case 421:return S0(t);case 444:return T0(t);case 445:return P0(t);case 466:return _0(t);case 481:return ll(globalThis.decodeURIComponent(t));default:return L(t,"base16")}}function hl(r){let t,e;if(r.stringTuples().forEach(([n,o])=>{(n===w0.code||n===x0.code)&&(e=o),n===E0.code&&(t=o)}),t==null||e==null)throw new Error("Invalid multiaddr");return new rn(e,t)}var cl=Object.values(Sn).map(r=>r.decoder),v0=function(){let r=cl[0].or(cl[1]);return cl.slice(2).forEach(t=>r=r.or(t)),r}();function Yd(r){if(!bs(r))throw new Error("invalid ip address");return il(r)}function A0(r){let t=Xd(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!bs(t))throw new Error("invalid ip address");return t}function pl(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Qd(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function ll(r){let t=L(r),e=Uint8Array.from(It(t.length));return Dt([e,t],e.length+t.length)}function ul(r){let t=se(r);if(r=r.slice(mt(t)),r.length!==t)throw new Error("inconsistent lengths");return M(r)}function S0(r){let t;r[0]==="Q"||r[0]==="1"?t=ee(j.decode(`z${r}`)).bytes:t=it.parse(r).multihash.bytes;let e=Uint8Array.from(It(t.length));return Dt([e,t],e.length+t.length)}function _0(r){let t=v0.decode(r),e=Uint8Array.from(It(t.length));return Dt([e,t],e.length+t.length)}function I0(r){let t=se(r),e=r.slice(mt(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+M(e,"base64url")}function C0(r){let t=se(r),e=r.slice(mt(t));if(e.length!==t)throw new Error("inconsistent lengths");return M(e,"base58btc")}function T0(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=$t.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=pl(n);return Dt([e,o],e.length+o.length)}function P0(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=$t.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=pl(n);return Dt([e,o],e.length+o.length)}function Zd(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=M(t,"base32"),o=Qd(e);return`${n}:${o}`}function Jd(r){r=ml(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=W(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw new ws("invalid address: "+r);if(a.path===!0){n=ml(o.slice(s).join("/")),t.push([a.code,dl(a.code,n)]),e.push([a.code,n]);break}let c=dl(a.code,o[s]);t.push([a.code,c]),e.push([a.code,fl(a.code,c)])}return{string:th(e),bytes:xs(t),tuples:t,stringTuples:e,path:n}}function gl(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=se(r,o),i=mt(s),a=W(s),c=L0(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw new ws("Invalid address Uint8Array: "+M(r,"base16"));t.push([s,u]);let l=fl(s,u);if(e.push([s,l]),a.path===!0){n=l;break}}return{bytes:Uint8Array.from(r),string:th(e),tuples:t,stringTuples:e,path:n}}function th(r){let t=[];return r.map(e=>{let n=W(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),ml(t.join("/"))}function xs(r){return Dt(r.map(t=>{let e=W(t[0]),n=Uint8Array.from(It(e.code));return t.length>1&&t[1]!=null&&(n=Dt([n,t[1]])),n}))}function L0(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=se(t instanceof Uint8Array?t:Uint8Array.from(t));return e+mt(e)}}function ml(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var ws=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var D0=Symbol.for("nodejs.util.inspect.custom"),bl=Symbol.for("@multiformats/js-multiaddr/multiaddr"),R0=[W("dns").code,W("dns4").code,W("dns6").code,W("dnsaddr").code],yl=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},Es=class r{bytes;#t;#e;#r;#a;[bl]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=gl(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Jd(t)}else if(Ve(t))e=gl(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=W("tcp"),a=W("udp"),c=W("ip4"),u=W("ip6"),l=W("dns6"),f=W("ip6zone");for(let[m,h]of this.stringTuples())m===f.code&&(s=`%${h??""}`),R0.includes(m)&&(e=i.name==="tcp"?"tcp":"udp",o=443,n=`${h??""}${s}`,t=m===l.code?6:4),(m===i.code||m===a.code)&&(e=W(m).name==="tcp"?"tcp":"udp",o=parseInt(h??"")),(m===c.code||m===u.code)&&(e=W(m).name==="tcp"?"tcp":"udp",n=`${h??""}${s}`,t=m===u.code?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}protos(){return this.#e.map(([t])=>Object.assign({},W(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>W(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(xs(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===on.p2p.code&&t.push([n,o]),n===on["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?M(j.decode(`z${n}`),"base58btc"):M(it.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(t){return tt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=sn.get(e.name);if(n==null)throw new yl(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>G(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)}[D0](){return`Multiaddr(${this.#t})`}};var sn=new Map;function Ve(r){return!!r?.[bl]}function G(r){return new Es(r)}var k0=32,{code:M0}=W("dnsaddr"),wl=class extends Error{constructor(t="Max recursive depth reached"){super(t),this.name="RecursionLimitError"}},ur=async function(t,e={}){let n=e.maxRecursiveDepth??k0;if(n===0)throw new wl("Max recursive depth reached");let[,o]=t.stringTuples().find(([u])=>u===M0)??[],i=await(e?.dns??qd()).query(`_dnsaddr.${o}`,{signal:e?.signal,types:[jt.TXT]}),a=t.getPeerId(),c=[];for(let u of i.Answer){let l=u.data.replace(/["']/g,"").trim().split("=")[1];if(l==null||a!=null&&!l.includes(a))continue;let f=G(l);if(l.startsWith("/dnsaddr")){let d=await f.resolve({...e,maxRecursiveDepth:n-1});c.push(...d.map(m=>m.toString()))}else c.push(f.toString())}return c};var O0={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:ur}},transportManager:{faultTolerance:We.FATAL_ALL}};async function eh(r){let t=us(O0,r);if(t.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new k("Private network is enforced, but no protector was provided");return t}function N0(r,t){try{if(typeof r=="string"&&r.length>0)return B0(r);if(typeof r=="number"&&isFinite(r))return t?.long?U0(r):F0(r);throw new Error("Value is not a string or number.")}catch(e){let n=K0(e)?`${e.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function B0(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!t)return NaN;let e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*315576e5;case"weeks":case"week":case"w":return e*6048e5;case"days":case"day":case"d":return e*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return e*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return e*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return e*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var As=N0;function F0(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 U0(r){let t=Math.abs(r);return t>=864e5?vs(r,t,864e5,"day"):t>=36e5?vs(r,t,36e5,"hour"):t>=6e4?vs(r,t,6e4,"minute"):t>=1e3?vs(r,t,1e3,"second"):`${r} ms`}function vs(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function K0(r){return typeof r=="object"&&r!==null&&"message"in r}function xl(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=o,e.enabled=i,e.humanize=As,e.destroy=u,Object.keys(r).forEach(l=>{e[l]=r[l]}),e.names=[],e.skips=[],e.formatters={};function t(l){let f=0;for(let d=0;d<l.length;d++)f=(f<<5)-f+l.charCodeAt(d),f|=0;return e.colors[Math.abs(f)%e.colors.length]}e.selectColor=t;function e(l){let f,d=null,m,h;function g(...b){if(!g.enabled)return;let v=g,C=Number(new Date),x=C-(f||C);v.diff=x,v.prev=f,v.curr=C,f=C,b[0]=e.coerce(b[0]),typeof b[0]!="string"&&b.unshift("%O");let p=0;b[0]=b[0].replace(/%([a-zA-Z%])/g,(T,P)=>{if(T==="%%")return"%";p++;let D=e.formatters[P];if(typeof D=="function"){let F=b[p];T=D.call(v,F),b.splice(p,1),p--}return T}),e.formatArgs.call(v,b),(v.log||e.log).apply(v,b)}return g.namespace=l,g.useColors=e.useColors(),g.color=e.selectColor(l),g.extend=n,g.destroy=e.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(m!==e.namespaces&&(m=e.namespaces,h=e.enabled(l)),h),set:b=>{d=b}}),typeof e.init=="function"&&e.init(g),g}function n(l,f){let d=e(this.namespace+(typeof f>"u"?":":f)+l);return d.log=this.log,d}function o(l){e.save(l),e.namespaces=l,e.names=[],e.skips=[];let f,d=(typeof l=="string"?l:"").split(/[\s,]+/),m=d.length;for(f=0;f<m;f++)d[f]&&(l=d[f].replace(/\*/g,".*?"),l[0]==="-"?e.skips.push(new RegExp("^"+l.substr(1)+"$")):e.names.push(new RegExp("^"+l+"$")))}function s(){let l=[...e.names.map(a),...e.skips.map(a).map(f=>"-"+f)].join(",");return e.enable(""),l}function i(l){if(l[l.length-1]==="*")return!0;let f,d;for(f=0,d=e.skips.length;f<d;f++)if(e.skips[f].test(l))return!1;for(f=0,d=e.names.length;f<d;f++)if(e.names[f].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack??l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return e.setupFormatters(e.formatters),e.enable(e.load()),e}var Ss=G0(),q0=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function z0(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function V0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+As(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 H0=console.debug??console.log??(()=>{});function $0(r){try{r?Ss?.setItem("debug",r):Ss?.removeItem("debug")}catch{}}function W0(){let r;try{r=Ss?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function G0(){try{return localStorage}catch{}}function j0(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var rh=xl({formatArgs:V0,save:$0,load:W0,useColors:z0,setupFormatters:j0,colors:q0,storage:Ss,log:H0});var zt=rh;zt.formatters.b=r=>r==null?"undefined":j.baseEncode(r);zt.formatters.t=r=>r==null?"undefined":$t.baseEncode(r);zt.formatters.m=r=>r==null?"undefined":Pa.baseEncode(r);zt.formatters.p=r=>r==null?"undefined":r.toString();zt.formatters.c=r=>r==null?"undefined":r.toString();zt.formatters.k=r=>r==null?"undefined":r.toString();zt.formatters.a=r=>r==null?"undefined":r.toString();zt.formatters.e=r=>r==null?"undefined":nh(r.stack)??nh(r.message)??r.toString();function X0(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 _s(){return{forComponent(r){return Y0(r)}}}function Y0(r){let t=X0(`${r}:trace`);return zt.enabled(`${r}:trace`)&&zt.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=zt(`${r}:trace`)),Object.assign(zt(r),{error:zt(`${r}:error`),trace:t})}function nh(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 Is(r){let t=ee(j.decode(`z${r}`));return Zr(t)}var Yt=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=Is(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=Is(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return fr(this.set.values(),t=>Is(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},oh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},sh=new globalThis.TextEncoder;function Z0(r,t){let e=El[t],n=oh[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function Q0(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=oh[t],s=r;for(;s.length>0;){let i=sh.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 vl(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 Q0(r,t,e);r=sh.encode(r)}return Z0(r,t)}var no={hash:r=>Number(vl(r,{size:32})),hashV:(r,t)=>J0(no.hash(r,t))};function J0(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),L(t,"base16")}var Al=64,le=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Al)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=ct(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?tt(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 le))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof le))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 le))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 le))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var ty=500,oo=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??no,this.seed=t.seed??hr(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=L(t));let e=new le(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<ty;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=L(t));let e=new le(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=L(t));let e=new le(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}},ey={1:.5,2:.84,4:.95,8:.98};function ry(r=.001){return r>.002?2:r>1e-5?4:8}function ih(r,t=.001){let e=ry(t),n=ey[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Al);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var Cs=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??no,this.seed=t.seed??hr(0,Math.pow(2,10)),this.filterSeries=[new oo({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=L(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 oo({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=L(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=L(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 so(r,t=.001,e){return new Cs({...ih(r,t),...e??{}})}var Sl=class extends Yt{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 _l(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Sl({name:t,metrics:e}):n=new Yt,n}var io;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&e.payload.byteLength>0&&(n.uint32(26),n.bytes(e.payload)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={publicKey:ct(0),payloadType:ct(0),payload:ct(0),signature:ct(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.payloadType=e.bytes();break}case 3:{s.payload=e.bytes();break}case 5:{s.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Nt(e,r.codec()),r.decode=(e,n)=>Ot(e,r.codec(),n)})(io||(io={}));var Ts=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var an=class r{static createFromProtobuf=t=>{let e=io.decode(t),n=Yr(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e,n)=>{if(e==null)throw new Error("Missing private key");let o=t.domain,s=t.codec,i=t.marshal(),a=ah(o,s,i),c=await e.sign(a.subarray(),n);return new r({publicKey:e.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(t,e,n)=>{let o=r.createFromProtobuf(t);if(!await o.validate(e,n))throw new Ts("Envelope signature is not valid for the given domain");return o};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=io.encode({publicKey:Xt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return t==null?!1:tt(this.marshal(),t.marshal())}async validate(t,e){let n=ah(t,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,e)}},ah=(r,t,e)=>{let n=L(r),o=It(n.byteLength),s=It(t.length),i=It(e.length);return new Y(o,n,s,t,i,e)};function ch(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 lh="libp2p-peer-record",uh=Uint8Array.from([3,1]);var ao;(function(r){let t;(function(n){let o;n.codec=()=>(o==null&&(o=Bt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:ct(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(l&7);break}}}return c})),o),n.encode=s=>Nt(s,n.codec()),n.decode=(s,i)=>Ot(s,n.codec(),i)})(t=r.AddressInfo||(r.AddressInfo={}));let e;r.codec=()=>(e==null&&(e=Bt((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o,s={})=>{let i={peerId:ct(0),seq:0n,addresses:[]},a=o==null?n.len:n.pos+o;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new 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=>Nt(n,r.codec()),r.decode=(n,o)=>Ot(n,r.codec(),o)})(ao||(ao={}));var mr=class r{static createFromProtobuf=t=>{let e=ao.decode(t),n=Zr(ee(e.peerId)),o=(e.addresses??[]).map(i=>G(i.multiaddr)),s=e.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=lh;static CODEC=uh;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=ao.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||!ch(this.multiaddrs,t.multiaddrs))}};function ny(r){return r[Symbol.asyncIterator]!=null}function oy(r){if(ny(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 co=oy;var ue=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};function lt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Ps=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}},cn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Ps(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 Ps(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 Il=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Ls(r={}){return sy(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 sy(r,t){t=t??{};let e=t.onEnd,n=new cn,o,s,i,a=lt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((b,v)=>{s=C=>{s=null,n.push(C);try{b(r(n))}catch(x){v(x)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=lt()})}},u=b=>s!=null?s(b):(n.push(b),o),l=b=>(n=new cn,s!=null?s({error:b}):(n.push({error:b}),o)),f=b=>{if(i)return o;if(t?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:b})},d=b=>i?o:(i=!0,b!=null?l(b):u({done:!0})),m=()=>(n=new cn,d(),{done:!0}),h=b=>(d(b),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:h,push:f,end:d,get readableLength(){return n.size},onEmpty:async b=>{let v=b?.signal;if(v?.throwIfAborted(),n.isEmpty())return;let C,x;v!=null&&(C=new Promise((p,w)=>{x=()=>{w(new Il)},v.addEventListener("abort",x)}));try{await Promise.race([a.promise,C])}finally{x!=null&&v!=null&&v?.removeEventListener("abort",x)}}},e==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(b){return g.throw(b),e!=null&&(e(b),e=void 0),{done:!0}},return(){return g.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(b){return g.end(b),e!=null&&(e(b),e=void 0),o},get readableLength(){return g.readableLength},onEmpty:b=>g.onEmpty(b)},o}var Cl=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 ge(r,t,e,n){let o=new Cl(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){e?.removeEventListener("abort",l),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),i(d);return}a(),s(f)},u=f=>{a(),i(f.detail)},l=()=>{a(),i(o)};e?.addEventListener("abort",l),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var Ds=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var Rs=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 Et(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new Rs(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new Rs(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 ks=class{deferred;signal;constructor(t){this.signal=t,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new ue)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function iy(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ms=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=iy(),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 ue),this.cleanup())}async join(t={}){let e=new ks(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 Et(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)})}};function Tl(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 lo=class extends Ht{concurrency;maxSize;queue;pending;sort;autoStart;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=t.autoStart??!0,this.sort=t.sort,this.queue=[],this.emitEmpty=Tl(this.emitEmpty.bind(this),1),this.emitIdle=Tl(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let 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.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Ds;let n=new Ms(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new ue)}),this.clear()}async onEmpty(t){this.size!==0&&await ge(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await ge(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await ge(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=Ls({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new ue("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var Os="lock:worker:request-read",Ns="lock:worker:abort-read-request",Bs="lock:worker:release-read",Fs="lock:master:grant-read",Us="lock:master:error-read",Ks="lock:worker:request-write",qs="lock:worker:abort-write-request",zs="lock:worker:release-write",Vs="lock:master:grant-write",Hs="lock:master:error-write",$s="lock:worker:finalize",Ws="mortice",fh={singleProcess:!1};var Pl=(r,t,e,n,o,s,i,a,c)=>u=>{if(u.data==null)return;let l={type:u.data.type,name:u.data.name,identifier:u.data.identifier};l.type===o&&r.safeDispatchEvent(e,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{t.postMessage({type:c,name:l.name,identifier:l.identifier}),await new Promise(f=>{let d=m=>{if(m?.data==null)return;let h={type:m.data.type,name:m.data.name,identifier:m.data.identifier};h.type===a&&h.identifier===l.identifier&&(t.removeEventListener("message",d),f())};t.addEventListener("message",d)})},onError:f=>{t.postMessage({type:i,name:l.name,identifier:l.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),l.type===s&&r.safeDispatchEvent(n,{detail:{name:l.name,identifier:l.identifier}}),l.type===$s&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}})};var dh=(r=10)=>Math.random().toString().substring(2,r+2);var Gs=class{name;channel;constructor(t){this.name=t,this.channel=new BroadcastChannel(Ws)}readLock(t){return this.sendRequest(Os,Ns,Fs,Us,Bs,t)}writeLock(t){return this.sendRequest(Ks,qs,Vs,Hs,zs,t)}finalize(){this.channel.postMessage({type:$s,name:this.name}),this.channel.close()}async sendRequest(t,e,n,o,s,i){i?.signal?.throwIfAborted();let a=dh();return this.channel.postMessage({type:t,identifier:a,name:this.name}),new Promise((c,u)=>{let l=()=>{this.channel.postMessage({type:e,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",l,{once:!0});let f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",l),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",l);let m=new Error;d.data.error!=null&&(m.message=d.data.error.message,m.name=d.data.error.name,m.stack=d.data.error.stack),u(m)}};this.channel.addEventListener("message",f)})}};var hh=r=>{if(r=Object.assign({},fh,r),!!globalThis.document||r.singleProcess){let e=new BroadcastChannel(Ws),n=new Ht;return e.addEventListener("message",Pl(n,e,"requestReadLock","abortReadLockRequest",Os,Ns,Us,Bs,Fs)),e.addEventListener("message",Pl(n,e,"requestWriteLock","abortWriteLockRequest",Ks,qs,Hs,zs,Vs)),n}return new Gs(r.name)};var gr=new Map,uo;function ph(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function ay(r){if(uo==null&&(uo=hh(r),!ph(uo))){let t=uo;t.addEventListener("requestReadLock",e=>{let n=e.detail.name,o=e.detail.identifier,s=gr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};t.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.signal}).then(async c=>{await e.detail.handler().finally(()=>{c()})}).catch(c=>{e.detail.onError(c)}).finally(()=>{t.removeEventListener("abortReadLockRequest",a)})}),t.addEventListener("requestWriteLock",e=>{let n=e.detail.name,o=e.detail.identifier,s=gr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};t.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.signal}).then(async c=>{await e.detail.handler().finally(()=>{c()})}).catch(c=>{e.detail.onError(c)}).finally(()=>{t.removeEventListener("abortWriteLockRequest",a)})}),t.addEventListener("finalizeRequest",e=>{let n=e.detail.name,o=gr.get(n);o?.finalize()})}return uo}async function Ll(r,t){let e,n,o=new Promise((i,a)=>{e=i,n=a}),s=()=>{n(new ue)};return t?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{e(()=>{t?.signal?.removeEventListener("abort",s),i()})})},{signal:t?.signal}).catch(i=>{n(i)}),o}var mh=(r,t)=>{let e=gr.get(r);if(e!=null)return e;let n=ay(t);if(ph(n))return e=n,gr.set(r,e),e;let o=new lo({concurrency:1}),s;return e={async readLock(i){if(s!=null)return Ll(s,i);s=new lo({concurrency:t.concurrency,autoStart:!1});let a=s,c=Ll(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,Ll(o,i)},finalize:()=>{gr.delete(r)},queue:o},gr.set(r,e),e};var cy={name:"lock",concurrency:1/0,singleProcess:!1};function Dl(r){let t=Object.assign({},cy,r);return mh(t.name,t)}var Pe;(function(r){let t;(function(o){let s;o.codec=()=>(s==null&&(s=Bt((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let u={key:"",value:ct(0)},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let f=i.uint32();switch(f>>>3){case 1:{u.key=i.string();break}case 2:{u.value=i.bytes();break}default:{i.skipType(f&7);break}}}return u})),s),o.encode=i=>Nt(i,o.codec()),o.decode=(i,a)=>Ot(i,o.codec(),a)})(t=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let e;(function(o){let s;o.codec=()=>(s==null&&(s=Bt((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),Xs.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let u={key:""},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let f=i.uint32();switch(f>>>3){case 1:{u.key=i.string();break}case 2:{u.value=Xs.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return u})),s),o.encode=i=>Nt(i,o.codec()),o.decode=(i,a)=>Ot(i,o.codec(),a)})(e=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Bt((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),js.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);o.updated!=null&&(s.uint32(64),s.uint64Number(o.updated)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new ir('Decode error - map field "addresses" had too many elements');a.addresses.push(js.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 zn('Decode error - map field "metadata" had too many elements');let l=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(l.key,l.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new zn('Decode error - map field "tags" had too many elements');let l=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(l.key,l.value);break}case 8:{a.updated=o.uint64Number();break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Nt(o,r.codec()),r.decode=(o,s)=>Ot(o,r.codec(),s)})(Pe||(Pe={}));var js;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.multiaddr!=null&&e.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(e.multiaddr)),e.isCertified!=null&&(n.uint32(16),n.bool(e.isCertified)),e.observed!=null&&(n.uint32(24),n.uint64Number(e.observed)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={multiaddr:ct(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.multiaddr=e.bytes();break}case 2:{s.isCertified=e.bool();break}case 3:{s.observed=e.uint64Number();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Nt(e,r.codec()),r.decode=(e,n)=>Ot(e,r.codec(),n)})(js||(js={}));var Xs;(function(r){let t;r.codec=()=>(t==null&&(t=Bt((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=>Nt(e,r.codec()),r.decode=(e,n)=>Ot(e,r.codec(),n)})(Xs||(Xs={}));function ly(r,t){if(r.publicKey!=null||t.publicKey==null)return r;let e;r.type==="RSA"&&(e=r.toMultihash());let n=Yr(t.publicKey,e);return Gc(n)}function gh(r,t,e){let n=Pe.decode(t);return ln(r,n,e)}function ln(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:ly(r,t),addresses:t.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-e).map(({multiaddr:s,isCertified:i})=>({multiaddr:G(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}function yh(r,t){return uy(r.addresses,t.addresses)&&fy(r.protocols,t.protocols)&&dy(r.publicKey,t.publicKey)&&hy(r.peerRecordEnvelope,t.peerRecordEnvelope)&&py(r.metadata,t.metadata)&&my(r.tags,t.tags)}function uy(r,t){return wh(r,t,(e,n)=>!(e.isCertified!==n.isCertified||!tt(e.multiaddr,n.multiaddr)))}function fy(r,t){return wh(r,t,(e,n)=>e===n)}function dy(r,t){return bh(r,t)}function hy(r,t){return bh(r,t)}function py(r,t){return xh(r,t,(e,n)=>tt(e,n))}function my(r,t){return xh(r,t,(e,n)=>e.value===n.value&&e.expiry===n.expiry)}function bh(r,t){return r==null&&t==null?!0:r!=null&&t!=null?tt(r,t):!1}function wh(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 xh(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 Le="/",Eh=new TextEncoder().encode(Le),Ys=Eh[0],yr=class r{_buf;constructor(t,e){if(typeof t=="string")this._buf=L(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]!==Ys)throw new Error("Invalid key")}toString(t="utf8"){return M(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(Le))}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=Eh),this._buf[0]!==Ys){let t=new Uint8Array(this._buf.byteLength+1);t.fill(Ys,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ys;)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(Le).slice(1)}type(){return gy(this.baseNamespace())}name(){return yy(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(Le)||(t+=Le),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(Le):new r(t.slice(0,-1).join(Le))}child(t){return this.toString()===Le?t:t.toString()===Le?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(),...by(t.map(e=>e.namespaces()))])}};function gy(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function yy(r){let t=r.split(":");return t[t.length-1]}function by(r){return[].concat(...r)}var Rl="/peers/";function fo(r){if(!ke(r)||r.type==null)throw new k("Invalid PeerId");let t=r.toCID().toString();return new yr(`${Rl}${t}`)}async function vh(r,t,e,n,o){let s=new Map;for(let i of e){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=G(i.multiaddr)),!Ve(i.multiaddr))throw new k("Multiaddr was invalid");if(!await t(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),u=s.get(c);u!=null?i.isCertified=u.isCertified||a:s.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...s.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getPeerId();return r.equals(c)&&(a=a.decapsulate(G(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function Qs(r,t,e,n){if(t==null)throw new k("Invalid PeerData");if(t.publicKey!=null&&r.publicKey!=null&&!t.publicKey.equals(r.publicKey))throw new k("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new k("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(e==="patch"){if((t.multiaddrs!=null||t.addresses!=null)&&(s=[],t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses)),t.protocols!=null&&(i=new Set(t.protocols)),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);a=Zs(d,{validate:Ah})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);c=Zs(d,{validate:Sh,map:_h})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}if(e==="merge"){if(t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses),t.protocols!=null&&(i=new Set([...i,...t.protocols])),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(let[m,h]of d)h==null?a.delete(m):a.set(m,h);a=Zs([...a.entries()],{validate:Ah})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),m=new Map(c);for(let[h,g]of d)g==null?m.delete(h):m.set(h,g);c=Zs([...m.entries()],{validate:Sh,map:_h})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}let l;o?.id.publicKey!=null?l=Xt(o.id.publicKey):t.publicKey!=null?l=Xt(t.publicKey):r.publicKey!=null&&(l=Xt(r.publicKey));let f={addresses:await vh(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((d,m)=>d.localeCompare(m)),metadata:a,tags:c,publicKey:l,peerRecordEnvelope:u};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(m=>tt(m.multiaddr,m.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function Zs(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 Ah(r,t){if(typeof r!="string")throw new k("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new k("Metadata value must be a Uint8Array")}function Sh(r,t){if(typeof r!="string")throw new k("Tag name must be a string");if(t.value!=null){if(parseInt(`${t.value}`,10)!==t.value)throw new k("Tag value must be an integer");if(t.value<0||t.value>100)throw new k("Tag value must be between 0-100")}if(t.ttl!=null){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new k("Tag ttl must be an integer");if(t.ttl<0)throw new k("Tag ttl must be between greater than 0")}}function _h(r,t){let e;t.expiry!=null&&(e=t.expiry),t.ttl!=null&&(e=BigInt(Date.now()+Number(t.ttl)));let n={value:t.value??0};return e!=null&&(n.expiry=e),n}function Ih(r){let t=r.toString().split("/")[2],e=it.parse(t,$t);return Zn(e)}function kl(r,t,e){let n=Ih(r);return gh(n,t,e)}function wy(r,t){return{prefix:Rl,filters:(r.filters??[]).map(e=>({key:n,value:o})=>e(kl(n,o,t))),orders:(r.orders??[]).map(e=>(n,o)=>e(kl(n.key,n.value,t),kl(o.key,o.value,t)))}}var Js=class{peerId;datastore;locks;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.locks=_l({name:"libp2p_peer_store_locks",metrics:t.metrics}),this.maxAddressAge=e.maxAddressAge??36e5,this.maxPeerAge=e.maxPeerAge??216e5}getLock(t){let e=this.locks.get(t);return e==null&&(e={refs:0,lock:Dl({name:t.toString(),singleProcess:!0})},this.locks.set(t,e)),e.refs++,e}maybeRemoveLock(t,e){e.refs--,e.refs===0&&(e.lock.finalize(),this.locks.delete(t))}async getReadLock(t,e){let n=this.getLock(t);try{let o=await n.lock.readLock(e);return()=>{o(),this.maybeRemoveLock(t,n)}}catch(o){throw this.maybeRemoveLock(t,n),o}}async getWriteLock(t,e){let n=this.getLock(t);try{let o=await n.lock.writeLock(e);return()=>{o(),this.maybeRemoveLock(t,n)}}catch(o){throw this.maybeRemoveLock(t,n),o}}async has(t,e){try{return await this.load(t,e),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(t,e){this.peerId.equals(t)||await this.datastore.delete(fo(t),e)}async load(t,e){let n=fo(t),o=await this.datastore.get(n,e),s=Pe.decode(o);if(this.#r(t,s))throw await this.datastore.delete(n,e),new Ge;return ln(t,s,this.peerId.equals(t)?1/0:this.maxAddressAge)}async save(t,e,n){let o=await this.#t(t,n),s=await Qs(t,e,"patch",{...n,addressFilter:this.addressFilter});return this.#e(t,s,o)}async patch(t,e,n){let o=await this.#t(t,n),s=await Qs(t,e,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#e(t,s,o)}async merge(t,e,n){let o=await this.#t(t,n),s=await Qs(t,e,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#e(t,s,o)}async*all(t){for await(let{key:e,value:n}of this.datastore.query(wy(t??{},this.maxAddressAge),t)){let o=Ih(e);if(o.equals(this.peerId))continue;let s=Pe.decode(n);if(this.#r(o,s)){await this.datastore.delete(e,t);continue}yield ln(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#t(t,e){try{let n=fo(t),o=await this.datastore.get(n,e),s=Pe.decode(o);if(this.#r(t,s))throw await this.datastore.delete(n,e),new Ge;return{peerPB:s,peer:ln(t,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#e(t,e,n,o){e.updated=Date.now();let s=Pe.encode(e);return await this.datastore.put(fo(t),s,o),{peer:ln(t,e,this.maxAddressAge),previous:n?.peer,updated:n==null||!yh(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 Js(t,e)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(t,e){for await(let n of this.store.all(e))t(n)}async all(t){return co(this.store.all(t))}async delete(t,e){let n=await this.store.getReadLock(t,e);try{await this.store.delete(t,e)}finally{n()}}async has(t,e){let n=await this.store.getReadLock(t,e);try{return await this.store.has(t,e)}finally{this.log.trace("has release read lock"),n?.()}}async get(t,e){let n=await this.store.getReadLock(t,e);try{return await this.store.load(t,e)}finally{n?.()}}async getInfo(t,e){let n=await this.get(t,e);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(t,e,n){let o=await this.store.getWriteLock(t,n);try{let s=await this.store.save(t,e,n);return this.#t(t,s),s.peer}finally{o?.()}}async patch(t,e,n){let o=await this.store.getWriteLock(t,n);try{let s=await this.store.patch(t,e,n);return this.#t(t,s),s.peer}finally{o?.()}}async merge(t,e,n){let o=await this.store.getWriteLock(t,n);try{let s=await this.store.merge(t,e,n);return this.#t(t,s),s.peer}finally{o?.()}}async consumePeerRecord(t,e,n){let o=ke(e)?e:ke(e?.expectedPeer)?e.expectedPeer:void 0,s=ke(e)||e===void 0?n:e,i=await an.openAndCertify(t,mr.DOMAIN,s),a=Zn(i.publicKey.toCID());if(o?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",o,a),!1;let c=mr.createFromProtobuf(i.payload),u;try{u=await this.get(a,s)}catch(l){if(l.name!=="NotFoundError")throw l}if(u?.peerRecordEnvelope!=null){let l=an.createFromProtobuf(u.peerRecordEnvelope),f=mr.createFromProtobuf(l.payload);if(f.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:t,addresses:c.multiaddrs.map(l=>({isCertified:!0,multiaddr:l}))},s),!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 Ch(r,t={}){return new Ml(r,t)}var ti=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 xy(r){return r[Symbol.asyncIterator]!=null}function Ey(r){if(xy(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Ol=Ey;function vy(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 Th=vy;function Ay(r){return r[Symbol.asyncIterator]!=null}function Sy(r,t){let e=0;if(Ay(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=Th(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(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 br=Sy;function _y(r){return r[Symbol.asyncIterator]!=null}function Iy(r,t){return _y(r)?async function*(){yield*(await co(r)).sort(t)}():function*(){yield*co(r).sort(t)}()}var Nl=Iy;function Cy(r){return r[Symbol.asyncIterator]!=null}function Ty(r,t){return Cy(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var Bl=Ty;var ei=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 Ol(this.putMany(t,n)),t=[],await Ol(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=br(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>br(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>Nl(o,s),n)),t.offset!=null){let o=0,s=t.offset;n=br(n,()=>o++>=s)}return t.limit!=null&&(n=Bl(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=br(n,s=>s.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>br(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>Nl(o,s),n)),t.offset!=null){let o=t.offset,s=0;n=br(n,()=>s++>=o)}return t.limit!=null&&(n=Bl(n,t.limit)),n}};var ri=class extends ei{data;constructor(){super(),this.data=new Map}put(t,e,n){return n?.signal?.throwIfAborted(),this.data.set(t.toString(),e),t}get(t,e){e?.signal?.throwIfAborted();let n=this.data.get(t.toString());if(n==null)throw new ti;return n}has(t,e){return e?.signal?.throwIfAborted(),this.data.has(t.toString())}delete(t,e){e?.signal?.throwIfAborted(),this.data.delete(t.toString())}*_all(t,e){e?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new yr(n),value:o},e?.signal?.throwIfAborted()}*_allKeys(t,e){e?.signal?.throwIfAborted();for(let n of this.data.keys())yield new yr(n),e?.signal?.throwIfAborted()}};function ho(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 Lh=Po(Ph(),1),Py=["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"],Ly=Py.map(r=>new Lh.Netmask(r));function Fl(r){for(let t of Ly)if(t.contains(r))return!0;return!1}function Dy(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Ry(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 Fl(o)}function ky(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function My(r){let t=r.split(":"),e=t[t.length-1];return Fl(e)}function Oy(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 He(r){return ce(r)?Fl(r):Dy(r)?Ry(r):ky(r)?My(r):nn(r)?Oy(r):void 0}var Ny=r=>r.toString().split("/").slice(1),un=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),z=r=>({match:t=>un(e=>e===r).match(t),pattern:r}),wr=()=>({match:r=>un(t=>typeof t=="string").match(r),pattern:"{string}"}),fn=()=>({match:r=>un(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),et=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{j.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),mo=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{La.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Z=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Pt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),H=(...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 st(...r){function t(o){let s=Ny(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=et(),Dh=st(By),oi=H(z("dns4"),wr()),si=H(z("dns6"),wr()),ii=H(z("dnsaddr"),wr()),Kl=H(z("dns"),wr()),GI=st(oi,Z(et())),jI=st(si,Z(et())),XI=st(ii,Z(et())),YI=st(Pt(Kl,ii,oi,si),Z(et())),Rh=H(z("ip4"),un(ce)),kh=H(z("ip6"),un(nn)),ql=Pt(Rh,kh),De=Pt(ql,Kl,oi,si,ii),ZI=st(Pt(ql,H(Pt(Kl,ii,oi,si),Z(et())))),zl=st(Rh),Vl=st(kh),QI=st(ql),Hl=H(De,z("tcp"),fn()),go=H(De,z("udp"),fn()),yo=st(H(Hl,Z(et()))),JI=st(go),$l=H(go,z("quic"),Z(et())),ai=H(go,z("quic-v1"),Z(et())),Fy=Pt($l,ai),t4=st($l),Mh=st(ai),Ul=Pt(De,Hl,go,$l,ai),Oh=Pt(H(Ul,z("ws"),Z(et()))),xr=st(Oh),Nh=Pt(H(Ul,z("wss"),Z(et())),H(Ul,z("tls"),Z(H(z("sni"),wr())),z("ws"),Z(et()))),bo=st(Nh),Bh=H(go,z("webrtc-direct"),Z(mo()),Z(mo()),Z(et())),Wl=st(Bh),Fh=H(ai,z("webtransport"),Z(mo()),Z(mo()),Z(et())),Gl=st(Fh),ni=Pt(Oh,Nh,H(Hl,Z(et())),H(Fy,Z(et())),H(De,Z(et())),Bh,Fh,et()),e4=st(ni),Uy=H(ni,z("p2p-circuit"),et()),wo=st(Uy),Ky=Pt(H(ni,z("p2p-circuit"),z("webrtc"),Z(et())),H(ni,z("webrtc"),Z(et())),H(z("webrtc"),Z(et()))),jl=st(Ky),qy=Pt(H(De,z("tcp"),fn(),z("http"),Z(et())),H(De,z("http"),Z(et()))),r4=st(qy),zy=Pt(H(De,z("tcp"),Pt(H(z("443"),z("http")),H(fn(),z("https")),H(fn(),z("tls"),z("http"))),Z(et())),H(De,z("tls"),z("http"),Z(et())),H(De,z("https"),Z(et()))),n4=st(zy),Vy=Pt(H(z("memory"),wr(),Z(et()))),o4=st(Vy);var Xl=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Lt(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Xl({name:t,metrics:e}):n=new Map,n}var Uh=864e13;var Hy=448,Yl=449,$y=53,Wy=54,Gy=55,jy=56,ci=class{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Lt({name:"libp2p_address_manager_dns_mappings",metrics:t.metrics})}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=He(n)===!0;this.mappings.set(n,{domain:t,verified:o,expires:o?Uh-Date.now():0,lastVerified:o?Uh-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:G(`/${s.map(l=>[W(l[0]).name,l[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return e}maybeAddSNITuple(t,e){for(let n=0;n<t.length;n++)if(t[n][0]===Hy&&t[n+1]?.[0]!==Yl)return t.splice(n+1,0,[Yl,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]===Yl||e[0]===$y||e[0]===Wy||e[0]===Gy||e[0]===jy)return e[1]}};var Zl=4,Ql=41,Jl=6,Xy=273,li=class{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Lt({name:"libp2p_address_manager_ip_mappings",metrics:t.metrics})}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:ce(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]===Jl?"tcp":"udp",s=parseInt(e[1][1]??"0"),i=!1;for(let[a,c]of this.mappings.entries()){for(let u=0;u<c.length;u++){let l=c[u];l.externalIp===n&&l.externalPort===s&&l.protocol===o&&(this.log("removing %s:%s to %s:%s %s IP mapping",l.externalIp,l.externalPort,n,s,o),i=i||l.verified,c.splice(u,1),u--)}c.length===0&&this.mappings.delete(a)}return i}getAll(t){let e=[];for(let{multiaddr:n}of t){let o=n.stringTuples(),s;if((o[0][0]===Zl||o[0][0]===Ql)&&o[1][0]===Jl?s=`${o[0][1]}-${o[1][1]}-tcp`:(o[0][0]===Zl||o[0][0]===Ql)&&o[1][0]===Xy&&(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?Zl:Ql,o[0][1]=a.externalIp,o[1][1]=`${a.externalPort}`,e.push({multiaddr:G(`/${o.map(c=>[W(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]===Jl?"tcp":"udp",i=parseInt(n[1][1]??"0"),a=!1;for(let c of this.mappings.values())for(let u=0;u<c.length;u++){let l=c[u];l.externalIp===o&&l.externalPort===i&&l.protocol===s&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",l.externalIp,l.externalPort,o,i,s),a=a||l.verified,l.verified=!1,l.expires=Date.now()+e)}return a}};function Kh(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 ui(r){try{let[[t]]=r.stringTuples();return t===4||t===41}catch{}return!1}function Er(r){try{if(!ui(r))return!1;let[[,t]]=r.stringTuples();return t==null?!1:He(t)??!1}catch{}return!0}var Yy={maxObservedAddresses:10},fi=class{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Lt({name:"libp2p_address_manager_observed_addresses",metrics:t.metrics}),this.maxObservedAddresses=e.maxObservedAddresses??Yy.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)||Kh(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:G(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 Zy=[4,41,53,54,55,56];function tu(r){try{let[[t]]=r.stringTuples();return Zy.includes(t)}catch{}return!1}var Qy={maxObservedAddresses:10},di=class{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Lt({name:"libp2p_address_manager_transport_addresses",metrics:t.metrics}),this.maxObservedAddresses=e.maxObservedAddresses??Qy.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:!tu(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(tu(t)){let e=t.toOptions();return`${e.host}-${e.port}-${e.transport}`}return t.toString()}};var qh=6e4,zh={maxObservedAddresses:10,addressVerificationTTL:qh*10,addressVerificationRetry:qh*5},Jy=r=>r;function eu(r,t){let e=r.getPeerId();return e!=null&&me(e).equals(t)&&(r=r.decapsulate(G(`/p2p/${t.toString()}`))),r}var hi=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 fi(t,e),this.dnsMappings=new ci(t,e),this.ipMappings=new li(t,e),this.transportAddresses=new di(t,e),this.announceFilter=e.announceFilter??Jy,this.observedAddressFilter=so(1024),this.addressVerificationTTL=e.addressVerificationTTL??zh.addressVerificationTTL,this.addressVerificationRetry=e.addressVerificationRetry??zh.addressVerificationRetry,this._updatePeerStoreAddresses=ho(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=>G(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>G(t))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(t=>G(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=eu(t,this.components.peerId),!this.ipMappings.has(t)&&(this.dnsMappings.has(t)||this.observed.add(t)))}confirmObservedAddr(t,e){t=eu(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=eu(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=G(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(G(`/dns/${t}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.add(t,e,n,o,s),this.observed.removePrefixed(`/ip${ce(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.remove(G(`/ip${ce(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"||He(e.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>xr.exactMatch(s)||bo.exactMatch(s),s=>yo.exactMatch(s),s=>Mh.exactMatch(s)];for(let s of o){if(!s(t))continue;let i=n.filter(u=>u.getAddrs().filter(l=>l.toOptions().family===4&&s(l)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(u=>u.toOptions().host!=="127.0.0.1").pop();if(a==null)continue;let c=a.toOptions();return this.observed.remove(t),this.ipMappings.add(c.host,c.port,e.host,e.port,e.transport),!0}return!1}};var Vh;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Vh||(Vh={}));var pi=class extends Error{constructor(t="Missing service"){super(t),this.name="MissingServiceError"}},mi=class extends Error{constructor(t="Unmet service dependencies"){super(t),this.name="UnmetServiceDependenciesError"}},dn=class extends Error{constructor(t="No content routers available"){super(t),this.name="NoContentRoutersError"}},xo=class extends Error{constructor(t="No peer routers available"){super(t),this.name="NoPeerRoutersError"}},gi=class extends Error{constructor(t="Should not try to find self"){super(t),this.name="QueriedForSelfError"}},yi=class extends Error{constructor(t="Unhandled protocol error"){super(t),this.name="UnhandledProtocolError"}},bi=class extends Error{constructor(t="Duplicate protocol handler error"){super(t),this.name="DuplicateProtocolHandlerError"}},Eo=class extends Error{constructor(t="Dial denied error"){super(t),this.name="DialDeniedError"}},wi=class extends Error{constructor(t="No transport was configured to listen on this address"){super(t),this.name="UnsupportedListenAddressError"}},xi=class extends Error{constructor(t="Configured listen addresses could not be listened on"){super(t),this.name="UnsupportedListenAddressesError"}},Ei=class extends Error{constructor(t="No valid addresses"){super(t),this.name="NoValidAddressesError"}},vi=class extends Error{constructor(t="Connection intercepted"){super(t),this.name="ConnectionInterceptedError"}},Ai=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"}},Ar=class extends Error{constructor(t="Encryption failed"){super(t),this.name="EncryptionFailedError"}},Si=class extends Error{constructor(t="Transport unavailable"){super(t),this.name="TransportUnavailableError"}};var ru=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=_s())}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(e=>Fo(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")}},eb=["metrics","connectionProtector","dns"],rb=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Hh(r={}){let t=new ru(r);return new Proxy(t,{get(n,o,s){if(typeof o=="string"&&!rb.includes(o)){let i=t.components[o];if(i==null&&!eb.includes(o))throw new pi(`${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 $h(r){let t={};for(let e of Object.values(r.components))for(let n of nb(e))t[n]=!0;for(let e of Object.values(r.components))for(let n of ob(e))if(t[n]!==!0)throw new mi(`Service "${sb(e)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function nb(r){return Array.isArray(r?.[wn])?r[wn]:[]}function ob(r){return Array.isArray(r?.[pa])?r[pa]:[]}function sb(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var ib=4,ab=41;function Wh(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{if(xr.matches(t))return!1;let e=t.stringTuples();return e[0][0]===ib||e[0][0]===ab?!!He(`${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 Gh=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},cb=new WeakMap;function lb({clearTimeout:r,setTimeout:t}={}){return(e,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Gh());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(Gh())},l=()=>{o&&o.removeEventListener("abort",u)},f=new Promise((d,m)=>{i=()=>{l(),d(n)},a=m,s=(t??setTimeout)(i,e)});return o&&o.addEventListener("abort",u,{once:!0}),cb.set(f,()=>{c(s),s=null,i()}),f}}var ub=lb(),jh=ub;var _i=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}},Ii=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var Ci=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 nu}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 _i("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 jh(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)}},nu=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 Ti(r){if(ke(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:me(n),t.forEach(o=>{if(!Ve(o))throw new Me("Invalid multiaddr");let s=o.getPeerId();if(s==null){if(e!=null)throw new k("Multiaddrs must all have the same peer id or have no peer id")}else{let i=me(s);if(e?.equals(i)!==!0)throw new k("Multiaddrs must all have the same peer id or have no peer id")}})}return t=t.filter(n=>!Dh.exactMatch(n)),{peerId:e,multiaddrs:t}}var fb=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Xh(r,t){let e=r?.streams?.map(o=>o.protocol)??[],n=t?.closableProtocols??fb;if(!(e.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(t)}catch(o){r?.abort(o)}}var Yh="last-dial-failure",Zh="last-dial-success";var Pi=100,Li=50;async function Qh(r,t){let e=!1;for(let o of sn.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 vo(r){try{let t;if(typeof r=="string"?t=G(r):t=r,!t.protoNames().includes("ipcidr")){let n=t.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(n)}return hl(t)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var db={maxConnections:Pi,allow:[]},Di=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(t,e={}){this.maxConnections=e.maxConnections??db.maxConnections,this.allow=(e.allow??[]).map(n=>vo(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 Yt;for(let a of t){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let u=await this.peerStore.get(c);n.set(c,[...u.tags.values()].reduce((l,f)=>l+f.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(t,n),s=Math.max(e-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>u.contains(a.remoteAddr.nodeAddress().address))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await Xh(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})}};var Ri=class{deferred;signal;constructor(t){this.signal=t,this.deferred=lt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Jt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function hb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ki=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=hb(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Jt),this.cleanup())}async join(t={}){let e=new Ri(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 Et(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 hn=class extends Ht{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=[],this.emitEmpty=ho(this.emitEmpty.bind(this),1),this.emitIdle=ho(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let 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 Ii;let n=new ki(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Jt)}),this.clear()}async onEmpty(t){this.size!==0&&await ge(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await ge(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await ge(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=Ls({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new Jt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var Mi=class extends hn{constructor(t={}){super({...t,sort:(e,n)=>e.options.priority>n.options.priority?-1:e.options.priority<n.options.priority?1:0})}};function Re(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 Jh(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function ou(r){if(!ui(r))return!1;let{address:t}=r.nodeAddress();return Jh(t)}function pb(r,t){let e=yo.exactMatch(r.multiaddr),n=yo.exactMatch(t.multiaddr);if(e&&!n)return-1;if(!e&&n)return 1;let o=bo.exactMatch(r.multiaddr),s=bo.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=jl.exactMatch(r.multiaddr),u=jl.exactMatch(t.multiaddr);if(c&&!u)return-1;if(!c&&u)return 1;let l=Wl.exactMatch(r.multiaddr),f=Wl.exactMatch(t.multiaddr);if(l&&!f)return-1;if(!l&&f)return 1;let d=Gl.exactMatch(r.multiaddr),m=Gl.exactMatch(t.multiaddr);return d&&!m?-1:!d&&m?1:0}function mb(r,t){let e=ou(r.multiaddr),n=ou(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function gb(r,t){let e=Er(r.multiaddr),n=Er(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function yb(r,t){return r.isCertified&&!t.isCertified?-1:!r.isCertified&&t.isCertified?1:0}function bb(r,t){let e=wo.exactMatch(r.multiaddr),n=wo.exactMatch(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function tp(r){return r.sort(pb).sort(yb).sort(bb).sort(gb).sort(mb)}var Oi={maxParallelDials:Li,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:ur}},Ni=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(t,e={}){this.addressSorter=e.addressSorter,this.maxPeerAddrsToDial=e.maxPeerAddrsToDial??Oi.maxPeerAddrsToDial,this.maxDialQueueLength=e.maxDialQueueLength??Oi.maxDialQueueLength,this.dialTimeout=e.dialTimeout??Oi.dialTimeout,this.connections=e.connections??new Yt,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??{}))sn.set(n,o);this.queue=new Mi({concurrency:e.maxParallelDials??Oi.maxParallelDials,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("error",n=>{n.detail?.name!==Jt.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(t,e={}){let{peerId:n,multiaddrs:o}=Ti(t),s=Array.from(this.connections.values()).flat().find(a=>e.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s?.status==="open")return this.log("already connected to %a",s.remoteAddr),e.onProgress?.(new dt("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return e.onProgress?.(new dt("dial-queue:already-in-dial-queue")),i.join(e)}if(this.queue.size>=this.maxDialQueueLength)throw new Dr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),e.onProgress?.(new dt("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new dt("dial-queue:start-dial"));let c=Re([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:n,priority:e.priority??cu,multiaddrs:new Set(o.map(a=>a.toString())),signal:e.signal??AbortSignal.timeout(this.dialTimeout),onProgress:e.onProgress})}async dialPeer(t,e){let n=t.peerId,o=t.multiaddrs,s=new Set,i=t.multiaddrs.size===0,a=0,c=0,u=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let l=[],f=new Set(t.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...t,signal:e});for(let m of d){if(s.has(m.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",m.multiaddr,n);continue}l.push(m)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,l.map(m=>m.multiaddr.toString())),t?.onProgress?.(new dt("dial-queue:calculated-addresses",l));for(let m of l){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,t.peerId),new Dr("Peer had more than maxPeerAddrsToDial");a++;try{let h=await this.components.transportManager.dial(m.multiaddr,{...t,signal:e});this.log("dial to %a succeeded",m.multiaddr);try{await this.components.peerStore.merge(h.remotePeer,{multiaddrs:[h.remoteAddr],metadata:{[Zh]:L(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}return h}catch(h){if(this.log.error("dial failed to %a",m.multiaddr,h),s.add(m.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[Yh]:L(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}if(e.aborted)throw new Oo(h.message);u.push(h)}}}throw u.length===1?u[0]:new AggregateError(u,"All multiaddr dials failed")}async calculateMultiaddrs(t,e=new Set,n={}){let o=[...e].map(f=>({multiaddr:G(f),isCertified:!1}));if(t!=null){if(this.components.peerId.equals(t))throw new Dr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(t)===!0)throw new Eo("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 Qh(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 Ei("The dial request has no valid addresses");let u=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||u.push(f);let l=this.addressSorter==null?tp(u):u.sort(this.addressSorter);if(l.length===0)throw new Eo("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",t??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",t??"unknown peer",l.map(({multiaddr:f})=>f.toString())),l}async isDialable(t,e={}){Array.isArray(t)||(t=[t]);try{let n=await this.calculateMultiaddrs(void 0,new Set(t.map(o=>o.toString())),e);return e.runOnLimitedConnection===!1?n.find(o=>!wo.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var Bi=class extends hn{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var ap=Po(sp(),1);var xb=Object.prototype.toString,Eb=r=>xb.call(r)==="[object Error]",vb=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 lu(r){return r&&Eb(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:vb.has(r.message):!1}var uu=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}},ip=(r,t,e)=>{let n=e.retries-(t-1);return r.attemptNumber=t,r.retriesLeft=n,r};async function fu(r,t){return new Promise((e,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;let o=ap.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 uu)throw c.originalError;if(c instanceof TypeError&&!lu(c))throw c;if(ip(c,a,t),await t.shouldRetry(c)||(o.stop(),n(c)),await t.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(u){ip(u,a,t),i(),n(u)}}})})}var Fi=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.queue=new Bi({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);cp(e)&&(this.queue.has(t)||this.queue.add(async n=>{await fu(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(ha)&&(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=>cp(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 cp(r){for(let t of r.tags.keys())if(t.startsWith(ha))return!0;return!1}var cu=50,du={maxConnections:Pi,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Ui=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??du.maxConnections,this.maxConnections<1)throw new k("Connection Manager maxConnections must be greater than 0");this.connections=new Yt,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=>vo(n)),this.deny=(e.deny??[]).map(n=>vo(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=e.maxIncomingPendingConnections??du.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Ci({points:e.inboundConnectionThreshold??du.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Di({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{maxConnections:this.maxConnections,allow:e.allow?.map(n=>G(n))}),this.dialQueue=new Ni(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 Fi({events:t.events,peerStore:t.peerStore,logger:t.logger,connectionManager:this},{retries:e.reconnectRetries,retryInterval:e.reconnectRetryInterval,backoffFactor:e.reconnectBackoffFactor,maxParallelReconnects:e.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let t={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let e of this.connections.values())for(let n of e)t[n.direction]++;return t}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let t={};for(let e of this.connections.values())for(let n of e)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;t[s]=(t[s]??0)+1}return t}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let t={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))t[i]=t[i]??[],t[i].push(a)}let e={};for(let[n,o]of Object.entries(t)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);e[n]=o[s]}return e}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await Su(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 _u(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 ye("Not started");this.outboundPendingConnections++;try{e.signal?.throwIfAborted();let{peerId:n}=Ti(t);if(this.peerId.equals(n))throw new Lr("Can not dial self");if(n!=null&&e.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),e.onProgress?.(new dt("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(t,{...e,priority:e.priority??cu});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 Me("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=>G(n))}))}async isDialable(t,e={}){return this.dialQueue.isDialable(t,e)}};var pn=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 _b=1.2,Ib=2,Cb=5e3,Tb=6e4,Pb=5e3,Ki=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(t={}){let e=t.interval??Pb;this.success=new pn(e),this.failure=new pn(e),this.next=new pn(e),this.failureMultiplier=t.failureMultiplier??Ib,this.timeoutMultiplier=t.timeoutMultiplier??_b,this.minTimeout=t.minTimeout??Cb,this.maxTimeout=t.maxTimeout??Tb,t.metricName!=null&&(this.metric=t.metrics?.registerMetricGroup(t.metricName))}getTimeoutSignal(t={}){let e=Math.round(this.next.movingAverage*(t.timeoutFactor??this.timeoutMultiplier));e<this.minTimeout&&(e=this.minTimeout),e>this.maxTimeout&&(e=this.maxTimeout);let n=AbortSignal.timeout(e),o=Re([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 hu=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=lt(),this.haveNext=lt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=lt(),t}async throw(t){return this.ended=!0,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=lt(),await Et(this.readNext.promise,e?.signal,e)}};function qi(){return new hu}var zi=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Vi(r,t){let e=qi();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 Y;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:u}=await Et(n.next(),i?.signal);return c===!0?null:u}for(;o.byteLength<i.bytes;){let{value:c,done:u}=await Et(n.next(),i?.signal);if(u===!0)throw new zi("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 Lb=1e4,Db="1.0.0",Rb="ping",kb="ipfs",lp=32,Mb=!0,Hi=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(t,e={}){this.components=t,this.protocol=`/${e.protocolPrefix??kb}/${Rb}/${Db}`,this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=e.pingInterval??Lb,this.abortConnectionOnPingFailure=e.abortConnectionOnPingFailure??Mb,this.timeout=new Ki({...e.pingTimeout??{},metrics:t.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[wn]=["@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=Vi(o);e=Date.now(),await Promise.all([s.write(jr(lp),{signal:n}),s.read({bytes:lp,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 Ob(r){return r[Symbol.asyncIterator]!=null}async function Nb(r,t,e){try{await Promise.all(r.map(async n=>{for await(let o of n)await t.push(o,{signal:e}),e.throwIfAborted()})),await t.end(void 0,{signal:e})}catch(n){await t.end(n,{signal:e}).catch(()=>{})}}async function*Bb(r){let t=new AbortController,e=qi();Nb(r,e,t.signal).catch(()=>{});try{yield*e}finally{t.abort()}}function*Fb(r){for(let t of r)yield*t}function Ub(...r){let t=[];for(let e of r)Ob(e)||t.push(e);return t.length===r.length?Fb(t):Bb(r)}var Ao=Ub;var $i=class{routers;started;components;constructor(t,e){this.routers=e.routers??[],this.started=!1,this.components=t,this.findProviders=t.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=t.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=t.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=t.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:M(n,"base36")})})??this.put,this.get=t.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:M(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(t,e={}){if(this.routers.length===0)throw new dn("No content routers available");let n=this,o=new dr;for await(let s of Ao(...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},e),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(t,e={}){if(this.routers.length===0)throw new dn("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 dn("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 ye;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 ye;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(t,e)))}};var Wi=globalThis.CustomEvent??Event;async function*pu(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered??!1,o=new EventTarget,s=[],i=lt(),a=lt(),c=!1,u,l=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let h of r){if(s.length===e&&(i=lt(),await i.promise),l)break;let g={done:!1};s.push(g),h().then(b=>{g.done=!0,g.ok=!0,g.value=b,o.dispatchEvent(new Wi("task-complete"))},b=>{g.done=!0,g.err=b,o.dispatchEvent(new Wi("task-complete"))})}c=!0,o.dispatchEvent(new Wi("task-complete"))}catch(h){u=h,o.dispatchEvent(new Wi("task-complete"))}});function f(){return n?s[0]?.done:!!s.find(h=>h.done)}function*d(){for(;s.length>0&&s[0].done;){let h=s[0];if(s.shift(),h.ok)yield h.value;else throw l=!0,i.resolve(),h.err;i.resolve()}}function*m(){for(;f();)for(let h=0;h<s.length;h++)if(s[h].done){let g=s[h];if(s.splice(h,1),h--,g.ok)yield g.value;else throw l=!0,i.resolve(),g.err;i.resolve()}}for(;;){if(f()||(a=lt(),await a.promise),u!=null||(n?yield*d():yield*m(),u!=null))throw u;if(c&&s.length===0)break}}var Gi=class{log;peerId;peerStore;routers;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-routing"),this.peerId=t.peerId,this.peerStore=t.peerStore,this.routers=e.routers??[],this.findPeer=t.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=t.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:M(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(t,e){if(this.routers.length===0)throw new xo("No peer routers available");if(t.toString()===this.peerId.toString())throw new gi("Should not try to find self");let n=this,o=Ao(...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},e),s;throw new Ge}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new xo("No peer routers available");let n=this,o=so(1024);for await(let s of pu(async function*(){let i=Ao(...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},e),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var ji=class extends Ht{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=Re([this.shutdownController.signal,t?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=lt(),yield(await ge(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=Re([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=jr(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 Et(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 mu=32,gu=64,Xi=class{log;topologies;handlers;components;constructor(t){this.components=t,this.log=t.logger.forComponent("libp2p:registrar"),this.topologies=new Map,t.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let e={};for(let[n,o]of this.topologies)e[n]=o.size;return e}}),this.handlers=Lt({name:"libp2p_registrar_protocol_handlers",metrics:t.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(t){let e=this.handlers.get(t);if(e==null)throw new yi(`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 bi(`Handler already registered for protocol ${t}`);let o=us.bind({ignoreUndefined:!0})({maxInboundStreams:mu,maxOutboundStreams:gu},n);this.handlers.set(t,{handler:e,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[t]},n)}async unhandle(t,e){(Array.isArray(t)?t:[t]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},e)}async register(t,e){if(e==null)throw new k("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,n={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(e,n).then(o=>{for(let s of o.protocols){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(e)!==!1&&(a.filter?.remove(e),a.onDisconnect?.(e))}}).catch(o=>{o.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",e,o)})}_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 Yi=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=Lt({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Lt({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=e.faultTolerance??We.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(t){let e=t[Symbol.toStringTag];if(e==null)throw new k("Transport must have a valid tag");if(this.transports.has(e))throw new k(`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 Si(`No transport available for address ${String(t)}`);return e?.onProgress?.(new dt("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(t,{...e,upgrader:this.components.upgrader})}getAddrs(){let t=[];for(let e of this.listeners.values())for(let n of e)t=[...t,...n.getAddrs()];return t}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(t){for(let e of this.transports.values())if(e.dialFilter([t]).length>0)return e}listenTransportForMultiaddr(t){for(let e of this.transports.values())if(e.listenFilter([t]).length>0)return e}async listen(t){if(!this.isStarted())throw new ye("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 wi)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(t);for(let c of a){this.log("creating listener for %s on %a",s,c);let u=i.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(s)??[];l==null&&(l=[],this.listeners.set(s,l)),l.push(u),u.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:u})}),u.addEventListener("close",()=>{let f=l.findIndex(d=>d===u);l.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:u})}),zl.matches(c)?e.ipv4.attempts++:Vl.matches(c)&&e.ipv6.attempts++,n.push(u.listen(c).then(()=>{e.errors.delete(c.toString()),zl.matches(c)&&e.ipv4.success++,Vl.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===We.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new xi(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
|
|
3
3
|
${[...e.errors.entries()].map(([s,i])=>`
|
|
4
4
|
${s}: ${`${i.stack??i}`.split(`
|
|
5
5
|
`).join(`
|
|
6
6
|
`)}
|
|
7
|
-
`).join("")}`)}}ipv6Unsupported(t){if(t.ipv4.attempts===0||t.ipv6.attempts===0)return!1;let e=t.ipv4.attempts===t.ipv4.success,n=t.ipv6.success===0;return e&&n}async remove(t){let e=this.listeners.get(t)??[];this.log.trace("removing transport %s",t);let n=[];for(this.log.trace("closing listeners for %s",t);e.length>0;){let o=e.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(t),this.listeners.delete(t)}async removeAll(){let t=[];for(let e of this.transports.keys())t.push(this.remove(e));await Promise.all(t)}};var
|
|
8
|
-
`);async function _r(r,t,e){await r.write(t,e)}async function
|
|
7
|
+
`).join("")}`)}}ipv6Unsupported(t){if(t.ipv4.attempts===0||t.ipv6.attempts===0)return!1;let e=t.ipv4.attempts===t.ipv4.success,n=t.ipv6.success===0;return e&&n}async remove(t){let e=this.listeners.get(t)??[];this.log.trace("removing transport %s",t);let n=[];for(this.log.trace("closing listeners for %s",t);e.length>0;){let o=e.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(t),this.listeners.delete(t)}async removeAll(){let t=[];for(let e of this.transports.keys())t.push(this.remove(e));await Promise.all(t)}};var vt="/multistream/1.0.0";var Zi=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Qi=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ji=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function So(r,t={}){let e=Vi(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=mt(t.maxDataLength));let n=t?.lengthDecoder??se,o=t?.lengthEncoder??It;return{read:async i=>{let a=-1,c=new Y;for(;;){c.append(await e.read({...i,bytes:1}));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Zi("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ji("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Qi("message length too long");return e.read({...i,bytes:a})},write:async(i,a)=>{await e.write(new Y(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new Y(...i.flatMap(u=>[o(u.byteLength),u]));await e.write(c,a)},unwrap:()=>e.unwrap()}}var qb=L(`
|
|
8
|
+
`);async function _r(r,t,e){await r.write(t,e)}async function up(r,t,e){await r.writeV(t,e)}async function zb(r,t){let e=await r.read(t);if(e.byteLength===0||e.get(e.byteLength-1)!==qb[0])throw t.log.error("Invalid mss message - missing newline",e),new Mo("Missing newline");return e.sublist(0,-1)}async function $e(r,t){let e=await zb(r,t);return M(e.subarray())}async function _o(r,t,e){if(t=Array.isArray(t)?[...t]:[t],t.length===1&&e.negotiateFully===!1)return Vb(r,t[0],e);let n=So(r,{...e,maxDataLength:1024}),o=t.shift();if(o==null)throw new Error("At least one protocol must be specified");e.log.trace('select: write ["%s", "%s"]',vt,o);let s=L(`${vt}
|
|
9
9
|
`),i=L(`${o}
|
|
10
|
-
`);await
|
|
11
|
-
`),e),e.log.trace("select: reading protocol response");let
|
|
12
|
-
`;yield new Y(Uint8Array.from([19]),L(`${
|
|
13
|
-
`),
|
|
10
|
+
`);await up(n,[s,i],e),e.log.trace("select: reading multistream-select header");let a=await $e(n,e);if(e.log.trace('select: read "%s"',a),a===vt&&(e.log.trace("select: reading protocol response"),a=await $e(n,e),e.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of t){e.log.trace('select: write "%s"',c),await _r(n,L(`${c}
|
|
11
|
+
`),e),e.log.trace("select: reading protocol response");let u=await $e(n,e);if(e.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new bn("protocol selection failed")}function Vb(r,t,e){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=lt(),c=!1,u=!1,l=lt(),f=!1,d=!1,m=lt(),h=So({sink:n,source:o},{...e,maxDataLength:1024});r.sink=async C=>{let{sink:x}=h.unwrap();await x(async function*(){let p=!1;for await(let w of C){if(u&&await l.promise,c)yield w;else{u=!0,e.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',vt,t,w.byteLength);let T=`${t}
|
|
12
|
+
`;yield new Y(Uint8Array.from([19]),L(`${vt}
|
|
13
|
+
`),It(T.length),L(T),w).subarray(),e.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',vt,t,w.byteLength),c=!0,u=!1,l.resolve(),g().catch(P=>{e.log.error("could not finish optimistic protocol negotiation of %s",t,P)})}p=!0}p||await g()}())};async function g(){if(i){e.log.trace("optimistic: already negotiating %s stream",t),await a.promise;return}i=!0;try{c||(e.log.trace("optimistic: doing send protocol for %s stream",t),await b()),f||(e.log.trace("optimistic: doing read protocol for %s stream",t),await v())}finally{i=!1,s=!0,a.resolve()}}async function b(){if(u){await l.promise;return}u=!0;try{e.log.trace('optimistic: write ["%s", "%s", data] in source',vt,t),await h.writeV([L(`${vt}
|
|
14
14
|
`),L(`${t}
|
|
15
|
-
`)]),e.log.trace('optimistic: wrote ["%s", "%s", data] in source',
|
|
16
|
-
`),e),e.log.trace('handle: responded with "%s" for "%s"',
|
|
17
|
-
`),e),e.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new Y(...t.map(i=>
|
|
15
|
+
`)]),e.log.trace('optimistic: wrote ["%s", "%s", data] in source',vt,t)}finally{c=!0,u=!1,l.resolve()}}async function v(){if(d){await m.promise;return}d=!0;try{e.log.trace("optimistic: reading multistream select header");let C=await $e(h,e);if(e.log.trace('optimistic: read multistream select header "%s"',C),C===vt&&(C=await $e(h,e)),e.log.trace('optimistic: read protocol "%s", expecting "%s"',C,t),C!==t)throw new bn("protocol selection failed")}finally{f=!0,d=!1,m.resolve()}}if(r.source=async function*(){await g(),e.log.trace('optimistic: reading data from "%s" stream',t),yield*h.unwrap().source}(),r.closeRead!=null){let C=r.closeRead.bind(r);r.closeRead=async x=>{s||await g().catch(p=>{e.log.error("could not negotiate protocol before close read",p)}),await C(x)}}if(r.closeWrite!=null){let C=r.closeWrite.bind(r);r.closeWrite=async x=>{s||await g().catch(p=>{e.log.error("could not negotiate protocol before close write",p)}),await C(x)}}if(r.close!=null){let C=r.close.bind(r);r.close=async x=>{let p=[];u&&p.push(l.promise),d&&p.push(m.promise),p.length>0?await Et(Promise.all(p),x?.signal):(s=!0,i=!1,a.resolve()),await C(x)}}return{stream:r,protocol:t}}var ta=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},mn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ea=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Io=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ra(r){return r[Symbol.asyncIterator]!=null}function dp(r,t){if(r.byteLength>t)throw new mn("Message length too long")}var oa=r=>{let t=mt(r),e=St(t);return It(r,e),oa.bytes=t,e};oa.bytes=0;function sa(r,t){t=t??{};let e=t.lengthEncoder??oa,n=t?.maxDataLength??4194304;function*o(s){dp(s,n);let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return ra(r)?async function*(){for await(let s of r)yield*o(s)}():function*(){for(let s of r)yield*o(s)}()}sa.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??oa,n=t?.maxDataLength??4194304;return dp(r,n),new Y(e(r.byteLength),r)};var Ir;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ir||(Ir={}));var wu=r=>{let t=se(r);return wu.bytes=mt(t),t};wu.bytes=0;function bu(r,t){let e=new Y,n=Ir.LENGTH,o=-1,s=t?.lengthDecoder??wu,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===Ir.LENGTH)try{if(o=s(e),o<0)throw new ta("Invalid message length");if(o>a)throw new mn("Message length too long");let u=s.bytes;e.consume(u),t?.onLength!=null&&t.onLength(o),n=Ir.DATA}catch(u){if(u instanceof RangeError){if(e.byteLength>i)throw new ea("Message length length too long");break}throw u}if(n===Ir.DATA){if(e.byteLength<o)break;let u=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(u),yield u,n=Ir.LENGTH}}}return ra(r)?async function*(){for await(let u of r)e.append(u),yield*c();if(e.byteLength>0)throw new Io("Unexpected end of input")}():function*(){for(let u of r)e.append(u),yield*c();if(e.byteLength>0)throw new Io("Unexpected end of input")}()}bu.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return bu(n,{...t??{},onLength:s=>{e=s}})};async function Co(r,t,e){t=Array.isArray(t)?t:[t],e.log.trace("handle: available protocols %s",t);let n=So(r,{...e,maxDataLength:1024,maxLengthLength:2});for(;;){e.log.trace("handle: reading incoming string");let o=await $e(n,e);if(e.log.trace('handle: read "%s"',o),o===vt){e.log.trace('handle: respond with "%s" for "%s"',vt,o),await _r(n,L(`${vt}
|
|
16
|
+
`),e),e.log.trace('handle: responded with "%s" for "%s"',vt,o);continue}if(t.includes(o))return e.log.trace('handle: respond with "%s" for "%s"',o,o),await _r(n,L(`${o}
|
|
17
|
+
`),e),e.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new Y(...t.map(i=>sa.single(L(`${i}
|
|
18
18
|
`))),L(`
|
|
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,L(`na
|
|
20
|
-
`),e),e.log('handle: responded with "na" for "%s"',o)}}var Cb=500,lu=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";[du]=!0;get streams(){return this._getStreams()}async newStream(t,e){if(this.status==="closing")throw new Po("the connection is being closed");if(this.status==="closed")throw new Tr("the connection is closed");if(Array.isArray(t)||(t=[t]),this.limits!=null&&e?.runOnLimitedConnection!==!0)throw new kr("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(Cb);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 lu(r)}function Tb(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return nu}function Lb(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??ou}function rp(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var Vi=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 ni(`The multiaddr connection is blocked by gater.${t}`)}createInboundAbortSignal(t){let e=Te([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 Bt(this.components.connectionManager.acceptIncomingConnection(t),o),!n)throw new oi("Connection denied");await Bt(this.shouldBlockConnection("denyInboundConnection",t),o),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=de(n),await Bt(this.shouldBlockConnection("denyOutboundConnection",o,t),e.signal));let s="outbound";return e.initiator===!1&&(s="inbound"),await this._performUpgrade(t,s,e)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(t,e,n){let o,s,i,a,c;this.components.metrics?.trackMultiaddrConnection(t),t.log.trace("starting the %s connection upgrade",e);let l=t;if(n?.skipProtection!==!0){let u=this.components.connectionProtector;u!=null&&(t.log("protecting the %s connection",e),l=await u.protect(t,n))}try{if(o=l,n?.skipEncryption!==!0){n?.onProgress?.(new dt(`upgrader:encrypt-${e}-connection`)),{conn:o,remotePeer:s,protocol:c,streamMuxer:a}=await(e==="inbound"?this._encryptInbound(l,n):this._encryptOutbound(l,n));let u={...l,...o};await this.shouldBlockConnection(e==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,u)}else{let u=t.remoteAddr.getPeerId();if(u==null)throw new De(`${e} connection that skipped encryption must have a peer id`);let f=de(u);c="native",s=f}if(s.equals(this.components.peerId)){let u=new Lr("Can not dial self");throw t.abort(u),u}if(i=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(a==null&&this.streamMuxers.size>0){n?.onProgress?.(new dt(`upgrader:multiplex-${e}-connection`));let u=await(e==="inbound"?this._multiplexInbound({...l,...o},this.streamMuxers,n):this._multiplexOutbound({...l,...o},this.streamMuxers,n));a=u.muxerFactory,i=u.stream}}catch(u){throw t.log.error("failed to upgrade inbound connection %s %a - %e",e==="inbound"?"from":"to",t.remoteAddr,u),u}return await this.shouldBlockConnection(e==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,t),t.log("successfully upgraded %s connection",e),this._createConnection({cryptoProtocol:c,direction:e,maConn:t,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:n?.limits})}_createConnection(t){let{cryptoProtocol:e,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,limits:c}=t,l,u,f;a!=null&&(l=a.createStreamMuxer({direction:n,onIncomingStream:h=>{if(f==null)return;let m=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Promise.resolve().then(async()=>{let b=this.components.registrar.getProtocols(),{stream:v,protocol:C}=await Ao(h,b,{signal:m,log:h.log,yieldBytes:!1});if(f==null)return;f.log("incoming stream opened on %s",C);let x=Tb(C,this.components.registrar);if(rp(C,"inbound",f)===x){let w=new Ro(`Too many inbound protocol streams for protocol "${C}" - limit ${x}`);throw h.abort(w),w}h.source=v.source,h.sink=v.sink,h.protocol=C,v.closeWrite!=null&&(h.closeWrite=v.closeWrite),v.closeRead!=null&&(h.closeRead=v.closeRead),v.close!=null&&(h.close=v.close),await this.components.peerStore.merge(i,{protocols:[C]},{signal:m}),this.components.metrics?.trackProtocolStream(h,f),this._onStream({connection:f,stream:h,protocol:C})}).catch(async b=>{f.log.error("error handling incoming stream id %s - %e",h.id,b),h.timeline.close==null&&await h.close({signal:m}).catch(v=>h.abort(v))})}}),u=async(h,m={})=>{if(l==null)throw new vr("Connection is not multiplexed");f.log.trace("starting new stream for protocols %s",h);let b=await l.newStream();f.log.trace("started new stream %s for protocols %s",b.id,h);try{if(m.signal==null){b.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",h);let w=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);m={...m,signal:w}}b.log.trace("selecting protocol from protocols %s",h);let{stream:v,protocol:C}=await vo(b,h,{...m,log:b.log,yieldBytes:!0});b.log.trace("selected protocol %s",C);let x=Lb(C,this.components.registrar,m),p=rp(C,"outbound",f);if(p>=x){let w=new Mo(`Too many outbound protocol streams for protocol "${C}" - ${p}/${x}`);throw b.abort(w),w}return await this.components.peerStore.merge(i,{protocols:[C]}),b.source=v.source,b.sink=v.sink,b.protocol=C,v.closeWrite!=null&&(b.closeWrite=v.closeWrite),v.closeRead!=null&&(b.closeRead=v.closeRead),v.close!=null&&(b.close=v.close),this.components.metrics?.trackProtocolStream(b,f),b}catch(v){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,h,v),b.timeline.close==null&&b.abort(v),v}},Promise.all([l.sink(s.source),s.sink(l.source)]).catch(h=>{f.log.error("error piping data through muxer - %e",h)}));let d=o.timeline;o.timeline=new Proxy(d,{set:(...h)=>(h[1]==="close"&&h[2]!=null&&d.close==null&&(async()=>{try{f.status==="open"&&await f.close()}catch(m){f.log.error("error closing connection after timeline close %e",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:f})}})().catch(m=>{f.log.error("error thrown while dispatching connection:close event %e",m)}),Reflect.set(...h))}),o.timeline.upgraded=Date.now();let g=()=>{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??g,getStreams:()=>l?.streams??[],close:async h=>{await l?.close(h),await o.close(h)},abort:h=>{o.abort(h),l?.abort(h)}}),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 kr("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 Ao(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 vo(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 vo(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 Ao(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 Hi="2.8.8-5b004c0c4",$i="js-libp2p";function op(r,t){return`${r??$i}/${t??Hi} browser/${globalThis.navigator.userAgent}`}var Gi=class extends pe{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new pe,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??Ss(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=t.nodeInfo?.name??$i,s=t.nodeInfo?.version??Hi,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 Bs,connectionGater:kh(t.connectionGater),dns:t.dns});this.peerStore=this.configureComponent("peerStore",hh(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 Vi(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 Ri(this.components,t.transportManager)),this.configureComponent("connectionManager",new vi(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Ci(this.components,t.connectionMonitor)),this.configureComponent("registrar",new ki(this.components)),this.configureComponent("addressManager",new js(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 Li(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 Pi(this.components,{routers:c})),this.configureComponent("randomWalk",new Di(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[Wi]!=null&&(this.log("registering service %s for content routing",l),c.push(f[Wi])),f[Xi]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[Xi])),f[ji]!=null&&(this.log("registering service %s for peer discovery",l),f[ji].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={}){ze(t)&&(t=de(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,e);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Tt([L("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=jr(o);return await this.peerStore.patch(t,{publicKey:s},e),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,e){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async n=>{await this.components.registrar.unhandle(n,e)}))}async register(t,e,n){return this.components.registrar.register(t,e,n)}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 Db(r={}){r.privateKey??=await dd("Ed25519");let t=new Gi({...await Vd(r),peerId:gd(r.privateKey)});return r.start!==!1&&await t.start(),t}return pp(kb);})();
|
|
20
|
+
`),e),e.log('handle: responded with "na" for "%s"',o)}}var Wb=500,xu=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";[Au]=!0;get streams(){return this._getStreams()}async newStream(t,e){if(this.status==="closing")throw new Do("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 Rr("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(Wb);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 hp(r){return new xu(r)}function jb(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return mu}function Xb(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??gu}function pp(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var ia=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(t,e){this.components=t,this.connectionEncrypters=Lt({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),e.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Lt({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),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"),inboundErrors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_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 vi(`The multiaddr connection is blocked by gater.${t}`)}createInboundAbortSignal(t){let e=Re([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 Et(this.components.connectionManager.acceptIncomingConnection(t),o),!n)throw new Ai("Connection denied");await Et(this.shouldBlockConnection("denyInboundConnection",t),o),await this._performUpgrade(t,"inbound",{...e,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(t,e){try{this.metrics.dials?.increment({outbound:!0});let n=t.remoteAddr.getPeerId(),o;n!=null&&(o=me(n),await Et(this.shouldBlockConnection("denyOutboundConnection",o,t),e.signal));let s="outbound";return e.initiator===!1&&(s="inbound"),await this._performUpgrade(t,s,e)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(t,e,n){let o,s,i,a,c;this.components.metrics?.trackMultiaddrConnection(t),t.log.trace("starting the %s connection upgrade",e);let u=t;if(n?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(t.log("protecting the %s connection",e),u=await l.protect(t,n))}try{if(o=u,n?.skipEncryption!==!0){n?.onProgress?.(new dt(`upgrader:encrypt-${e}-connection`)),{conn:o,remotePeer:s,protocol:c,streamMuxer:a}=await(e==="inbound"?this._encryptInbound(u,n):this._encryptOutbound(u,n));let l={...u,...o};await this.shouldBlockConnection(e==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,l)}else{let l=t.remoteAddr.getPeerId();if(l==null)throw new Me(`${e} connection that skipped encryption must have a peer id`);let f=me(l);c="native",s=f}if(s.equals(this.components.peerId)){let l=new Lr("Can not dial self");throw t.abort(l),l}if(i=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(a==null&&this.streamMuxers.size>0){n?.onProgress?.(new dt(`upgrader:multiplex-${e}-connection`));let l=await(e==="inbound"?this._multiplexInbound({...u,...o},this.streamMuxers,n):this._multiplexOutbound({...u,...o},this.streamMuxers,n));a=l.muxerFactory,i=l.stream}}catch(l){throw t.log.error("failed to upgrade inbound connection %s %a - %e",e==="inbound"?"from":"to",t.remoteAddr,l),l}return await this.shouldBlockConnection(e==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,t),t.log("successfully upgraded %s connection",e),this._createConnection({cryptoProtocol:c,direction:e,maConn:t,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:n?.limits})}_createConnection(t){let{cryptoProtocol:e,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,limits:c}=t,u,l,f;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:h=>{if(f==null)return;let g=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Promise.resolve().then(async()=>{let b=this.components.registrar.getProtocols(),{stream:v,protocol:C}=await Co(h,b,{signal:g,log:h.log,yieldBytes:!1});if(f==null)return;f.log("incoming stream opened on %s",C);let x=jb(C,this.components.registrar);if(pp(C,"inbound",f)===x){let w=new No(`Too many inbound protocol streams for protocol "${C}" - limit ${x}`);throw h.abort(w),w}h.source=v.source,h.sink=v.sink,h.protocol=C,v.closeWrite!=null&&(h.closeWrite=v.closeWrite),v.closeRead!=null&&(h.closeRead=v.closeRead),v.close!=null&&(h.close=v.close),await this.components.peerStore.merge(i,{protocols:[C]},{signal:g}),this.components.metrics?.trackProtocolStream(h,f),this._onStream({connection:f,stream:h,protocol:C})}).catch(async b=>{f.log.error("error handling incoming stream id %s - %e",h.id,b),h.timeline.close==null&&await h.close({signal:g}).catch(v=>h.abort(v))})}}),l=async(h,g={})=>{if(u==null)throw new vr("Connection is not multiplexed");f.log.trace("starting new stream for protocols %s",h);let b=await u.newStream();f.log.trace("started new stream %s for protocols %s",b.id,h);try{if(g.signal==null){b.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",h);let w=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);g={...g,signal:w}}b.log.trace("selecting protocol from protocols %s",h);let{stream:v,protocol:C}=await _o(b,h,{...g,log:b.log,yieldBytes:!0});b.log.trace("selected protocol %s",C);let x=Xb(C,this.components.registrar,g),p=pp(C,"outbound",f);if(p>=x){let w=new Bo(`Too many outbound protocol streams for protocol "${C}" - ${p}/${x}`);throw b.abort(w),w}return await this.components.peerStore.merge(i,{protocols:[C]}),b.source=v.source,b.sink=v.sink,b.protocol=C,v.closeWrite!=null&&(b.closeWrite=v.closeWrite),v.closeRead!=null&&(b.closeRead=v.closeRead),v.close!=null&&(b.close=v.close),this.components.metrics?.trackProtocolStream(b,f),b}catch(v){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,h,v),b.timeline.close==null&&b.abort(v),v}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(h=>{f.log.error("error piping data through muxer - %e",h)}));let d=o.timeline;o.timeline=new Proxy(d,{set:(...h)=>(h[1]==="close"&&h[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(...h))}),o.timeline.upgraded=Date.now();let m=()=>{throw new vr("Connection is not multiplexed")};return f=hp({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:e,limits:c,logger:this.components.logger,newStream:l??m,getStreams:()=>u?.streams??[],close:async h=>{await u?.close(h),await o.close(h)},abort:h=>{o.abort(h),u?.abort(h)}}),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 Rr("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 Co(t,n,{...e,log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new Ar(`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 Ar(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 _o(t,n,{...e,log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new Ar(`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 Ar(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 _o(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 Co(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 aa="2.8.8-8e87be9e6",ca="js-libp2p";function gp(r,t){return`${r??ca}/${t??aa} browser/${globalThis.navigator.userAgent}`}var la=class extends Ht{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new Ht,n=e.dispatchEvent.bind(e);e.dispatchEvent=u=>{let l=n(u),f=this.dispatchEvent(new CustomEvent(u.type,{detail:u.detail}));return l||f},this.peerId=t.peerId,this.logger=t.logger??_s(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=t.nodeInfo?.name??ca,s=t.nodeInfo?.version??aa,i=this.components=Hh({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:{name:o,version:s,userAgent:t.nodeInfo?.userAgent??gp(o,s)},logger:this.logger,events:e,datastore:t.datastore??new ri,connectionGater:Wh(t.connectionGater),dns:t.dns});t.metrics!=null&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",Ch(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...t.peerStore})),i.events.addEventListener("peer:update",u=>{if(u.detail.previous==null){let l={id:u.detail.peer.id,multiaddrs:u.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:l})}}),t.connectionProtector!=null&&this.configureComponent("connectionProtector",t.connectionProtector(i)),this.components.upgrader=new ia(this.components,{connectionEncrypters:(t.connectionEncrypters??[]).map((u,l)=>this.configureComponent(`connection-encryption-${l}`,u(this.components))),streamMuxers:(t.streamMuxers??[]).map((u,l)=>this.configureComponent(`stream-muxers-${l}`,u(this.components))),inboundUpgradeTimeout:t.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:t.connectionManager?.inboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:t.connectionManager?.outboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new Yi(this.components,t.transportManager)),this.configureComponent("connectionManager",new Ui(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Hi(this.components,t.connectionMonitor)),this.configureComponent("registrar",new Xi(this.components)),this.configureComponent("addressManager",new hi(this.components,t.addresses));let a=(t.peerRouters??[]).map((u,l)=>this.configureComponent(`peer-router-${l}`,u(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Gi(this.components,{routers:a}));let c=(t.contentRouters??[]).map((u,l)=>this.configureComponent(`content-router-${l}`,u(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new $i(this.components,{routers:c})),this.configureComponent("randomWalk",new ji(this.components)),(t.peerDiscovery??[]).forEach((u,l)=>{this.configureComponent(`peer-discovery-${l}`,u(this.components)).addEventListener("peer",d=>{this.#t(d)})}),t.transports?.forEach((u,l)=>{this.components.transportManager.add(this.configureComponent(`transport-${l}`,u(this.components)))}),t.services!=null)for(let u of Object.keys(t.services)){let l=t.services[u],f=l(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",u);continue}this.services[u]=f,this.configureComponent(u,f),f[ua]!=null&&(this.log("registering service %s for content routing",u),c.push(f[ua])),f[da]!=null&&(this.log("registering service %s for peer routing",u),a.push(f[da])),f[fa]!=null&&(this.log("registering service %s for peer discovery",u),f[fa].addEventListener?.("peer",d=>{this.#t(d)}))}$h(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 k("no protocols were provided to open a stream");if(e=Array.isArray(e)?e:[e],e.length===0)throw new k("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={}){Ve(t)&&(t=me(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,e);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Dt([L("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=Yr(o);return await this.peerStore.patch(t,{publicKey:s},e),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,e){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async n=>{await this.components.registrar.unhandle(n,e)}))}async register(t,e,n){return this.components.registrar.register(t,e,n)}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 Yb(r={}){r.privateKey??=await Sd("Ed25519");let t=new la({...await eh(r),peerId:Td(r.privateKey)});return r.start!==!1&&await t.start(),t}return Ip(Zb);})();
|
|
21
21
|
/*! Bundled license information:
|
|
22
22
|
|
|
23
23
|
@noble/hashes/esm/utils.js:
|