@libp2p/circuit-relay-v2 3.2.8-78cd7d53e → 3.2.8-d53ef170c

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.
Files changed (2) hide show
  1. package/dist/index.min.js +1 -1
  2. package/package.json +10 -10
package/dist/index.min.js CHANGED
@@ -1,5 +1,5 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PCircuitRelayV2 = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var Libp2PCircuitRelayV2=(()=>{var Eo=Object.defineProperty;var Nu=Object.getOwnPropertyDescriptor;var Uu=Object.getOwnPropertyNames;var Ou=Object.prototype.hasOwnProperty;var It=(r,t)=>{for(var e in t)Eo(r,e,{get:t[e],enumerable:!0})},ku=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Uu(t))!Ou.call(r,o)&&o!==e&&Eo(r,o,{get:()=>t[o],enumerable:!(n=Nu(t,o))||n.enumerable});return r};var Mu=r=>ku(Eo({},"__esModule",{value:!0}),r);var Kd={};It(Kd,{RELAY_V2_HOP_CODEC:()=>Ft,RELAY_V2_STOP_CODEC:()=>qe,circuitRelayServer:()=>fu,circuitRelayTransport:()=>_u});var So=Symbol.for("@libp2p/peer-id");var vo="keep-alive";var Hs=Symbol.for("@libp2p/transport");var Vs;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Vs||(Vs={}));var ee=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var lt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},He=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Yr=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Xr=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var jr=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var gr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}},Re=class extends Error{static name="ListenError";constructor(t="Listen error"){super(t),this.name="ListenError"}};var Ge=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Mt=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:i})=>i!==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 Gs(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Ws(...r){let t=[];for(let e of r)Gs(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 $s(...r){let t=[];for(let e of r)Gs(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 Zs=Symbol.for("@libp2p/service-capabilities"),Ys=Symbol.for("@libp2p/service-dependencies");async function Xs(r,t,e){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,t,e.subarray())}function ot(r=0){return new Uint8Array(r)}function Lt(r=0){return new Uint8Array(r)}function Ut(r,t){t==null&&(t=r.reduce((o,i)=>o+i.length,0));let e=Lt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}function ft(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}var Qs=Symbol.for("@achingbrain/uint8arraylist");function js(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 Qr(r){return!!r?.[Qs]}var ct=class r{bufs;length;[Qs]=!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(Qr(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(Qr(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=js(this.bufs,t);return e.buf[e.index]}set(t,e){let n=js(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(Qr(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 Ut(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Ut(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),i=new r;return i.length=o,i.bufs=[...n],i}_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 i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=o,c=a+s.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(s);break}let f=t-a;n.push(s.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(s);continue}n.push(s.subarray(t-a));continue}if(u){if(e===c){n.push(s);break}n.push(s.subarray(0,e-a));break}n.push(s)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Qr(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 i=256,s=new Int32Array(i);for(let f=0;f<i;f++)s[f]=-1;for(let f=0;f<o;f++)s[n[f]]=f;let a=s,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=Lt(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=ot(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=ot(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=ot(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=Lt(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=ot(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=ot(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=ot(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=ot(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=ot(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(!ft(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,i)=>o+i.byteLength,0)),n.length=e,n}};var Lo={};It(Lo,{base10:()=>Hu});var Tp=new Uint8Array(0);function Js(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 re(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 ta(r){return new TextEncoder().encode(r)}function ea(r){return new TextDecoder().decode(r)}function Ku(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 i=r.charAt(o),s=i.charCodeAt(0);if(e[s]!==255)throw new TypeError(i+" is ambiguous");e[s]=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(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var b=0,h=0,w=0,S=y.length;w!==S&&y[w]===0;)w++,b++;for(var m=(S-w)*u+1>>>0,_=new Uint8Array(m);w!==S;){for(var C=y[w],D=0,I=m-1;(C!==0||D<h)&&I!==-1;I--,D++)C+=256*_[I]>>>0,_[I]=C%a>>>0,C=C/a>>>0;if(C!==0)throw new Error("Non-zero carry");h=D,w++}for(var R=m-h;R!==m&&_[R]===0;)R++;for(var T=c.repeat(b);R<m;++R)T+=r.charAt(_[R]);return T}function d(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var b=0;if(y[b]!==" "){for(var h=0,w=0;y[b]===c;)h++,b++;for(var S=(y.length-b)*l+1>>>0,m=new Uint8Array(S);y[b];){var _=e[y.charCodeAt(b)];if(_===255)return;for(var C=0,D=S-1;(_!==0||C<w)&&D!==-1;D--,C++)_+=a*m[D]>>>0,m[D]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");w=C,b++}if(y[b]!==" "){for(var I=S-w;I!==S&&m[I]===0;)I++;for(var R=new Uint8Array(h+(S-I)),T=h;I!==S;)R[T++]=m[I++];return R}}}function g(y){var b=d(y);if(b)return b;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:g}}var qu=Ku,Fu=qu,na=Fu;var Ao=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")}},_o=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 oa(this,t)}},Io=class{decoders;constructor(t){this.decoders=t}or(t){return oa(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 oa(r,t){return new Io({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var To=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 Ao(t,e,n),this.decoder=new _o(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function We({name:r,prefix:t,encode:e,decode:n}){return new To(r,t,e,n)}function pe({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=na(e,r);return We({prefix:t,name:r,encode:n,decode:i=>re(o(i))})}function zu(r,t,e,n){let o={};for(let u=0;u<t.length;++u)o[t[u]]=u;let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*e/8|0),a=0,c=0,l=0;for(let u=0;u<i;++u){let f=o[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|f,a+=e,a>=8&&(a-=8,s[l++]=255&c>>a)}if(a>=e||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return s}function Vu(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>e;)s-=e,i+=t[o&a>>s];if(s!==0&&(i+=t[o&a<<e-s]),n)for(;(i.length*e&7)!==0;)i+="=";return i}function st({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return We({prefix:t,name:r,encode(o){return Vu(o,n,e)},decode(o){return zu(o,n,e,r)}})}var Hu=pe({prefix:"9",name:"base10",alphabet:"0123456789"});var Ro={};It(Ro,{base16:()=>Gu,base16upper:()=>Wu});var Gu=st({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Wu=st({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Co={};It(Co,{base2:()=>$u});var $u=st({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Do={};It(Do,{base256emoji:()=>Qu});var ia=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}"),Zu=ia.reduce((r,t,e)=>(r[e]=t,r),[]),Yu=ia.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Xu(r){return r.reduce((t,e)=>(t+=Zu[e],t),"")}function ju(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Yu[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Qu=We({prefix:"\u{1F680}",name:"base256emoji",encode:Xu,decode:ju});var Bo={};It(Bo,{base32:()=>ne,base32hex:()=>rl,base32hexpad:()=>ol,base32hexpadupper:()=>il,base32hexupper:()=>nl,base32pad:()=>tl,base32padupper:()=>el,base32upper:()=>Ju,base32z:()=>sl});var ne=st({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ju=st({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),tl=st({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),el=st({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),rl=st({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),nl=st({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ol=st({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),il=st({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),sl=st({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Po={};It(Po,{base36:()=>br,base36upper:()=>al});var br=pe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),al=pe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var No={};It(No,{base58btc:()=>Z,base58flickr:()=>cl});var Z=pe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),cl=pe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Oo={};It(Oo,{base64:()=>ul,base64pad:()=>ll,base64url:()=>Uo,base64urlpad:()=>fl});var ul=st({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ll=st({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Uo=st({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),fl=st({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ko={};It(ko,{base8:()=>hl});var hl=st({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Mo={};It(Mo,{identity:()=>dl});var dl=We({prefix:"\0",name:"identity",encode:r=>ea(r),decode:r=>ta(r)});var Vp=new TextEncoder,Hp=new TextDecoder;var qo={};It(qo,{identity:()=>Vt});var yl=ca,sa=128,gl=127,bl=~gl,xl=Math.pow(2,31);function ca(r,t,e){t=t||[],e=e||0;for(var n=e;r>=xl;)t[e++]=r&255|sa,r/=128;for(;r&bl;)t[e++]=r&255|sa,r>>>=7;return t[e]=r|0,ca.bytes=e-n+1,t}var wl=Ko,El=128,aa=127;function Ko(r,n){var e=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw Ko.bytes=0,new RangeError("Could not decode varint");s=r[i++],e+=o<28?(s&aa)<<o:(s&aa)*Math.pow(2,o),o+=7}while(s>=El);return Ko.bytes=i-n,e}var Sl=Math.pow(2,7),vl=Math.pow(2,14),Al=Math.pow(2,21),_l=Math.pow(2,28),Il=Math.pow(2,35),Tl=Math.pow(2,42),Ll=Math.pow(2,49),Rl=Math.pow(2,56),Cl=Math.pow(2,63),Dl=function(r){return r<Sl?1:r<vl?2:r<Al?3:r<_l?4:r<Il?5:r<Tl?6:r<Ll?7:r<Rl?8:r<Cl?9:10},Bl={encode:yl,decode:wl,encodingLength:Dl},Pl=Bl,xr=Pl;function wr(r,t=0){return[xr.decode(r,t),xr.decode.bytes]}function $e(r,t,e=0){return xr.encode(r,t,e),t}function Ze(r){return xr.encodingLength(r)}function zt(r,t){let e=t.byteLength,n=Ze(r),o=n+Ze(e),i=new Uint8Array(o+e);return $e(r,i,0),$e(e,i,n),i.set(t,o),new Ye(r,e,t,i)}function Kt(r){let t=re(r),[e,n]=wr(t),[o,i]=wr(t.subarray(n)),s=t.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Ye(e,o,s,t)}function ua(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Js(r.bytes,e.bytes)}}var Ye=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};var la=0,Nl="identity",fa=re;function Ul(r){return zt(la,fa(r))}var Vt={code:la,name:Nl,encode:fa,digest:Ul};var Vo={};It(Vo,{sha256:()=>Xe,sha512:()=>Ol});function zo({name:r,code:t,encode:e}){return new Fo(r,t,e)}var Fo=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?zt(this.code,e):e.then(n=>zt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function da(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Xe=zo({name:"sha2-256",code:18,encode:da("SHA-256")}),Ol=zo({name:"sha2-512",code:19,encode:da("SHA-512")});function pa(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Ml(e,Ho(r),t??Z.encoder);default:return Kl(e,Ho(r),t??ne.encoder)}}var ma=new WeakMap;function Ho(r){let t=ma.get(r);if(t==null){let e=new Map;return ma.set(r,e),e}return t}var at=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Er)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==ql)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=zt(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&ua(t.multihash,n.multihash)}toString(t){return pa(this,t)}toJSON(){return{"/":pa(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:i,bytes:s}=e;return new r(n,o,i,s??ya(n,o,i.bytes))}else if(e[Fl]===!0){let{version:n,multihash:o,code:i}=e,s=Kt(o);return r.create(n,i,s)}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!==Er)throw new Error(`Version 0 CID must use dag-pb (code: ${Er}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=ya(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Er,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=re(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let i=o.subarray(e.multihashSize-e.digestSize),s=new Ye(e.multihashCode,e.digestSize,i,o);return[e.version===0?r.createV0(s):r.createV1(e.codec,s),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,d]=wr(t.subarray(e));return e+=d,f},o=n(),i=Er;if(o===18?(o=0,e=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=e,a=n(),c=n(),l=e+c,u=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=kl(t,e),i=r.decode(o);if(i.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ho(i).set(n,t),i}};function kl(r,t){switch(r[0]){case"Q":{let e=t??Z;return[Z.prefix,e.decode(`${Z.prefix}${r}`)]}case Z.prefix:{let e=t??Z;return[Z.prefix,e.decode(r)]}case ne.prefix:{let e=t??ne;return[ne.prefix,e.decode(r)]}case br.prefix:{let e=t??br;return[br.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 Ml(r,t,e){let{prefix:n}=e;if(n!==Z.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let i=e.encode(r).slice(1);return t.set(n,i),i}else return o}function Kl(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let i=e.encode(r);return t.set(n,i),i}else return o}var Er=112,ql=18;function ya(r,t,e){let n=Ze(r),o=n+Ze(t),i=new Uint8Array(o+e.byteLength);return $e(r,i,0),$e(t,i,n),i.set(e,o),i}var Fl=Symbol.for("@ipld/js-cid/CID");var Sr={...Mo,...Co,...ko,...Lo,...Ro,...Bo,...Po,...No,...Oo,...Do},hm={...Vo,...qo};function ba(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var ga=ba("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Go=ba("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=Lt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),zl={utf8:ga,"utf-8":ga,hex:Sr.base16,latin1:Go,ascii:Go,binary:Go,...Sr},tn=zl;function M(r,t="utf8"){let e=tn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function O(r,t="utf8"){let e=tn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Vl=parseInt("11111",2),Wo=parseInt("10000000",2),Hl=parseInt("01111111",2),xa={0:vr,1:vr,2:Gl,3:Zl,4:Yl,5:$l,6:Wl,16:vr,22:vr,48:vr};function oe(r,t={offset:0}){let e=r[t.offset]&Vl;if(t.offset++,xa[e]!=null)return xa[e](r,t);throw new Error("No decoder for tag "+e)}function Ar(r,t){let e=0;if((r[t.offset]&Wo)===Wo){let n=r[t.offset]&Hl,o="0x";t.offset++;for(let i=0;i<n;i++,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 vr(r,t){Ar(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=oe(r,t);if(n===null)break;e.push(n)}return e}function Gl(r,t){let e=Ar(r,t),n=t.offset,o=t.offset+e,i=[];for(let s=n;s<o;s++)s===n&&r[s]===0||i.push(r[s]);return t.offset+=e,Uint8Array.from(i)}function Wl(r,t){let e=Ar(r,t),n=t.offset+e,o=r[t.offset];t.offset++;let i=0,s=0;o<40?(i=0,s=o):o<80?(i=1,s=o-40):(i=2,s=o-80);let a=`${i}.${s}`,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 $l(r,t){return t.offset++,null}function Zl(r,t){let e=Ar(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 Yl(r,t){let e=Ar(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function Xl(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new ct;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function $o(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=Xl(r.byteLength);return new ct(Uint8Array.from([t.byteLength|Wo]),t)}function Rt(r){let t=new ct,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new ct(Uint8Array.from([2]),$o(t),t)}function en(r){let t=Uint8Array.from([0]),e=new ct(t,r);return new ct(Uint8Array.from([3]),$o(e),e)}function me(r,t=48){let e=new ct;for(let n of r)e.append(n);return new ct(Uint8Array.from([t]),$o(e),e)}var je=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=wa(this.jwk)),this._raw}toMultihash(){return Vt.digest(jt(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ft(this.raw,t.raw)}async verify(t,e){return Xs(this.jwk,e,t)}};var jl=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Ql=Uint8Array.from([6,5,43,129,4,0,34]),Jl=Uint8Array.from([6,5,43,129,4,0,35]),tf={ext:!0,kty:"EC",crv:"P-256"},ef={ext:!0,kty:"EC",crv:"P-384"},rf={ext:!0,kty:"EC",crv:"P-521"},Zo=32,Yo=48,Xo=66;function jo(r){let t=oe(r);return Ea(t)}function Ea(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Zo*2+1)return n=O(t.subarray(e,e+Zo),"base64url"),o=O(t.subarray(e+Zo),"base64url"),new je({...tf,key_ops:["verify"],x:n,y:o});if(t.byteLength===Yo*2+1)return n=O(t.subarray(e,e+Yo),"base64url"),o=O(t.subarray(e+Yo),"base64url"),new je({...ef,key_ops:["verify"],x:n,y:o});if(t.byteLength===Xo*2+1)return n=O(t.subarray(e,e+Xo),"base64url"),o=O(t.subarray(e+Xo),"base64url"),new je({...rf,key_ops:["verify"],x:n,y:o});throw new lt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function wa(r){return me([Rt(Uint8Array.from([1])),me([nf(r.crv)],160),me([en(new ct(Uint8Array.from([4]),M(r.x??"","base64url"),M(r.y??"","base64url")))],161)]).subarray()}function nf(r){if(r==="P-256")return jl;if(r==="P-384")return Ql;if(r==="P-521")return Jl;throw new lt(`Invalid curve ${r}`)}function Sa(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function of(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Qe(r,...t){if(!of(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 va(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Sa(r.outputLen),Sa(r.blockLen)}function Je(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 Aa(r,t){Qe(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}var Ce=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function rn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Ht(r,t){return r<<32-t|r>>>t}function _a(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function _r(r){return typeof r=="string"&&(r=_a(r)),Qe(r),r}function Qo(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Qe(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let i=r[n];e.set(i,o),o+=i.length}return e}var tr=class{clone(){return this._cloneInto()}};function nn(r){let t=n=>r().update(_r(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function on(r=32){if(Ce&&typeof Ce.getRandomValues=="function")return Ce.getRandomValues(new Uint8Array(r));if(Ce&&typeof Ce.randomBytes=="function")return Ce.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function sf(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(e>>o&i),a=Number(e&i),c=n?4:0,l=n?0:4;r.setUint32(t+c,s,n),r.setUint32(t+l,a,n)}function Ia(r,t,e){return r&t^~r&e}function Ta(r,t,e){return r&t^r&e^t&e}var er=class extends tr{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=rn(this.buffer)}update(t){Je(this);let{view:e,buffer:n,blockLen:o}=this;t=_r(t);let i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=rn(t);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Je(this),Aa(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;e[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>o-s&&(this.process(n,0),s=0);for(let f=s;f<o;f++)e[f]=0;sf(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=rn(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],i)}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:i,destroyed:s,pos:a}=this;return t.length=o,t.pos=a,t.finished=i,t.destroyed=s,o%e&&t.buffer.set(n),t}};var sn=BigInt(4294967295),Jo=BigInt(32);function La(r,t=!1){return t?{h:Number(r&sn),l:Number(r>>Jo&sn)}:{h:Number(r>>Jo&sn)|0,l:Number(r&sn)|0}}function af(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:i,l:s}=La(r[o],t);[e[o],n[o]]=[i,s]}return[e,n]}var cf=(r,t)=>BigInt(r>>>0)<<Jo|BigInt(t>>>0),uf=(r,t,e)=>r>>>e,lf=(r,t,e)=>r<<32-e|t>>>e,ff=(r,t,e)=>r>>>e|t<<32-e,hf=(r,t,e)=>r<<32-e|t>>>e,df=(r,t,e)=>r<<64-e|t>>>e-32,pf=(r,t,e)=>r>>>e-32|t<<64-e,mf=(r,t)=>t,yf=(r,t)=>r,gf=(r,t,e)=>r<<e|t>>>32-e,bf=(r,t,e)=>t<<e|r>>>32-e,xf=(r,t,e)=>t<<e-32|r>>>64-e,wf=(r,t,e)=>r<<e-32|t>>>64-e;function Ef(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Sf=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),vf=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Af=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),_f=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,If=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Tf=(r,t,e,n,o,i)=>t+e+n+o+i+(r/2**32|0)|0;var Lf={fromBig:La,split:af,toBig:cf,shrSH:uf,shrSL:lf,rotrSH:ff,rotrSL:hf,rotrBH:df,rotrBL:pf,rotr32H:mf,rotr32L:yf,rotlSH:gf,rotlSL:bf,rotlBH:xf,rotlBL:wf,add:Ef,add3L:Sf,add3H:vf,add4L:Af,add4H:_f,add5H:Tf,add5L:If},U=Lf;var[Rf,Cf]=U.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),ye=new Uint32Array(80),ge=new Uint32Array(80),ti=class extends er{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:g,Gl:y,Hh:b,Hl:h}=this;return[t,e,n,o,i,s,a,c,l,u,f,d,g,y,b,h]}set(t,e,n,o,i,s,a,c,l,u,f,d,g,y,b,h){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|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=y|0,this.Hh=b|0,this.Hl=h|0}process(t,e){for(let m=0;m<16;m++,e+=4)ye[m]=t.getUint32(e),ge[m]=t.getUint32(e+=4);for(let m=16;m<80;m++){let _=ye[m-15]|0,C=ge[m-15]|0,D=U.rotrSH(_,C,1)^U.rotrSH(_,C,8)^U.shrSH(_,C,7),I=U.rotrSL(_,C,1)^U.rotrSL(_,C,8)^U.shrSL(_,C,7),R=ye[m-2]|0,T=ge[m-2]|0,et=U.rotrSH(R,T,19)^U.rotrBH(R,T,61)^U.shrSH(R,T,6),H=U.rotrSL(R,T,19)^U.rotrBL(R,T,61)^U.shrSL(R,T,6),z=U.add4L(I,H,ge[m-7],ge[m-16]),ht=U.add4H(z,D,et,ye[m-7],ye[m-16]);ye[m]=ht|0,ge[m]=z|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:g,Fl:y,Gh:b,Gl:h,Hh:w,Hl:S}=this;for(let m=0;m<80;m++){let _=U.rotrSH(f,d,14)^U.rotrSH(f,d,18)^U.rotrBH(f,d,41),C=U.rotrSL(f,d,14)^U.rotrSL(f,d,18)^U.rotrBL(f,d,41),D=f&g^~f&b,I=d&y^~d&h,R=U.add5L(S,C,I,Cf[m],ge[m]),T=U.add5H(R,w,_,D,Rf[m],ye[m]),et=R|0,H=U.rotrSH(n,o,28)^U.rotrBH(n,o,34)^U.rotrBH(n,o,39),z=U.rotrSL(n,o,28)^U.rotrBL(n,o,34)^U.rotrBL(n,o,39),ht=n&i^n&a^i&a,v=o&s^o&c^s&c;w=b|0,S=h|0,b=g|0,h=y|0,g=f|0,y=d|0,{h:f,l:d}=U.add(l|0,u|0,T|0,et|0),l=a|0,u=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let L=U.add3L(et,z,v);n=U.add3H(L,T,H,ht),o=L|0}({h:n,l:o}=U.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=U.add(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=U.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=U.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=U.add(this.Eh|0,this.El|0,f|0,d|0),{h:g,l:y}=U.add(this.Fh|0,this.Fl|0,g|0,y|0),{h:b,l:h}=U.add(this.Gh|0,this.Gl|0,b|0,h|0),{h:w,l:S}=U.add(this.Hh|0,this.Hl|0,w|0,S|0),this.set(n,o,i,s,a,c,l,u,f,d,g,y,b,h,w,S)}roundClean(){ye.fill(0),ge.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Ra=nn(()=>new ti);var un={};It(un,{aInRange:()=>Ct,abool:()=>Gt,abytes:()=>rr,bitGet:()=>Of,bitLen:()=>oi,bitMask:()=>Tr,bitSet:()=>kf,bytesToHex:()=>se,bytesToNumberBE:()=>ae,bytesToNumberLE:()=>xe,concatBytes:()=>ce,createHmacDrbg:()=>ii,ensureBytes:()=>it,equalBytes:()=>Nf,hexToBytes:()=>Be,hexToNumber:()=>ni,inRange:()=>Ir,isBytes:()=>be,memoized:()=>Ne,notImplemented:()=>Kf,numberToBytesBE:()=>we,numberToBytesLE:()=>Pe,numberToHexUnpadded:()=>De,numberToVarBytesBE:()=>Pf,utf8ToBytes:()=>Uf,validateObject:()=>Qt});var an=BigInt(0),cn=BigInt(1),Df=BigInt(2);function be(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function rr(r){if(!be(r))throw new Error("Uint8Array expected")}function Gt(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}var Bf=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function se(r){rr(r);let t="";for(let e=0;e<r.length;e++)t+=Bf[r[e]];return t}function De(r){let t=r.toString(16);return t.length&1?"0"+t:t}function ni(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?an:BigInt("0x"+r)}var ie={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ca(r){if(r>=ie._0&&r<=ie._9)return r-ie._0;if(r>=ie.A&&r<=ie.F)return r-(ie.A-10);if(r>=ie.a&&r<=ie.f)return r-(ie.a-10)}function Be(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,i=0;o<e;o++,i+=2){let s=Ca(r.charCodeAt(i)),a=Ca(r.charCodeAt(i+1));if(s===void 0||a===void 0){let c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function ae(r){return ni(se(r))}function xe(r){return rr(r),ni(se(Uint8Array.from(r).reverse()))}function we(r,t){return Be(r.toString(16).padStart(t*2,"0"))}function Pe(r,t){return we(r,t).reverse()}function Pf(r){return Be(De(r))}function it(r,t,e){let n;if(typeof t=="string")try{n=Be(t)}catch(i){throw new Error(r+" must be hex string or Uint8Array, cause: "+i)}else if(be(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 ce(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];rr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let i=r[n];e.set(i,o),o+=i.length}return e}function Nf(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function Uf(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var ei=r=>typeof r=="bigint"&&an<=r;function Ir(r,t,e){return ei(r)&&ei(t)&&ei(e)&&t<=r&&r<e}function Ct(r,t,e,n){if(!Ir(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function oi(r){let t;for(t=0;r>an;r>>=cn,t+=1);return t}function Of(r,t){return r>>BigInt(t)&cn}function kf(r,t,e){return r|(e?cn:an)<<BigInt(t)}var Tr=r=>(Df<<BigInt(r-1))-cn,ri=r=>new Uint8Array(r),Da=r=>Uint8Array.from(r);function ii(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=ri(r),o=ri(r),i=0,s=()=>{n.fill(1),o.fill(0),i=0},a=(...f)=>e(o,n,...f),c=(f=ri())=>{o=a(Da([0]),f),n=a(),f.length!==0&&(o=a(Da([1]),f),n=a())},l=()=>{if(i++>=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 ce(...d)};return(f,d)=>{s(),c(f);let g;for(;!(g=d(l()));)c();return s(),g}}var Mf={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"||be(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 Qt(r,t,e={}){let n=(o,i,s)=>{let a=Mf[i];if(typeof a!="function")throw new Error("invalid validator function");let c=r[o];if(!(s&&c===void 0)&&!a(c,r))throw new Error("param "+String(o)+" is invalid. Expected "+i+", got "+c)};for(let[o,i]of Object.entries(t))n(o,i,!1);for(let[o,i]of Object.entries(e))n(o,i,!0);return r}var Kf=()=>{throw new Error("not implemented")};function Ne(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let i=r(e,...n);return t.set(e,i),i}}var dt=BigInt(0),rt=BigInt(1),Ue=BigInt(2),qf=BigInt(3),si=BigInt(4),Ba=BigInt(5),Pa=BigInt(8),Ff=BigInt(9),zf=BigInt(16);function X(r,t){let e=r%t;return e>=dt?e:t+e}function Vf(r,t,e){if(t<dt)throw new Error("invalid exponent, negatives unsupported");if(e<=dt)throw new Error("invalid modulus");if(e===rt)return dt;let n=rt;for(;t>dt;)t&rt&&(n=n*r%e),r=r*r%e,t>>=rt;return n}function nt(r,t,e){let n=r;for(;t-- >dt;)n*=n,n%=e;return n}function ln(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=X(r,t),n=t,o=dt,i=rt,s=rt,a=dt;for(;e!==dt;){let l=n/e,u=n%e,f=o-s*l,d=i-a*l;n=e,e=u,o=s,i=a,s=f,a=d}if(n!==rt)throw new Error("invert: does not exist");return X(o,t)}function Hf(r){let t=(r-rt)/Ue,e,n,o;for(e=r-rt,n=0;e%Ue===dt;e/=Ue,n++);for(o=Ue;o<r&&Vf(o,t,r)!==r-rt;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let s=(r+rt)/si;return function(c,l){let u=c.pow(l,s);if(!c.eql(c.sqr(u),l))throw new Error("Cannot find square root");return u}}let i=(e+rt)/Ue;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),e),f=a.pow(c,i),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let g=1;for(let b=a.sqr(d);g<l&&!a.eql(b,a.ONE);g++)b=a.sqr(b);let y=a.pow(u,rt<<BigInt(l-g-1));u=a.sqr(y),f=a.mul(f,y),d=a.mul(d,u),l=g}return f}}function Gf(r){if(r%si===qf){let t=(r+rt)/si;return function(n,o){let i=n.pow(o,t);if(!n.eql(n.sqr(i),o))throw new Error("Cannot find square root");return i}}if(r%Pa===Ba){let t=(r-Ba)/Pa;return function(n,o){let i=n.mul(o,Ue),s=n.pow(i,t),a=n.mul(o,s),c=n.mul(n.mul(a,Ue),s),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%zf,Hf(r)}var Na=(r,t)=>(X(r,t)&rt)===rt,Wf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ai(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Wf.reduce((n,o)=>(n[o]="function",n),t);return Qt(r,e)}function $f(r,t,e){if(e<dt)throw new Error("invalid exponent, negatives unsupported");if(e===dt)return r.ONE;if(e===rt)return t;let n=r.ONE,o=t;for(;e>dt;)e&rt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=rt;return n}function Zf(r,t){let e=new Array(t.length),n=t.reduce((i,s,a)=>r.is0(s)?i:(e[a]=i,r.mul(i,s)),r.ONE),o=r.inv(n);return t.reduceRight((i,s,a)=>r.is0(s)?i:(e[a]=r.mul(i,e[a]),r.mul(i,s)),o),e}function ci(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Ee(r,t,e=!1,n={}){if(r<=dt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:i}=ci(r,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let s,a=Object.freeze({ORDER:r,isLE:e,BITS:o,BYTES:i,MASK:Tr(o),ZERO:dt,ONE:rt,create:c=>X(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&rt)===rt,neg:c=>X(-c,r),eql:(c,l)=>c===l,sqr:c=>X(c*c,r),add:(c,l)=>X(c+l,r),sub:(c,l)=>X(c-l,r),mul:(c,l)=>X(c*l,r),pow:(c,l)=>$f(a,c,l),div:(c,l)=>X(c*ln(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>ln(c,r),sqrt:n.sqrt||(c=>(s||(s=Gf(r)),s(a,c))),invertBatch:c=>Zf(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?Pe(c,i):we(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return e?xe(c):ae(c)}});return Object.freeze(a)}function Ua(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 ui(r){let t=Ua(r);return t+Math.ceil(t/2)}function Oa(r,t,e=!1){let n=r.length,o=Ua(t),i=ui(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=e?xe(r):ae(r),a=X(s,t-rt)+rt;return e?Pe(a,o):we(a,o)}var ka=BigInt(0),fn=BigInt(1);function li(r,t){let e=t.negate();return r?e:t}function Ma(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function fi(r,t){Ma(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1);return{windows:e,windowSize:n}}function Yf(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 Xf(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 hi=new WeakMap,Ka=new WeakMap;function di(r){return Ka.get(r)||1}function hn(r,t){return{constTimeNegate:li,hasPrecomputes(e){return di(e)!==1},unsafeLadder(e,n,o=r.ZERO){let i=e;for(;n>ka;)n&fn&&(o=o.add(i)),i=i.double(),n>>=fn;return o},precomputeWindow(e,n){let{windows:o,windowSize:i}=fi(n,t),s=[],a=e,c=a;for(let l=0;l<o;l++){c=a,s.push(c);for(let u=1;u<i;u++)c=c.add(a),s.push(c);a=c.double()}return s},wNAF(e,n,o){let{windows:i,windowSize:s}=fi(e,t),a=r.ZERO,c=r.BASE,l=BigInt(2**e-1),u=2**e,f=BigInt(e);for(let d=0;d<i;d++){let g=d*s,y=Number(o&l);o>>=f,y>s&&(y-=u,o+=fn);let b=g,h=g+Math.abs(y)-1,w=d%2!==0,S=y<0;y===0?c=c.add(li(w,n[b])):a=a.add(li(S,n[h]))}return{p:a,f:c}},wNAFUnsafe(e,n,o,i=r.ZERO){let{windows:s,windowSize:a}=fi(e,t),c=BigInt(2**e-1),l=2**e,u=BigInt(e);for(let f=0;f<s;f++){let d=f*a;if(o===ka)break;let g=Number(o&c);if(o>>=u,g>a&&(g-=l,o+=fn),g===0)continue;let y=n[d+Math.abs(g)-1];g<0&&(y=y.negate()),i=i.add(y)}return i},getPrecomputes(e,n,o){let i=hi.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&hi.set(n,o(i))),i},wNAFCached(e,n,o){let i=di(e);return this.wNAF(i,this.getPrecomputes(i,e,o),n)},wNAFCachedUnsafe(e,n,o,i){let s=di(e);return s===1?this.unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,o),n,i)},setWindowSize(e,n){Ma(n,t),Ka.set(e,n),hi.delete(e)}}}function dn(r,t,e,n){if(Yf(e,r),Xf(n,t),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,i=oi(BigInt(e.length)),s=i>12?i-3:i>4?i-2:i?2:1,a=(1<<s)-1,c=new Array(a+1).fill(o),l=Math.floor((t.BITS-1)/s)*s,u=o;for(let f=l;f>=0;f-=s){c.fill(o);for(let g=0;g<n.length;g++){let y=n[g],b=Number(y>>BigInt(f)&BigInt(a));c[b]=c[b].add(e[g])}let d=o;for(let g=c.length-1,y=o;g>0;g--)y=y.add(c[g]),d=d.add(y);if(u=u.add(d),f!==0)for(let g=0;g<s;g++)u=u.double()}return u}function Lr(r){return ai(r.Fp),Qt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ci(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Wt=BigInt(0),Dt=BigInt(1),pn=BigInt(2),jf=BigInt(8),Qf={zip215:!0};function Jf(r){let t=Lr(r);return Qt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function qa(r){let t=Jf(r),{Fp:e,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=t,l=pn<<BigInt(a*8)-Dt,u=e.create,f=Ee(t.n,t.nBitLength),d=t.uvRatio||((x,p)=>{try{return{isValid:!0,value:e.sqrt(x*e.inv(p))}}catch{return{isValid:!1,value:Wt}}}),g=t.adjustScalarBytes||(x=>x),y=t.domain||((x,p,E)=>{if(Gt("phflag",E),p.length||E)throw new Error("Contexts/pre-hash are not supported");return x});function b(x,p){Ct("coordinate "+x,p,Wt,l)}function h(x){if(!(x instanceof m))throw new Error("ExtendedPoint expected")}let w=Ne((x,p)=>{let{ex:E,ey:A,ez:B}=x,P=x.is0();p==null&&(p=P?jf:e.inv(B));let k=u(E*p),V=u(A*p),N=u(B*p);if(P)return{x:Wt,y:Dt};if(N!==Dt)throw new Error("invZ was invalid");return{x:k,y:V}}),S=Ne(x=>{let{a:p,d:E}=t;if(x.is0())throw new Error("bad point: ZERO");let{ex:A,ey:B,ez:P,et:k}=x,V=u(A*A),N=u(B*B),$=u(P*P),J=u($*$),pt=u(V*p),mt=u($*u(pt+N)),gt=u(J+u(E*u(V*N)));if(mt!==gt)throw new Error("bad point: equation left != right (1)");let bt=u(A*B),Tt=u(P*k);if(bt!==Tt)throw new Error("bad point: equation left != right (2)");return!0});class m{constructor(p,E,A,B){this.ex=p,this.ey=E,this.ez=A,this.et=B,b("x",p),b("y",E),b("z",A),b("t",B),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(p){if(p instanceof m)throw new Error("extended point not allowed");let{x:E,y:A}=p||{};return b("x",E),b("y",A),new m(E,A,Dt,u(E*A))}static normalizeZ(p){let E=e.invertBatch(p.map(A=>A.ez));return p.map((A,B)=>A.toAffine(E[B])).map(m.fromAffine)}static msm(p,E){return dn(m,f,p,E)}_setWindowSize(p){D.setWindowSize(this,p)}assertValidity(){S(this)}equals(p){h(p);let{ex:E,ey:A,ez:B}=this,{ex:P,ey:k,ez:V}=p,N=u(E*V),$=u(P*B),J=u(A*V),pt=u(k*B);return N===$&&J===pt}is0(){return this.equals(m.ZERO)}negate(){return new m(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:p}=t,{ex:E,ey:A,ez:B}=this,P=u(E*E),k=u(A*A),V=u(pn*u(B*B)),N=u(p*P),$=E+A,J=u(u($*$)-P-k),pt=N+k,mt=pt-V,gt=N-k,bt=u(J*mt),Tt=u(pt*gt),_t=u(J*gt),Yt=u(mt*pt);return new m(bt,Tt,Yt,_t)}add(p){h(p);let{a:E,d:A}=t,{ex:B,ey:P,ez:k,et:V}=this,{ex:N,ey:$,ez:J,et:pt}=p;if(E===BigInt(-1)){let Os=u((P-B)*($+N)),ks=u((P+B)*($-N)),wo=u(ks-Os);if(wo===Wt)return this.double();let Ms=u(k*pn*pt),Ks=u(V*pn*J),qs=Ks+Ms,Fs=ks+Os,zs=Ks-Ms,Cu=u(qs*wo),Du=u(Fs*zs),Bu=u(qs*zs),Pu=u(wo*Fs);return new m(Cu,Du,Pu,Bu)}let mt=u(B*N),gt=u(P*$),bt=u(V*A*pt),Tt=u(k*J),_t=u((B+P)*(N+$)-mt-gt),Yt=Tt-bt,te=Tt+bt,yr=u(gt-E*mt),Iu=u(_t*Yt),Tu=u(te*yr),Lu=u(_t*yr),Ru=u(Yt*te);return new m(Iu,Tu,Ru,Lu)}subtract(p){return this.add(p.negate())}wNAF(p){return D.wNAFCached(this,p,m.normalizeZ)}multiply(p){let E=p;Ct("scalar",E,Dt,n);let{p:A,f:B}=this.wNAF(E);return m.normalizeZ([A,B])[0]}multiplyUnsafe(p,E=m.ZERO){let A=p;return Ct("scalar",A,Wt,n),A===Wt?C:this.is0()||A===Dt?this:D.wNAFCachedUnsafe(this,A,m.normalizeZ,E)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return D.unsafeLadder(this,n).is0()}toAffine(p){return w(this,p)}clearCofactor(){let{h:p}=t;return p===Dt?this:this.multiplyUnsafe(p)}static fromHex(p,E=!1){let{d:A,a:B}=t,P=e.BYTES;p=it("pointHex",p,P),Gt("zip215",E);let k=p.slice(),V=p[P-1];k[P-1]=V&-129;let N=xe(k),$=E?l:e.ORDER;Ct("pointHex.y",N,Wt,$);let J=u(N*N),pt=u(J-Dt),mt=u(A*J-B),{isValid:gt,value:bt}=d(pt,mt);if(!gt)throw new Error("Point.fromHex: invalid y coordinate");let Tt=(bt&Dt)===Dt,_t=(V&128)!==0;if(!E&&bt===Wt&&_t)throw new Error("Point.fromHex: x=0 and x_0=1");return _t!==Tt&&(bt=u(-bt)),m.fromAffine({x:bt,y:N})}static fromPrivateKey(p){return T(p).point}toRawBytes(){let{x:p,y:E}=this.toAffine(),A=Pe(E,e.BYTES);return A[A.length-1]|=p&Dt?128:0,A}toHex(){return se(this.toRawBytes())}}m.BASE=new m(t.Gx,t.Gy,Dt,u(t.Gx*t.Gy)),m.ZERO=new m(Wt,Dt,Dt,Wt);let{BASE:_,ZERO:C}=m,D=hn(m,a*8);function I(x){return X(x,n)}function R(x){return I(xe(x))}function T(x){let p=e.BYTES;x=it("private key",x,p);let E=it("hashed private key",i(x),2*p),A=g(E.slice(0,p)),B=E.slice(p,2*p),P=R(A),k=_.multiply(P),V=k.toRawBytes();return{head:A,prefix:B,scalar:P,point:k,pointBytes:V}}function et(x){return T(x).pointBytes}function H(x=new Uint8Array,...p){let E=ce(...p);return R(i(y(E,it("context",x),!!o)))}function z(x,p,E={}){x=it("message",x),o&&(x=o(x));let{prefix:A,scalar:B,pointBytes:P}=T(p),k=H(E.context,A,x),V=_.multiply(k).toRawBytes(),N=H(E.context,V,P,x),$=I(k+N*B);Ct("signature.s",$,Wt,n);let J=ce(V,Pe($,e.BYTES));return it("result",J,e.BYTES*2)}let ht=Qf;function v(x,p,E,A=ht){let{context:B,zip215:P}=A,k=e.BYTES;x=it("signature",x,2*k),p=it("message",p),E=it("publicKey",E,k),P!==void 0&&Gt("zip215",P),o&&(p=o(p));let V=xe(x.slice(k,2*k)),N,$,J;try{N=m.fromHex(E,P),$=m.fromHex(x.slice(0,k),P),J=_.multiplyUnsafe(V)}catch{return!1}if(!P&&N.isSmallOrder())return!1;let pt=H(B,$.toRawBytes(),N.toRawBytes(),p);return $.add(N.multiplyUnsafe(pt)).subtract(J).clearCofactor().equals(m.ZERO)}return _._setWindowSize(8),{CURVE:t,getPublicKey:et,sign:z,verify:v,ExtendedPoint:m,utils:{getExtendedPublicKey:T,randomPrivateKey:()=>s(e.BYTES),precompute(x=8,p=m.BASE){return p._setWindowSize(x),p.multiply(BigInt(3)),p}}}}var pi=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Fa=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),m0=BigInt(0),th=BigInt(1),za=BigInt(2),y0=BigInt(3),eh=BigInt(5),rh=BigInt(8);function nh(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),i=pi,a=r*r%i*r%i,c=nt(a,za,i)*a%i,l=nt(c,th,i)*r%i,u=nt(l,eh,i)*l%i,f=nt(u,t,i)*u%i,d=nt(f,e,i)*f%i,g=nt(d,n,i)*d%i,y=nt(g,o,i)*g%i,b=nt(y,o,i)*g%i,h=nt(b,t,i)*u%i;return{pow_p_5_8:nt(h,za,i)*r%i,b2:a}}function oh(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function ih(r,t){let e=pi,n=X(t*t*t,e),o=X(n*n*t,e),i=nh(r*o).pow_p_5_8,s=X(r*n*i,e),a=X(t*s*s,e),c=s,l=X(s*Fa,e),u=a===r,f=a===X(-r,e),d=a===X(-r*Fa,e);return u&&(s=c),(f||d)&&(s=l),Na(s,e)&&(s=X(-s,e)),{isValid:u||f,value:s}}var sh=Ee(pi,void 0,!0),ah={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:sh,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:rh,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Ra,randomBytes:on,adjustScalarBytes:oh,uvRatio:ih},Va=qa(ah);var mn=32;function Ha(r,t,e){return Va.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}var yn=class{type="Ed25519";raw;constructor(t){this.raw=mi(t,mn)}toMultihash(){return Vt.digest(jt(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ft(this.raw,t.raw)}verify(t,e){return Ha(this.raw,e,t)}};function yi(r){return r=mi(r,mn),new yn(r)}function mi(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new lt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var uh=Math.pow(2,7),lh=Math.pow(2,14),fh=Math.pow(2,21),gi=Math.pow(2,28),bi=Math.pow(2,35),xi=Math.pow(2,42),wi=Math.pow(2,49),W=128,xt=127;function wt(r){if(r<uh)return 1;if(r<lh)return 2;if(r<fh)return 3;if(r<gi)return 4;if(r<bi)return 5;if(r<xi)return 6;if(r<wi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ei(r,t,e=0){switch(wt(r)){case 8:t[e++]=r&255|W,r/=128;case 7:t[e++]=r&255|W,r/=128;case 6:t[e++]=r&255|W,r/=128;case 5:t[e++]=r&255|W,r/=128;case 4:t[e++]=r&255|W,r>>>=7;case 3:t[e++]=r&255|W,r>>>=7;case 2:t[e++]=r&255|W,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function hh(r,t,e=0){switch(wt(r)){case 8:t.set(e++,r&255|W),r/=128;case 7:t.set(e++,r&255|W),r/=128;case 6:t.set(e++,r&255|W),r/=128;case 5:t.set(e++,r&255|W),r/=128;case 4:t.set(e++,r&255|W),r>>>=7;case 3:t.set(e++,r&255|W),r>>>=7;case 2:t.set(e++,r&255|W),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Si(r,t){let e=r[t],n=0;if(n+=e&xt,e<W||(e=r[t+1],n+=(e&xt)<<7,e<W)||(e=r[t+2],n+=(e&xt)<<14,e<W)||(e=r[t+3],n+=(e&xt)<<21,e<W)||(e=r[t+4],n+=(e&xt)*gi,e<W)||(e=r[t+5],n+=(e&xt)*bi,e<W)||(e=r[t+6],n+=(e&xt)*xi,e<W)||(e=r[t+7],n+=(e&xt)*wi,e<W))return n;throw new RangeError("Could not decode varint")}function dh(r,t){let e=r.get(t),n=0;if(n+=e&xt,e<W||(e=r.get(t+1),n+=(e&xt)<<7,e<W)||(e=r.get(t+2),n+=(e&xt)<<14,e<W)||(e=r.get(t+3),n+=(e&xt)<<21,e<W)||(e=r.get(t+4),n+=(e&xt)*gi,e<W)||(e=r.get(t+5),n+=(e&xt)*bi,e<W)||(e=r.get(t+6),n+=(e&xt)*xi,e<W)||(e=r.get(t+7),n+=(e&xt)*wi,e<W))return n;throw new RangeError("Could not decode varint")}function qt(r,t,e=0){return t==null&&(t=Lt(wt(r))),t instanceof Uint8Array?Ei(r,t,e):hh(r,t,e)}function ue(r,t=0){return r instanceof Uint8Array?Si(r,t):dh(r,t)}var vi=new Float32Array([-0]),Se=new Uint8Array(vi.buffer);function Wa(r,t,e){vi[0]=r,t[e]=Se[0],t[e+1]=Se[1],t[e+2]=Se[2],t[e+3]=Se[3]}function $a(r,t){return Se[0]=r[t],Se[1]=r[t+1],Se[2]=r[t+2],Se[3]=r[t+3],vi[0]}var Ai=new Float64Array([-0]),Et=new Uint8Array(Ai.buffer);function Za(r,t,e){Ai[0]=r,t[e]=Et[0],t[e+1]=Et[1],t[e+2]=Et[2],t[e+3]=Et[3],t[e+4]=Et[4],t[e+5]=Et[5],t[e+6]=Et[6],t[e+7]=Et[7]}function Ya(r,t){return Et[0]=r[t],Et[1]=r[t+1],Et[2]=r[t+2],Et[3]=r[t+3],Et[4]=r[t+4],Et[5]=r[t+5],Et[6]=r[t+6],Et[7]=r[t+7],Ai[0]}var ph=BigInt(Number.MAX_SAFE_INTEGER),mh=BigInt(Number.MIN_SAFE_INTEGER),Ot=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 Oe;if(t<ph&&t>mh)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>Xa&&(o=0n,++n>Xa&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return Oe;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):Oe}},Oe=new Ot(0,0);Oe.toBigInt=function(){return 0n};Oe.zzEncode=Oe.zzDecode=function(){return this};Oe.length=function(){return 1};var Xa=4294967296n;function ja(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 Qa(r,t,e){if(e-t<1)return"";let o,i=[],s=0,a;for(;t<e;)a=r[t++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(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,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function _i(r,t,e){let n=e,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,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 $t(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function bn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Ii=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,$t(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 $t(this,4);return bn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw $t(this,4);return bn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw $t(this,4);let t=$a(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw $t(this,4);let t=Ya(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 $t(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Qa(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw $t(this,t);this.pos+=t}else do if(this.pos>=this.len)throw $t(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 Ot(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 $t(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 $t(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 $t(this,8);let t=bn(this.buf,this.pos+=4),e=bn(this.buf,this.pos+=4);return new Ot(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=Si(this.buf,this.pos);return this.pos+=wt(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 Ti(r){return new Ii(r instanceof Uint8Array?r:r.subarray())}function Bt(r,t,e){let n=Ti(r);return t.decode(n,void 0,e)}function Li(r){let t=r??8192,e=t>>>1,n,o=t;return function(s){if(s<1||s>e)return Lt(s);o+s>t&&(n=Lt(t),o=0);let a=n.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}var ke=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Ri(){}var Di=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},yh=Li();function gh(r){return globalThis.Buffer!=null?Lt(r):yh(r)}var Cr=class{len;head;tail;states;constructor(){this.len=0,this.head=new ke(Ri,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new ke(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Bi((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(xn,10,Ot.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Ot.fromBigInt(t);return this._push(xn,e.length(),e)}uint64Number(t){return this._push(Ei,wt(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=Ot.fromBigInt(t).zzEncode();return this._push(xn,e.length(),e)}sint64Number(t){let e=Ot.fromNumber(t).zzEncode();return this._push(xn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Ci,1,t?1:0)}fixed32(t){return this._push(Rr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Ot.fromBigInt(t);return this._push(Rr,4,e.lo)._push(Rr,4,e.hi)}fixed64Number(t){let e=Ot.fromNumber(t);return this._push(Rr,4,e.lo)._push(Rr,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(Wa,4,t)}double(t){return this._push(Za,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Ci,1,0):this.uint32(e)._push(xh,e,t)}string(t){let e=ja(t);return e!==0?this.uint32(e)._push(_i,e,t):this._push(Ci,1,0)}fork(){return this.states=new Di(this),this.head=this.tail=new ke(Ri,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 ke(Ri,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=gh(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Ci(r,t,e){t[e]=r&255}function bh(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Bi=class extends ke{next;constructor(t,e){super(bh,t,e),this.next=void 0}};function xn(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 Rr(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 xh(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Cr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(wh,t,r),this},Cr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Eh,t,r),this});function wh(r,t,e){t.set(r,e)}function Eh(r,t,e){r.length<40?_i(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(M(r),e)}function Pi(){return new Cr}function Pt(r,t){let e=Pi();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var nr;(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"})(nr||(nr={}));function wn(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Me(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(i,s){let a=t(i);s.int32(a)},n=function(i){let s=i.int32();return t(s)};return wn("enum",nr.VARINT,e,n)}function Nt(r,t){return wn("message",nr.LENGTH_DELIMITED,r,t)}var Dr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ut;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ut||(ut={}));var Ni;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Ni||(Ni={}));(function(r){r.codec=()=>Me(Ni)})(ut||(ut={}));var Jt;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ut.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.Type=ut.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Jt||(Jt={}));var Ui;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ut.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.Type=ut.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Ui||(Ui={}));var Br=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},En=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var ec={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new En("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 ve=ec;var Nr={};It(Nr,{MAX_RSA_KEY_SIZE:()=>ki,generateRSAKeyPair:()=>sc,jwkToJWKKeyPair:()=>ac,jwkToPkcs1:()=>Ih,jwkToPkix:()=>Fi,jwkToRSAPrivateKey:()=>ic,pkcs1MessageToJwk:()=>Ki,pkcs1MessageToRSAPrivateKey:()=>zi,pkcs1ToJwk:()=>_h,pkcs1ToRSAPrivateKey:()=>oc,pkixMessageToJwk:()=>qi,pkixMessageToRSAPublicKey:()=>Hi,pkixToJwk:()=>Th,pkixToRSAPublicKey:()=>Vi});var Sh=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ae=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),_e=new Uint32Array(64),Oi=class extends er{constructor(){super(64,32,8,!1),this.A=Ae[0]|0,this.B=Ae[1]|0,this.C=Ae[2]|0,this.D=Ae[3]|0,this.E=Ae[4]|0,this.F=Ae[5]|0,this.G=Ae[6]|0,this.H=Ae[7]|0}get(){let{A:t,B:e,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[t,e,n,o,i,s,a,c]}set(t,e,n,o,i,s,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)_e[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=_e[f-15],g=_e[f-2],y=Ht(d,7)^Ht(d,18)^d>>>3,b=Ht(g,17)^Ht(g,19)^g>>>10;_e[f]=b+_e[f-7]+y+_e[f-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=Ht(a,6)^Ht(a,11)^Ht(a,25),g=u+d+Ia(a,c,l)+Sh[f]+_e[f]|0,b=(Ht(n,2)^Ht(n,13)^Ht(n,22))+Ta(n,o,i)|0;u=l,l=c,c=a,a=s+g|0,s=i,i=o,o=n,n=g+b|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+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,i,s,a,c,l,u)}roundClean(){_e.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var or=nn(()=>new Oi);var ir=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=Nr.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return at.createV1(114,this._multihash)}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ft(this.raw,t.raw)}verify(t,e){return nc(this.jwk,e,t)}},Pr=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=Nr.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ft(this.raw,t.raw)}sign(t){return rc(this.jwk,t)}};var ki=8192,Mi=18,vh=1062,Ah=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function _h(r){let t=oe(r);return Ki(t)}function Ki(r){return{n:O(r[1],"base64url"),e:O(r[2],"base64url"),d:O(r[3],"base64url"),p:O(r[4],"base64url"),q:O(r[5],"base64url"),dp:O(r[6],"base64url"),dq:O(r[7],"base64url"),qi:O(r[8],"base64url"),kty:"RSA"}}function Ih(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 lt("JWK was missing components");return me([Rt(Uint8Array.from([0])),Rt(M(r.n,"base64url")),Rt(M(r.e,"base64url")),Rt(M(r.d,"base64url")),Rt(M(r.p,"base64url")),Rt(M(r.q,"base64url")),Rt(M(r.dp,"base64url")),Rt(M(r.dq,"base64url")),Rt(M(r.qi,"base64url"))]).subarray()}function Th(r){let t=oe(r,{offset:0});return qi(t)}function qi(r){let t=oe(r[1],{offset:0});return{kty:"RSA",n:O(t[0],"base64url"),e:O(t[1],"base64url")}}function Fi(r){if(r.n==null||r.e==null)throw new lt("JWK was missing components");return me([Ah,en(me([Rt(M(r.n,"base64url")),Rt(M(r.e,"base64url"))]))]).subarray()}function oc(r){let t=oe(r);return zi(t)}function zi(r){let t=Ki(r);return ic(t)}function Vi(r,t){if(r.byteLength>=vh)throw new He("Key size is too large");let e=oe(r,{offset:0});return Hi(e,r,t)}function Hi(r,t,e){let n=qi(r);if(e==null){let o=or(Jt.encode({Type:ut.RSA,Data:t}));e=zt(Mi,o)}return new ir(n,e)}function ic(r){if(uc(r)>ki)throw new lt("Key size is too large");let t=ac(r),e=or(Jt.encode({Type:ut.RSA,Data:Fi(t.publicKey)})),n=zt(Mi,e);return new Pr(t.privateKey,new ir(t.publicKey,n))}async function sc(r){if(r>ki)throw new lt("Key size is too large");let t=await cc(r),e=or(Jt.encode({Type:ut.RSA,Data:Fi(t.publicKey)})),n=zt(Mi,e);return new Pr(t.privateKey,new ir(t.publicKey,n))}function ac(r){if(r==null)throw new lt("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function cc(r){let t=await ve.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await Lh(t);return{privateKey:e[0],publicKey:e[1]}}async function rc(r,t){let e=await ve.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await ve.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function nc(r,t,e){let n=await ve.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return ve.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function Lh(r){if(r.privateKey==null||r.publicKey==null)throw new lt("Private and public key are required");return Promise.all([ve.get().subtle.exportKey("jwk",r.privateKey),ve.get().subtle.exportKey("jwk",r.publicKey)])}function uc(r){if(r.kty!=="RSA")throw new lt("invalid key type");if(r.n==null)throw new lt("invalid key modulus");return M(r.n,"base64url").length*8}var Sn=class extends tr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,va(t);let n=_r(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,i=new Uint8Array(o);i.set(n.length>o?t.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=t.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),i.fill(0)}update(t){return Je(this),this.iHash.update(t),this}digestInto(t){Je(this),Qe(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:i,blockLen:s,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Gi=(r,t,e)=>new Sn(r,t).update(e).digest();Gi.create=(r,t)=>new Sn(r,t);function lc(r){r.lowS!==void 0&&Gt("lowS",r.lowS),r.prehash!==void 0&&Gt("prehash",r.prehash)}function Rh(r){let t=Lr(r);Qt(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:Ch,hexToBytes:Dh}=un,Wi=class extends Error{constructor(t=""){super(t)}},le={Err:Wi,_tlv:{encode:(r,t)=>{let{Err:e}=le;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=De(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let i=n>127?De(o.length/2|128):"";return De(r)+i+o+t},decode(r,t){let{Err:e}=le,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++],i=!!(o&128),s=0;if(!i)s=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)s=s<<8|u;if(n+=c,s<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+s);if(a.length!==s)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(r){let{Err:t}=le;if(r<fe)throw new t("integer: negative integers are not allowed");let e=De(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}=le;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 Ch(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=le,o=typeof r=="string"?Dh(r):r;rr(o);let{v:i,l:s}=n.decode(48,o);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{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}=le,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),i=n+o;return t.encode(48,i)}},fe=BigInt(0),yt=BigInt(1),Gy=BigInt(2),fc=BigInt(3),Wy=BigInt(4);function Bh(r){let t=Rh(r),{Fp:e}=t,n=Ee(t.n,t.nBitLength),o=t.toBytes||((b,h,w)=>{let S=h.toAffine();return ce(Uint8Array.from([4]),e.toBytes(S.x),e.toBytes(S.y))}),i=t.fromBytes||(b=>{let h=b.subarray(1),w=e.fromBytes(h.subarray(0,e.BYTES)),S=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:w,y:S}});function s(b){let{a:h,b:w}=t,S=e.sqr(b),m=e.mul(S,b);return e.add(e.add(m,e.mul(b,h)),w)}if(!e.eql(e.sqr(t.Gy),s(t.Gx)))throw new Error("bad generator point: equation left != right");function a(b){return Ir(b,yt,t.n)}function c(b){let{allowedPrivateKeyLengths:h,nByteLength:w,wrapPrivateKey:S,n:m}=t;if(h&&typeof b!="bigint"){if(be(b)&&(b=se(b)),typeof b!="string"||!h.includes(b.length))throw new Error("invalid private key");b=b.padStart(w*2,"0")}let _;try{_=typeof b=="bigint"?b:ae(it("private key",b,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof b)}return S&&(_=X(_,m)),Ct("private key",_,yt,m),_}function l(b){if(!(b instanceof d))throw new Error("ProjectivePoint expected")}let u=Ne((b,h)=>{let{px:w,py:S,pz:m}=b;if(e.eql(m,e.ONE))return{x:w,y:S};let _=b.is0();h==null&&(h=_?e.ONE:e.inv(m));let C=e.mul(w,h),D=e.mul(S,h),I=e.mul(m,h);if(_)return{x:e.ZERO,y:e.ZERO};if(!e.eql(I,e.ONE))throw new Error("invZ was invalid");return{x:C,y:D}}),f=Ne(b=>{if(b.is0()){if(t.allowInfinityPoint&&!e.is0(b.py))return;throw new Error("bad point: ZERO")}let{x:h,y:w}=b.toAffine();if(!e.isValid(h)||!e.isValid(w))throw new Error("bad point: x or y not FE");let S=e.sqr(w),m=s(h);if(!e.eql(S,m))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,w,S){if(this.px=h,this.py=w,this.pz=S,h==null||!e.isValid(h))throw new Error("x required");if(w==null||!e.isValid(w))throw new Error("y required");if(S==null||!e.isValid(S))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:w,y:S}=h||{};if(!h||!e.isValid(w)||!e.isValid(S))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let m=_=>e.eql(_,e.ZERO);return m(w)&&m(S)?d.ZERO:new d(w,S,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let w=e.invertBatch(h.map(S=>S.pz));return h.map((S,m)=>S.toAffine(w[m])).map(d.fromAffine)}static fromHex(h){let w=d.fromAffine(i(it("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,w){return dn(d,n,h,w)}_setWindowSize(h){y.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:w,py:S,pz:m}=this,{px:_,py:C,pz:D}=h,I=e.eql(e.mul(w,D),e.mul(_,m)),R=e.eql(e.mul(S,D),e.mul(C,m));return I&&R}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:w}=t,S=e.mul(w,fc),{px:m,py:_,pz:C}=this,D=e.ZERO,I=e.ZERO,R=e.ZERO,T=e.mul(m,m),et=e.mul(_,_),H=e.mul(C,C),z=e.mul(m,_);return z=e.add(z,z),R=e.mul(m,C),R=e.add(R,R),D=e.mul(h,R),I=e.mul(S,H),I=e.add(D,I),D=e.sub(et,I),I=e.add(et,I),I=e.mul(D,I),D=e.mul(z,D),R=e.mul(S,R),H=e.mul(h,H),z=e.sub(T,H),z=e.mul(h,z),z=e.add(z,R),R=e.add(T,T),T=e.add(R,T),T=e.add(T,H),T=e.mul(T,z),I=e.add(I,T),H=e.mul(_,C),H=e.add(H,H),T=e.mul(H,z),D=e.sub(D,T),R=e.mul(H,et),R=e.add(R,R),R=e.add(R,R),new d(D,I,R)}add(h){l(h);let{px:w,py:S,pz:m}=this,{px:_,py:C,pz:D}=h,I=e.ZERO,R=e.ZERO,T=e.ZERO,et=t.a,H=e.mul(t.b,fc),z=e.mul(w,_),ht=e.mul(S,C),v=e.mul(m,D),L=e.add(w,S),x=e.add(_,C);L=e.mul(L,x),x=e.add(z,ht),L=e.sub(L,x),x=e.add(w,m);let p=e.add(_,D);return x=e.mul(x,p),p=e.add(z,v),x=e.sub(x,p),p=e.add(S,m),I=e.add(C,D),p=e.mul(p,I),I=e.add(ht,v),p=e.sub(p,I),T=e.mul(et,x),I=e.mul(H,v),T=e.add(I,T),I=e.sub(ht,T),T=e.add(ht,T),R=e.mul(I,T),ht=e.add(z,z),ht=e.add(ht,z),v=e.mul(et,v),x=e.mul(H,x),ht=e.add(ht,v),v=e.sub(z,v),v=e.mul(et,v),x=e.add(x,v),z=e.mul(ht,x),R=e.add(R,z),z=e.mul(p,x),I=e.mul(L,I),I=e.sub(I,z),z=e.mul(L,ht),T=e.mul(p,T),T=e.add(T,z),new d(I,R,T)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return y.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){let{endo:w,n:S}=t;Ct("scalar",h,fe,S);let m=d.ZERO;if(h===fe)return m;if(this.is0()||h===yt)return this;if(!w||y.hasPrecomputes(this))return y.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:_,k1:C,k2neg:D,k2:I}=w.splitScalar(h),R=m,T=m,et=this;for(;C>fe||I>fe;)C&yt&&(R=R.add(et)),I&yt&&(T=T.add(et)),et=et.double(),C>>=yt,I>>=yt;return _&&(R=R.negate()),D&&(T=T.negate()),T=new d(e.mul(T.px,w.beta),T.py,T.pz),R.add(T)}multiply(h){let{endo:w,n:S}=t;Ct("scalar",h,yt,S);let m,_;if(w){let{k1neg:C,k1:D,k2neg:I,k2:R}=w.splitScalar(h),{p:T,f:et}=this.wNAF(D),{p:H,f:z}=this.wNAF(R);T=y.constTimeNegate(C,T),H=y.constTimeNegate(I,H),H=new d(e.mul(H.px,w.beta),H.py,H.pz),m=T.add(H),_=et.add(z)}else{let{p:C,f:D}=this.wNAF(h);m=C,_=D}return d.normalizeZ([m,_])[0]}multiplyAndAddUnsafe(h,w,S){let m=d.BASE,_=(D,I)=>I===fe||I===yt||!D.equals(m)?D.multiplyUnsafe(I):D.multiply(I),C=_(this,w).add(_(h,S));return C.is0()?void 0:C}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:w}=t;if(h===yt)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:w}=t;return h===yt?this:w?w(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return Gt("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return Gt("isCompressed",h),se(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let g=t.nBitLength,y=hn(d,t.endo?Math.ceil(g/2):g);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:a}}function Ph(r){let t=Lr(r);return Qt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function hc(r){let t=Ph(r),{Fp:e,n}=t,o=e.BYTES+1,i=2*e.BYTES+1;function s(v){return X(v,n)}function a(v){return ln(v,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=Bh({...t,toBytes(v,L,x){let p=L.toAffine(),E=e.toBytes(p.x),A=ce;return Gt("isCompressed",x),x?A(Uint8Array.from([L.hasEvenY()?2:3]),E):A(Uint8Array.from([4]),E,e.toBytes(p.y))},fromBytes(v){let L=v.length,x=v[0],p=v.subarray(1);if(L===o&&(x===2||x===3)){let E=ae(p);if(!Ir(E,yt,e.ORDER))throw new Error("Point is not on curve");let A=u(E),B;try{B=e.sqrt(A)}catch(V){let N=V instanceof Error?": "+V.message:"";throw new Error("Point is not on curve"+N)}let P=(B&yt)===yt;return(x&1)===1!==P&&(B=e.neg(B)),{x:E,y:B}}else if(L===i&&x===4){let E=e.fromBytes(p.subarray(0,e.BYTES)),A=e.fromBytes(p.subarray(e.BYTES,2*e.BYTES));return{x:E,y:A}}else{let E=o,A=i;throw new Error("invalid Point, expected length of "+E+", or uncompressed "+A+", got "+L)}}}),d=v=>se(we(v,t.nByteLength));function g(v){let L=n>>yt;return v>L}function y(v){return g(v)?s(-v):v}let b=(v,L,x)=>ae(v.slice(L,x));class h{constructor(L,x,p){this.r=L,this.s=x,this.recovery=p,this.assertValidity()}static fromCompact(L){let x=t.nByteLength;return L=it("compactSignature",L,x*2),new h(b(L,0,x),b(L,x,2*x))}static fromDER(L){let{r:x,s:p}=le.toSig(it("DER",L));return new h(x,p)}assertValidity(){Ct("r",this.r,yt,n),Ct("s",this.s,yt,n)}addRecoveryBit(L){return new h(this.r,this.s,L)}recoverPublicKey(L){let{r:x,s:p,recovery:E}=this,A=D(it("msgHash",L));if(E==null||![0,1,2,3].includes(E))throw new Error("recovery id invalid");let B=E===2||E===3?x+t.n:x;if(B>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let P=(E&1)===0?"02":"03",k=c.fromHex(P+d(B)),V=a(B),N=s(-A*V),$=s(p*V),J=c.BASE.multiplyAndAddUnsafe(k,N,$);if(!J)throw new Error("point at infinify");return J.assertValidity(),J}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,s(-this.s),this.recovery):this}toDERRawBytes(){return Be(this.toDERHex())}toDERHex(){return le.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Be(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let w={isValidPrivateKey(v){try{return l(v),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let v=ui(t.n);return Oa(t.randomBytes(v),t.n)},precompute(v=8,L=c.BASE){return L._setWindowSize(v),L.multiply(BigInt(3)),L}};function S(v,L=!0){return c.fromPrivateKey(v).toRawBytes(L)}function m(v){let L=be(v),x=typeof v=="string",p=(L||x)&&v.length;return L?p===o||p===i:x?p===2*o||p===2*i:v instanceof c}function _(v,L,x=!0){if(m(v))throw new Error("first arg must be private key");if(!m(L))throw new Error("second arg must be public key");return c.fromHex(L).multiply(l(v)).toRawBytes(x)}let C=t.bits2int||function(v){if(v.length>8192)throw new Error("input is too large");let L=ae(v),x=v.length*8-t.nBitLength;return x>0?L>>BigInt(x):L},D=t.bits2int_modN||function(v){return s(C(v))},I=Tr(t.nBitLength);function R(v){return Ct("num < 2^"+t.nBitLength,v,fe,I),we(v,t.nByteLength)}function T(v,L,x=et){if(["recovered","canonical"].some(mt=>mt in x))throw new Error("sign() legacy options not supported");let{hash:p,randomBytes:E}=t,{lowS:A,prehash:B,extraEntropy:P}=x;A==null&&(A=!0),v=it("msgHash",v),lc(x),B&&(v=it("prehashed msgHash",p(v)));let k=D(v),V=l(L),N=[R(V),R(k)];if(P!=null&&P!==!1){let mt=P===!0?E(e.BYTES):P;N.push(it("extraEntropy",mt))}let $=ce(...N),J=k;function pt(mt){let gt=C(mt);if(!f(gt))return;let bt=a(gt),Tt=c.BASE.multiply(gt).toAffine(),_t=s(Tt.x);if(_t===fe)return;let Yt=s(bt*s(J+_t*V));if(Yt===fe)return;let te=(Tt.x===_t?0:2)|Number(Tt.y&yt),yr=Yt;return A&&g(Yt)&&(yr=y(Yt),te^=1),new h(_t,yr,te)}return{seed:$,k2sig:pt}}let et={lowS:t.lowS,prehash:!1},H={lowS:t.lowS,prehash:!1};function z(v,L,x=et){let{seed:p,k2sig:E}=T(v,L,x),A=t;return ii(A.hash.outputLen,A.nByteLength,A.hmac)(p,E)}c.BASE._setWindowSize(8);function ht(v,L,x,p=H){let E=v;L=it("msgHash",L),x=it("publicKey",x);let{lowS:A,prehash:B,format:P}=p;if(lc(p),"strict"in p)throw new Error("options.strict was renamed to lowS");if(P!==void 0&&P!=="compact"&&P!=="der")throw new Error("format must be compact or der");let k=typeof E=="string"||be(E),V=!k&&!P&&typeof E=="object"&&E!==null&&typeof E.r=="bigint"&&typeof E.s=="bigint";if(!k&&!V)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let N,$;try{if(V&&(N=new h(E.r,E.s)),k){try{P!=="compact"&&(N=h.fromDER(E))}catch(te){if(!(te instanceof le.Err))throw te}!N&&P!=="der"&&(N=h.fromCompact(E))}$=c.fromHex(x)}catch{return!1}if(!N||A&&N.hasHighS())return!1;B&&(L=t.hash(L));let{r:J,s:pt}=N,mt=D(L),gt=a(pt),bt=s(mt*gt),Tt=s(J*gt),_t=c.BASE.multiplyAndAddUnsafe($,bt,Tt)?.toAffine();return _t?s(_t.x)===J:!1}return{CURVE:t,getPublicKey:S,getSharedSecret:_,sign:z,verify:ht,ProjectivePoint:c,Signature:h,utils:w}}function Nh(r){return{hash:r,hmac:(t,...e)=>Gi(r,t,Qo(...e)),randomBytes:on}}function dc(r,t){let e=n=>hc({...r,...Nh(n)});return{...e(t),create:e}}var yc=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),pc=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Uh=BigInt(1),$i=BigInt(2),mc=(r,t)=>(r+t/$i)/t;function Oh(r){let t=yc,e=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=nt(u,e,t)*u%t,d=nt(f,e,t)*u%t,g=nt(d,$i,t)*l%t,y=nt(g,o,t)*g%t,b=nt(y,i,t)*y%t,h=nt(b,a,t)*b%t,w=nt(h,c,t)*h%t,S=nt(w,a,t)*b%t,m=nt(S,e,t)*u%t,_=nt(m,s,t)*y%t,C=nt(_,n,t)*l%t,D=nt(C,$i,t);if(!Zi.eql(Zi.sqr(D),r))throw new Error("Cannot find square root");return D}var Zi=Ee(yc,void 0,void 0,{sqrt:Oh}),Ke=dc({a:BigInt(0),b:BigInt(7),Fp:Zi,n:pc,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=pc,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Uh*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=e,s=BigInt("0x100000000000000000000000000000000"),a=mc(i*r,t),c=mc(-n*r,t),l=X(r-a*e-c*o,t),u=X(-a*n-c*i,t),f=l>s,d=u>s;if(f&&(l=t-l),d&&(u=t-u),l>s||u>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},or),eg=BigInt(0);var rg=Ke.ProjectivePoint;function gc(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function bc(r,t,e){let n=Xe.digest(e instanceof Uint8Array?e:e.subarray());if(gc(n))return n.then(({digest:o})=>Ke.verify(t,o,r)).catch(o=>{throw new Br(String(o))});try{return Ke.verify(t,n.digest,r)}catch(o){throw new Br(String(o))}}var vn=class{type="secp256k1";raw;_key;constructor(t){this._key=wc(t),this.raw=xc(this._key)}toMultihash(){return Vt.digest(jt(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ft(this.raw,t.raw)}verify(t,e){return bc(this._key,e,t)}};function Yi(r){return new vn(r)}function xc(r){return Ke.ProjectivePoint.fromHex(r).toRawBytes(!0)}function wc(r){try{return Ke.ProjectivePoint.fromHex(r),r}catch(t){throw new He(String(t))}}function Ec(r,t){let{Type:e,Data:n}=Jt.decode(r),o=n??new Uint8Array;switch(e){case ut.RSA:return Vi(o,t);case ut.Ed25519:return yi(o);case ut.secp256k1:return Yi(o);case ut.ECDSA:return jo(o);default:throw new Ge}}function Sc(r){let{Type:t,Data:e}=Jt.decode(r.digest),n=e??new Uint8Array;switch(t){case ut.Ed25519:return yi(n);case ut.secp256k1:return Yi(n);case ut.ECDSA:return jo(n);default:throw new Ge}}function jt(r){return Jt.encode({Type:ut[r.type],Data:r.raw})}var vc=Symbol.for("nodejs.util.inspect.custom"),kh=114,Ur=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[So]=!0;toString(){return this.string==null&&(this.string=Z.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return at.createV1(kh,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return ft(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return ft(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[vc](){return`PeerId(${this.toString()})`}},An=class extends Ur{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},_n=class extends Ur{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},In=class extends Ur{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Mh=2336,Or=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Vt.digest(M(this.url))}[vc](){return`PeerId(${this.url})`}[So]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return at.createV1(Mh,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=O(t)),t.toString()===this.toString())}};var Kh=114,Ac=2336;function Xi(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Kt(Z.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return qh(at.parse(r));if(t==null)throw new lt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Kt(t.decode(r))}return sr(e)}function sr(r){if(zh(r))return new An({multihash:r});if(Fh(r))try{let t=Sc(r);if(t.type==="Ed25519")return new _n({multihash:r,publicKey:t});if(t.type==="secp256k1")return new In({multihash:r,publicKey:t})}catch{let e=O(r.digest);return new Or(new URL(e))}throw new Xr("Supplied PeerID Multihash is invalid")}function qh(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Kh&&r.code!==Ac)throw new Yr("Supplied PeerID CID is invalid");if(r.code===Ac){let t=O(r.multihash.digest);return new Or(new URL(t))}return sr(r.multihash)}function Fh(r){return r.code===Vt.code}function zh(r){return r.code===Xe.code}var kr;(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 i={publicKey:ot(0),payloadType:ot(0),payload:ot(0),signature:ot(0)},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.publicKey=e.bytes();break}case 2:{i.payloadType=e.bytes();break}case 3:{i.payload=e.bytes();break}case 5:{i.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(kr||(kr={}));var Tn=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var Mr=class r{static createFromProtobuf=async t=>{let e=kr.decode(t),n=Ec(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e)=>{if(e==null)throw new Error("Missing private key");let n=t.domain,o=t.codec,i=t.marshal(),s=_c(n,o,i),a=await e.sign(s.subarray());return new r({publicKey:e.publicKey,payloadType:o,payload:i,signature:a})};static openAndCertify=async(t,e)=>{let n=await r.createFromProtobuf(t);if(!await n.validate(e))throw new Tn("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(t){let{publicKey:e,payloadType:n,payload:o,signature:i}=t;this.publicKey=e,this.payloadType=n,this.payload=o,this.signature=i}marshal(){return this.marshaled==null&&(this.marshaled=kr.encode({publicKey:jt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return ft(this.marshal(),t.marshal())}async validate(t){let e=_c(t,this.payloadType,this.payload);return this.publicKey.verify(e.subarray(),this.signature)}},_c=(r,t,e)=>{let n=M(r),o=qt(n.byteLength),i=qt(t.length),s=qt(e.length);return new ct(o,n,i,t,s,e)};var Ln=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 i=0,s=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(i*=t,i+=u,i>l||(s+=1,e!==void 0&&s>e))return}if(s!==0)return!n&&c&&s>1?void 0:i})}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 s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return e[o]=s[0],e[o+1]=s[1],e[o+2]=s[2],e[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];e[o]=i>>8,e[o+1]=i&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 i=new Uint8Array(14),s=16-(n+2),[a]=t(i.subarray(0,s));return e.set(i.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Ic=45,Vh=15,ar=new Ln;function ji(r){if(!(r.length>Vh))return ar.new(r).parseWith(()=>ar.readIPv4Addr())}function Qi(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ic))return ar.new(r).parseWith(()=>ar.readIPv6Addr())}function Rn(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Ic)return;let e=ar.new(r).parseWith(()=>ar.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}var Tb=parseInt("0xFFFF",16),Lb=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Cn(r){return!!ji(r)}function Dn(r){return!!Qi(r)}function Bn(r){return!!Rn(r)}var Rc=Cn,Zh=Dn,Ji=function(r){let t=0;if(r=r.toString().trim(),Rc(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Zh(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=Rc(e[n]),s;i&&(s=Ji(e[n]),e[n]=O(s.slice(0,2),"base16")),s!=null&&++n<8&&e.splice(n,0,O(s.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 i=[n,1];for(n=9-e.length;n>0;n--)i.push("0");e.splice.apply(e,i)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let i=parseInt(e[n],16);o[t++]=i>>8&255,o[t++]=i&255}return o}throw new Error("invalid ip address")},Cc=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 i=0;i<e;i++)o.push(r[t+i]);return o.join(".")}if(e===16){let o=[];for(let i=0;i<e;i+=2)o.push(n.getUint16(t+i).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var cr={},ts={},Xh=[[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"]];Xh.forEach(r=>{let t=jh(...r);ts[t.code]=t,cr[t.name]=t});function jh(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function Q(r){if(typeof r=="number"){if(ts[r]!=null)return ts[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(cr[r]!=null)return cr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var fx=Q("ip4"),hx=Q("ip6"),dx=Q("ipcidr");function os(r,t){switch(Q(r).code){case 4:case 41:return Jh(t);case 42:return ns(t);case 43:return O(t,"base10");case 6:case 273:case 33:case 132:return Pc(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ns(t);case 421:return nd(t);case 444:return Bc(t);case 445:return Bc(t);case 466:return rd(t);case 481:return globalThis.encodeURIComponent(ns(t));default:return O(t,"base16")}}function is(r,t){switch(Q(r).code){case 4:return Dc(t);case 41:return Dc(t);case 42:return rs(t);case 43:return M(t,"base10");case 6:case 273:case 33:case 132:return ss(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return rs(t);case 421:return td(t);case 444:return od(t);case 445:return id(t);case 466:return ed(t);case 481:return rs(globalThis.decodeURIComponent(t));default:return M(t,"base16")}}var es=Object.values(Sr).map(r=>r.decoder),Qh=function(){let r=es[0].or(es[1]);return es.slice(2).forEach(t=>r=r.or(t)),r}();function Dc(r){if(!Bn(r))throw new Error("invalid ip address");return Ji(r)}function Jh(r){let t=Cc(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!Bn(t))throw new Error("invalid ip address");return t}function ss(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Pc(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function rs(r){let t=M(r),e=Uint8Array.from(qt(t.length));return Ut([e,t],e.length+t.length)}function ns(r){let t=ue(r);if(r=r.slice(wt(t)),r.length!==t)throw new Error("inconsistent lengths");return O(r)}function td(r){let t;r[0]==="Q"||r[0]==="1"?t=Kt(Z.decode(`z${r}`)).bytes:t=at.parse(r).multihash.bytes;let e=Uint8Array.from(qt(t.length));return Ut([e,t],e.length+t.length)}function ed(r){let t=Qh.decode(r),e=Uint8Array.from(qt(t.length));return Ut([e,t],e.length+t.length)}function rd(r){let t=ue(r),e=r.slice(wt(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+O(e,"base64url")}function nd(r){let t=ue(r),e=r.slice(wt(t));if(e.length!==t)throw new Error("inconsistent lengths");return O(e,"base58btc")}function od(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=ne.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=ss(n);return Ut([e,o],e.length+o.length)}function id(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=ne.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=ss(n);return Ut([e,o],e.length+o.length)}function Bc(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=O(t,"base32"),o=Pc(e);return`${n}:${o}`}function Nc(r){r=as(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 i=0;i<o.length;i++){let s=o[i],a=Q(s);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(i++,i>=o.length)throw new Pn("invalid address: "+r);if(a.path===!0){n=as(o.slice(i).join("/")),t.push([a.code,is(a.code,n)]),e.push([a.code,n]);break}let c=is(a.code,o[i]);t.push([a.code,c]),e.push([a.code,os(a.code,c)])}return{string:Uc(e),bytes:Nn(t),tuples:t,stringTuples:e,path:n}}function cs(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let i=ue(r,o),s=wt(i),a=Q(i),c=sd(a,r.slice(o+s));if(c===0){t.push([i]),e.push([i]),o+=s;continue}let l=r.slice(o+s,o+s+c);if(o+=c+s,o>r.length)throw new Pn("Invalid address Uint8Array: "+O(r,"base16"));t.push([i,l]);let u=os(i,l);if(e.push([i,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:Uc(e),tuples:t,stringTuples:e,path:n}}function Uc(r){let t=[];return r.map(e=>{let n=Q(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),as(t.join("/"))}function Nn(r){return Ut(r.map(t=>{let e=Q(t[0]),n=Uint8Array.from(qt(e.code));return t.length>1&&t[1]!=null&&(n=Ut([n,t[1]])),n}))}function sd(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=ue(t instanceof Uint8Array?t:Uint8Array.from(t));return e+wt(e)}}function as(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var Pn=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var ad=Symbol.for("nodejs.util.inspect.custom"),ls=Symbol.for("@multiformats/js-multiaddr/multiaddr"),cd=[Q("dns").code,Q("dns4").code,Q("dns6").code,Q("dnsaddr").code],us=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},Un=class r{bytes;#t;#e;#r;#n;[ls]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=cs(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Nc(t)}else if(kc(t))e=cs(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.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,i="",s=Q("tcp"),a=Q("udp"),c=Q("ip4"),l=Q("ip6"),u=Q("dns6"),f=Q("ip6zone");for(let[g,y]of this.stringTuples())g===f.code&&(i=`%${y??""}`),cd.includes(g)&&(e=s.name==="tcp"?"tcp":"udp",o=443,n=`${y??""}${i}`,t=g===u.code?6:4),(g===s.code||g===a.code)&&(e=Q(g).name==="tcp"?"tcp":"udp",o=parseInt(y??"")),(g===c.code||g===l.code)&&(e=Q(g).name==="tcp"?"tcp":"udp",n=`${y??""}${i}`,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({},Q(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>Q(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(Nn(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===cr.p2p.code&&t.push([n,o]),n===cr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?O(Z.decode(`z${n}`),"base58btc"):O(at.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return ft(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(i=>i.resolvable);if(e==null)return[this];let n=Oc.get(e.name);if(n==null)throw new us(`no available resolver for ${e.name}`);return(await n(this,t)).map(i=>St(i))}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)}[ad](){return`Multiaddr(${this.#t})`}};var Oc=new Map;function kc(r){return!!r?.[ls]}function St(r){return new Un(r)}function vt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var On=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 he(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new On(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new On(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((i,s)=>{n=()=>{s(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var fs=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=vt(),this.haveNext=vt()}[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=vt(),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=vt(),await he(this.readNext.promise,e?.signal,e)}};function Mc(){return new fs}var kn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Kc(r,t){let e=Mc();r.sink(e).catch(async s=>{await e.end(s)}),r.sink=async s=>{for await(let a of s)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 ct;return{read:async s=>{if(s?.signal?.throwIfAborted(),s?.bytes==null){let{done:c,value:l}=await he(n.next(),s?.signal);return c===!0?null:l}for(;o.byteLength<s.bytes;){let{value:c,done:l}=await he(n.next(),s?.signal);if(l===!0)throw new kn("unexpected end of input");o.append(c)}let a=o.sublist(0,s.bytes);return o.consume(s.bytes),a},write:async(s,a)=>{a?.signal?.throwIfAborted(),s instanceof Uint8Array?await e.push(s,a):await e.push(s.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let s=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*s}()}return r}}}var Mn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Kn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},qn=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function qc(r,t={}){let e=Kc(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=wt(t.maxDataLength));let n=t?.lengthDecoder??ue,o=t?.lengthEncoder??qt;return{read:async s=>{let a=-1,c=new ct;for(;;){c.append(await e.read({...s,bytes:1}));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Mn("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new qn("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Kn("message length too long");return e.read({...s,bytes:a})},write:async(s,a)=>{await e.write(new ct(o(s.byteLength),s),a)},writeV:async(s,a)=>{let c=new ct(...s.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Ie(r,t){let e=qc(r,t),n={read:async(o,i)=>{let s=await e.read(i);return o.decode(s)},write:async(o,i,s)=>{await e.write(i.encode(o),s)},writeV:async(o,i,s)=>{await e.writeV(o.map(a=>i.encode(a)),s)},pb:o=>({read:async i=>n.read(o,i),write:async(i,s)=>n.write(i,o,s),writeV:async(i,s)=>n.writeV(i,o,s),unwrap:()=>n}),unwrap:()=>e.unwrap()};return n}var hs=1e3,Fc=60*hs,Fn=290,zc=15,Vc=2*60*Fc,Hc=1,zn=2e3,Gc=100,ds="circuit-relay-source",Kr=`${vo}-circuit-relay`,ps=`${vo}-circuit-relay-source`,Wc=2*Fc,$c=BigInt(1<<17),Ft="/libp2p/circuit/relay/0.2.0/hop",qe="/libp2p/circuit/relay/0.2.0/stop",Zc=30*hs,sw=30*hs,qr=300,Yc=4096,Xc=.001;var Y;(function(r){let t;(function(o){o.RESERVE="RESERVE",o.CONNECT="CONNECT",o.STATUS="STATUS"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.RESERVE=0]="RESERVE",o[o.CONNECT=1]="CONNECT",o[o.STATUS=2]="STATUS"})(e||(e={})),function(o){o.codec=()=>Me(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Nt((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.type!=null&&(i.uint32(8),r.Type.codec().encode(o.type,i)),o.peer!=null&&(i.uint32(18),ur.codec().encode(o.peer,i)),o.reservation!=null&&(i.uint32(26),Vn.codec().encode(o.reservation,i)),o.limit!=null&&(i.uint32(34),lr.codec().encode(o.limit,i)),o.status!=null&&(i.uint32(40),q.codec().encode(o.status,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=ur.codec().decode(o,o.uint32(),{limits:s.limits?.peer});break}case 3:{a.reservation=Vn.codec().decode(o,o.uint32(),{limits:s.limits?.reservation});break}case 4:{a.limit=lr.codec().decode(o,o.uint32(),{limits:s.limits?.limit});break}case 5:{a.status=q.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Pt(o,r.codec()),r.decode=(o,i)=>Bt(o,r.codec(),i)})(Y||(Y={}));var kt;(function(r){let t;(function(o){o.CONNECT="CONNECT",o.STATUS="STATUS"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.CONNECT=0]="CONNECT",o[o.STATUS=1]="STATUS"})(e||(e={})),function(o){o.codec=()=>Me(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Nt((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.type!=null&&(i.uint32(8),r.Type.codec().encode(o.type,i)),o.peer!=null&&(i.uint32(18),ur.codec().encode(o.peer,i)),o.limit!=null&&(i.uint32(26),lr.codec().encode(o.limit,i)),o.status!=null&&(i.uint32(32),q.codec().encode(o.status,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=ur.codec().decode(o,o.uint32(),{limits:s.limits?.peer});break}case 3:{a.limit=lr.codec().decode(o,o.uint32(),{limits:s.limits?.limit});break}case 4:{a.status=q.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Pt(o,r.codec()),r.decode=(o,i)=>Bt(o,r.codec(),i)})(kt||(kt={}));var ur;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.id!=null&&e.id.byteLength>0&&(n.uint32(10),n.bytes(e.id)),e.addrs!=null)for(let i of e.addrs)n.uint32(18),n.bytes(i);o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={id:ot(0),addrs:[]},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.id=e.bytes();break}case 2:{if(o.limits?.addrs!=null&&i.addrs.length===o.limits.addrs)throw new Dr('Decode error - map field "addrs" had too many elements');i.addrs.push(e.bytes());break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(ur||(ur={}));var Vn;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.expire!=null&&e.expire!==0n&&(n.uint32(8),n.uint64(e.expire)),e.addrs!=null)for(let i of e.addrs)n.uint32(18),n.bytes(i);e.voucher!=null&&(n.uint32(26),Hn.codec().encode(e.voucher,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={expire:0n,addrs:[]},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.expire=e.uint64();break}case 2:{if(o.limits?.addrs!=null&&i.addrs.length===o.limits.addrs)throw new Dr('Decode error - map field "addrs" had too many elements');i.addrs.push(e.bytes());break}case 3:{i.voucher=Hn.codec().decode(e,e.uint32(),{limits:o.limits?.voucher});break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Vn||(Vn={}));var lr;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.duration!=null&&(n.uint32(8),n.uint32(e.duration)),e.data!=null&&(n.uint32(16),n.uint64(e.data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.duration=e.uint32();break}case 2:{i.data=e.uint64();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(lr||(lr={}));var q;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(q||(q={}));var ms;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(ms||(ms={}));(function(r){r.codec=()=>Me(ms)})(q||(q={}));var fr;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.relay!=null&&e.relay.byteLength>0&&(n.uint32(10),n.bytes(e.relay)),e.peer!=null&&e.peer.byteLength>0&&(n.uint32(18),n.bytes(e.peer)),e.expiration!=null&&e.expiration!==0n&&(n.uint32(24),n.uint64(e.expiration)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={relay:ot(0),peer:ot(0),expiration:0n},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.relay=e.bytes();break}case 2:{i.peer=e.bytes();break}case 3:{i.expiration=e.uint64();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(fr||(fr={}));var Hn;(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&&(n.uint32(26),fr.codec().encode(e.payload,n)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={publicKey:ot(0),payloadType:ot(0),signature:ot(0)},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.publicKey=e.bytes();break}case 2:{i.payloadType=e.bytes();break}case 3:{i.payload=fr.codec().decode(e,e.uint32(),{limits:o.limits?.payload});break}case 5:{i.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Hn||(Hn={}));var ud=r=>r.toString().split("/").slice(1),hr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),K=r=>({match:t=>hr(e=>e===r).match(t),pattern:r}),Fe=()=>({match:r=>hr(t=>typeof t=="string").match(r),pattern:"{string}"}),Fr=()=>({match:r=>hr(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),j=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{Z.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),zr=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Uo.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),G=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),At=(...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(", ")})`}),F=(...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 tt(...r){function t(o){let i=ud(o);for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function e(o){return t(o)!==!1}function n(o){let i=t(o);return i===!1?!1:i.length===0}return{matchers:r,matches:e,exactMatch:n}}var Wn=F(K("dns4"),Fe()),$n=F(K("dns6"),Fe()),Zn=F(K("dnsaddr"),Fe()),gs=F(K("dns"),Fe()),yw=tt(Wn,G(j())),gw=tt($n,G(j())),bw=tt(Zn,G(j())),xw=tt(At(gs,Zn,Wn,$n),G(j())),jc=F(K("ip4"),hr(Cn)),Qc=F(K("ip6"),hr(Dn)),bs=At(jc,Qc),de=At(bs,gs,Wn,$n,Zn),ww=tt(At(bs,F(At(gs,Zn,Wn,$n),G(j())))),Ew=tt(jc),Sw=tt(Qc),vw=tt(bs),xs=F(de,K("tcp"),Fr()),Vr=F(de,K("udp"),Fr()),Aw=tt(F(xs,G(j()))),_w=tt(Vr),ws=F(Vr,K("quic"),G(j())),Yn=F(Vr,K("quic-v1"),G(j())),ld=At(ws,Yn),Iw=tt(ws),Tw=tt(Yn),ys=At(de,xs,Vr,ws,Yn),Jc=At(F(ys,K("ws"),G(j()))),Lw=tt(Jc),tu=At(F(ys,K("wss"),G(j())),F(ys,K("tls"),G(F(K("sni"),Fe())),K("ws"),G(j()))),Rw=tt(tu),eu=F(Vr,K("webrtc-direct"),G(zr()),G(zr()),G(j())),Cw=tt(eu),ru=F(Yn,K("webtransport"),G(zr()),G(zr()),G(j())),Dw=tt(ru),Gn=At(Jc,tu,F(xs,G(j())),F(ld,G(j())),F(de,G(j())),eu,ru,j()),nu=tt(Gn),fd=F(Gn,K("p2p-circuit"),j()),Xn=tt(fd),hd=At(F(Gn,K("p2p-circuit"),K("webrtc"),G(j())),F(Gn,K("webrtc"),G(j())),F(K("webrtc"),G(j()))),Bw=tt(hd),dd=At(F(de,K("tcp"),Fr(),K("http"),G(j())),F(de,K("http"),G(j()))),Pw=tt(dd),pd=At(F(de,K("tcp"),At(F(K("443"),K("http")),F(Fr(),K("https"))),G(j())),F(de,K("tls"),K("http"),G(j())),F(de,K("https"),G(j()))),Nw=tt(pd),md=At(F(K("memory"),Fe(),G(j()))),Uw=tt(md);function jn(r){let t=new globalThis.AbortController;function e(){t.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let i of r){if(i?.aborted===!0){e();break}i?.addEventListener!=null&&i.addEventListener("abort",e)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}var Qn=class extends Error{constructor(t="Transfer limit error"){super(t),this.name="TransferLimitError"}},Hr=class extends Error{constructor(t="Duration limit error"){super(t),this.name="DurationLimitError"}},Gr=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},Jn=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},to=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};async function*ou(r,t,e){let n=t.remaining;for await(let o of r){let i=BigInt(o.byteLength);if(t.remaining-i<0){let s=Number(t.remaining);t.remaining=0n;try{s!==0&&(yield o.subarray(0,s))}catch(a){e.log.error(a)}throw new Qn(`data limit of ${n} bytes exceeded`)}t.remaining-=i,yield o}}function iu(r,t,e,n,o){function i(f){r.abort(f),t.abort(f)}let s=[e,n.signal];n.limit?.duration!=null&&(o.log("limiting relayed connection duration to %dms",n.limit.duration),s.push(AbortSignal.timeout(n.limit.duration)));let a=jn(s),c=!1,l=!1,u;n.limit?.data!=null&&(u={remaining:n.limit.data}),queueMicrotask(()=>{let f=()=>{o.log("relayed connection reached time limit"),t.abort(new Hr(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",f,{once:!0}),t.sink(u==null?r.source:ou(r.source,u,o)).catch(d=>{o.log.error("error while relaying streams src -> dst",d),i(d)}).finally(()=>{c=!0,l&&(a.removeEventListener("abort",f),a.clear())})}),queueMicrotask(()=>{let f=()=>{o.log("relayed connection reached time limit"),r.abort(new Hr(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",f,{once:!0}),r.sink(u==null?t.source:ou(t.source,u,o)).catch(d=>{o.log.error("error while relaying streams dst -> src",d),i(d)}).finally(()=>{l=!0,c&&(a.removeEventListener("abort",f),a.clear())})})}function Es(r){let t=r*BigInt(1e3),e=new Date().getTime();return Number(t-BigInt(e))}var Wr=class{expires;bytes;constructor(t){t?.duration!=null&&t?.duration!==0&&(this.expires=Date.now()+t.duration*1e3),this.bytes=t?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(t){this.bytes!=null&&(this.bytes-=BigInt(t.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let t={};if(this.bytes!=null){let e=this;Object.defineProperty(t,"bytes",{get(){return e.bytes}})}if(this.expires!=null){let e=this;Object.defineProperty(t,"seconds",{get(){return Math.round(((e.expires??0)-Date.now())/1e3)}})}return t}},eo=tt(F(nu.matchers[0],K("p2p-circuit"))),ro=tt(K("p2p-circuit"));function no(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}var Te=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 no(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 no(this.map.values(),t=>t.key)}values(){return no(this.map.values(),t=>t.value)}get size(){return this.map.size}};var Ss={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},su={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},au=new globalThis.TextEncoder;function yd(r,t){let e=Ss[t],n=su[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function gd(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Ss[t],o=su[t],i=r;for(;i.length>0;){let s=au.encodeInto(i,e);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function vs(r,{size:t=32,utf8Buffer:e}={}){if(!Ss[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 gd(r,t,e);r=au.encode(r)}return yd(r,t)}var $r={hash:r=>Number(vs(r,{size:32})),hashV:(r,t)=>bd($r.hash(r,t))};function bd(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),M(t,"base16")}var As=64,Zt=class{fp;h;seed;constructor(t,e,n,o=2){if(o>As)throw new TypeError("Invalid Fingerprint Size");let i=e.hashV(t,n),s=ot(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?ft(this.fp,t.fp):!1}};function ze(r,t){return Math.floor(Math.random()*(t-r))+r}var Ve=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Zt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Zt))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 Zt))throw new TypeError("Invalid Fingerprint");let e=ze(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Zt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var xd=500,Zr=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??$r,this.seed=t.seed??ze(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=M(t));let e=new Zt(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 Ve(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Ve(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let i=[n,o],s=i[ze(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new Ve(this.bucketSize));for(let a=0;a<xd;a++){let c=this.buckets[s].swap(e);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new Ve(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=M(t));let e=new Zt(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 i=(n^e.hash())%this.filterSize;return this.buckets[i]?.has(e)??!1}remove(t){typeof t=="string"&&(t=M(t));let e=new Zt(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 i=(n^e.hash())%this.filterSize,s=this.buckets[i]?.remove(e)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},wd={1:.5,2:.84,4:.95,8:.98};function Ed(r=.001){return r>.002?2:r>1e-5?4:8}function cu(r,t=.001){let e=Ed(t),n=wd[e],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),As);return{filterSize:o,bucketSize:e,fingerprintSize:i}}var oo=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??$r,this.seed=t.seed??ze(0,Math.pow(2,10)),this.filterSeries=[new Zr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=M(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 Zr({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=M(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=M(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 dr(r,t=.001,e){return new oo({...cu(r,t),...e??{}})}var io=class{filter;constructor(t,e){this.filter=dr(t,e)}has(t){return this.filter.has(t.toMultihash().bytes)}add(t){this.filter.add(t.toMultihash().bytes)}remove(t){this.filter.remove?.(t.toMultihash().bytes)}};function _s(r,t=.001){return new io(r,t)}var Is=class extends Te{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 Ts(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Is({name:t,metrics:e}):n=new Te,n}var Ls=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"}};function uu(r,t){let e=new Ls(t?.errorMessage,t?.errorCode,t?.errorName),n=new AbortController,o=()=>{n.abort(e)},i=AbortSignal.timeout(r);i.addEventListener("abort",o);let s=n.signal;return s.reset=a=>{i?.removeEventListener("abort",o),i=AbortSignal.timeout(a??r),i.addEventListener("abort",()=>{n.abort(e)})},s.clear=()=>{i?.removeEventListener("abort",o),i=void 0},s}var so=class{reservations;maxReservations;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:circuit-relay:server:reservation-store"),this.maxReservations=e.maxReservations??zc,this.applyDefaultLimit=e.applyDefaultLimit!==!1,this.reservationTtl=e.reservationTtl??Vc,this.defaultDurationLimit=e.defaultDurationLimit??Wc,this.defaultDataLimit=e.defaultDataLimit??$c,this.reservations=Ts({metrics:t.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(t,e,n){let o=this.reservations.get(t);if(this.reservations.size>=this.maxReservations&&o==null)return{status:q.RESERVATION_REFUSED};let i=new Date(Date.now()+this.reservationTtl),s;return this.applyDefaultLimit&&(s=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),o!=null?(this.log("refreshing reservation for client %p",t),o.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",t),o={addr:e,expiry:i,limit:s,signal:uu(this.reservationTtl)}),this.reservations.set(t,o),o.signal.addEventListener("abort",()=>{this.reservations.delete(t)}),{status:q.OK,expire:Math.round(i.getTime()/1e3)}}removeReservation(t){this.reservations.delete(t)}get(t){return this.reservations.get(t)}clear(){this.reservations.clear()}};var ao=class r{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:t,peer:e,expiration:n}){this.relay=t,this.peer=e,this.expiration=n}marshal(){return fr.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,expiration:BigInt(this.expiration)})}equals(t){return!(!(t instanceof r)||!this.peer.equals(t.peer)||!this.relay.equals(t.relay)||this.expiration!==t.expiration)}};var lu=r=>r.protoCodes().includes(Fn),Sd={maxOutboundStopStreams:qr},Rs=class extends Mt{registrar;peerStore;addressManager;peerId;privateKey;connectionManager;connectionGater;reservationStore;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:server"),this.registrar=t.registrar,this.peerStore=t.peerStore,this.addressManager=t.addressManager,this.peerId=t.peerId,this.privateKey=t.privateKey,this.connectionManager=t.connectionManager,this.connectionGater=t.connectionGater,this.started=!1,this.hopTimeout=e?.hopTimeout??Zc,this.maxInboundHopStreams=e.maxInboundHopStreams,this.maxOutboundHopStreams=e.maxOutboundHopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??Sd.maxOutboundStopStreams,this.reservationStore=new so(t,e.reservations),this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.registrar.handle(Ft,t=>{this.onHop(t).catch(e=>{this.log.error(e)})},{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.registrar.unhandle(Ft),this.started=!1}async onHop({connection:t,stream:e}){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n={signal:AbortSignal.timeout(this.hopTimeout)},o=Ie(e);try{let i=await o.pb(Y).read(n);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:t,stream:o,request:i},n)}catch(i){this.log.error("error while handling hop",i),await o.pb(Y).write({type:Y.Type.STATUS,status:q.MALFORMED_MESSAGE},n),e.abort(i)}}async handleHopProtocol({stream:t,request:e,connection:n},o){switch(this.log("received hop message"),e.type){case Y.Type.RESERVE:await this.handleReserve({stream:t,request:e,connection:n},o);break;case Y.Type.CONNECT:await this.handleConnect({stream:t,request:e,connection:n},o);break;default:this.log.error("invalid hop request type %s via peer %p",e.type,n.remotePeer),await t.pb(Y).write({type:Y.Type.STATUS,status:q.UNEXPECTED_MESSAGE})}}async handleReserve({stream:t,connection:e},n){let o=t.pb(Y);if(this.log("hop reserve request from %p",e.remotePeer),lu(e.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",e.remotePeer),await o.write({type:Y.Type.STATUS,status:q.PERMISSION_DENIED},n);return}if(await this.connectionGater.denyInboundRelayReservation?.(e.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",e.remotePeer),await o.write({type:Y.Type.STATUS,status:q.PERMISSION_DENIED},n);return}let i=this.reservationStore.reserve(e.remotePeer,e.remoteAddr);try{if(i.status!==q.OK){await o.write({type:Y.Type.STATUS,status:i.status},n);return}if(i.expire!=null){let s=i.expire*1e3-Date.now();await this.peerStore.merge(e.remotePeer,{tags:{[ds]:{value:1,ttl:s},[ps]:{value:1,ttl:s}}})}await o.write({type:Y.Type.STATUS,status:q.OK,reservation:await this.makeReservation(e.remotePeer,BigInt(i.expire??0)),limit:this.reservationStore.get(e.remotePeer)?.limit},n),this.log("sent confirmation response to %s",e.remotePeer)}catch(s){this.log.error("failed to send confirmation response to %p - %e",e.remotePeer,s),this.reservationStore.removeReservation(e.remotePeer);try{await this.peerStore.merge(e.remotePeer,{tags:{[ds]:void 0,[ps]:void 0}})}catch(a){this.log.error("failed to untag relay source peer %p - %e",e.remotePeer,a)}}}async makeReservation(t,e){let n=[];for(let i of this.addressManager.getAddresses())i.toString().includes("/p2p-circuit")||n.push(i.bytes);let o=await Mr.seal(new ao({peer:t,relay:this.peerId,expiration:e}),this.privateKey);return{addrs:n,expire:e,voucher:{publicKey:jt(o.publicKey),payloadType:o.payloadType,payload:{peer:t.toMultihash().bytes,relay:this.peerId.toMultihash().bytes,expiration:e},signature:o.signature}}}async handleConnect({stream:t,request:e,connection:n},o){let i=t.pb(Y);if(lu(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await i.write({type:Y.Type.STATUS,status:q.PERMISSION_DENIED},o);return}this.log("hop connect request from %p",n.remotePeer);let s;try{if(e.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");e.peer.addrs.forEach(St),s=sr(Kt(e.peer.id))}catch(d){this.log.error("invalid hop connect request via peer %p %s",n.remotePeer,d),await i.write({type:Y.Type.STATUS,status:q.MALFORMED_MESSAGE},o);return}let a=this.reservationStore.get(s);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",s,n.remotePeer,q.NO_RESERVATION),await i.write({type:Y.Type.STATUS,status:q.NO_RESERVATION},o);return}if(await this.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,s)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,s),await i.write({type:Y.Type.STATUS,status:q.PERMISSION_DENIED},o);return}let c=this.connectionManager.getConnections(s);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",s,n.remotePeer),await i.write({type:Y.Type.STATUS,status:q.NO_RESERVATION},o);return}let l=c[0],u=await this.stopHop({connection:l,request:{type:kt.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},o);if(u==null){this.log.error("failed to open stream to destination peer %p",l?.remotePeer),await i.write({type:Y.Type.STATUS,status:q.CONNECTION_FAILED},o);return}await i.write({type:Y.Type.STATUS,status:q.OK,limit:a?.limit},o);let f=t.unwrap();this.log("connection from %p to %p established - merging streams",n.remotePeer,s),iu(f,u,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:t,request:e},n){this.log("starting circuit relay v2 stop request to %s",t.remotePeer);let o=await t.newStream([qe],{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),i=Ie(o),s=i.pb(kt);await s.write(e,n);let a;try{a=await s.read(n)}catch{this.log.error("error parsing stop message response from %p",t.remotePeer)}if(a==null){this.log.error("could not read response from %p",t.remotePeer),await o.close(n);return}if(a.status===q.OK)return this.log("stop request to %p was successful",t.remotePeer),i.unwrap();this.log("stop request failed with code %d",a.status),await o.close(n)}get reservations(){return this.reservationStore.reservations}};function fu(r={}){return t=>new Rs(t,r)}function vd(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 hu=vd;function Ad(r){return r[Symbol.asyncIterator]!=null}function du(r){return r?.then!=null}function _d(r,t){let e=0;if(Ad(r))return async function*(){for await(let c of r){let l=t(c,e++);du(l)&&await l,yield c}}();let n=hu(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();if(typeof t(o,e++)?.then=="function")return async function*(){yield o;for await(let c of n){let l=t(c,e++);du(l)&&await l,yield c}}();let a=t;return function*(){yield o;for(let c of n)a(c,e++),yield c}()}var pu=_d;var uo=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}},pr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new uo(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 uo(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 Cs=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function lo(r={}){return Id(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 Id(r,t){t=t??{};let e=t.onEnd,n=new pr,o,i,s,a=vt(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((h,w)=>{i=S=>{i=null,n.push(S);try{h(r(n))}catch(m){w(m)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=vt()})}},l=h=>i!=null?i(h):(n.push(h),o),u=h=>(n=new pr,i!=null?i({error:h}):(n.push({error:h}),o)),f=h=>{if(s)return o;if(t?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:h})},d=h=>s?o:(s=!0,h!=null?u(h):l({done:!0})),g=()=>(n=new pr,d(),{done:!0}),y=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:g,throw:y,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let w=h?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let S,m;w!=null&&(S=new Promise((_,C)=>{m=()=>{C(new Cs)},w.addEventListener("abort",m)}));try{await Promise.race([a.promise,S])}finally{m!=null&&w!=null&&w?.removeEventListener("abort",m)}}},e==null)return o;let b=o;return o={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(h){return b.throw(h),e!=null&&(e(h),e=void 0),{done:!0}},return(){return b.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(h){return b.end(h),e!=null&&(e(h),e=void 0),o},get readableLength(){return b.readableLength},onEmpty:h=>b.onEmpty(h)},o}var Ds=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=vt(),this.haveNext=vt()}[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=vt(),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=vt(),await he(this.readNext.promise,e?.signal,e)}};function mu(){return new Ds}function Td(r){return r[Symbol.asyncIterator]!=null}async function Ld(r,t){try{await Promise.all(r.map(async e=>{for await(let n of e)await t.push(n)})),await t.end()}catch(e){await t.end(e).catch(()=>{})}}async function*Rd(r){let t=mu();Ld(r,t).catch(()=>{}),yield*t}function*Cd(r){for(let t of r)yield*t}function Dd(...r){let t=[];for(let e of r)Td(e)||t.push(e);return t.length===r.length?Cd(t):Rd(r)}var yu=Dd;function gu(r,...t){if(r==null)throw new Error("Empty pipeline");if(Bs(r)){let n=r;r=()=>n.source}else if(xu(r)||bu(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Bs(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)Bs(e[n])&&(e[n]=Pd(e[n]));return Bd(...e)}var Bd=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},bu=r=>r?.[Symbol.asyncIterator]!=null,xu=r=>r?.[Symbol.iterator]!=null,Bs=r=>r==null?!1:r.sink!=null&&r.source!=null,Pd=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=lo({objectMode:!0});e.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(bu(i))o=async function*(){yield*i,n.end()};else if(xu(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return yu(n,o())}return r.source};function Ps(r){let{stream:t,remoteAddr:e,logger:n,onDataRead:o,onDataWrite:i}=r,s=n.forComponent("libp2p:stream:converter"),a=!1,c=!1,l=t.close.bind(t);t.close=async y=>{await l(y),g(!0)};let u=t.abort.bind(t);t.abort=y=>{u(y),g(!0)};let f=t.sink.bind(t);t.sink=async y=>{try{await f(gu(y,b=>pu(b,h=>i?.(h))))}catch(b){b.type!=="aborted"&&s.error("%s error in sink",e,b)}finally{c=!0,g()}};let d={log:s,sink:t.sink,source:async function*(){try{for await(let y of t.source)o?.(y),yield y}finally{a=!0,g()}}(),remoteAddr:e,timeline:{open:Date.now(),close:void 0},close:t.close,abort:t.abort};function g(y){y===!0&&(a=!0,c=!0),a&&c&&d.timeline.close==null&&(d.timeline.close=Date.now())}return d}var Le=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Ns=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 fo(r,t,e,n){let o=new Ns(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((i,s)=>{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(),s(d);return}a(),i(f)},l=f=>{a(),s(f.detail)},u=()=>{a(),s(o)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var ho=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var po=class{deferred;signal;constructor(t){this.signal=t,this.deferred=vt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new ee)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Nd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var mo=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Nd(),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 ee),this.cleanup())}async join(t={}){let e=new po(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 he(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 yo=class extends Mt{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new ho;let n=new mo(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 i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,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 ee)}),this.clear()}async onEmpty(t){this.size!==0&&await fo(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await fo(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await fo(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=lo({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},i=c=>{n(c.detail)},s=()=>{n()},a=()=>{n(new ee("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",i),this.addEventListener("idle",s),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("error",i),this.removeEventListener("idle",s),t?.signal?.removeEventListener("abort",a),n()}}};var mr=class extends yo{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var go=class extends Mt{peerStore;registrar;connectionManager;randomWalk;started;running;topologyId;log;discoveryController;filter;queue;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.started=!1,this.running=!1,this.peerStore=t.peerStore,this.registrar=t.registrar,this.connectionManager=t.connectionManager,this.randomWalk=t.randomWalk,this.filter=e.filter,this.discoveryController=new AbortController,this.discoveryController.signal}isStarted(){return this.started}async start(){this.topologyId=await this.registrar.register(Ft,{filter:this.filter,onConnect:t=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",t,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:t})}}),this.started=!0}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.discoveryController?.abort(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,Promise.resolve().then(async()=>{this.log("searching peer store for relays");let t=await this.peerStore.all({filters:[n=>n.protocols.includes(Ft)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let i=wu(n),s=wu(o);return i>s?-1:s>i?1:0}]});for(let n of t)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",t.length);let e=this.queue=new mr({concurrency:5});this.log("start random walk");for await(let n of this.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),e.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(o=>o.toString()));continue}e.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await e.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,e.size,e.running),e.add(async()=>{let o=jn([this.discoveryController.signal,AbortSignal.timeout(5e3)]);try{await this.connectionManager.openConnection(n.id,{signal:o})}finally{o.clear()}},{peerId:n.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to random peer %p",n.id,o)})}this.log("stop random walk"),await e.onIdle()}).catch(t=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network",t)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort()}};function wu(r){let t=r.metadata.get("last-dial-success");return t==null?0:new Date(O(t)).getTime()}var Us=class extends Mt{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=t.connectionManager,this.addressManager=t.addressManager,this.reservationStore=t.reservationStore,this.listeningAddrs=[],this.listenTimeout=e.listenTimeout??zn,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=t=>{this.log("relay removed %p our relay %p",t.detail.relay,this.relay,this.relay?.equals(t.detail.relay)),this.relay?.equals(t.detail.relay)===!0&&(this.log("relay peer removed %p",t.detail.relay),this.listeningAddrs.forEach(e=>{this.addressManager.removeObservedAddr(e)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=t=>{let{details:e}=t.detail;e.type!=="configured"&&e.id===this.reservationId&&this.addedRelay(t.detail)};async listen(t){if(ro.exactMatch(t))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(eo.exactMatch(t)){this.log("listen on specific relay server %a",t);let e=AbortSignal.timeout(this.listenTimeout);let n=t.decapsulate("/p2p-circuit"),o=await this.connectionManager.openConnection(n,{signal:e});if(!this.reservationStore.hasReservation(o.remotePeer)){this.log("making reservation on peer %p",o.remotePeer);let i=await this.reservationStore.addRelay(o.remotePeer,"configured");this.addedRelay(i)}}else throw new Re(`Could not listen on p2p-circuit address "${t}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(t){this.log("relay peer added %p",t.relay),this.relay=t.relay,this.listeningAddrs=t.details.reservation.addrs.map(e=>St(e).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(e=>{this.addressManager.confirmObservedAddr(e,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function Eu(r){return new Us(r)}var Su="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var vu=(r=21)=>{let t="",e=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)t+=Su[e[r]&63];return t};var Ud=60*1e3*10,Od=60*1e3*5,kd=30*1e3,bo=class extends Mt{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(t,e){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=t.peerId,this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.reservations=new Te,this.pendingReservations=[],this.maxReservationQueueLength=e?.maxReservationQueueLength??Gc,this.reservationCompletionTimeout=e?.reservationCompletionTimeout??zn,this.started=!1,this.relayFilter=dr(100),this.reserveQueue=new mr({concurrency:e?.reservationConcurrency??Hc,metricName:"libp2p_relay_reservation_queue",metrics:t.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(i=>i.connection===n.detail.id)!=null&&this.#e(n.detail.remotePeer).catch(i=>{this.log("could not remove relay %p - %e",n.detail,i)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let t=await this.peerStore.all({filters:[e=>e.tags.has(Kr)]});this.log("removing tag from %d old relays",t.length),await Promise.all(t.map(async e=>{await this.peerStore.merge(e.id,{tags:{[Kr]:void 0}})})),this.log("redialing %d old relays",t.length),await Promise.all(t.map(async e=>this.addRelay(e.id,"discovered"))),this.#r()}).catch(t=>{this.log.error(t)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:t})=>{clearTimeout(t)}),this.reservations.clear(),this.started=!1}reserveRelay(){let t=vu();return this.pendingReservations.push(t),this.#r(),t}async addRelay(t,e){if(this.peerId.equals(t))throw this.log.trace("not trying to use self as relay"),new Re("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new to("The reservation queue is full");let n=this.reserveQueue.find(t);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",t),n.join();if(this.relayFilter.has(t.toMultihash().bytes))throw new Re("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",t),this.reserveQueue.add(async()=>{let o=Date.now();try{let i=this.reservations.get(t);if(i!=null){let y=this.connectionManager.getConnections(t),b=!1;if(y.length===0&&this.log("already have relay reservation with %p but we are no longer connected",t),y.map(h=>h.id).includes(i.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",t),b=!0),b&&Es(i.reservation.expire)>Ud)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",t),{relay:t,details:i};await this.#e(t)}if(e==="discovered"&&this.pendingReservations.length===0)throw new Gr("Not making reservation on discovered relay because we do not need any more relays");let s=AbortSignal.timeout(this.reservationCompletionTimeout);let a=await this.connectionManager.openConnection(t,{signal:s});if(Xn.matches(a.remoteAddr))throw new Jn("not creating reservation over relayed connection");let c=await this.#t(a,{signal:s}),l=Es(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",t,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-Od,kd),Math.pow(2,31)-1),f=setTimeout(()=>{this.log("refresh reservation to relay %p",t),this.addRelay(t,e).catch(async y=>{this.log.error("could not refresh reservation to relay %p - %e",t,y),await this.#e(t)}).catch(y=>{this.log.error("could not remove expired reservation to relay %p - %e",t,y)})},u),d;if(e==="discovered"){let y=this.pendingReservations.pop();if(y==null)throw new Gr("Made reservation on relay but did not need any more discovered relays");d={timeout:f,reservation:c,type:e,connection:a.id,id:y}}else d={timeout:f,reservation:c,type:e,connection:a.id};this.reservations.set(t,d),await this.peerStore.merge(t,{tags:{[Kr]:{value:1,ttl:l}}}),this.#r();let g={relay:t,details:d};return this.safeDispatchEvent("relay:created-reservation",{detail:g}),g}catch(i){throw e==="discovered"&&i.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",t,Date.now()-o,i),(i.name==="DialError"||i.name==="UnsupportedProtocolError")&&this.relayFilter.add(t.toMultihash().bytes),this.#e(t).catch(s=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",t,s)}),i}},{peerId:t})}hasReservation(t){return this.reservations.has(t)}getReservation(t){return this.reservations.get(t)?.reservation}reservationCount(t){return t==null?this.reservations.size:[...this.reservations.values()].reduce((e,n)=>(n.type===t&&e++,e),0)}cancelReservations(){[...this.reservations.values()].forEach(t=>{clearTimeout(t.timeout)}),this.reservations.clear()}async#t(t,e){e.signal?.throwIfAborted(),this.log("requesting reservation from %p",t.remotePeer);let n=await t.newStream(Ft,e),i=Ie(n).pb(Y);this.log.trace("send RESERVE to %p",t.remotePeer),await i.write({type:Y.Type.RESERVE},e);let s;try{this.log.trace("reading response from %p",t.remotePeer),s=await i.read(e)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(e)}if(this.log.trace("read response %o",s),s.status===q.OK&&s.reservation!=null){let c=new Set;c.add(t.remoteAddr.toString());for(let l of s.reservation.addrs){let u=St(l);u.getPeerId()==null&&(u=u.encapsulate(`/p2p/${t.remotePeer}`)),u=St(u.toString().replace(`/p2p/${t.remotePeer}/p2p/${t.remotePeer}`,`/p2p/${t.remotePeer}`)),c.add(u.toString())}return s.reservation.addrs=[...c].map(l=>St(l).bytes),s.reservation}let a=`reservation failed with status ${s.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#e(t){let e=this.reservations.get(t);e!=null&&(this.log("removing relay reservation with %p from local store",t),clearTimeout(e.timeout),this.reservations.delete(t),e.type==="discovered"&&this.pendingReservations.push(e.id),await this.peerStore.merge(t,{tags:{[Kr]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:t,details:e}}),this.#r())}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=dr(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var Md=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(St)}catch{return!1}return!0},Au={maxInboundStopStreams:qr,maxOutboundStopStreams:qr,stopTimeout:3e4},xo=class{discovery;registrar;peerStore;connectionManager;transportManager;peerId;upgrader;addressManager;connectionGater;reservationStore;logger;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:circuit-relay:transport"),this.registrar=t.registrar,this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.transportManager=t.transportManager,this.logger=t.logger,this.peerId=t.peerId,this.upgrader=t.upgrader,this.addressManager=t.addressManager,this.connectionGater=t.connectionGater,this.maxInboundStopStreams=e.maxInboundStopStreams??Au.maxInboundStopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??Au.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new go(t,{filter:e.discoveryFilter??_s(Yc,Xc)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{o.name!=="HadEnoughRelaysError"&&o.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p",n.detail,o)})}),this.reservationStore=new bo(t,e),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[Zs]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Ys](){return this.discovery!=null?["@libp2p/identify"]:[]}[Hs]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,await this.registrar.handle(qe,t=>{let e=this.upgrader.createInboundAbortSignal(this.shutdownController.signal);this.onStop(t,e).catch(n=>{this.log.error("error while handling STOP protocol",n),t.stream.abort(n)}).finally(()=>{e.clear()})},{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await Ws(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await $s(this.discovery,this.reservationStore),await this.registrar.unhandle(qe),this.started=!1}async dial(t,e){if(t.protoCodes().filter(g=>g===Fn).length!==1){let g="Invalid circuit relay address";throw this.log.error(g,t),new gr(g)}let n=t.toString().split("/p2p-circuit"),o=St(n[0]),i=St(n[n.length-1]),s=o.getPeerId(),a=i.getPeerId();if(s==null||a==null){let g=`ircuit relay dial to ${t.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${g}`),new gr(`C${g}`)}let c=Xi(s),l=Xi(a),f=this.connectionManager.getConnections(c)[0];f==null?(await this.peerStore.merge(c,{multiaddrs:[o]}),e.onProgress?.(new Le("circuit-relay:open-connection")),f=await this.connectionManager.openConnection(c,e)):e.onProgress?.(new Le("circuit-relay:reuse-connection"));let d;try{e.onProgress?.(new Le("circuit-relay:open-hop-stream")),d=await f.newStream(Ft,e);let g=Ie(d),y=g.pb(Y);e.onProgress?.(new Le("circuit-relay:write-connect-message")),await y.write({type:Y.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[St(i).bytes]}},e),e.onProgress?.(new Le("circuit-relay:read-connect-response"));let b=await y.read(e);if(b.status!==q.OK)throw new jr(`failed to connect via relay with status ${b?.status?.toString()??"undefined"}`);let h=new Wr(b.limit),w=Ps({stream:g.unwrap(),remoteAddr:t,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`),logger:this.logger,onDataRead:h.onData,onDataWrite:h.onData});return this.log("new outbound relayed connection %a",w.remoteAddr),await this.upgrader.upgradeOutbound(w,{...e,limits:h.getLimits()})}catch(g){throw this.log.error("circuit relay dial to destination %p via relay %p failed",l,c,g),d?.abort(g),g}}createListener(t){return Eu({peerId:this.peerId,connectionManager:this.connectionManager,addressManager:this.addressManager,reservationStore:this.reservationStore,logger:this.logger})}listenFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>eo.exactMatch(e)||ro.exactMatch(e))}dialFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>Xn.exactMatch(e))}async onStop({connection:t,stream:e},n){if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(f){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on",f)}let o=Ie(e).pb(kt),i=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,i.type),i?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await o.write({type:kt.Type.STATUS,status:q.MALFORMED_MESSAGE},{signal:n}),await e.close();return}if(i.type!==kt.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:kt.Type.STATUS,status:q.UNEXPECTED_MESSAGE},{signal:n}),await e.close();return}if(!Md(i)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:kt.Type.STATUS,status:q.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let s=sr(Kt(i.peer.id));if(await this.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,s)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await o.write({type:kt.Type.STATUS,status:q.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await o.write({type:kt.Type.STATUS,status:q.OK},{signal:n});let a=new Wr(i.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${s.toString()}`),l=this.addressManager.getAddresses()[0],u=Ps({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:l,logger:this.logger,onDataRead:a.onData,onDataWrite:a.onData});this.log("new inbound relayed connection %a",u.remoteAddr),await this.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),this.log("%s connection %a upgraded","inbound",u.remoteAddr)}};function _u(r={}){return t=>new xo(t,r)}return Mu(Kd);})();
2
+ "use strict";var Libp2PCircuitRelayV2=(()=>{var Eo=Object.defineProperty;var Nu=Object.getOwnPropertyDescriptor;var Uu=Object.getOwnPropertyNames;var Ou=Object.prototype.hasOwnProperty;var It=(r,t)=>{for(var e in t)Eo(r,e,{get:t[e],enumerable:!0})},ku=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Uu(t))!Ou.call(r,o)&&o!==e&&Eo(r,o,{get:()=>t[o],enumerable:!(n=Nu(t,o))||n.enumerable});return r};var Mu=r=>ku(Eo({},"__esModule",{value:!0}),r);var Kd={};It(Kd,{RELAY_V2_HOP_CODEC:()=>Ft,RELAY_V2_STOP_CODEC:()=>qe,circuitRelayServer:()=>fu,circuitRelayTransport:()=>_u});var So=Symbol.for("@libp2p/peer-id");var vo="keep-alive";var Gs=Symbol.for("@libp2p/transport");var Hs;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Hs||(Hs={}));var ee=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var lt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},He=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Yr=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},jr=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var Xr=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var gr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}},Re=class extends Error{static name="ListenError";constructor(t="Listen error"){super(t),this.name="ListenError"}};var Ge=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Mt=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:i})=>i!==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 Ws(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function $s(...r){let t=[];for(let e of r)Ws(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 Zs(...r){let t=[];for(let e of r)Ws(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 Ys=Symbol.for("@libp2p/service-capabilities"),js=Symbol.for("@libp2p/service-dependencies");var Lo={};It(Lo,{base58btc:()=>Z,base58flickr:()=>Hu});var mp=new Uint8Array(0);function Xs(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 re(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 Qs(r){return new TextEncoder().encode(r)}function Js(r){return new TextDecoder().decode(r)}function Ku(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 i=r.charAt(o),s=i.charCodeAt(0);if(e[s]!==255)throw new TypeError(i+" is ambiguous");e[s]=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(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var b=0,h=0,w=0,S=y.length;w!==S&&y[w]===0;)w++,b++;for(var m=(S-w)*u+1>>>0,_=new Uint8Array(m);w!==S;){for(var C=y[w],D=0,I=m-1;(C!==0||D<h)&&I!==-1;I--,D++)C+=256*_[I]>>>0,_[I]=C%a>>>0,C=C/a>>>0;if(C!==0)throw new Error("Non-zero carry");h=D,w++}for(var R=m-h;R!==m&&_[R]===0;)R++;for(var T=c.repeat(b);R<m;++R)T+=r.charAt(_[R]);return T}function d(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var b=0;if(y[b]!==" "){for(var h=0,w=0;y[b]===c;)h++,b++;for(var S=(y.length-b)*l+1>>>0,m=new Uint8Array(S);y[b];){var _=e[y.charCodeAt(b)];if(_===255)return;for(var C=0,D=S-1;(_!==0||C<w)&&D!==-1;D--,C++)_+=a*m[D]>>>0,m[D]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");w=C,b++}if(y[b]!==" "){for(var I=S-w;I!==S&&m[I]===0;)I++;for(var R=new Uint8Array(h+(S-I)),T=h;I!==S;)R[T++]=m[I++];return R}}}function g(y){var b=d(y);if(b)return b;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:g}}var qu=Ku,Fu=qu,ea=Fu;var Ao=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")}},_o=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 ra(this,t)}},Io=class{decoders;constructor(t){this.decoders=t}or(t){return ra(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 ra(r,t){return new Io({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var To=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 Ao(t,e,n),this.decoder=new _o(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function We({name:r,prefix:t,encode:e,decode:n}){return new To(r,t,e,n)}function pe({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=ea(e,r);return We({prefix:t,name:r,encode:n,decode:i=>re(o(i))})}function zu(r,t,e,n){let o={};for(let u=0;u<t.length;++u)o[t[u]]=u;let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*e/8|0),a=0,c=0,l=0;for(let u=0;u<i;++u){let f=o[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|f,a+=e,a>=8&&(a-=8,s[l++]=255&c>>a)}if(a>=e||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return s}function Vu(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>e;)s-=e,i+=t[o&a>>s];if(s!==0&&(i+=t[o&a<<e-s]),n)for(;(i.length*e&7)!==0;)i+="=";return i}function st({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return We({prefix:t,name:r,encode(o){return Vu(o,n,e)},decode(o){return zu(o,n,e,r)}})}var Z=pe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Hu=pe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ro={};It(Ro,{base32:()=>ne,base32hex:()=>Zu,base32hexpad:()=>ju,base32hexpadupper:()=>Xu,base32hexupper:()=>Yu,base32pad:()=>Wu,base32padupper:()=>$u,base32upper:()=>Gu,base32z:()=>Qu});var ne=st({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Gu=st({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Wu=st({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),$u=st({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Zu=st({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Yu=st({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ju=st({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Xu=st({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Qu=st({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Co={};It(Co,{base36:()=>br,base36upper:()=>Ju});var br=pe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ju=pe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var tl=ia,na=128,el=127,rl=~el,nl=Math.pow(2,31);function ia(r,t,e){t=t||[],e=e||0;for(var n=e;r>=nl;)t[e++]=r&255|na,r/=128;for(;r&rl;)t[e++]=r&255|na,r>>>=7;return t[e]=r|0,ia.bytes=e-n+1,t}var ol=Do,il=128,oa=127;function Do(r,n){var e=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw Do.bytes=0,new RangeError("Could not decode varint");s=r[i++],e+=o<28?(s&oa)<<o:(s&oa)*Math.pow(2,o),o+=7}while(s>=il);return Do.bytes=i-n,e}var sl=Math.pow(2,7),al=Math.pow(2,14),cl=Math.pow(2,21),ul=Math.pow(2,28),ll=Math.pow(2,35),fl=Math.pow(2,42),hl=Math.pow(2,49),dl=Math.pow(2,56),pl=Math.pow(2,63),ml=function(r){return r<sl?1:r<al?2:r<cl?3:r<ul?4:r<ll?5:r<fl?6:r<hl?7:r<dl?8:r<pl?9:10},yl={encode:tl,decode:ol,encodingLength:ml},gl=yl,xr=gl;function wr(r,t=0){return[xr.decode(r,t),xr.decode.bytes]}function $e(r,t,e=0){return xr.encode(r,t,e),t}function Ze(r){return xr.encodingLength(r)}function zt(r,t){let e=t.byteLength,n=Ze(r),o=n+Ze(e),i=new Uint8Array(o+e);return $e(r,i,0),$e(e,i,n),i.set(t,o),new Ye(r,e,t,i)}function Kt(r){let t=re(r),[e,n]=wr(t),[o,i]=wr(t.subarray(n)),s=t.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Ye(e,o,s,t)}function sa(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Xs(r.bytes,e.bytes)}}var Ye=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function aa(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return xl(e,Bo(r),t??Z.encoder);default:return wl(e,Bo(r),t??ne.encoder)}}var ca=new WeakMap;function Bo(r){let t=ca.get(r);if(t==null){let e=new Map;return ca.set(r,e),e}return t}var at=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Er)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==El)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=zt(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&sa(t.multihash,n.multihash)}toString(t){return aa(this,t)}toJSON(){return{"/":aa(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:i,bytes:s}=e;return new r(n,o,i,s??ua(n,o,i.bytes))}else if(e[Sl]===!0){let{version:n,multihash:o,code:i}=e,s=Kt(o);return r.create(n,i,s)}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!==Er)throw new Error(`Version 0 CID must use dag-pb (code: ${Er}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=ua(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Er,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=re(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let i=o.subarray(e.multihashSize-e.digestSize),s=new Ye(e.multihashCode,e.digestSize,i,o);return[e.version===0?r.createV0(s):r.createV1(e.codec,s),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,d]=wr(t.subarray(e));return e+=d,f},o=n(),i=Er;if(o===18?(o=0,e=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=e,a=n(),c=n(),l=e+c,u=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=bl(t,e),i=r.decode(o);if(i.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Bo(i).set(n,t),i}};function bl(r,t){switch(r[0]){case"Q":{let e=t??Z;return[Z.prefix,e.decode(`${Z.prefix}${r}`)]}case Z.prefix:{let e=t??Z;return[Z.prefix,e.decode(r)]}case ne.prefix:{let e=t??ne;return[ne.prefix,e.decode(r)]}case br.prefix:{let e=t??br;return[br.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 xl(r,t,e){let{prefix:n}=e;if(n!==Z.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let i=e.encode(r).slice(1);return t.set(n,i),i}else return o}function wl(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let i=e.encode(r);return t.set(n,i),i}else return o}var Er=112,El=18;function ua(r,t,e){let n=Ze(r),o=n+Ze(t),i=new Uint8Array(o+e.byteLength);return $e(r,i,0),$e(t,i,n),i.set(e,o),i}var Sl=Symbol.for("@ipld/js-cid/CID");var Po={};It(Po,{identity:()=>Vt});var la=0,vl="identity",fa=re;function Al(r){return zt(la,fa(r))}var Vt={code:la,name:vl,encode:fa,digest:Al};function ft(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 ot(r=0){return new Uint8Array(r)}function Lt(r=0){return new Uint8Array(r)}function Ut(r,t){t==null&&(t=r.reduce((o,i)=>o+i.length,0));let e=Lt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var da=Symbol.for("@achingbrain/uint8arraylist");function ha(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 Jr(r){return!!r?.[da]}var ct=class r{bufs;length;[da]=!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(Jr(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(Jr(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=ha(this.bufs,t);return e.buf[e.index]}set(t,e){let n=ha(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(Jr(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 Ut(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Ut(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),i=new r;return i.length=o,i.bufs=[...n],i}_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 i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=o,c=a+s.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(s);break}let f=t-a;n.push(s.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(s);continue}n.push(s.subarray(t-a));continue}if(u){if(e===c){n.push(s);break}n.push(s.subarray(0,e-a));break}n.push(s)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Jr(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 i=256,s=new Int32Array(i);for(let f=0;f<i;f++)s[f]=-1;for(let f=0;f<o;f++)s[n[f]]=f;let a=s,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=Lt(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=ot(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=ot(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=ot(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=Lt(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=ot(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=ot(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=ot(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=ot(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=ot(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(!ft(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,i)=>o+i.byteLength,0)),n.length=e,n}};var No={};It(No,{base10:()=>_l});var _l=pe({prefix:"9",name:"base10",alphabet:"0123456789"});var Uo={};It(Uo,{base16:()=>Il,base16upper:()=>Tl});var Il=st({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Tl=st({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Oo={};It(Oo,{base2:()=>Ll});var Ll=st({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ko={};It(ko,{base256emoji:()=>Pl});var pa=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}"),Rl=pa.reduce((r,t,e)=>(r[e]=t,r),[]),Cl=pa.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Dl(r){return r.reduce((t,e)=>(t+=Rl[e],t),"")}function Bl(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Cl[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Pl=We({prefix:"\u{1F680}",name:"base256emoji",encode:Dl,decode:Bl});var Ko={};It(Ko,{base64:()=>Nl,base64pad:()=>Ul,base64url:()=>Mo,base64urlpad:()=>Ol});var Nl=st({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ul=st({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Mo=st({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ol=st({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var qo={};It(qo,{base8:()=>kl});var kl=st({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Fo={};It(Fo,{identity:()=>Ml});var Ml=We({prefix:"\0",name:"identity",encode:r=>Js(r),decode:r=>Qs(r)});var Qp=new TextEncoder,Jp=new TextDecoder;var Ho={};It(Ho,{sha256:()=>je,sha512:()=>Fl});function Vo({name:r,code:t,encode:e}){return new zo(r,t,e)}var zo=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?zt(this.code,e):e.then(n=>zt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ya(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var je=Vo({name:"sha2-256",code:18,encode:ya("SHA-256")}),Fl=Vo({name:"sha2-512",code:19,encode:ya("SHA-512")});var Sr={...Fo,...Oo,...qo,...No,...Uo,...Ro,...Co,...Lo,...Ko,...ko},fm={...Ho,...Po};function ba(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var ga=ba("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Go=ba("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=Lt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),zl={utf8:ga,"utf-8":ga,hex:Sr.base16,latin1:Go,ascii:Go,binary:Go,...Sr},tn=zl;function M(r,t="utf8"){let e=tn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function O(r,t="utf8"){let e=tn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Vl=parseInt("11111",2),Wo=parseInt("10000000",2),Hl=parseInt("01111111",2),xa={0:vr,1:vr,2:Gl,3:Zl,4:Yl,5:$l,6:Wl,16:vr,22:vr,48:vr};function oe(r,t={offset:0}){let e=r[t.offset]&Vl;if(t.offset++,xa[e]!=null)return xa[e](r,t);throw new Error("No decoder for tag "+e)}function Ar(r,t){let e=0;if((r[t.offset]&Wo)===Wo){let n=r[t.offset]&Hl,o="0x";t.offset++;for(let i=0;i<n;i++,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 vr(r,t){Ar(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=oe(r,t);if(n===null)break;e.push(n)}return e}function Gl(r,t){let e=Ar(r,t),n=t.offset,o=t.offset+e,i=[];for(let s=n;s<o;s++)s===n&&r[s]===0||i.push(r[s]);return t.offset+=e,Uint8Array.from(i)}function Wl(r,t){let e=Ar(r,t),n=t.offset+e,o=r[t.offset];t.offset++;let i=0,s=0;o<40?(i=0,s=o):o<80?(i=1,s=o-40):(i=2,s=o-80);let a=`${i}.${s}`,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 $l(r,t){return t.offset++,null}function Zl(r,t){let e=Ar(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 Yl(r,t){let e=Ar(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function jl(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new ct;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function $o(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=jl(r.byteLength);return new ct(Uint8Array.from([t.byteLength|Wo]),t)}function Rt(r){let t=new ct,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new ct(Uint8Array.from([2]),$o(t),t)}function en(r){let t=Uint8Array.from([0]),e=new ct(t,r);return new ct(Uint8Array.from([3]),$o(e),e)}function me(r,t=48){let e=new ct;for(let n of r)e.append(n);return new ct(Uint8Array.from([t]),$o(e),e)}async function wa(r,t,e){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,t,e.subarray())}var Xl=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Ql=Uint8Array.from([6,5,43,129,4,0,34]),Jl=Uint8Array.from([6,5,43,129,4,0,35]),tf={ext:!0,kty:"EC",crv:"P-256"},ef={ext:!0,kty:"EC",crv:"P-384"},rf={ext:!0,kty:"EC",crv:"P-521"},Zo=32,Yo=48,jo=66;function Xo(r){let t=oe(r);return Ea(t)}function Ea(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Zo*2+1)return n=O(t.subarray(e,e+Zo),"base64url"),o=O(t.subarray(e+Zo),"base64url"),new Xe({...tf,key_ops:["verify"],x:n,y:o});if(t.byteLength===Yo*2+1)return n=O(t.subarray(e,e+Yo),"base64url"),o=O(t.subarray(e+Yo),"base64url"),new Xe({...ef,key_ops:["verify"],x:n,y:o});if(t.byteLength===jo*2+1)return n=O(t.subarray(e,e+jo),"base64url"),o=O(t.subarray(e+jo),"base64url"),new Xe({...rf,key_ops:["verify"],x:n,y:o});throw new lt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Sa(r){return me([Rt(Uint8Array.from([1])),me([nf(r.crv)],160),me([en(new ct(Uint8Array.from([4]),M(r.x??"","base64url"),M(r.y??"","base64url")))],161)]).subarray()}function nf(r){if(r==="P-256")return Xl;if(r==="P-384")return Ql;if(r==="P-521")return Jl;throw new lt(`Invalid curve ${r}`)}var Xe=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Sa(this.jwk)),this._raw}toMultihash(){return Vt.digest(Xt(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ft(this.raw,t.raw)}async verify(t,e){return wa(this.jwk,e,t)}};function va(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function of(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Qe(r,...t){if(!of(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 Aa(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");va(r.outputLen),va(r.blockLen)}function Je(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 _a(r,t){Qe(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}var Ce=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function rn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Ht(r,t){return r<<32-t|r>>>t}function Ia(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function _r(r){return typeof r=="string"&&(r=Ia(r)),Qe(r),r}function Qo(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Qe(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let i=r[n];e.set(i,o),o+=i.length}return e}var tr=class{clone(){return this._cloneInto()}};function nn(r){let t=n=>r().update(_r(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function on(r=32){if(Ce&&typeof Ce.getRandomValues=="function")return Ce.getRandomValues(new Uint8Array(r));if(Ce&&typeof Ce.randomBytes=="function")return Ce.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function sf(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(e>>o&i),a=Number(e&i),c=n?4:0,l=n?0:4;r.setUint32(t+c,s,n),r.setUint32(t+l,a,n)}function Ta(r,t,e){return r&t^~r&e}function La(r,t,e){return r&t^r&e^t&e}var er=class extends tr{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=rn(this.buffer)}update(t){Je(this);let{view:e,buffer:n,blockLen:o}=this;t=_r(t);let i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=rn(t);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Je(this),_a(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;e[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>o-s&&(this.process(n,0),s=0);for(let f=s;f<o;f++)e[f]=0;sf(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=rn(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],i)}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:i,destroyed:s,pos:a}=this;return t.length=o,t.pos=a,t.finished=i,t.destroyed=s,o%e&&t.buffer.set(n),t}};var sn=BigInt(4294967295),Jo=BigInt(32);function Ra(r,t=!1){return t?{h:Number(r&sn),l:Number(r>>Jo&sn)}:{h:Number(r>>Jo&sn)|0,l:Number(r&sn)|0}}function af(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:i,l:s}=Ra(r[o],t);[e[o],n[o]]=[i,s]}return[e,n]}var cf=(r,t)=>BigInt(r>>>0)<<Jo|BigInt(t>>>0),uf=(r,t,e)=>r>>>e,lf=(r,t,e)=>r<<32-e|t>>>e,ff=(r,t,e)=>r>>>e|t<<32-e,hf=(r,t,e)=>r<<32-e|t>>>e,df=(r,t,e)=>r<<64-e|t>>>e-32,pf=(r,t,e)=>r>>>e-32|t<<64-e,mf=(r,t)=>t,yf=(r,t)=>r,gf=(r,t,e)=>r<<e|t>>>32-e,bf=(r,t,e)=>t<<e|r>>>32-e,xf=(r,t,e)=>t<<e-32|r>>>64-e,wf=(r,t,e)=>r<<e-32|t>>>64-e;function Ef(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Sf=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),vf=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Af=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),_f=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,If=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Tf=(r,t,e,n,o,i)=>t+e+n+o+i+(r/2**32|0)|0;var Lf={fromBig:Ra,split:af,toBig:cf,shrSH:uf,shrSL:lf,rotrSH:ff,rotrSL:hf,rotrBH:df,rotrBL:pf,rotr32H:mf,rotr32L:yf,rotlSH:gf,rotlSL:bf,rotlBH:xf,rotlBL:wf,add:Ef,add3L:Sf,add3H:vf,add4L:Af,add4H:_f,add5H:Tf,add5L:If},U=Lf;var[Rf,Cf]=U.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),ye=new Uint32Array(80),ge=new Uint32Array(80),ti=class extends er{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:g,Gl:y,Hh:b,Hl:h}=this;return[t,e,n,o,i,s,a,c,l,u,f,d,g,y,b,h]}set(t,e,n,o,i,s,a,c,l,u,f,d,g,y,b,h){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|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=y|0,this.Hh=b|0,this.Hl=h|0}process(t,e){for(let m=0;m<16;m++,e+=4)ye[m]=t.getUint32(e),ge[m]=t.getUint32(e+=4);for(let m=16;m<80;m++){let _=ye[m-15]|0,C=ge[m-15]|0,D=U.rotrSH(_,C,1)^U.rotrSH(_,C,8)^U.shrSH(_,C,7),I=U.rotrSL(_,C,1)^U.rotrSL(_,C,8)^U.shrSL(_,C,7),R=ye[m-2]|0,T=ge[m-2]|0,et=U.rotrSH(R,T,19)^U.rotrBH(R,T,61)^U.shrSH(R,T,6),H=U.rotrSL(R,T,19)^U.rotrBL(R,T,61)^U.shrSL(R,T,6),z=U.add4L(I,H,ge[m-7],ge[m-16]),ht=U.add4H(z,D,et,ye[m-7],ye[m-16]);ye[m]=ht|0,ge[m]=z|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:g,Fl:y,Gh:b,Gl:h,Hh:w,Hl:S}=this;for(let m=0;m<80;m++){let _=U.rotrSH(f,d,14)^U.rotrSH(f,d,18)^U.rotrBH(f,d,41),C=U.rotrSL(f,d,14)^U.rotrSL(f,d,18)^U.rotrBL(f,d,41),D=f&g^~f&b,I=d&y^~d&h,R=U.add5L(S,C,I,Cf[m],ge[m]),T=U.add5H(R,w,_,D,Rf[m],ye[m]),et=R|0,H=U.rotrSH(n,o,28)^U.rotrBH(n,o,34)^U.rotrBH(n,o,39),z=U.rotrSL(n,o,28)^U.rotrBL(n,o,34)^U.rotrBL(n,o,39),ht=n&i^n&a^i&a,v=o&s^o&c^s&c;w=b|0,S=h|0,b=g|0,h=y|0,g=f|0,y=d|0,{h:f,l:d}=U.add(l|0,u|0,T|0,et|0),l=a|0,u=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let L=U.add3L(et,z,v);n=U.add3H(L,T,H,ht),o=L|0}({h:n,l:o}=U.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=U.add(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=U.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=U.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=U.add(this.Eh|0,this.El|0,f|0,d|0),{h:g,l:y}=U.add(this.Fh|0,this.Fl|0,g|0,y|0),{h:b,l:h}=U.add(this.Gh|0,this.Gl|0,b|0,h|0),{h:w,l:S}=U.add(this.Hh|0,this.Hl|0,w|0,S|0),this.set(n,o,i,s,a,c,l,u,f,d,g,y,b,h,w,S)}roundClean(){ye.fill(0),ge.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Ca=nn(()=>new ti);var un={};It(un,{aInRange:()=>Ct,abool:()=>Gt,abytes:()=>rr,bitGet:()=>Of,bitLen:()=>oi,bitMask:()=>Tr,bitSet:()=>kf,bytesToHex:()=>se,bytesToNumberBE:()=>ae,bytesToNumberLE:()=>xe,concatBytes:()=>ce,createHmacDrbg:()=>ii,ensureBytes:()=>it,equalBytes:()=>Nf,hexToBytes:()=>Be,hexToNumber:()=>ni,inRange:()=>Ir,isBytes:()=>be,memoized:()=>Ne,notImplemented:()=>Kf,numberToBytesBE:()=>we,numberToBytesLE:()=>Pe,numberToHexUnpadded:()=>De,numberToVarBytesBE:()=>Pf,utf8ToBytes:()=>Uf,validateObject:()=>Qt});var an=BigInt(0),cn=BigInt(1),Df=BigInt(2);function be(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function rr(r){if(!be(r))throw new Error("Uint8Array expected")}function Gt(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}var Bf=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function se(r){rr(r);let t="";for(let e=0;e<r.length;e++)t+=Bf[r[e]];return t}function De(r){let t=r.toString(16);return t.length&1?"0"+t:t}function ni(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?an:BigInt("0x"+r)}var ie={_0:48,_9:57,A:65,F:70,a:97,f:102};function Da(r){if(r>=ie._0&&r<=ie._9)return r-ie._0;if(r>=ie.A&&r<=ie.F)return r-(ie.A-10);if(r>=ie.a&&r<=ie.f)return r-(ie.a-10)}function Be(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,i=0;o<e;o++,i+=2){let s=Da(r.charCodeAt(i)),a=Da(r.charCodeAt(i+1));if(s===void 0||a===void 0){let c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function ae(r){return ni(se(r))}function xe(r){return rr(r),ni(se(Uint8Array.from(r).reverse()))}function we(r,t){return Be(r.toString(16).padStart(t*2,"0"))}function Pe(r,t){return we(r,t).reverse()}function Pf(r){return Be(De(r))}function it(r,t,e){let n;if(typeof t=="string")try{n=Be(t)}catch(i){throw new Error(r+" must be hex string or Uint8Array, cause: "+i)}else if(be(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 ce(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];rr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let i=r[n];e.set(i,o),o+=i.length}return e}function Nf(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function Uf(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var ei=r=>typeof r=="bigint"&&an<=r;function Ir(r,t,e){return ei(r)&&ei(t)&&ei(e)&&t<=r&&r<e}function Ct(r,t,e,n){if(!Ir(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function oi(r){let t;for(t=0;r>an;r>>=cn,t+=1);return t}function Of(r,t){return r>>BigInt(t)&cn}function kf(r,t,e){return r|(e?cn:an)<<BigInt(t)}var Tr=r=>(Df<<BigInt(r-1))-cn,ri=r=>new Uint8Array(r),Ba=r=>Uint8Array.from(r);function ii(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=ri(r),o=ri(r),i=0,s=()=>{n.fill(1),o.fill(0),i=0},a=(...f)=>e(o,n,...f),c=(f=ri())=>{o=a(Ba([0]),f),n=a(),f.length!==0&&(o=a(Ba([1]),f),n=a())},l=()=>{if(i++>=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 ce(...d)};return(f,d)=>{s(),c(f);let g;for(;!(g=d(l()));)c();return s(),g}}var Mf={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"||be(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 Qt(r,t,e={}){let n=(o,i,s)=>{let a=Mf[i];if(typeof a!="function")throw new Error("invalid validator function");let c=r[o];if(!(s&&c===void 0)&&!a(c,r))throw new Error("param "+String(o)+" is invalid. Expected "+i+", got "+c)};for(let[o,i]of Object.entries(t))n(o,i,!1);for(let[o,i]of Object.entries(e))n(o,i,!0);return r}var Kf=()=>{throw new Error("not implemented")};function Ne(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let i=r(e,...n);return t.set(e,i),i}}var dt=BigInt(0),rt=BigInt(1),Ue=BigInt(2),qf=BigInt(3),si=BigInt(4),Pa=BigInt(5),Na=BigInt(8),Ff=BigInt(9),zf=BigInt(16);function j(r,t){let e=r%t;return e>=dt?e:t+e}function Vf(r,t,e){if(t<dt)throw new Error("invalid exponent, negatives unsupported");if(e<=dt)throw new Error("invalid modulus");if(e===rt)return dt;let n=rt;for(;t>dt;)t&rt&&(n=n*r%e),r=r*r%e,t>>=rt;return n}function nt(r,t,e){let n=r;for(;t-- >dt;)n*=n,n%=e;return n}function ln(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=j(r,t),n=t,o=dt,i=rt,s=rt,a=dt;for(;e!==dt;){let l=n/e,u=n%e,f=o-s*l,d=i-a*l;n=e,e=u,o=s,i=a,s=f,a=d}if(n!==rt)throw new Error("invert: does not exist");return j(o,t)}function Hf(r){let t=(r-rt)/Ue,e,n,o;for(e=r-rt,n=0;e%Ue===dt;e/=Ue,n++);for(o=Ue;o<r&&Vf(o,t,r)!==r-rt;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let s=(r+rt)/si;return function(c,l){let u=c.pow(l,s);if(!c.eql(c.sqr(u),l))throw new Error("Cannot find square root");return u}}let i=(e+rt)/Ue;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),e),f=a.pow(c,i),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let g=1;for(let b=a.sqr(d);g<l&&!a.eql(b,a.ONE);g++)b=a.sqr(b);let y=a.pow(u,rt<<BigInt(l-g-1));u=a.sqr(y),f=a.mul(f,y),d=a.mul(d,u),l=g}return f}}function Gf(r){if(r%si===qf){let t=(r+rt)/si;return function(n,o){let i=n.pow(o,t);if(!n.eql(n.sqr(i),o))throw new Error("Cannot find square root");return i}}if(r%Na===Pa){let t=(r-Pa)/Na;return function(n,o){let i=n.mul(o,Ue),s=n.pow(i,t),a=n.mul(o,s),c=n.mul(n.mul(a,Ue),s),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%zf,Hf(r)}var Ua=(r,t)=>(j(r,t)&rt)===rt,Wf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ai(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Wf.reduce((n,o)=>(n[o]="function",n),t);return Qt(r,e)}function $f(r,t,e){if(e<dt)throw new Error("invalid exponent, negatives unsupported");if(e===dt)return r.ONE;if(e===rt)return t;let n=r.ONE,o=t;for(;e>dt;)e&rt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=rt;return n}function Zf(r,t){let e=new Array(t.length),n=t.reduce((i,s,a)=>r.is0(s)?i:(e[a]=i,r.mul(i,s)),r.ONE),o=r.inv(n);return t.reduceRight((i,s,a)=>r.is0(s)?i:(e[a]=r.mul(i,e[a]),r.mul(i,s)),o),e}function ci(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Ee(r,t,e=!1,n={}){if(r<=dt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:i}=ci(r,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let s,a=Object.freeze({ORDER:r,isLE:e,BITS:o,BYTES:i,MASK:Tr(o),ZERO:dt,ONE:rt,create:c=>j(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&rt)===rt,neg:c=>j(-c,r),eql:(c,l)=>c===l,sqr:c=>j(c*c,r),add:(c,l)=>j(c+l,r),sub:(c,l)=>j(c-l,r),mul:(c,l)=>j(c*l,r),pow:(c,l)=>$f(a,c,l),div:(c,l)=>j(c*ln(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>ln(c,r),sqrt:n.sqrt||(c=>(s||(s=Gf(r)),s(a,c))),invertBatch:c=>Zf(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?Pe(c,i):we(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return e?xe(c):ae(c)}});return Object.freeze(a)}function Oa(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 ui(r){let t=Oa(r);return t+Math.ceil(t/2)}function ka(r,t,e=!1){let n=r.length,o=Oa(t),i=ui(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=e?xe(r):ae(r),a=j(s,t-rt)+rt;return e?Pe(a,o):we(a,o)}var Ma=BigInt(0),fn=BigInt(1);function li(r,t){let e=t.negate();return r?e:t}function Ka(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function fi(r,t){Ka(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1);return{windows:e,windowSize:n}}function Yf(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 jf(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 hi=new WeakMap,qa=new WeakMap;function di(r){return qa.get(r)||1}function hn(r,t){return{constTimeNegate:li,hasPrecomputes(e){return di(e)!==1},unsafeLadder(e,n,o=r.ZERO){let i=e;for(;n>Ma;)n&fn&&(o=o.add(i)),i=i.double(),n>>=fn;return o},precomputeWindow(e,n){let{windows:o,windowSize:i}=fi(n,t),s=[],a=e,c=a;for(let l=0;l<o;l++){c=a,s.push(c);for(let u=1;u<i;u++)c=c.add(a),s.push(c);a=c.double()}return s},wNAF(e,n,o){let{windows:i,windowSize:s}=fi(e,t),a=r.ZERO,c=r.BASE,l=BigInt(2**e-1),u=2**e,f=BigInt(e);for(let d=0;d<i;d++){let g=d*s,y=Number(o&l);o>>=f,y>s&&(y-=u,o+=fn);let b=g,h=g+Math.abs(y)-1,w=d%2!==0,S=y<0;y===0?c=c.add(li(w,n[b])):a=a.add(li(S,n[h]))}return{p:a,f:c}},wNAFUnsafe(e,n,o,i=r.ZERO){let{windows:s,windowSize:a}=fi(e,t),c=BigInt(2**e-1),l=2**e,u=BigInt(e);for(let f=0;f<s;f++){let d=f*a;if(o===Ma)break;let g=Number(o&c);if(o>>=u,g>a&&(g-=l,o+=fn),g===0)continue;let y=n[d+Math.abs(g)-1];g<0&&(y=y.negate()),i=i.add(y)}return i},getPrecomputes(e,n,o){let i=hi.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&hi.set(n,o(i))),i},wNAFCached(e,n,o){let i=di(e);return this.wNAF(i,this.getPrecomputes(i,e,o),n)},wNAFCachedUnsafe(e,n,o,i){let s=di(e);return s===1?this.unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,o),n,i)},setWindowSize(e,n){Ka(n,t),qa.set(e,n),hi.delete(e)}}}function dn(r,t,e,n){if(Yf(e,r),jf(n,t),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,i=oi(BigInt(e.length)),s=i>12?i-3:i>4?i-2:i?2:1,a=(1<<s)-1,c=new Array(a+1).fill(o),l=Math.floor((t.BITS-1)/s)*s,u=o;for(let f=l;f>=0;f-=s){c.fill(o);for(let g=0;g<n.length;g++){let y=n[g],b=Number(y>>BigInt(f)&BigInt(a));c[b]=c[b].add(e[g])}let d=o;for(let g=c.length-1,y=o;g>0;g--)y=y.add(c[g]),d=d.add(y);if(u=u.add(d),f!==0)for(let g=0;g<s;g++)u=u.double()}return u}function Lr(r){return ai(r.Fp),Qt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ci(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Wt=BigInt(0),Dt=BigInt(1),pn=BigInt(2),Xf=BigInt(8),Qf={zip215:!0};function Jf(r){let t=Lr(r);return Qt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Fa(r){let t=Jf(r),{Fp:e,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=t,l=pn<<BigInt(a*8)-Dt,u=e.create,f=Ee(t.n,t.nBitLength),d=t.uvRatio||((x,p)=>{try{return{isValid:!0,value:e.sqrt(x*e.inv(p))}}catch{return{isValid:!1,value:Wt}}}),g=t.adjustScalarBytes||(x=>x),y=t.domain||((x,p,E)=>{if(Gt("phflag",E),p.length||E)throw new Error("Contexts/pre-hash are not supported");return x});function b(x,p){Ct("coordinate "+x,p,Wt,l)}function h(x){if(!(x instanceof m))throw new Error("ExtendedPoint expected")}let w=Ne((x,p)=>{let{ex:E,ey:A,ez:B}=x,P=x.is0();p==null&&(p=P?Xf:e.inv(B));let k=u(E*p),V=u(A*p),N=u(B*p);if(P)return{x:Wt,y:Dt};if(N!==Dt)throw new Error("invZ was invalid");return{x:k,y:V}}),S=Ne(x=>{let{a:p,d:E}=t;if(x.is0())throw new Error("bad point: ZERO");let{ex:A,ey:B,ez:P,et:k}=x,V=u(A*A),N=u(B*B),$=u(P*P),J=u($*$),pt=u(V*p),mt=u($*u(pt+N)),gt=u(J+u(E*u(V*N)));if(mt!==gt)throw new Error("bad point: equation left != right (1)");let bt=u(A*B),Tt=u(P*k);if(bt!==Tt)throw new Error("bad point: equation left != right (2)");return!0});class m{constructor(p,E,A,B){this.ex=p,this.ey=E,this.ez=A,this.et=B,b("x",p),b("y",E),b("z",A),b("t",B),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(p){if(p instanceof m)throw new Error("extended point not allowed");let{x:E,y:A}=p||{};return b("x",E),b("y",A),new m(E,A,Dt,u(E*A))}static normalizeZ(p){let E=e.invertBatch(p.map(A=>A.ez));return p.map((A,B)=>A.toAffine(E[B])).map(m.fromAffine)}static msm(p,E){return dn(m,f,p,E)}_setWindowSize(p){D.setWindowSize(this,p)}assertValidity(){S(this)}equals(p){h(p);let{ex:E,ey:A,ez:B}=this,{ex:P,ey:k,ez:V}=p,N=u(E*V),$=u(P*B),J=u(A*V),pt=u(k*B);return N===$&&J===pt}is0(){return this.equals(m.ZERO)}negate(){return new m(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:p}=t,{ex:E,ey:A,ez:B}=this,P=u(E*E),k=u(A*A),V=u(pn*u(B*B)),N=u(p*P),$=E+A,J=u(u($*$)-P-k),pt=N+k,mt=pt-V,gt=N-k,bt=u(J*mt),Tt=u(pt*gt),_t=u(J*gt),Yt=u(mt*pt);return new m(bt,Tt,Yt,_t)}add(p){h(p);let{a:E,d:A}=t,{ex:B,ey:P,ez:k,et:V}=this,{ex:N,ey:$,ez:J,et:pt}=p;if(E===BigInt(-1)){let ks=u((P-B)*($+N)),Ms=u((P+B)*($-N)),wo=u(Ms-ks);if(wo===Wt)return this.double();let Ks=u(k*pn*pt),qs=u(V*pn*J),Fs=qs+Ks,zs=Ms+ks,Vs=qs-Ks,Cu=u(Fs*wo),Du=u(zs*Vs),Bu=u(Fs*Vs),Pu=u(wo*zs);return new m(Cu,Du,Pu,Bu)}let mt=u(B*N),gt=u(P*$),bt=u(V*A*pt),Tt=u(k*J),_t=u((B+P)*(N+$)-mt-gt),Yt=Tt-bt,te=Tt+bt,yr=u(gt-E*mt),Iu=u(_t*Yt),Tu=u(te*yr),Lu=u(_t*yr),Ru=u(Yt*te);return new m(Iu,Tu,Ru,Lu)}subtract(p){return this.add(p.negate())}wNAF(p){return D.wNAFCached(this,p,m.normalizeZ)}multiply(p){let E=p;Ct("scalar",E,Dt,n);let{p:A,f:B}=this.wNAF(E);return m.normalizeZ([A,B])[0]}multiplyUnsafe(p,E=m.ZERO){let A=p;return Ct("scalar",A,Wt,n),A===Wt?C:this.is0()||A===Dt?this:D.wNAFCachedUnsafe(this,A,m.normalizeZ,E)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return D.unsafeLadder(this,n).is0()}toAffine(p){return w(this,p)}clearCofactor(){let{h:p}=t;return p===Dt?this:this.multiplyUnsafe(p)}static fromHex(p,E=!1){let{d:A,a:B}=t,P=e.BYTES;p=it("pointHex",p,P),Gt("zip215",E);let k=p.slice(),V=p[P-1];k[P-1]=V&-129;let N=xe(k),$=E?l:e.ORDER;Ct("pointHex.y",N,Wt,$);let J=u(N*N),pt=u(J-Dt),mt=u(A*J-B),{isValid:gt,value:bt}=d(pt,mt);if(!gt)throw new Error("Point.fromHex: invalid y coordinate");let Tt=(bt&Dt)===Dt,_t=(V&128)!==0;if(!E&&bt===Wt&&_t)throw new Error("Point.fromHex: x=0 and x_0=1");return _t!==Tt&&(bt=u(-bt)),m.fromAffine({x:bt,y:N})}static fromPrivateKey(p){return T(p).point}toRawBytes(){let{x:p,y:E}=this.toAffine(),A=Pe(E,e.BYTES);return A[A.length-1]|=p&Dt?128:0,A}toHex(){return se(this.toRawBytes())}}m.BASE=new m(t.Gx,t.Gy,Dt,u(t.Gx*t.Gy)),m.ZERO=new m(Wt,Dt,Dt,Wt);let{BASE:_,ZERO:C}=m,D=hn(m,a*8);function I(x){return j(x,n)}function R(x){return I(xe(x))}function T(x){let p=e.BYTES;x=it("private key",x,p);let E=it("hashed private key",i(x),2*p),A=g(E.slice(0,p)),B=E.slice(p,2*p),P=R(A),k=_.multiply(P),V=k.toRawBytes();return{head:A,prefix:B,scalar:P,point:k,pointBytes:V}}function et(x){return T(x).pointBytes}function H(x=new Uint8Array,...p){let E=ce(...p);return R(i(y(E,it("context",x),!!o)))}function z(x,p,E={}){x=it("message",x),o&&(x=o(x));let{prefix:A,scalar:B,pointBytes:P}=T(p),k=H(E.context,A,x),V=_.multiply(k).toRawBytes(),N=H(E.context,V,P,x),$=I(k+N*B);Ct("signature.s",$,Wt,n);let J=ce(V,Pe($,e.BYTES));return it("result",J,e.BYTES*2)}let ht=Qf;function v(x,p,E,A=ht){let{context:B,zip215:P}=A,k=e.BYTES;x=it("signature",x,2*k),p=it("message",p),E=it("publicKey",E,k),P!==void 0&&Gt("zip215",P),o&&(p=o(p));let V=xe(x.slice(k,2*k)),N,$,J;try{N=m.fromHex(E,P),$=m.fromHex(x.slice(0,k),P),J=_.multiplyUnsafe(V)}catch{return!1}if(!P&&N.isSmallOrder())return!1;let pt=H(B,$.toRawBytes(),N.toRawBytes(),p);return $.add(N.multiplyUnsafe(pt)).subtract(J).clearCofactor().equals(m.ZERO)}return _._setWindowSize(8),{CURVE:t,getPublicKey:et,sign:z,verify:v,ExtendedPoint:m,utils:{getExtendedPublicKey:T,randomPrivateKey:()=>s(e.BYTES),precompute(x=8,p=m.BASE){return p._setWindowSize(x),p.multiply(BigInt(3)),p}}}}var pi=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),za=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),m0=BigInt(0),th=BigInt(1),Va=BigInt(2),y0=BigInt(3),eh=BigInt(5),rh=BigInt(8);function nh(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),i=pi,a=r*r%i*r%i,c=nt(a,Va,i)*a%i,l=nt(c,th,i)*r%i,u=nt(l,eh,i)*l%i,f=nt(u,t,i)*u%i,d=nt(f,e,i)*f%i,g=nt(d,n,i)*d%i,y=nt(g,o,i)*g%i,b=nt(y,o,i)*g%i,h=nt(b,t,i)*u%i;return{pow_p_5_8:nt(h,Va,i)*r%i,b2:a}}function oh(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function ih(r,t){let e=pi,n=j(t*t*t,e),o=j(n*n*t,e),i=nh(r*o).pow_p_5_8,s=j(r*n*i,e),a=j(t*s*s,e),c=s,l=j(s*za,e),u=a===r,f=a===j(-r,e),d=a===j(-r*za,e);return u&&(s=c),(f||d)&&(s=l),Ua(s,e)&&(s=j(-s,e)),{isValid:u||f,value:s}}var sh=Ee(pi,void 0,!0),ah={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:sh,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:rh,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Ca,randomBytes:on,adjustScalarBytes:oh,uvRatio:ih},Ha=Fa(ah);var mn=32;function Ga(r,t,e){return Ha.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}var yn=class{type="Ed25519";raw;constructor(t){this.raw=mi(t,mn)}toMultihash(){return Vt.digest(Xt(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ft(this.raw,t.raw)}verify(t,e){return Ga(this.raw,e,t)}};function yi(r){return r=mi(r,mn),new yn(r)}function mi(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new lt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var uh=Math.pow(2,7),lh=Math.pow(2,14),fh=Math.pow(2,21),gi=Math.pow(2,28),bi=Math.pow(2,35),xi=Math.pow(2,42),wi=Math.pow(2,49),W=128,xt=127;function wt(r){if(r<uh)return 1;if(r<lh)return 2;if(r<fh)return 3;if(r<gi)return 4;if(r<bi)return 5;if(r<xi)return 6;if(r<wi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ei(r,t,e=0){switch(wt(r)){case 8:t[e++]=r&255|W,r/=128;case 7:t[e++]=r&255|W,r/=128;case 6:t[e++]=r&255|W,r/=128;case 5:t[e++]=r&255|W,r/=128;case 4:t[e++]=r&255|W,r>>>=7;case 3:t[e++]=r&255|W,r>>>=7;case 2:t[e++]=r&255|W,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function hh(r,t,e=0){switch(wt(r)){case 8:t.set(e++,r&255|W),r/=128;case 7:t.set(e++,r&255|W),r/=128;case 6:t.set(e++,r&255|W),r/=128;case 5:t.set(e++,r&255|W),r/=128;case 4:t.set(e++,r&255|W),r>>>=7;case 3:t.set(e++,r&255|W),r>>>=7;case 2:t.set(e++,r&255|W),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Si(r,t){let e=r[t],n=0;if(n+=e&xt,e<W||(e=r[t+1],n+=(e&xt)<<7,e<W)||(e=r[t+2],n+=(e&xt)<<14,e<W)||(e=r[t+3],n+=(e&xt)<<21,e<W)||(e=r[t+4],n+=(e&xt)*gi,e<W)||(e=r[t+5],n+=(e&xt)*bi,e<W)||(e=r[t+6],n+=(e&xt)*xi,e<W)||(e=r[t+7],n+=(e&xt)*wi,e<W))return n;throw new RangeError("Could not decode varint")}function dh(r,t){let e=r.get(t),n=0;if(n+=e&xt,e<W||(e=r.get(t+1),n+=(e&xt)<<7,e<W)||(e=r.get(t+2),n+=(e&xt)<<14,e<W)||(e=r.get(t+3),n+=(e&xt)<<21,e<W)||(e=r.get(t+4),n+=(e&xt)*gi,e<W)||(e=r.get(t+5),n+=(e&xt)*bi,e<W)||(e=r.get(t+6),n+=(e&xt)*xi,e<W)||(e=r.get(t+7),n+=(e&xt)*wi,e<W))return n;throw new RangeError("Could not decode varint")}function qt(r,t,e=0){return t==null&&(t=Lt(wt(r))),t instanceof Uint8Array?Ei(r,t,e):hh(r,t,e)}function ue(r,t=0){return r instanceof Uint8Array?Si(r,t):dh(r,t)}var vi=new Float32Array([-0]),Se=new Uint8Array(vi.buffer);function $a(r,t,e){vi[0]=r,t[e]=Se[0],t[e+1]=Se[1],t[e+2]=Se[2],t[e+3]=Se[3]}function Za(r,t){return Se[0]=r[t],Se[1]=r[t+1],Se[2]=r[t+2],Se[3]=r[t+3],vi[0]}var Ai=new Float64Array([-0]),Et=new Uint8Array(Ai.buffer);function Ya(r,t,e){Ai[0]=r,t[e]=Et[0],t[e+1]=Et[1],t[e+2]=Et[2],t[e+3]=Et[3],t[e+4]=Et[4],t[e+5]=Et[5],t[e+6]=Et[6],t[e+7]=Et[7]}function ja(r,t){return Et[0]=r[t],Et[1]=r[t+1],Et[2]=r[t+2],Et[3]=r[t+3],Et[4]=r[t+4],Et[5]=r[t+5],Et[6]=r[t+6],Et[7]=r[t+7],Ai[0]}var ph=BigInt(Number.MAX_SAFE_INTEGER),mh=BigInt(Number.MIN_SAFE_INTEGER),Ot=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 Oe;if(t<ph&&t>mh)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>Xa&&(o=0n,++n>Xa&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return Oe;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):Oe}},Oe=new Ot(0,0);Oe.toBigInt=function(){return 0n};Oe.zzEncode=Oe.zzDecode=function(){return this};Oe.length=function(){return 1};var Xa=4294967296n;function Qa(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 Ja(r,t,e){if(e-t<1)return"";let o,i=[],s=0,a;for(;t<e;)a=r[t++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(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,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function _i(r,t,e){let n=e,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,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 $t(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function bn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Ii=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,$t(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 $t(this,4);return bn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw $t(this,4);return bn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw $t(this,4);let t=Za(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw $t(this,4);let t=ja(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 $t(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Ja(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw $t(this,t);this.pos+=t}else do if(this.pos>=this.len)throw $t(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 Ot(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 $t(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 $t(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 $t(this,8);let t=bn(this.buf,this.pos+=4),e=bn(this.buf,this.pos+=4);return new Ot(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=Si(this.buf,this.pos);return this.pos+=wt(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 Ti(r){return new Ii(r instanceof Uint8Array?r:r.subarray())}function Bt(r,t,e){let n=Ti(r);return t.decode(n,void 0,e)}function Li(r){let t=r??8192,e=t>>>1,n,o=t;return function(s){if(s<1||s>e)return Lt(s);o+s>t&&(n=Lt(t),o=0);let a=n.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}var ke=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Ri(){}var Di=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},yh=Li();function gh(r){return globalThis.Buffer!=null?Lt(r):yh(r)}var Cr=class{len;head;tail;states;constructor(){this.len=0,this.head=new ke(Ri,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new ke(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Bi((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(xn,10,Ot.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Ot.fromBigInt(t);return this._push(xn,e.length(),e)}uint64Number(t){return this._push(Ei,wt(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=Ot.fromBigInt(t).zzEncode();return this._push(xn,e.length(),e)}sint64Number(t){let e=Ot.fromNumber(t).zzEncode();return this._push(xn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Ci,1,t?1:0)}fixed32(t){return this._push(Rr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Ot.fromBigInt(t);return this._push(Rr,4,e.lo)._push(Rr,4,e.hi)}fixed64Number(t){let e=Ot.fromNumber(t);return this._push(Rr,4,e.lo)._push(Rr,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($a,4,t)}double(t){return this._push(Ya,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Ci,1,0):this.uint32(e)._push(xh,e,t)}string(t){let e=Qa(t);return e!==0?this.uint32(e)._push(_i,e,t):this._push(Ci,1,0)}fork(){return this.states=new Di(this),this.head=this.tail=new ke(Ri,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 ke(Ri,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=gh(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Ci(r,t,e){t[e]=r&255}function bh(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Bi=class extends ke{next;constructor(t,e){super(bh,t,e),this.next=void 0}};function xn(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 Rr(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 xh(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Cr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(wh,t,r),this},Cr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Eh,t,r),this});function wh(r,t,e){t.set(r,e)}function Eh(r,t,e){r.length<40?_i(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(M(r),e)}function Pi(){return new Cr}function Pt(r,t){let e=Pi();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var nr;(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"})(nr||(nr={}));function wn(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Me(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(i,s){let a=t(i);s.int32(a)},n=function(i){let s=i.int32();return t(s)};return wn("enum",nr.VARINT,e,n)}function Nt(r,t){return wn("message",nr.LENGTH_DELIMITED,r,t)}var Dr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ut;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ut||(ut={}));var Ni;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Ni||(Ni={}));(function(r){r.codec=()=>Me(Ni)})(ut||(ut={}));var Jt;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ut.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.Type=ut.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Jt||(Jt={}));var Ui;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ut.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.Type=ut.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Ui||(Ui={}));var Br=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},En=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var rc={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new En("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 ve=rc;var Nr={};It(Nr,{MAX_RSA_KEY_SIZE:()=>ki,generateRSAKeyPair:()=>sc,jwkToJWKKeyPair:()=>ac,jwkToPkcs1:()=>Ih,jwkToPkix:()=>Fi,jwkToRSAPrivateKey:()=>Gi,pkcs1MessageToJwk:()=>Ki,pkcs1MessageToRSAPrivateKey:()=>zi,pkcs1ToJwk:()=>_h,pkcs1ToRSAPrivateKey:()=>ic,pkixMessageToJwk:()=>qi,pkixMessageToRSAPublicKey:()=>Hi,pkixToJwk:()=>Th,pkixToRSAPublicKey:()=>Vi});var Sh=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ae=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),_e=new Uint32Array(64),Oi=class extends er{constructor(){super(64,32,8,!1),this.A=Ae[0]|0,this.B=Ae[1]|0,this.C=Ae[2]|0,this.D=Ae[3]|0,this.E=Ae[4]|0,this.F=Ae[5]|0,this.G=Ae[6]|0,this.H=Ae[7]|0}get(){let{A:t,B:e,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[t,e,n,o,i,s,a,c]}set(t,e,n,o,i,s,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)_e[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=_e[f-15],g=_e[f-2],y=Ht(d,7)^Ht(d,18)^d>>>3,b=Ht(g,17)^Ht(g,19)^g>>>10;_e[f]=b+_e[f-7]+y+_e[f-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=Ht(a,6)^Ht(a,11)^Ht(a,25),g=u+d+Ta(a,c,l)+Sh[f]+_e[f]|0,b=(Ht(n,2)^Ht(n,13)^Ht(n,22))+La(n,o,i)|0;u=l,l=c,c=a,a=s+g|0,s=i,i=o,o=n,n=g+b|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+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,i,s,a,c,l,u)}roundClean(){_e.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var or=nn(()=>new Oi);var ir=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=Nr.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return at.createV1(114,this._multihash)}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ft(this.raw,t.raw)}verify(t,e){return oc(this.jwk,e,t)}},Pr=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=Nr.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ft(this.raw,t.raw)}sign(t){return nc(this.jwk,t)}};var ki=8192,Mi=18,vh=1062,Ah=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function _h(r){let t=oe(r);return Ki(t)}function Ki(r){return{n:O(r[1],"base64url"),e:O(r[2],"base64url"),d:O(r[3],"base64url"),p:O(r[4],"base64url"),q:O(r[5],"base64url"),dp:O(r[6],"base64url"),dq:O(r[7],"base64url"),qi:O(r[8],"base64url"),kty:"RSA"}}function Ih(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 lt("JWK was missing components");return me([Rt(Uint8Array.from([0])),Rt(M(r.n,"base64url")),Rt(M(r.e,"base64url")),Rt(M(r.d,"base64url")),Rt(M(r.p,"base64url")),Rt(M(r.q,"base64url")),Rt(M(r.dp,"base64url")),Rt(M(r.dq,"base64url")),Rt(M(r.qi,"base64url"))]).subarray()}function Th(r){let t=oe(r,{offset:0});return qi(t)}function qi(r){let t=oe(r[1],{offset:0});return{kty:"RSA",n:O(t[0],"base64url"),e:O(t[1],"base64url")}}function Fi(r){if(r.n==null||r.e==null)throw new lt("JWK was missing components");return me([Ah,en(me([Rt(M(r.n,"base64url")),Rt(M(r.e,"base64url"))]))]).subarray()}function ic(r){let t=oe(r);return zi(t)}function zi(r){let t=Ki(r);return Gi(t)}function Vi(r,t){if(r.byteLength>=vh)throw new He("Key size is too large");let e=oe(r,{offset:0});return Hi(e,r,t)}function Hi(r,t,e){let n=qi(r);if(e==null){let o=or(Jt.encode({Type:ut.RSA,Data:t}));e=zt(Mi,o)}return new ir(n,e)}function Gi(r){if(uc(r)>ki)throw new lt("Key size is too large");let t=ac(r),e=or(Jt.encode({Type:ut.RSA,Data:Fi(t.publicKey)})),n=zt(Mi,e);return new Pr(t.privateKey,new ir(t.publicKey,n))}async function sc(r){if(r>ki)throw new lt("Key size is too large");let t=await cc(r),e=or(Jt.encode({Type:ut.RSA,Data:Fi(t.publicKey)})),n=zt(Mi,e);return new Pr(t.privateKey,new ir(t.publicKey,n))}function ac(r){if(r==null)throw new lt("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function cc(r){let t=await ve.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await Lh(t);return{privateKey:e[0],publicKey:e[1]}}async function nc(r,t){let e=await ve.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await ve.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function oc(r,t,e){let n=await ve.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return ve.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function Lh(r){if(r.privateKey==null||r.publicKey==null)throw new lt("Private and public key are required");return Promise.all([ve.get().subtle.exportKey("jwk",r.privateKey),ve.get().subtle.exportKey("jwk",r.publicKey)])}function uc(r){if(r.kty!=="RSA")throw new lt("invalid key type");if(r.n==null)throw new lt("invalid key modulus");return M(r.n,"base64url").length*8}var Sn=class extends tr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Aa(t);let n=_r(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,i=new Uint8Array(o);i.set(n.length>o?t.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=t.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),i.fill(0)}update(t){return Je(this),this.iHash.update(t),this}digestInto(t){Je(this),Qe(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:i,blockLen:s,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Wi=(r,t,e)=>new Sn(r,t).update(e).digest();Wi.create=(r,t)=>new Sn(r,t);function lc(r){r.lowS!==void 0&&Gt("lowS",r.lowS),r.prehash!==void 0&&Gt("prehash",r.prehash)}function Rh(r){let t=Lr(r);Qt(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:Ch,hexToBytes:Dh}=un,$i=class extends Error{constructor(t=""){super(t)}},le={Err:$i,_tlv:{encode:(r,t)=>{let{Err:e}=le;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=De(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let i=n>127?De(o.length/2|128):"";return De(r)+i+o+t},decode(r,t){let{Err:e}=le,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++],i=!!(o&128),s=0;if(!i)s=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)s=s<<8|u;if(n+=c,s<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+s);if(a.length!==s)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(r){let{Err:t}=le;if(r<fe)throw new t("integer: negative integers are not allowed");let e=De(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}=le;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 Ch(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=le,o=typeof r=="string"?Dh(r):r;rr(o);let{v:i,l:s}=n.decode(48,o);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{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}=le,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),i=n+o;return t.encode(48,i)}},fe=BigInt(0),yt=BigInt(1),Gy=BigInt(2),fc=BigInt(3),Wy=BigInt(4);function Bh(r){let t=Rh(r),{Fp:e}=t,n=Ee(t.n,t.nBitLength),o=t.toBytes||((b,h,w)=>{let S=h.toAffine();return ce(Uint8Array.from([4]),e.toBytes(S.x),e.toBytes(S.y))}),i=t.fromBytes||(b=>{let h=b.subarray(1),w=e.fromBytes(h.subarray(0,e.BYTES)),S=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:w,y:S}});function s(b){let{a:h,b:w}=t,S=e.sqr(b),m=e.mul(S,b);return e.add(e.add(m,e.mul(b,h)),w)}if(!e.eql(e.sqr(t.Gy),s(t.Gx)))throw new Error("bad generator point: equation left != right");function a(b){return Ir(b,yt,t.n)}function c(b){let{allowedPrivateKeyLengths:h,nByteLength:w,wrapPrivateKey:S,n:m}=t;if(h&&typeof b!="bigint"){if(be(b)&&(b=se(b)),typeof b!="string"||!h.includes(b.length))throw new Error("invalid private key");b=b.padStart(w*2,"0")}let _;try{_=typeof b=="bigint"?b:ae(it("private key",b,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof b)}return S&&(_=j(_,m)),Ct("private key",_,yt,m),_}function l(b){if(!(b instanceof d))throw new Error("ProjectivePoint expected")}let u=Ne((b,h)=>{let{px:w,py:S,pz:m}=b;if(e.eql(m,e.ONE))return{x:w,y:S};let _=b.is0();h==null&&(h=_?e.ONE:e.inv(m));let C=e.mul(w,h),D=e.mul(S,h),I=e.mul(m,h);if(_)return{x:e.ZERO,y:e.ZERO};if(!e.eql(I,e.ONE))throw new Error("invZ was invalid");return{x:C,y:D}}),f=Ne(b=>{if(b.is0()){if(t.allowInfinityPoint&&!e.is0(b.py))return;throw new Error("bad point: ZERO")}let{x:h,y:w}=b.toAffine();if(!e.isValid(h)||!e.isValid(w))throw new Error("bad point: x or y not FE");let S=e.sqr(w),m=s(h);if(!e.eql(S,m))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,w,S){if(this.px=h,this.py=w,this.pz=S,h==null||!e.isValid(h))throw new Error("x required");if(w==null||!e.isValid(w))throw new Error("y required");if(S==null||!e.isValid(S))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:w,y:S}=h||{};if(!h||!e.isValid(w)||!e.isValid(S))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let m=_=>e.eql(_,e.ZERO);return m(w)&&m(S)?d.ZERO:new d(w,S,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let w=e.invertBatch(h.map(S=>S.pz));return h.map((S,m)=>S.toAffine(w[m])).map(d.fromAffine)}static fromHex(h){let w=d.fromAffine(i(it("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,w){return dn(d,n,h,w)}_setWindowSize(h){y.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:w,py:S,pz:m}=this,{px:_,py:C,pz:D}=h,I=e.eql(e.mul(w,D),e.mul(_,m)),R=e.eql(e.mul(S,D),e.mul(C,m));return I&&R}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:w}=t,S=e.mul(w,fc),{px:m,py:_,pz:C}=this,D=e.ZERO,I=e.ZERO,R=e.ZERO,T=e.mul(m,m),et=e.mul(_,_),H=e.mul(C,C),z=e.mul(m,_);return z=e.add(z,z),R=e.mul(m,C),R=e.add(R,R),D=e.mul(h,R),I=e.mul(S,H),I=e.add(D,I),D=e.sub(et,I),I=e.add(et,I),I=e.mul(D,I),D=e.mul(z,D),R=e.mul(S,R),H=e.mul(h,H),z=e.sub(T,H),z=e.mul(h,z),z=e.add(z,R),R=e.add(T,T),T=e.add(R,T),T=e.add(T,H),T=e.mul(T,z),I=e.add(I,T),H=e.mul(_,C),H=e.add(H,H),T=e.mul(H,z),D=e.sub(D,T),R=e.mul(H,et),R=e.add(R,R),R=e.add(R,R),new d(D,I,R)}add(h){l(h);let{px:w,py:S,pz:m}=this,{px:_,py:C,pz:D}=h,I=e.ZERO,R=e.ZERO,T=e.ZERO,et=t.a,H=e.mul(t.b,fc),z=e.mul(w,_),ht=e.mul(S,C),v=e.mul(m,D),L=e.add(w,S),x=e.add(_,C);L=e.mul(L,x),x=e.add(z,ht),L=e.sub(L,x),x=e.add(w,m);let p=e.add(_,D);return x=e.mul(x,p),p=e.add(z,v),x=e.sub(x,p),p=e.add(S,m),I=e.add(C,D),p=e.mul(p,I),I=e.add(ht,v),p=e.sub(p,I),T=e.mul(et,x),I=e.mul(H,v),T=e.add(I,T),I=e.sub(ht,T),T=e.add(ht,T),R=e.mul(I,T),ht=e.add(z,z),ht=e.add(ht,z),v=e.mul(et,v),x=e.mul(H,x),ht=e.add(ht,v),v=e.sub(z,v),v=e.mul(et,v),x=e.add(x,v),z=e.mul(ht,x),R=e.add(R,z),z=e.mul(p,x),I=e.mul(L,I),I=e.sub(I,z),z=e.mul(L,ht),T=e.mul(p,T),T=e.add(T,z),new d(I,R,T)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return y.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){let{endo:w,n:S}=t;Ct("scalar",h,fe,S);let m=d.ZERO;if(h===fe)return m;if(this.is0()||h===yt)return this;if(!w||y.hasPrecomputes(this))return y.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:_,k1:C,k2neg:D,k2:I}=w.splitScalar(h),R=m,T=m,et=this;for(;C>fe||I>fe;)C&yt&&(R=R.add(et)),I&yt&&(T=T.add(et)),et=et.double(),C>>=yt,I>>=yt;return _&&(R=R.negate()),D&&(T=T.negate()),T=new d(e.mul(T.px,w.beta),T.py,T.pz),R.add(T)}multiply(h){let{endo:w,n:S}=t;Ct("scalar",h,yt,S);let m,_;if(w){let{k1neg:C,k1:D,k2neg:I,k2:R}=w.splitScalar(h),{p:T,f:et}=this.wNAF(D),{p:H,f:z}=this.wNAF(R);T=y.constTimeNegate(C,T),H=y.constTimeNegate(I,H),H=new d(e.mul(H.px,w.beta),H.py,H.pz),m=T.add(H),_=et.add(z)}else{let{p:C,f:D}=this.wNAF(h);m=C,_=D}return d.normalizeZ([m,_])[0]}multiplyAndAddUnsafe(h,w,S){let m=d.BASE,_=(D,I)=>I===fe||I===yt||!D.equals(m)?D.multiplyUnsafe(I):D.multiply(I),C=_(this,w).add(_(h,S));return C.is0()?void 0:C}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:w}=t;if(h===yt)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:w}=t;return h===yt?this:w?w(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return Gt("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return Gt("isCompressed",h),se(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let g=t.nBitLength,y=hn(d,t.endo?Math.ceil(g/2):g);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:a}}function Ph(r){let t=Lr(r);return Qt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function hc(r){let t=Ph(r),{Fp:e,n}=t,o=e.BYTES+1,i=2*e.BYTES+1;function s(v){return j(v,n)}function a(v){return ln(v,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=Bh({...t,toBytes(v,L,x){let p=L.toAffine(),E=e.toBytes(p.x),A=ce;return Gt("isCompressed",x),x?A(Uint8Array.from([L.hasEvenY()?2:3]),E):A(Uint8Array.from([4]),E,e.toBytes(p.y))},fromBytes(v){let L=v.length,x=v[0],p=v.subarray(1);if(L===o&&(x===2||x===3)){let E=ae(p);if(!Ir(E,yt,e.ORDER))throw new Error("Point is not on curve");let A=u(E),B;try{B=e.sqrt(A)}catch(V){let N=V instanceof Error?": "+V.message:"";throw new Error("Point is not on curve"+N)}let P=(B&yt)===yt;return(x&1)===1!==P&&(B=e.neg(B)),{x:E,y:B}}else if(L===i&&x===4){let E=e.fromBytes(p.subarray(0,e.BYTES)),A=e.fromBytes(p.subarray(e.BYTES,2*e.BYTES));return{x:E,y:A}}else{let E=o,A=i;throw new Error("invalid Point, expected length of "+E+", or uncompressed "+A+", got "+L)}}}),d=v=>se(we(v,t.nByteLength));function g(v){let L=n>>yt;return v>L}function y(v){return g(v)?s(-v):v}let b=(v,L,x)=>ae(v.slice(L,x));class h{constructor(L,x,p){this.r=L,this.s=x,this.recovery=p,this.assertValidity()}static fromCompact(L){let x=t.nByteLength;return L=it("compactSignature",L,x*2),new h(b(L,0,x),b(L,x,2*x))}static fromDER(L){let{r:x,s:p}=le.toSig(it("DER",L));return new h(x,p)}assertValidity(){Ct("r",this.r,yt,n),Ct("s",this.s,yt,n)}addRecoveryBit(L){return new h(this.r,this.s,L)}recoverPublicKey(L){let{r:x,s:p,recovery:E}=this,A=D(it("msgHash",L));if(E==null||![0,1,2,3].includes(E))throw new Error("recovery id invalid");let B=E===2||E===3?x+t.n:x;if(B>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let P=(E&1)===0?"02":"03",k=c.fromHex(P+d(B)),V=a(B),N=s(-A*V),$=s(p*V),J=c.BASE.multiplyAndAddUnsafe(k,N,$);if(!J)throw new Error("point at infinify");return J.assertValidity(),J}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,s(-this.s),this.recovery):this}toDERRawBytes(){return Be(this.toDERHex())}toDERHex(){return le.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Be(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let w={isValidPrivateKey(v){try{return l(v),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let v=ui(t.n);return ka(t.randomBytes(v),t.n)},precompute(v=8,L=c.BASE){return L._setWindowSize(v),L.multiply(BigInt(3)),L}};function S(v,L=!0){return c.fromPrivateKey(v).toRawBytes(L)}function m(v){let L=be(v),x=typeof v=="string",p=(L||x)&&v.length;return L?p===o||p===i:x?p===2*o||p===2*i:v instanceof c}function _(v,L,x=!0){if(m(v))throw new Error("first arg must be private key");if(!m(L))throw new Error("second arg must be public key");return c.fromHex(L).multiply(l(v)).toRawBytes(x)}let C=t.bits2int||function(v){if(v.length>8192)throw new Error("input is too large");let L=ae(v),x=v.length*8-t.nBitLength;return x>0?L>>BigInt(x):L},D=t.bits2int_modN||function(v){return s(C(v))},I=Tr(t.nBitLength);function R(v){return Ct("num < 2^"+t.nBitLength,v,fe,I),we(v,t.nByteLength)}function T(v,L,x=et){if(["recovered","canonical"].some(mt=>mt in x))throw new Error("sign() legacy options not supported");let{hash:p,randomBytes:E}=t,{lowS:A,prehash:B,extraEntropy:P}=x;A==null&&(A=!0),v=it("msgHash",v),lc(x),B&&(v=it("prehashed msgHash",p(v)));let k=D(v),V=l(L),N=[R(V),R(k)];if(P!=null&&P!==!1){let mt=P===!0?E(e.BYTES):P;N.push(it("extraEntropy",mt))}let $=ce(...N),J=k;function pt(mt){let gt=C(mt);if(!f(gt))return;let bt=a(gt),Tt=c.BASE.multiply(gt).toAffine(),_t=s(Tt.x);if(_t===fe)return;let Yt=s(bt*s(J+_t*V));if(Yt===fe)return;let te=(Tt.x===_t?0:2)|Number(Tt.y&yt),yr=Yt;return A&&g(Yt)&&(yr=y(Yt),te^=1),new h(_t,yr,te)}return{seed:$,k2sig:pt}}let et={lowS:t.lowS,prehash:!1},H={lowS:t.lowS,prehash:!1};function z(v,L,x=et){let{seed:p,k2sig:E}=T(v,L,x),A=t;return ii(A.hash.outputLen,A.nByteLength,A.hmac)(p,E)}c.BASE._setWindowSize(8);function ht(v,L,x,p=H){let E=v;L=it("msgHash",L),x=it("publicKey",x);let{lowS:A,prehash:B,format:P}=p;if(lc(p),"strict"in p)throw new Error("options.strict was renamed to lowS");if(P!==void 0&&P!=="compact"&&P!=="der")throw new Error("format must be compact or der");let k=typeof E=="string"||be(E),V=!k&&!P&&typeof E=="object"&&E!==null&&typeof E.r=="bigint"&&typeof E.s=="bigint";if(!k&&!V)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let N,$;try{if(V&&(N=new h(E.r,E.s)),k){try{P!=="compact"&&(N=h.fromDER(E))}catch(te){if(!(te instanceof le.Err))throw te}!N&&P!=="der"&&(N=h.fromCompact(E))}$=c.fromHex(x)}catch{return!1}if(!N||A&&N.hasHighS())return!1;B&&(L=t.hash(L));let{r:J,s:pt}=N,mt=D(L),gt=a(pt),bt=s(mt*gt),Tt=s(J*gt),_t=c.BASE.multiplyAndAddUnsafe($,bt,Tt)?.toAffine();return _t?s(_t.x)===J:!1}return{CURVE:t,getPublicKey:S,getSharedSecret:_,sign:z,verify:ht,ProjectivePoint:c,Signature:h,utils:w}}function Nh(r){return{hash:r,hmac:(t,...e)=>Wi(r,t,Qo(...e)),randomBytes:on}}function dc(r,t){let e=n=>hc({...r,...Nh(n)});return{...e(t),create:e}}var yc=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),pc=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Uh=BigInt(1),Zi=BigInt(2),mc=(r,t)=>(r+t/Zi)/t;function Oh(r){let t=yc,e=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=nt(u,e,t)*u%t,d=nt(f,e,t)*u%t,g=nt(d,Zi,t)*l%t,y=nt(g,o,t)*g%t,b=nt(y,i,t)*y%t,h=nt(b,a,t)*b%t,w=nt(h,c,t)*h%t,S=nt(w,a,t)*b%t,m=nt(S,e,t)*u%t,_=nt(m,s,t)*y%t,C=nt(_,n,t)*l%t,D=nt(C,Zi,t);if(!Yi.eql(Yi.sqr(D),r))throw new Error("Cannot find square root");return D}var Yi=Ee(yc,void 0,void 0,{sqrt:Oh}),Ke=dc({a:BigInt(0),b:BigInt(7),Fp:Yi,n:pc,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=pc,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Uh*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=e,s=BigInt("0x100000000000000000000000000000000"),a=mc(i*r,t),c=mc(-n*r,t),l=j(r-a*e-c*o,t),u=j(-a*n-c*i,t),f=l>s,d=u>s;if(f&&(l=t-l),d&&(u=t-u),l>s||u>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},or),eg=BigInt(0);var rg=Ke.ProjectivePoint;function gc(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function bc(r,t,e){let n=je.digest(e instanceof Uint8Array?e:e.subarray());if(gc(n))return n.then(({digest:o})=>Ke.verify(t,o,r)).catch(o=>{throw new Br(String(o))});try{return Ke.verify(t,n.digest,r)}catch(o){throw new Br(String(o))}}var vn=class{type="secp256k1";raw;_key;constructor(t){this._key=wc(t),this.raw=xc(this._key)}toMultihash(){return Vt.digest(Xt(this))}toCID(){return at.createV1(114,this.toMultihash())}toString(){return Z.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:ft(this.raw,t.raw)}verify(t,e){return bc(this._key,e,t)}};function ji(r){return new vn(r)}function xc(r){return Ke.ProjectivePoint.fromHex(r).toRawBytes(!0)}function wc(r){try{return Ke.ProjectivePoint.fromHex(r),r}catch(t){throw new He(String(t))}}function Ec(r,t){let{Type:e,Data:n}=Jt.decode(r),o=n??new Uint8Array;switch(e){case ut.RSA:return Vi(o,t);case ut.Ed25519:return yi(o);case ut.secp256k1:return ji(o);case ut.ECDSA:return Xo(o);default:throw new Ge}}function Sc(r){let{Type:t,Data:e}=Jt.decode(r.digest),n=e??new Uint8Array;switch(t){case ut.Ed25519:return yi(n);case ut.secp256k1:return ji(n);case ut.ECDSA:return Xo(n);default:throw new Ge}}function Xt(r){return Jt.encode({Type:ut[r.type],Data:r.raw})}var vc=Symbol.for("nodejs.util.inspect.custom"),kh=114,Ur=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[So]=!0;toString(){return this.string==null&&(this.string=Z.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return at.createV1(kh,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return ft(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return ft(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[vc](){return`PeerId(${this.toString()})`}},An=class extends Ur{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},_n=class extends Ur{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},In=class extends Ur{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Mh=2336,Or=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Vt.digest(M(this.url))}[vc](){return`PeerId(${this.url})`}[So]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return at.createV1(Mh,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=O(t)),t.toString()===this.toString())}};var Kh=114,Ac=2336;function Xi(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Kt(Z.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return qh(at.parse(r));if(t==null)throw new lt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Kt(t.decode(r))}return sr(e)}function sr(r){if(zh(r))return new An({multihash:r});if(Fh(r))try{let t=Sc(r);if(t.type==="Ed25519")return new _n({multihash:r,publicKey:t});if(t.type==="secp256k1")return new In({multihash:r,publicKey:t})}catch{let e=O(r.digest);return new Or(new URL(e))}throw new jr("Supplied PeerID Multihash is invalid")}function qh(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Kh&&r.code!==Ac)throw new Yr("Supplied PeerID CID is invalid");if(r.code===Ac){let t=O(r.multihash.digest);return new Or(new URL(t))}return sr(r.multihash)}function Fh(r){return r.code===Vt.code}function zh(r){return r.code===je.code}var kr;(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 i={publicKey:ot(0),payloadType:ot(0),payload:ot(0),signature:ot(0)},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.publicKey=e.bytes();break}case 2:{i.payloadType=e.bytes();break}case 3:{i.payload=e.bytes();break}case 5:{i.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(kr||(kr={}));var Tn=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var Mr=class r{static createFromProtobuf=async t=>{let e=kr.decode(t),n=Ec(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e)=>{if(e==null)throw new Error("Missing private key");let n=t.domain,o=t.codec,i=t.marshal(),s=_c(n,o,i),a=await e.sign(s.subarray());return new r({publicKey:e.publicKey,payloadType:o,payload:i,signature:a})};static openAndCertify=async(t,e)=>{let n=await r.createFromProtobuf(t);if(!await n.validate(e))throw new Tn("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(t){let{publicKey:e,payloadType:n,payload:o,signature:i}=t;this.publicKey=e,this.payloadType=n,this.payload=o,this.signature=i}marshal(){return this.marshaled==null&&(this.marshaled=kr.encode({publicKey:Xt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return ft(this.marshal(),t.marshal())}async validate(t){let e=_c(t,this.payloadType,this.payload);return this.publicKey.verify(e.subarray(),this.signature)}},_c=(r,t,e)=>{let n=M(r),o=qt(n.byteLength),i=qt(t.length),s=qt(e.length);return new ct(o,n,i,t,s,e)};var Ln=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 i=0,s=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(i*=t,i+=u,i>l||(s+=1,e!==void 0&&s>e))return}if(s!==0)return!n&&c&&s>1?void 0:i})}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 s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return e[o]=s[0],e[o+1]=s[1],e[o+2]=s[2],e[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];e[o]=i>>8,e[o+1]=i&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 i=new Uint8Array(14),s=16-(n+2),[a]=t(i.subarray(0,s));return e.set(i.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Ic=45,Vh=15,ar=new Ln;function Qi(r){if(!(r.length>Vh))return ar.new(r).parseWith(()=>ar.readIPv4Addr())}function Ji(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ic))return ar.new(r).parseWith(()=>ar.readIPv6Addr())}function Rn(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Ic)return;let e=ar.new(r).parseWith(()=>ar.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}var Tb=parseInt("0xFFFF",16),Lb=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Cn(r){return!!Qi(r)}function Dn(r){return!!Ji(r)}function Bn(r){return!!Rn(r)}var Rc=Cn,Zh=Dn,ts=function(r){let t=0;if(r=r.toString().trim(),Rc(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Zh(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=Rc(e[n]),s;i&&(s=ts(e[n]),e[n]=O(s.slice(0,2),"base16")),s!=null&&++n<8&&e.splice(n,0,O(s.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 i=[n,1];for(n=9-e.length;n>0;n--)i.push("0");e.splice.apply(e,i)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let i=parseInt(e[n],16);o[t++]=i>>8&255,o[t++]=i&255}return o}throw new Error("invalid ip address")},Cc=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 i=0;i<e;i++)o.push(r[t+i]);return o.join(".")}if(e===16){let o=[];for(let i=0;i<e;i+=2)o.push(n.getUint16(t+i).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var cr={},es={},jh=[[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"]];jh.forEach(r=>{let t=Xh(...r);es[t.code]=t,cr[t.name]=t});function Xh(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function Q(r){if(typeof r=="number"){if(es[r]!=null)return es[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(cr[r]!=null)return cr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var fx=Q("ip4"),hx=Q("ip6"),dx=Q("ipcidr");function is(r,t){switch(Q(r).code){case 4:case 41:return Jh(t);case 42:return os(t);case 43:return O(t,"base10");case 6:case 273:case 33:case 132:return Pc(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return os(t);case 421:return nd(t);case 444:return Bc(t);case 445:return Bc(t);case 466:return rd(t);case 481:return globalThis.encodeURIComponent(os(t));default:return O(t,"base16")}}function ss(r,t){switch(Q(r).code){case 4:return Dc(t);case 41:return Dc(t);case 42:return ns(t);case 43:return M(t,"base10");case 6:case 273:case 33:case 132:return as(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ns(t);case 421:return td(t);case 444:return od(t);case 445:return id(t);case 466:return ed(t);case 481:return ns(globalThis.decodeURIComponent(t));default:return M(t,"base16")}}var rs=Object.values(Sr).map(r=>r.decoder),Qh=function(){let r=rs[0].or(rs[1]);return rs.slice(2).forEach(t=>r=r.or(t)),r}();function Dc(r){if(!Bn(r))throw new Error("invalid ip address");return ts(r)}function Jh(r){let t=Cc(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!Bn(t))throw new Error("invalid ip address");return t}function as(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Pc(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function ns(r){let t=M(r),e=Uint8Array.from(qt(t.length));return Ut([e,t],e.length+t.length)}function os(r){let t=ue(r);if(r=r.slice(wt(t)),r.length!==t)throw new Error("inconsistent lengths");return O(r)}function td(r){let t;r[0]==="Q"||r[0]==="1"?t=Kt(Z.decode(`z${r}`)).bytes:t=at.parse(r).multihash.bytes;let e=Uint8Array.from(qt(t.length));return Ut([e,t],e.length+t.length)}function ed(r){let t=Qh.decode(r),e=Uint8Array.from(qt(t.length));return Ut([e,t],e.length+t.length)}function rd(r){let t=ue(r),e=r.slice(wt(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+O(e,"base64url")}function nd(r){let t=ue(r),e=r.slice(wt(t));if(e.length!==t)throw new Error("inconsistent lengths");return O(e,"base58btc")}function od(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=ne.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=as(n);return Ut([e,o],e.length+o.length)}function id(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=ne.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=as(n);return Ut([e,o],e.length+o.length)}function Bc(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=O(t,"base32"),o=Pc(e);return`${n}:${o}`}function Nc(r){r=cs(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 i=0;i<o.length;i++){let s=o[i],a=Q(s);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(i++,i>=o.length)throw new Pn("invalid address: "+r);if(a.path===!0){n=cs(o.slice(i).join("/")),t.push([a.code,ss(a.code,n)]),e.push([a.code,n]);break}let c=ss(a.code,o[i]);t.push([a.code,c]),e.push([a.code,is(a.code,c)])}return{string:Uc(e),bytes:Nn(t),tuples:t,stringTuples:e,path:n}}function us(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let i=ue(r,o),s=wt(i),a=Q(i),c=sd(a,r.slice(o+s));if(c===0){t.push([i]),e.push([i]),o+=s;continue}let l=r.slice(o+s,o+s+c);if(o+=c+s,o>r.length)throw new Pn("Invalid address Uint8Array: "+O(r,"base16"));t.push([i,l]);let u=is(i,l);if(e.push([i,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:Uc(e),tuples:t,stringTuples:e,path:n}}function Uc(r){let t=[];return r.map(e=>{let n=Q(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),cs(t.join("/"))}function Nn(r){return Ut(r.map(t=>{let e=Q(t[0]),n=Uint8Array.from(qt(e.code));return t.length>1&&t[1]!=null&&(n=Ut([n,t[1]])),n}))}function sd(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=ue(t instanceof Uint8Array?t:Uint8Array.from(t));return e+wt(e)}}function cs(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var Pn=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var ad=Symbol.for("nodejs.util.inspect.custom"),fs=Symbol.for("@multiformats/js-multiaddr/multiaddr"),cd=[Q("dns").code,Q("dns4").code,Q("dns6").code,Q("dnsaddr").code],ls=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},Un=class r{bytes;#t;#e;#r;#n;[fs]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=us(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Nc(t)}else if(kc(t))e=us(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.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,i="",s=Q("tcp"),a=Q("udp"),c=Q("ip4"),l=Q("ip6"),u=Q("dns6"),f=Q("ip6zone");for(let[g,y]of this.stringTuples())g===f.code&&(i=`%${y??""}`),cd.includes(g)&&(e=s.name==="tcp"?"tcp":"udp",o=443,n=`${y??""}${i}`,t=g===u.code?6:4),(g===s.code||g===a.code)&&(e=Q(g).name==="tcp"?"tcp":"udp",o=parseInt(y??"")),(g===c.code||g===l.code)&&(e=Q(g).name==="tcp"?"tcp":"udp",n=`${y??""}${i}`,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({},Q(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>Q(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(Nn(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===cr.p2p.code&&t.push([n,o]),n===cr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?O(Z.decode(`z${n}`),"base58btc"):O(at.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return ft(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(i=>i.resolvable);if(e==null)return[this];let n=Oc.get(e.name);if(n==null)throw new ls(`no available resolver for ${e.name}`);return(await n(this,t)).map(i=>St(i))}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)}[ad](){return`Multiaddr(${this.#t})`}};var Oc=new Map;function kc(r){return!!r?.[fs]}function St(r){return new Un(r)}function vt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var On=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 he(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new On(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new On(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((i,s)=>{n=()=>{s(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var hs=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=vt(),this.haveNext=vt()}[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=vt(),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=vt(),await he(this.readNext.promise,e?.signal,e)}};function Mc(){return new hs}var kn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Kc(r,t){let e=Mc();r.sink(e).catch(async s=>{await e.end(s)}),r.sink=async s=>{for await(let a of s)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 ct;return{read:async s=>{if(s?.signal?.throwIfAborted(),s?.bytes==null){let{done:c,value:l}=await he(n.next(),s?.signal);return c===!0?null:l}for(;o.byteLength<s.bytes;){let{value:c,done:l}=await he(n.next(),s?.signal);if(l===!0)throw new kn("unexpected end of input");o.append(c)}let a=o.sublist(0,s.bytes);return o.consume(s.bytes),a},write:async(s,a)=>{a?.signal?.throwIfAborted(),s instanceof Uint8Array?await e.push(s,a):await e.push(s.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let s=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*s}()}return r}}}var Mn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Kn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},qn=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function qc(r,t={}){let e=Kc(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=wt(t.maxDataLength));let n=t?.lengthDecoder??ue,o=t?.lengthEncoder??qt;return{read:async s=>{let a=-1,c=new ct;for(;;){c.append(await e.read({...s,bytes:1}));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Mn("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new qn("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Kn("message length too long");return e.read({...s,bytes:a})},write:async(s,a)=>{await e.write(new ct(o(s.byteLength),s),a)},writeV:async(s,a)=>{let c=new ct(...s.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Ie(r,t){let e=qc(r,t),n={read:async(o,i)=>{let s=await e.read(i);return o.decode(s)},write:async(o,i,s)=>{await e.write(i.encode(o),s)},writeV:async(o,i,s)=>{await e.writeV(o.map(a=>i.encode(a)),s)},pb:o=>({read:async i=>n.read(o,i),write:async(i,s)=>n.write(i,o,s),writeV:async(i,s)=>n.writeV(i,o,s),unwrap:()=>n}),unwrap:()=>e.unwrap()};return n}var ds=1e3,Fc=60*ds,Fn=290,zc=15,Vc=2*60*Fc,Hc=1,zn=2e3,Gc=100,ps="circuit-relay-source",Kr=`${vo}-circuit-relay`,ms=`${vo}-circuit-relay-source`,Wc=2*Fc,$c=BigInt(1<<17),Ft="/libp2p/circuit/relay/0.2.0/hop",qe="/libp2p/circuit/relay/0.2.0/stop",Zc=30*ds,sw=30*ds,qr=300,Yc=4096,jc=.001;var Y;(function(r){let t;(function(o){o.RESERVE="RESERVE",o.CONNECT="CONNECT",o.STATUS="STATUS"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.RESERVE=0]="RESERVE",o[o.CONNECT=1]="CONNECT",o[o.STATUS=2]="STATUS"})(e||(e={})),function(o){o.codec=()=>Me(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Nt((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.type!=null&&(i.uint32(8),r.Type.codec().encode(o.type,i)),o.peer!=null&&(i.uint32(18),ur.codec().encode(o.peer,i)),o.reservation!=null&&(i.uint32(26),Vn.codec().encode(o.reservation,i)),o.limit!=null&&(i.uint32(34),lr.codec().encode(o.limit,i)),o.status!=null&&(i.uint32(40),q.codec().encode(o.status,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=ur.codec().decode(o,o.uint32(),{limits:s.limits?.peer});break}case 3:{a.reservation=Vn.codec().decode(o,o.uint32(),{limits:s.limits?.reservation});break}case 4:{a.limit=lr.codec().decode(o,o.uint32(),{limits:s.limits?.limit});break}case 5:{a.status=q.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Pt(o,r.codec()),r.decode=(o,i)=>Bt(o,r.codec(),i)})(Y||(Y={}));var kt;(function(r){let t;(function(o){o.CONNECT="CONNECT",o.STATUS="STATUS"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.CONNECT=0]="CONNECT",o[o.STATUS=1]="STATUS"})(e||(e={})),function(o){o.codec=()=>Me(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Nt((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.type!=null&&(i.uint32(8),r.Type.codec().encode(o.type,i)),o.peer!=null&&(i.uint32(18),ur.codec().encode(o.peer,i)),o.limit!=null&&(i.uint32(26),lr.codec().encode(o.limit,i)),o.status!=null&&(i.uint32(32),q.codec().encode(o.status,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=ur.codec().decode(o,o.uint32(),{limits:s.limits?.peer});break}case 3:{a.limit=lr.codec().decode(o,o.uint32(),{limits:s.limits?.limit});break}case 4:{a.status=q.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Pt(o,r.codec()),r.decode=(o,i)=>Bt(o,r.codec(),i)})(kt||(kt={}));var ur;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.id!=null&&e.id.byteLength>0&&(n.uint32(10),n.bytes(e.id)),e.addrs!=null)for(let i of e.addrs)n.uint32(18),n.bytes(i);o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={id:ot(0),addrs:[]},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.id=e.bytes();break}case 2:{if(o.limits?.addrs!=null&&i.addrs.length===o.limits.addrs)throw new Dr('Decode error - map field "addrs" had too many elements');i.addrs.push(e.bytes());break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(ur||(ur={}));var Vn;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.expire!=null&&e.expire!==0n&&(n.uint32(8),n.uint64(e.expire)),e.addrs!=null)for(let i of e.addrs)n.uint32(18),n.bytes(i);e.voucher!=null&&(n.uint32(26),Hn.codec().encode(e.voucher,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={expire:0n,addrs:[]},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.expire=e.uint64();break}case 2:{if(o.limits?.addrs!=null&&i.addrs.length===o.limits.addrs)throw new Dr('Decode error - map field "addrs" had too many elements');i.addrs.push(e.bytes());break}case 3:{i.voucher=Hn.codec().decode(e,e.uint32(),{limits:o.limits?.voucher});break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Vn||(Vn={}));var lr;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.duration!=null&&(n.uint32(8),n.uint32(e.duration)),e.data!=null&&(n.uint32(16),n.uint64(e.data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.duration=e.uint32();break}case 2:{i.data=e.uint64();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(lr||(lr={}));var q;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(q||(q={}));var ys;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(ys||(ys={}));(function(r){r.codec=()=>Me(ys)})(q||(q={}));var fr;(function(r){let t;r.codec=()=>(t==null&&(t=Nt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.relay!=null&&e.relay.byteLength>0&&(n.uint32(10),n.bytes(e.relay)),e.peer!=null&&e.peer.byteLength>0&&(n.uint32(18),n.bytes(e.peer)),e.expiration!=null&&e.expiration!==0n&&(n.uint32(24),n.uint64(e.expiration)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={relay:ot(0),peer:ot(0),expiration:0n},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.relay=e.bytes();break}case 2:{i.peer=e.bytes();break}case 3:{i.expiration=e.uint64();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(fr||(fr={}));var Hn;(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&&(n.uint32(26),fr.codec().encode(e.payload,n)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={publicKey:ot(0),payloadType:ot(0),signature:ot(0)},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.publicKey=e.bytes();break}case 2:{i.payloadType=e.bytes();break}case 3:{i.payload=fr.codec().decode(e,e.uint32(),{limits:o.limits?.payload});break}case 5:{i.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Bt(e,r.codec(),n)})(Hn||(Hn={}));var ud=r=>r.toString().split("/").slice(1),hr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),K=r=>({match:t=>hr(e=>e===r).match(t),pattern:r}),Fe=()=>({match:r=>hr(t=>typeof t=="string").match(r),pattern:"{string}"}),Fr=()=>({match:r=>hr(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),X=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{Z.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),zr=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Mo.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),G=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),At=(...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(", ")})`}),F=(...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 tt(...r){function t(o){let i=ud(o);for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function e(o){return t(o)!==!1}function n(o){let i=t(o);return i===!1?!1:i.length===0}return{matchers:r,matches:e,exactMatch:n}}var Wn=F(K("dns4"),Fe()),$n=F(K("dns6"),Fe()),Zn=F(K("dnsaddr"),Fe()),bs=F(K("dns"),Fe()),yw=tt(Wn,G(X())),gw=tt($n,G(X())),bw=tt(Zn,G(X())),xw=tt(At(bs,Zn,Wn,$n),G(X())),Xc=F(K("ip4"),hr(Cn)),Qc=F(K("ip6"),hr(Dn)),xs=At(Xc,Qc),de=At(xs,bs,Wn,$n,Zn),ww=tt(At(xs,F(At(bs,Zn,Wn,$n),G(X())))),Ew=tt(Xc),Sw=tt(Qc),vw=tt(xs),ws=F(de,K("tcp"),Fr()),Vr=F(de,K("udp"),Fr()),Aw=tt(F(ws,G(X()))),_w=tt(Vr),Es=F(Vr,K("quic"),G(X())),Yn=F(Vr,K("quic-v1"),G(X())),ld=At(Es,Yn),Iw=tt(Es),Tw=tt(Yn),gs=At(de,ws,Vr,Es,Yn),Jc=At(F(gs,K("ws"),G(X()))),Lw=tt(Jc),tu=At(F(gs,K("wss"),G(X())),F(gs,K("tls"),G(F(K("sni"),Fe())),K("ws"),G(X()))),Rw=tt(tu),eu=F(Vr,K("webrtc-direct"),G(zr()),G(zr()),G(X())),Cw=tt(eu),ru=F(Yn,K("webtransport"),G(zr()),G(zr()),G(X())),Dw=tt(ru),Gn=At(Jc,tu,F(ws,G(X())),F(ld,G(X())),F(de,G(X())),eu,ru,X()),nu=tt(Gn),fd=F(Gn,K("p2p-circuit"),X()),jn=tt(fd),hd=At(F(Gn,K("p2p-circuit"),K("webrtc"),G(X())),F(Gn,K("webrtc"),G(X())),F(K("webrtc"),G(X()))),Bw=tt(hd),dd=At(F(de,K("tcp"),Fr(),K("http"),G(X())),F(de,K("http"),G(X()))),Pw=tt(dd),pd=At(F(de,K("tcp"),At(F(K("443"),K("http")),F(Fr(),K("https"))),G(X())),F(de,K("tls"),K("http"),G(X())),F(de,K("https"),G(X()))),Nw=tt(pd),md=At(F(K("memory"),Fe(),G(X()))),Uw=tt(md);function Xn(r){let t=new globalThis.AbortController;function e(){t.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let i of r){if(i?.aborted===!0){e();break}i?.addEventListener!=null&&i.addEventListener("abort",e)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}var Qn=class extends Error{constructor(t="Transfer limit error"){super(t),this.name="TransferLimitError"}},Hr=class extends Error{constructor(t="Duration limit error"){super(t),this.name="DurationLimitError"}},Gr=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},Jn=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},to=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};async function*ou(r,t,e){let n=t.remaining;for await(let o of r){let i=BigInt(o.byteLength);if(t.remaining-i<0){let s=Number(t.remaining);t.remaining=0n;try{s!==0&&(yield o.subarray(0,s))}catch(a){e.log.error(a)}throw new Qn(`data limit of ${n} bytes exceeded`)}t.remaining-=i,yield o}}function iu(r,t,e,n,o){function i(f){r.abort(f),t.abort(f)}let s=[e,n.signal];n.limit?.duration!=null&&(o.log("limiting relayed connection duration to %dms",n.limit.duration),s.push(AbortSignal.timeout(n.limit.duration)));let a=Xn(s),c=!1,l=!1,u;n.limit?.data!=null&&(u={remaining:n.limit.data}),queueMicrotask(()=>{let f=()=>{o.log("relayed connection reached time limit"),t.abort(new Hr(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",f,{once:!0}),t.sink(u==null?r.source:ou(r.source,u,o)).catch(d=>{o.log.error("error while relaying streams src -> dst",d),i(d)}).finally(()=>{c=!0,l&&(a.removeEventListener("abort",f),a.clear())})}),queueMicrotask(()=>{let f=()=>{o.log("relayed connection reached time limit"),r.abort(new Hr(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",f,{once:!0}),r.sink(u==null?t.source:ou(t.source,u,o)).catch(d=>{o.log.error("error while relaying streams dst -> src",d),i(d)}).finally(()=>{l=!0,c&&(a.removeEventListener("abort",f),a.clear())})})}function Ss(r){let t=r*BigInt(1e3),e=new Date().getTime();return Number(t-BigInt(e))}var Wr=class{expires;bytes;constructor(t){t?.duration!=null&&t?.duration!==0&&(this.expires=Date.now()+t.duration*1e3),this.bytes=t?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(t){this.bytes!=null&&(this.bytes-=BigInt(t.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let t={};if(this.bytes!=null){let e=this;Object.defineProperty(t,"bytes",{get(){return e.bytes}})}if(this.expires!=null){let e=this;Object.defineProperty(t,"seconds",{get(){return Math.round(((e.expires??0)-Date.now())/1e3)}})}return t}},eo=tt(F(nu.matchers[0],K("p2p-circuit"))),ro=tt(K("p2p-circuit"));function no(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}var Te=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 no(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 no(this.map.values(),t=>t.key)}values(){return no(this.map.values(),t=>t.value)}get size(){return this.map.size}};var vs={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},su={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},au=new globalThis.TextEncoder;function yd(r,t){let e=vs[t],n=su[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function gd(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=vs[t],o=su[t],i=r;for(;i.length>0;){let s=au.encodeInto(i,e);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function As(r,{size:t=32,utf8Buffer:e}={}){if(!vs[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 gd(r,t,e);r=au.encode(r)}return yd(r,t)}var $r={hash:r=>Number(As(r,{size:32})),hashV:(r,t)=>bd($r.hash(r,t))};function bd(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),M(t,"base16")}var _s=64,Zt=class{fp;h;seed;constructor(t,e,n,o=2){if(o>_s)throw new TypeError("Invalid Fingerprint Size");let i=e.hashV(t,n),s=ot(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?ft(this.fp,t.fp):!1}};function ze(r,t){return Math.floor(Math.random()*(t-r))+r}var Ve=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof Zt))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof Zt))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 Zt))throw new TypeError("Invalid Fingerprint");let e=ze(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof Zt))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var xd=500,Zr=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??$r,this.seed=t.seed??ze(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=M(t));let e=new Zt(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 Ve(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Ve(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let i=[n,o],s=i[ze(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new Ve(this.bucketSize));for(let a=0;a<xd;a++){let c=this.buckets[s].swap(e);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new Ve(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=M(t));let e=new Zt(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 i=(n^e.hash())%this.filterSize;return this.buckets[i]?.has(e)??!1}remove(t){typeof t=="string"&&(t=M(t));let e=new Zt(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 i=(n^e.hash())%this.filterSize,s=this.buckets[i]?.remove(e)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},wd={1:.5,2:.84,4:.95,8:.98};function Ed(r=.001){return r>.002?2:r>1e-5?4:8}function cu(r,t=.001){let e=Ed(t),n=wd[e],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),_s);return{filterSize:o,bucketSize:e,fingerprintSize:i}}var oo=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??$r,this.seed=t.seed??ze(0,Math.pow(2,10)),this.filterSeries=[new Zr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=M(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 Zr({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=M(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=M(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 dr(r,t=.001,e){return new oo({...cu(r,t),...e??{}})}var io=class{filter;constructor(t,e){this.filter=dr(t,e)}has(t){return this.filter.has(t.toMultihash().bytes)}add(t){this.filter.add(t.toMultihash().bytes)}remove(t){this.filter.remove?.(t.toMultihash().bytes)}};function Is(r,t=.001){return new io(r,t)}var Ts=class extends Te{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 Ls(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Ts({name:t,metrics:e}):n=new Te,n}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"}};function uu(r,t){let e=new Rs(t?.errorMessage,t?.errorCode,t?.errorName),n=new AbortController,o=()=>{n.abort(e)},i=AbortSignal.timeout(r);i.addEventListener("abort",o);let s=n.signal;return s.reset=a=>{i?.removeEventListener("abort",o),i=AbortSignal.timeout(a??r),i.addEventListener("abort",()=>{n.abort(e)})},s.clear=()=>{i?.removeEventListener("abort",o),i=void 0},s}var so=class{reservations;maxReservations;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:circuit-relay:server:reservation-store"),this.maxReservations=e.maxReservations??zc,this.applyDefaultLimit=e.applyDefaultLimit!==!1,this.reservationTtl=e.reservationTtl??Vc,this.defaultDurationLimit=e.defaultDurationLimit??Wc,this.defaultDataLimit=e.defaultDataLimit??$c,this.reservations=Ls({metrics:t.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(t,e,n){let o=this.reservations.get(t);if(this.reservations.size>=this.maxReservations&&o==null)return{status:q.RESERVATION_REFUSED};let i=new Date(Date.now()+this.reservationTtl),s;return this.applyDefaultLimit&&(s=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),o!=null?(this.log("refreshing reservation for client %p",t),o.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",t),o={addr:e,expiry:i,limit:s,signal:uu(this.reservationTtl)}),this.reservations.set(t,o),o.signal.addEventListener("abort",()=>{this.reservations.delete(t)}),{status:q.OK,expire:Math.round(i.getTime()/1e3)}}removeReservation(t){this.reservations.delete(t)}get(t){return this.reservations.get(t)}clear(){this.reservations.clear()}};var ao=class r{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:t,peer:e,expiration:n}){this.relay=t,this.peer=e,this.expiration=n}marshal(){return fr.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,expiration:BigInt(this.expiration)})}equals(t){return!(!(t instanceof r)||!this.peer.equals(t.peer)||!this.relay.equals(t.relay)||this.expiration!==t.expiration)}};var lu=r=>r.protoCodes().includes(Fn),Sd={maxOutboundStopStreams:qr},Cs=class extends Mt{registrar;peerStore;addressManager;peerId;privateKey;connectionManager;connectionGater;reservationStore;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:server"),this.registrar=t.registrar,this.peerStore=t.peerStore,this.addressManager=t.addressManager,this.peerId=t.peerId,this.privateKey=t.privateKey,this.connectionManager=t.connectionManager,this.connectionGater=t.connectionGater,this.started=!1,this.hopTimeout=e?.hopTimeout??Zc,this.maxInboundHopStreams=e.maxInboundHopStreams,this.maxOutboundHopStreams=e.maxOutboundHopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??Sd.maxOutboundStopStreams,this.reservationStore=new so(t,e.reservations),this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.registrar.handle(Ft,t=>{this.onHop(t).catch(e=>{this.log.error(e)})},{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.registrar.unhandle(Ft),this.started=!1}async onHop({connection:t,stream:e}){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n={signal:AbortSignal.timeout(this.hopTimeout)},o=Ie(e);try{let i=await o.pb(Y).read(n);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:t,stream:o,request:i},n)}catch(i){this.log.error("error while handling hop",i),await o.pb(Y).write({type:Y.Type.STATUS,status:q.MALFORMED_MESSAGE},n),e.abort(i)}}async handleHopProtocol({stream:t,request:e,connection:n},o){switch(this.log("received hop message"),e.type){case Y.Type.RESERVE:await this.handleReserve({stream:t,request:e,connection:n},o);break;case Y.Type.CONNECT:await this.handleConnect({stream:t,request:e,connection:n},o);break;default:this.log.error("invalid hop request type %s via peer %p",e.type,n.remotePeer),await t.pb(Y).write({type:Y.Type.STATUS,status:q.UNEXPECTED_MESSAGE})}}async handleReserve({stream:t,connection:e},n){let o=t.pb(Y);if(this.log("hop reserve request from %p",e.remotePeer),lu(e.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",e.remotePeer),await o.write({type:Y.Type.STATUS,status:q.PERMISSION_DENIED},n);return}if(await this.connectionGater.denyInboundRelayReservation?.(e.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",e.remotePeer),await o.write({type:Y.Type.STATUS,status:q.PERMISSION_DENIED},n);return}let i=this.reservationStore.reserve(e.remotePeer,e.remoteAddr);try{if(i.status!==q.OK){await o.write({type:Y.Type.STATUS,status:i.status},n);return}if(i.expire!=null){let s=i.expire*1e3-Date.now();await this.peerStore.merge(e.remotePeer,{tags:{[ps]:{value:1,ttl:s},[ms]:{value:1,ttl:s}}})}await o.write({type:Y.Type.STATUS,status:q.OK,reservation:await this.makeReservation(e.remotePeer,BigInt(i.expire??0)),limit:this.reservationStore.get(e.remotePeer)?.limit},n),this.log("sent confirmation response to %s",e.remotePeer)}catch(s){this.log.error("failed to send confirmation response to %p - %e",e.remotePeer,s),this.reservationStore.removeReservation(e.remotePeer);try{await this.peerStore.merge(e.remotePeer,{tags:{[ps]:void 0,[ms]:void 0}})}catch(a){this.log.error("failed to untag relay source peer %p - %e",e.remotePeer,a)}}}async makeReservation(t,e){let n=[];for(let i of this.addressManager.getAddresses())i.toString().includes("/p2p-circuit")||n.push(i.bytes);let o=await Mr.seal(new ao({peer:t,relay:this.peerId,expiration:e}),this.privateKey);return{addrs:n,expire:e,voucher:{publicKey:Xt(o.publicKey),payloadType:o.payloadType,payload:{peer:t.toMultihash().bytes,relay:this.peerId.toMultihash().bytes,expiration:e},signature:o.signature}}}async handleConnect({stream:t,request:e,connection:n},o){let i=t.pb(Y);if(lu(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await i.write({type:Y.Type.STATUS,status:q.PERMISSION_DENIED},o);return}this.log("hop connect request from %p",n.remotePeer);let s;try{if(e.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");e.peer.addrs.forEach(St),s=sr(Kt(e.peer.id))}catch(d){this.log.error("invalid hop connect request via peer %p %s",n.remotePeer,d),await i.write({type:Y.Type.STATUS,status:q.MALFORMED_MESSAGE},o);return}let a=this.reservationStore.get(s);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",s,n.remotePeer,q.NO_RESERVATION),await i.write({type:Y.Type.STATUS,status:q.NO_RESERVATION},o);return}if(await this.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,s)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,s),await i.write({type:Y.Type.STATUS,status:q.PERMISSION_DENIED},o);return}let c=this.connectionManager.getConnections(s);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",s,n.remotePeer),await i.write({type:Y.Type.STATUS,status:q.NO_RESERVATION},o);return}let l=c[0],u=await this.stopHop({connection:l,request:{type:kt.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},o);if(u==null){this.log.error("failed to open stream to destination peer %p",l?.remotePeer),await i.write({type:Y.Type.STATUS,status:q.CONNECTION_FAILED},o);return}await i.write({type:Y.Type.STATUS,status:q.OK,limit:a?.limit},o);let f=t.unwrap();this.log("connection from %p to %p established - merging streams",n.remotePeer,s),iu(f,u,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:t,request:e},n){this.log("starting circuit relay v2 stop request to %s",t.remotePeer);let o=await t.newStream([qe],{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),i=Ie(o),s=i.pb(kt);await s.write(e,n);let a;try{a=await s.read(n)}catch{this.log.error("error parsing stop message response from %p",t.remotePeer)}if(a==null){this.log.error("could not read response from %p",t.remotePeer),await o.close(n);return}if(a.status===q.OK)return this.log("stop request to %p was successful",t.remotePeer),i.unwrap();this.log("stop request failed with code %d",a.status),await o.close(n)}get reservations(){return this.reservationStore.reservations}};function fu(r={}){return t=>new Cs(t,r)}function vd(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 hu=vd;function Ad(r){return r[Symbol.asyncIterator]!=null}function du(r){return r?.then!=null}function _d(r,t){let e=0;if(Ad(r))return async function*(){for await(let c of r){let l=t(c,e++);du(l)&&await l,yield c}}();let n=hu(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();if(typeof t(o,e++)?.then=="function")return async function*(){yield o;for await(let c of n){let l=t(c,e++);du(l)&&await l,yield c}}();let a=t;return function*(){yield o;for(let c of n)a(c,e++),yield c}()}var pu=_d;var uo=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}},pr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new uo(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 uo(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 Ds=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function lo(r={}){return Id(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 Id(r,t){t=t??{};let e=t.onEnd,n=new pr,o,i,s,a=vt(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((h,w)=>{i=S=>{i=null,n.push(S);try{h(r(n))}catch(m){w(m)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=vt()})}},l=h=>i!=null?i(h):(n.push(h),o),u=h=>(n=new pr,i!=null?i({error:h}):(n.push({error:h}),o)),f=h=>{if(s)return o;if(t?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:h})},d=h=>s?o:(s=!0,h!=null?u(h):l({done:!0})),g=()=>(n=new pr,d(),{done:!0}),y=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:g,throw:y,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let w=h?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let S,m;w!=null&&(S=new Promise((_,C)=>{m=()=>{C(new Ds)},w.addEventListener("abort",m)}));try{await Promise.race([a.promise,S])}finally{m!=null&&w!=null&&w?.removeEventListener("abort",m)}}},e==null)return o;let b=o;return o={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(h){return b.throw(h),e!=null&&(e(h),e=void 0),{done:!0}},return(){return b.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(h){return b.end(h),e!=null&&(e(h),e=void 0),o},get readableLength(){return b.readableLength},onEmpty:h=>b.onEmpty(h)},o}var Bs=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=vt(),this.haveNext=vt()}[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=vt(),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=vt(),await he(this.readNext.promise,e?.signal,e)}};function mu(){return new Bs}function Td(r){return r[Symbol.asyncIterator]!=null}async function Ld(r,t){try{await Promise.all(r.map(async e=>{for await(let n of e)await t.push(n)})),await t.end()}catch(e){await t.end(e).catch(()=>{})}}async function*Rd(r){let t=mu();Ld(r,t).catch(()=>{}),yield*t}function*Cd(r){for(let t of r)yield*t}function Dd(...r){let t=[];for(let e of r)Td(e)||t.push(e);return t.length===r.length?Cd(t):Rd(r)}var yu=Dd;function gu(r,...t){if(r==null)throw new Error("Empty pipeline");if(Ps(r)){let n=r;r=()=>n.source}else if(xu(r)||bu(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Ps(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)Ps(e[n])&&(e[n]=Pd(e[n]));return Bd(...e)}var Bd=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},bu=r=>r?.[Symbol.asyncIterator]!=null,xu=r=>r?.[Symbol.iterator]!=null,Ps=r=>r==null?!1:r.sink!=null&&r.source!=null,Pd=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=lo({objectMode:!0});e.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(bu(i))o=async function*(){yield*i,n.end()};else if(xu(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return yu(n,o())}return r.source};function Ns(r){let{stream:t,remoteAddr:e,logger:n,onDataRead:o,onDataWrite:i}=r,s=n.forComponent("libp2p:stream:converter"),a=!1,c=!1,l=t.close.bind(t);t.close=async y=>{await l(y),g(!0)};let u=t.abort.bind(t);t.abort=y=>{u(y),g(!0)};let f=t.sink.bind(t);t.sink=async y=>{try{await f(gu(y,b=>pu(b,h=>i?.(h))))}catch(b){b.type!=="aborted"&&s.error("%s error in sink",e,b)}finally{c=!0,g()}};let d={log:s,sink:t.sink,source:async function*(){try{for await(let y of t.source)o?.(y),yield y}finally{a=!0,g()}}(),remoteAddr:e,timeline:{open:Date.now(),close:void 0},close:t.close,abort:t.abort};function g(y){y===!0&&(a=!0,c=!0),a&&c&&d.timeline.close==null&&(d.timeline.close=Date.now())}return d}var Le=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Us=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 fo(r,t,e,n){let o=new Us(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((i,s)=>{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(),s(d);return}a(),i(f)},l=f=>{a(),s(f.detail)},u=()=>{a(),s(o)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var ho=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var po=class{deferred;signal;constructor(t){this.signal=t,this.deferred=vt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new ee)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Nd(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var mo=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Nd(),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 ee),this.cleanup())}async join(t={}){let e=new po(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 he(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 yo=class extends Mt{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new ho;let n=new mo(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 i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,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 ee)}),this.clear()}async onEmpty(t){this.size!==0&&await fo(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await fo(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await fo(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=lo({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},i=c=>{n(c.detail)},s=()=>{n()},a=()=>{n(new ee("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",i),this.addEventListener("idle",s),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("error",i),this.removeEventListener("idle",s),t?.signal?.removeEventListener("abort",a),n()}}};var mr=class extends yo{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var go=class extends Mt{peerStore;registrar;connectionManager;randomWalk;started;running;topologyId;log;discoveryController;filter;queue;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.started=!1,this.running=!1,this.peerStore=t.peerStore,this.registrar=t.registrar,this.connectionManager=t.connectionManager,this.randomWalk=t.randomWalk,this.filter=e.filter,this.discoveryController=new AbortController,this.discoveryController.signal}isStarted(){return this.started}async start(){this.topologyId=await this.registrar.register(Ft,{filter:this.filter,onConnect:t=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",t,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:t})}}),this.started=!0}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.discoveryController?.abort(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,Promise.resolve().then(async()=>{this.log("searching peer store for relays");let t=await this.peerStore.all({filters:[n=>n.protocols.includes(Ft)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let i=wu(n),s=wu(o);return i>s?-1:s>i?1:0}]});for(let n of t)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",t.length);let e=this.queue=new mr({concurrency:5});this.log("start random walk");for await(let n of this.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),e.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(o=>o.toString()));continue}e.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await e.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,e.size,e.running),e.add(async()=>{let o=Xn([this.discoveryController.signal,AbortSignal.timeout(5e3)]);try{await this.connectionManager.openConnection(n.id,{signal:o})}finally{o.clear()}},{peerId:n.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to random peer %p",n.id,o)})}this.log("stop random walk"),await e.onIdle()}).catch(t=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network",t)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort()}};function wu(r){let t=r.metadata.get("last-dial-success");return t==null?0:new Date(O(t)).getTime()}var Os=class extends Mt{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=t.connectionManager,this.addressManager=t.addressManager,this.reservationStore=t.reservationStore,this.listeningAddrs=[],this.listenTimeout=e.listenTimeout??zn,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=t=>{this.log("relay removed %p our relay %p",t.detail.relay,this.relay,this.relay?.equals(t.detail.relay)),this.relay?.equals(t.detail.relay)===!0&&(this.log("relay peer removed %p",t.detail.relay),this.listeningAddrs.forEach(e=>{this.addressManager.removeObservedAddr(e)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=t=>{let{details:e}=t.detail;e.type!=="configured"&&e.id===this.reservationId&&this.addedRelay(t.detail)};async listen(t){if(ro.exactMatch(t))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(eo.exactMatch(t)){this.log("listen on specific relay server %a",t);let e=AbortSignal.timeout(this.listenTimeout);let n=t.decapsulate("/p2p-circuit"),o=await this.connectionManager.openConnection(n,{signal:e});if(!this.reservationStore.hasReservation(o.remotePeer)){this.log("making reservation on peer %p",o.remotePeer);let i=await this.reservationStore.addRelay(o.remotePeer,"configured");this.addedRelay(i)}}else throw new Re(`Could not listen on p2p-circuit address "${t}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(t){this.log("relay peer added %p",t.relay),this.relay=t.relay,this.listeningAddrs=t.details.reservation.addrs.map(e=>St(e).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(e=>{this.addressManager.confirmObservedAddr(e,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function Eu(r){return new Os(r)}var Su="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var vu=(r=21)=>{let t="",e=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)t+=Su[e[r]&63];return t};var Ud=60*1e3*10,Od=60*1e3*5,kd=30*1e3,bo=class extends Mt{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(t,e){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=t.peerId,this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.reservations=new Te,this.pendingReservations=[],this.maxReservationQueueLength=e?.maxReservationQueueLength??Gc,this.reservationCompletionTimeout=e?.reservationCompletionTimeout??zn,this.started=!1,this.relayFilter=dr(100),this.reserveQueue=new mr({concurrency:e?.reservationConcurrency??Hc,metricName:"libp2p_relay_reservation_queue",metrics:t.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(i=>i.connection===n.detail.id)!=null&&this.#e(n.detail.remotePeer).catch(i=>{this.log("could not remove relay %p - %e",n.detail,i)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let t=await this.peerStore.all({filters:[e=>e.tags.has(Kr)]});this.log("removing tag from %d old relays",t.length),await Promise.all(t.map(async e=>{await this.peerStore.merge(e.id,{tags:{[Kr]:void 0}})})),this.log("redialing %d old relays",t.length),await Promise.all(t.map(async e=>this.addRelay(e.id,"discovered"))),this.#r()}).catch(t=>{this.log.error(t)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:t})=>{clearTimeout(t)}),this.reservations.clear(),this.started=!1}reserveRelay(){let t=vu();return this.pendingReservations.push(t),this.#r(),t}async addRelay(t,e){if(this.peerId.equals(t))throw this.log.trace("not trying to use self as relay"),new Re("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new to("The reservation queue is full");let n=this.reserveQueue.find(t);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",t),n.join();if(this.relayFilter.has(t.toMultihash().bytes))throw new Re("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",t),this.reserveQueue.add(async()=>{let o=Date.now();try{let i=this.reservations.get(t);if(i!=null){let y=this.connectionManager.getConnections(t),b=!1;if(y.length===0&&this.log("already have relay reservation with %p but we are no longer connected",t),y.map(h=>h.id).includes(i.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",t),b=!0),b&&Ss(i.reservation.expire)>Ud)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",t),{relay:t,details:i};await this.#e(t)}if(e==="discovered"&&this.pendingReservations.length===0)throw new Gr("Not making reservation on discovered relay because we do not need any more relays");let s=AbortSignal.timeout(this.reservationCompletionTimeout);let a=await this.connectionManager.openConnection(t,{signal:s});if(jn.matches(a.remoteAddr))throw new Jn("not creating reservation over relayed connection");let c=await this.#t(a,{signal:s}),l=Ss(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",t,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-Od,kd),Math.pow(2,31)-1),f=setTimeout(()=>{this.log("refresh reservation to relay %p",t),this.addRelay(t,e).catch(async y=>{this.log.error("could not refresh reservation to relay %p - %e",t,y),await this.#e(t)}).catch(y=>{this.log.error("could not remove expired reservation to relay %p - %e",t,y)})},u),d;if(e==="discovered"){let y=this.pendingReservations.pop();if(y==null)throw new Gr("Made reservation on relay but did not need any more discovered relays");d={timeout:f,reservation:c,type:e,connection:a.id,id:y}}else d={timeout:f,reservation:c,type:e,connection:a.id};this.reservations.set(t,d),await this.peerStore.merge(t,{tags:{[Kr]:{value:1,ttl:l}}}),this.#r();let g={relay:t,details:d};return this.safeDispatchEvent("relay:created-reservation",{detail:g}),g}catch(i){throw e==="discovered"&&i.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",t,Date.now()-o,i),(i.name==="DialError"||i.name==="UnsupportedProtocolError")&&this.relayFilter.add(t.toMultihash().bytes),this.#e(t).catch(s=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",t,s)}),i}},{peerId:t})}hasReservation(t){return this.reservations.has(t)}getReservation(t){return this.reservations.get(t)?.reservation}reservationCount(t){return t==null?this.reservations.size:[...this.reservations.values()].reduce((e,n)=>(n.type===t&&e++,e),0)}cancelReservations(){[...this.reservations.values()].forEach(t=>{clearTimeout(t.timeout)}),this.reservations.clear()}async#t(t,e){e.signal?.throwIfAborted(),this.log("requesting reservation from %p",t.remotePeer);let n=await t.newStream(Ft,e),i=Ie(n).pb(Y);this.log.trace("send RESERVE to %p",t.remotePeer),await i.write({type:Y.Type.RESERVE},e);let s;try{this.log.trace("reading response from %p",t.remotePeer),s=await i.read(e)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(e)}if(this.log.trace("read response %o",s),s.status===q.OK&&s.reservation!=null){let c=new Set;c.add(t.remoteAddr.toString());for(let l of s.reservation.addrs){let u=St(l);u.getPeerId()==null&&(u=u.encapsulate(`/p2p/${t.remotePeer}`)),u=St(u.toString().replace(`/p2p/${t.remotePeer}/p2p/${t.remotePeer}`,`/p2p/${t.remotePeer}`)),c.add(u.toString())}return s.reservation.addrs=[...c].map(l=>St(l).bytes),s.reservation}let a=`reservation failed with status ${s.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#e(t){let e=this.reservations.get(t);e!=null&&(this.log("removing relay reservation with %p from local store",t),clearTimeout(e.timeout),this.reservations.delete(t),e.type==="discovered"&&this.pendingReservations.push(e.id),await this.peerStore.merge(t,{tags:{[Kr]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:t,details:e}}),this.#r())}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=dr(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var Md=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(St)}catch{return!1}return!0},Au={maxInboundStopStreams:qr,maxOutboundStopStreams:qr,stopTimeout:3e4},xo=class{discovery;registrar;peerStore;connectionManager;transportManager;peerId;upgrader;addressManager;connectionGater;reservationStore;logger;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:circuit-relay:transport"),this.registrar=t.registrar,this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.transportManager=t.transportManager,this.logger=t.logger,this.peerId=t.peerId,this.upgrader=t.upgrader,this.addressManager=t.addressManager,this.connectionGater=t.connectionGater,this.maxInboundStopStreams=e.maxInboundStopStreams??Au.maxInboundStopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??Au.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new go(t,{filter:e.discoveryFilter??Is(Yc,jc)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{o.name!=="HadEnoughRelaysError"&&o.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p",n.detail,o)})}),this.reservationStore=new bo(t,e),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[Ys]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[js](){return this.discovery!=null?["@libp2p/identify"]:[]}[Gs]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,await this.registrar.handle(qe,t=>{let e=this.upgrader.createInboundAbortSignal(this.shutdownController.signal);this.onStop(t,e).catch(n=>{this.log.error("error while handling STOP protocol",n),t.stream.abort(n)}).finally(()=>{e.clear()})},{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await $s(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Zs(this.discovery,this.reservationStore),await this.registrar.unhandle(qe),this.started=!1}async dial(t,e){if(t.protoCodes().filter(g=>g===Fn).length!==1){let g="Invalid circuit relay address";throw this.log.error(g,t),new gr(g)}let n=t.toString().split("/p2p-circuit"),o=St(n[0]),i=St(n[n.length-1]),s=o.getPeerId(),a=i.getPeerId();if(s==null||a==null){let g=`ircuit relay dial to ${t.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${g}`),new gr(`C${g}`)}let c=Xi(s),l=Xi(a),f=this.connectionManager.getConnections(c)[0];f==null?(await this.peerStore.merge(c,{multiaddrs:[o]}),e.onProgress?.(new Le("circuit-relay:open-connection")),f=await this.connectionManager.openConnection(c,e)):e.onProgress?.(new Le("circuit-relay:reuse-connection"));let d;try{e.onProgress?.(new Le("circuit-relay:open-hop-stream")),d=await f.newStream(Ft,e);let g=Ie(d),y=g.pb(Y);e.onProgress?.(new Le("circuit-relay:write-connect-message")),await y.write({type:Y.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[St(i).bytes]}},e),e.onProgress?.(new Le("circuit-relay:read-connect-response"));let b=await y.read(e);if(b.status!==q.OK)throw new Xr(`failed to connect via relay with status ${b?.status?.toString()??"undefined"}`);let h=new Wr(b.limit),w=Ns({stream:g.unwrap(),remoteAddr:t,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`),logger:this.logger,onDataRead:h.onData,onDataWrite:h.onData});return this.log("new outbound relayed connection %a",w.remoteAddr),await this.upgrader.upgradeOutbound(w,{...e,limits:h.getLimits()})}catch(g){throw this.log.error("circuit relay dial to destination %p via relay %p failed",l,c,g),d?.abort(g),g}}createListener(t){return Eu({peerId:this.peerId,connectionManager:this.connectionManager,addressManager:this.addressManager,reservationStore:this.reservationStore,logger:this.logger})}listenFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>eo.exactMatch(e)||ro.exactMatch(e))}dialFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>jn.exactMatch(e))}async onStop({connection:t,stream:e},n){if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(f){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on",f)}let o=Ie(e).pb(kt),i=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,i.type),i?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await o.write({type:kt.Type.STATUS,status:q.MALFORMED_MESSAGE},{signal:n}),await e.close();return}if(i.type!==kt.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:kt.Type.STATUS,status:q.UNEXPECTED_MESSAGE},{signal:n}),await e.close();return}if(!Md(i)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:kt.Type.STATUS,status:q.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let s=sr(Kt(i.peer.id));if(await this.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,s)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await o.write({type:kt.Type.STATUS,status:q.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await o.write({type:kt.Type.STATUS,status:q.OK},{signal:n});let a=new Wr(i.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${s.toString()}`),l=this.addressManager.getAddresses()[0],u=Ns({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:l,logger:this.logger,onDataRead:a.onData,onDataWrite:a.onData});this.log("new inbound relayed connection %a",u.remoteAddr),await this.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),this.log("%s connection %a upgraded","inbound",u.remoteAddr)}};function _u(r={}){return t=>new xo(t,r)}return Mu(Kd);})();
3
3
  /*! Bundled license information:
4
4
 
5
5
  @noble/hashes/esm/utils.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@libp2p/circuit-relay-v2",
3
- "version": "3.2.8-78cd7d53e",
3
+ "version": "3.2.8-d53ef170c",
4
4
  "description": "Implementation of Circuit Relay v2",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/transport-circuit-relay-v2#readme",
@@ -52,13 +52,13 @@
52
52
  "doc-check": "aegir doc-check"
53
53
  },
54
54
  "dependencies": {
55
- "@libp2p/crypto": "5.0.15-78cd7d53e",
56
- "@libp2p/interface": "2.7.0-78cd7d53e",
57
- "@libp2p/interface-internal": "2.3.9-78cd7d53e",
58
- "@libp2p/peer-collections": "6.0.25-78cd7d53e",
59
- "@libp2p/peer-id": "5.1.0-78cd7d53e",
60
- "@libp2p/peer-record": "8.0.25-78cd7d53e",
61
- "@libp2p/utils": "6.6.0-78cd7d53e",
55
+ "@libp2p/crypto": "5.0.15-d53ef170c",
56
+ "@libp2p/interface": "2.7.0-d53ef170c",
57
+ "@libp2p/interface-internal": "2.3.9-d53ef170c",
58
+ "@libp2p/peer-collections": "6.0.25-d53ef170c",
59
+ "@libp2p/peer-id": "5.1.0-d53ef170c",
60
+ "@libp2p/peer-record": "8.0.25-d53ef170c",
61
+ "@libp2p/utils": "6.6.0-d53ef170c",
62
62
  "@multiformats/multiaddr": "^12.3.3",
63
63
  "@multiformats/multiaddr-matcher": "^1.6.0",
64
64
  "any-signal": "^4.1.1",
@@ -73,8 +73,8 @@
73
73
  "uint8arrays": "^5.1.0"
74
74
  },
75
75
  "devDependencies": {
76
- "@libp2p/interface-compliance-tests": "6.4.2-78cd7d53e",
77
- "@libp2p/logger": "5.1.13-78cd7d53e",
76
+ "@libp2p/interface-compliance-tests": "6.4.2-d53ef170c",
77
+ "@libp2p/logger": "5.1.13-d53ef170c",
78
78
  "aegir": "^45.1.1",
79
79
  "delay": "^6.0.0",
80
80
  "it-drain": "^3.0.7",