@libp2p/daemon-server 9.0.19 → 9.0.20-5466a8def
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +1 -1
- package/dist/index.min.js.map +2 -2
- package/package.json +10 -10
- package/dist/typedoc-urls.json +0 -12
package/dist/index.min.js
CHANGED
|
@@ -13,7 +13,7 @@ ${e}`)}`:n!=null?`${n.split(`
|
|
|
13
13
|
${e}`)}`:r!=null?`${r}`:`${t.toString()}`}function af(t){return t instanceof AggregateError||t?.name==="AggregateError"&&Array.isArray(t.errors)}function Ic(t,e=""){if(af(t)){let r=vc(t,e);return t.errors.length>0?(e=`${e} `,r+=`
|
|
14
14
|
${e}${t.errors.map(n=>`${Ic(n,`${e}`)}`).join(`
|
|
15
15
|
${e}`)}`):r+=`
|
|
16
|
-
${e}[Error list was empty]`,r.trim()}return vc(t,e)}Ce.formatters.e=t=>t==null?"undefined":Ic(t);function uf(t){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=t,e.destroy=()=>!0,e.extend=()=>e,e}function Tc(t){return{forComponent(e){return ht(e,t)}}}function ht(t,e){let r=uf(`${t}:trace`);return Ce.enabled(`${t}:trace`)&&Ce.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(r=Ce(`${t}:trace`,e)),Object.assign(Ce(t,e),{error:Ce(`${t}:error`,e),trace:r,newScope:n=>ht(`${t}:${n}`,e)})}function Sc(t){if(t!=null&&(t=t.trim(),t.length!==0))return t}var cn=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var j=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},an=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var un=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var pt=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Lr=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var ln=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Gt=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},fn=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}},dn=class extends Error{static name="AlreadyStartedError";constructor(e="Already started"){super(e),this.name="AlreadyStartedError"}};var Cr=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var hn=class extends Event{data;constructor(e,r){super("message",r),this.data=e}},zt=class extends Event{error;local;constructor(e,r,n){super("close",n),this.error=r,this.local=e}},pn=class extends zt{constructor(e,r){super(!0,e,r)}},mn=class extends zt{constructor(e,r){super(!1,e,r)}};var bs=Symbol.for("@libp2p/peer-id");var Dc=Symbol.for("@libp2p/transport");var Ac;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Ac||(Ac={}));var Lc=se("node:events"),yn=(t,...e)=>{try{(0,Lc.setMaxListeners)(t,...e)}catch{}};function lf(t){return typeof t?.handleEvent=="function"}function ff(t){return(t!==!0&&t!==!1&&t?.once)??!1}var Wt=class extends EventTarget{#e=new Map;constructor(){super(),yn(1/0,this)}listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){let i=ff(n);super.addEventListener(e,c=>{if(i){let s=this.#e.get(c.type);s!=null&&(s=s.filter(({callback:a})=>a!==r),this.#e.set(c.type,s))}lf(r)?r.handleEvent(c):r(c)},n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:r,once:i})}removeEventListener(e,r,n){super.removeEventListener(e.toString(),r??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:o})=>o!==r),this.#e.set(e,i))}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}};var Cc=Symbol.for("@libp2p/service-capabilities");function Ne(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}async function Bc(t,e,r,n){let i=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},i,e,r.subarray());return n?.signal?.throwIfAborted(),o}var Oc=se("node:buffer");function Qe(t,e){return Et(Oc.Buffer.concat(t,e))}var kc=Symbol.for("@achingbrain/uint8arraylist");function _c(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(let n of t){let i=r+n.byteLength;if(e<i)return{buf:n,index:e-r};r=i}throw new RangeError("index is out of bounds")}function bn(t){return!!t?.[kc]}var K=class t{bufs;length;[kc]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let r=0;for(let n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(bn(n)){r+=n.byteLength;for(let i of n.bufs)this.bufs.push(i)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...e){this.prependAll(e)}prependAll(e){let r=0;for(let n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(bn(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(e){let r=_c(this.bufs,e);return r.buf[r.index]}set(e,r){let n=_c(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(bn(e))for(let n=0;n<e.length;n++)this.set(r+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,r){let{bufs:n,length:i}=this._subList(e,r);return Qe(n,i)}subarray(e,r){let{bufs:n,length:i}=this._subList(e,r);return n.length===1?n[0]:Qe(n,i)}sublist(e,r){let{bufs:n,length:i}=this._subList(e,r),o=new t;return o.length=i,o.bufs=n,o}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],i=0;for(let o=0;o<this.bufs.length;o++){let c=this.bufs[o],s=i,a=s+c.byteLength;if(i=a,e>=a)continue;let u=e>=s&&e<a,l=r>s&&r<=a;if(u&&l){if(e===s&&r===a){n.push(c);break}let f=e-s;n.push(c.subarray(f,f+(r-e)));break}if(u){if(e===0){n.push(c);continue}n.push(c.subarray(e-s));continue}if(l){if(r===a){n.push(c);break}n.push(c.subarray(0,r-s));break}n.push(c)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!bn(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.length===0)return r>this.length?this.length:r;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let o=256,c=new Int32Array(o);for(let f=0;f<o;f++)c[f]=-1;for(let f=0;f<i;f++)c[n[f]]=f;let s=c,a=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=r;f<=a;f+=l){l=0;for(let d=u;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){l=Math.max(1,d-s[h]);break}}if(l===0)return f}return-1}getInt8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){let n=Le(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){let i=ae(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,r,n),this.write(i,e)}getInt32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){let i=ae(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,r,n),this.write(i,e)}getBigInt64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){let i=ae(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,r,n),this.write(i,e)}getUint8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){let n=Le(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){let i=ae(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,r,n),this.write(i,e)}getUint32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){let i=ae(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,r,n),this.write(i,e)}getBigUint64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){let i=ae(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,r,n),this.write(i,e)}getFloat32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){let i=ae(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,r,n),this.write(i,e)}getFloat64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){let i=ae(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,r,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof t)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!Ne(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){let n=new t;return n.bufs=e,r==null&&(r=e.reduce((i,o)=>i+o.byteLength,0)),n.length=r,n}};var Pc=se("node:buffer");function ne(t,e="utf8"){let r=Xr[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?Pc.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}var df=parseInt("11111",2),gs=parseInt("10000000",2),hf=parseInt("01111111",2),Nc={0:Br,1:Br,2:pf,3:bf,4:gf,5:yf,6:mf,16:Br,22:Br,48:Br};function ws(t,e={offset:0}){let r=t[e.offset]&df;if(e.offset++,Nc[r]!=null)return Nc[r](t,e);throw new Error("No decoder for tag "+r)}function Or(t,e){let r=0;if((t[e.offset]&gs)===gs){let n=t[e.offset]&hf,i="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)i+=t[e.offset].toString(16).padStart(2,"0");r=parseInt(i,16)}else r=t[e.offset],e.offset++;return r}function Br(t,e){Or(t,e);let r=[];for(;!(e.offset>=t.byteLength);){let n=ws(t,e);if(n===null)break;r.push(n)}return r}function pf(t,e){let r=Or(t,e),n=e.offset,i=e.offset+r,o=[];for(let c=n;c<i;c++)c===n&&t[c]===0||o.push(t[c]);return e.offset+=r,Uint8Array.from(o)}function mf(t,e){let r=Or(t,e),n=e.offset+r,i=t[e.offset];e.offset++;let o=0,c=0;i<40?(o=0,c=i):i<80?(o=1,c=i-40):(o=2,c=i-80);let s=`${o}.${c}`,a=[];for(;e.offset<n;){let u=t[e.offset];if(e.offset++,a.push(u&127),u<128){a.reverse();let l=0;for(let f=0;f<a.length;f++)l+=a[f]<<f*7;s+=`.${l}`,a=[]}}return s}function yf(t,e){return e.offset++,null}function bf(t,e){let r=Or(t,e),n=t[e.offset];e.offset++;let i=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return i}function gf(t,e){let r=Or(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function wf(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);let r=new K;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function Es(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);let e=wf(t.byteLength);return new K(Uint8Array.from([e.byteLength|gs]),e)}function Rc(t){let e=new K,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new K(Uint8Array.from([2]),Es(e),e)}function Uc(t){let e=Uint8Array.from([0]),r=new K(e,t);return new K(Uint8Array.from([3]),Es(r),r)}function gn(t,e=48){let r=new K;for(let n of t)r.append(n);return new K(Uint8Array.from([e]),Es(r),r)}var Ef=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),xf=Uint8Array.from([6,5,43,129,4,0,34]),vf=Uint8Array.from([6,5,43,129,4,0,35]),Sf={ext:!0,kty:"EC",crv:"P-256"},If={ext:!0,kty:"EC",crv:"P-384"},Tf={ext:!0,kty:"EC",crv:"P-521"},xs=32,vs=48,Ss=66;function Fc(t){let e=ws(t);return Mc(e)}function Mc(t){let e=t[1][1][0],r=1,n,i;if(e.byteLength===xs*2+1)return n=ne(e.subarray(r,r+xs),"base64url"),i=ne(e.subarray(r+xs),"base64url"),new Yt({...Sf,key_ops:["verify"],x:n,y:i});if(e.byteLength===vs*2+1)return n=ne(e.subarray(r,r+vs),"base64url"),i=ne(e.subarray(r+vs),"base64url"),new Yt({...If,key_ops:["verify"],x:n,y:i});if(e.byteLength===Ss*2+1)return n=ne(e.subarray(r,r+Ss),"base64url"),i=ne(e.subarray(r+Ss),"base64url"),new Yt({...Tf,key_ops:["verify"],x:n,y:i});throw new j(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function $c(t){return gn([Rc(Uint8Array.from([1])),gn([Af(t.crv)],160),gn([Uc(new K(Uint8Array.from([4]),xe(t.x??"","base64url"),xe(t.y??"","base64url")))],161)]).subarray()}function Af(t){if(t==="P-256")return Ef;if(t==="P-384")return xf;if(t==="P-521")return vf;throw new j(`Invalid curve ${t}`)}var Yt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=$c(this.jwk)),this._raw}toMultihash(){return Ge.digest(mt(this))}toCID(){return ie.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ne(this.raw,e.raw)}async verify(e,r,n){return Bc(this.jwk,r,e,n)}};var wn=_e(se("crypto"),1);var my=wn.default.generateKeyPairSync,_r=32;var Df=64;function Kc(t,e,r){if(t.byteLength!==_r)throw new TypeError('"key" must be 32 bytes in length.');if(!(t instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');if(e.byteLength!==Df)throw new TypeError('"sig" must be 64 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"sig" must be a node.js Buffer, or Uint8Array.');let n=wn.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:ne(t,"base64url"),kty:"OKP"}});return wn.default.verify(null,r instanceof Uint8Array?r:r.subarray(),n,e)}function Vc(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var En=class{type="Ed25519";raw;constructor(e){this.raw=Is(e,_r)}toMultihash(){return Ge.digest(mt(this))}toCID(){return ie.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ne(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();let i=Kc(this.raw,r,e);return Vc(i)?i.then(o=>(n?.signal?.throwIfAborted(),o)):i}};function Gc(t){return t=Is(t,_r),new En(t)}function Is(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new j(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}var Ie;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(Ie||(Ie={}));var Ts;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(Ts||(Ts={}));(function(t){t.codec=()=>ze(Ts)})(Ie||(Ie={}));var kr;(function(t){let e;t.codec=()=>(e==null&&(e=Z((o,c,s={})=>{s.lengthDelimited!==!1&&c.fork(),o.Type!=null&&(c.uint32(8),Ie.codec().encode(o.Type,c)),o.Data!=null&&(c.uint32(18),c.bytes(o.Data)),s.lengthDelimited!==!1&&c.ldelim()},(o,c,s={})=>{let a={},u=c==null?o.len:o.pos+c;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{a.Type=Ie.codec().decode(o);break}case 2:{a.Data=o.bytes();break}default:{o.skipType(l&7);break}}}return a},function*(o,c,s,a={}){let u=c==null?o.len:o.pos+c;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${s}.Type`,value:Ie.codec().decode(o)};break}case 2:{yield{field:`${s}.Data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function r(o){return Y(o,t.codec())}t.encode=r;function n(o,c){return W(o,t.codec(),c)}t.decode=n;function i(o,c){return q(o,t.codec(),c)}t.stream=i})(kr||(kr={}));var As;(function(t){let e;t.codec=()=>(e==null&&(e=Z((o,c,s={})=>{s.lengthDelimited!==!1&&c.fork(),o.Type!=null&&(c.uint32(8),Ie.codec().encode(o.Type,c)),o.Data!=null&&(c.uint32(18),c.bytes(o.Data)),s.lengthDelimited!==!1&&c.ldelim()},(o,c,s={})=>{let a={},u=c==null?o.len:o.pos+c;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{a.Type=Ie.codec().decode(o);break}case 2:{a.Data=o.bytes();break}default:{o.skipType(l&7);break}}}return a},function*(o,c,s,a={}){let u=c==null?o.len:o.pos+c;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${s}.Type`,value:Ie.codec().decode(o)};break}case 2:{yield{field:`${s}.Data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function r(o){return Y(o,t.codec())}t.encode=r;function n(o,c){return W(o,t.codec(),c)}t.decode=n;function i(o,c){return q(o,t.codec(),c)}t.stream=i})(As||(As={}));function Ds(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function yt(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(`${r}expected number, got ${typeof t}`)}if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new RangeError(`${r}expected integer >= 0, got ${t}`)}}function Je(t,e,r=""){let n=Ds(t),i=t?.length,o=e!==void 0;if(!n||o&&i!==e){let c=r&&`"${r}" `,s=o?` of length ${e}`:"",a=n?`length=${i}`:`type=${typeof t}`,u=c+"expected Uint8Array"+s+", got "+a;throw n?new RangeError(u):new TypeError(u)}return t}function xn(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(yt(t.outputLen),yt(t.blockLen),t.outputLen<1)throw new Error('"outputLen" must be >= 1');if(t.blockLen<1)throw new Error('"blockLen" must be >= 1')}function qt(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function vn(t,e){Je(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function Dt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Sn(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Ye(t,e){return t<<32-e|t>>>e}var Wc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Bf=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function In(t){if(Je(t),Wc)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Bf[t[r]];return e}var nt={_0:48,_9:57,A:65,F:70,a:97,f:102};function zc(t){if(t>=nt._0&&t<=nt._9)return t-nt._0;if(t>=nt.A&&t<=nt.F)return t-(nt.A-10);if(t>=nt.a&&t<=nt.f)return t-(nt.a-10)}function Ls(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Wc)try{return Uint8Array.fromHex(t)}catch(i){throw i instanceof SyntaxError?new RangeError(i.message):i}let e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let c=zc(t.charCodeAt(o)),s=zc(t.charCodeAt(o+1));if(c===void 0||s===void 0){let a=t[o]+t[o+1];throw new RangeError('hex string expected, got non-hex character "'+a+'" at index '+o)}n[i]=c*16+s}return n}function Yc(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];Je(i),e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}function qc(t,e={}){let r=(i,o)=>t(o).update(i).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=i=>t(i),Object.assign(r,e),Object.freeze(r)}function Zc(t=32){yt(t,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var jc=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Xc(t,e,r){return t&e^~t&r}function Qc(t,e,r){return t&e^t&r^e&r}var Tn=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,i){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Sn(this.buffer)}update(e){qt(this),Je(e);let{view:r,buffer:n,blockLen:i}=this,o=e.length;for(let c=0;c<o;){let s=Math.min(i-this.pos,o-c);if(s===i){let a=Sn(e);for(;i<=o-c;c+=i)this.process(a,c);continue}n.set(e.subarray(c,c+s),this.pos),this.pos+=s,c+=s,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){qt(this),vn(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:c}=this;r[c++]=128,Dt(this.buffer.subarray(c)),this.padOffset>i-c&&(this.process(n,0),c=0);for(let f=c;f<i;f++)r[f]=0;n.setBigUint64(i-8,BigInt(this.length*8),o),this.process(n,0);let s=Sn(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=a/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)s.setUint32(4*f,l[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:c,pos:s}=this;return e.destroyed=c,e.finished=o,e.length=i,e.pos=s,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},ot=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Of=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),bt=new Uint32Array(64),Cs=class extends Tn{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:i,E:o,F:c,G:s,H:a}=this;return[e,r,n,i,o,c,s,a]}set(e,r,n,i,o,c,s,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=c|0,this.G=s|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)bt[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let d=bt[f-15],h=bt[f-2],y=Ye(d,7)^Ye(d,18)^d>>>3,v=Ye(h,17)^Ye(h,19)^h>>>10;bt[f]=v+bt[f-7]+y+bt[f-16]|0}let{A:n,B:i,C:o,D:c,E:s,F:a,G:u,H:l}=this;for(let f=0;f<64;f++){let d=Ye(s,6)^Ye(s,11)^Ye(s,25),h=l+d+Xc(s,a,u)+Of[f]+bt[f]|0,v=(Ye(n,2)^Ye(n,13)^Ye(n,22))+Qc(n,i,o)|0;l=u,u=a,a=s,s=c+h|0,c=o,o=i,i=n,n=h+v|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,c=c+this.D|0,s=s+this.E|0,a=a+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,i,o,c,s,a,u,l)}roundClean(){Dt(bt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Dt(this.buffer)}},Bs=class extends Cs{A=ot[0]|0;B=ot[1]|0;C=ot[2]|0;D=ot[3]|0;E=ot[4]|0;F=ot[5]|0;G=ot[6]|0;H=ot[7]|0;constructor(){super(32)}};var Jc=qc(()=>new Bs,jc(1));var Ca=_e(se("node:crypto"),1);var fe=(t,e,r)=>Je(t,e,r),_s=yt,ks=In,st=(...t)=>Yc(...t),Ln=t=>Ls(t),Ps=Ds,Ns=t=>Zc(t),Dn=BigInt(0),Os=BigInt(1);function Lt(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new TypeError(r+"expected boolean, got type="+typeof t)}return t}function Cn(t){if(typeof t=="bigint"){if(!An(t))throw new RangeError("positive bigint expected, got "+t)}else _s(t);return t}function Pr(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(r+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){let r=e&&`"${e}" `;throw new RangeError(r+"expected safe integer, got "+t)}}function Nr(t){let e=Cn(t).toString(16);return e.length&1?"0"+e:e}function ea(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Dn:BigInt("0x"+t)}function Zt(t){return ea(In(t))}function Rs(t){return ea(In(_f(Je(t)).reverse()))}function Bn(t,e){if(yt(e),e===0)throw new RangeError("zero length");t=Cn(t);let r=t.toString(16);if(r.length>e*2)throw new RangeError("number too large");return Ls(r.padStart(e*2,"0"))}function Us(t,e){return Bn(t,e).reverse()}function _f(t){return Uint8Array.from(fe(t))}var An=t=>typeof t=="bigint"&&Dn<=t;function kf(t,e,r){return An(t)&&An(e)&&An(r)&&e<=t&&t<r}function Fs(t,e,r,n){if(!kf(e,r,n))throw new RangeError("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function jt(t){if(t<Dn)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>Dn;t>>=Os,e+=1);return e}var Rr=t=>(Os<<BigInt(t))-Os;function ta(t,e,r){if(yt(t,"hashLen"),yt(e,"qByteLen"),typeof r!="function")throw new TypeError("hmacFn must be a function");let n=m=>new Uint8Array(m),i=Uint8Array.of(),o=Uint8Array.of(0),c=Uint8Array.of(1),s=1e3,a=n(t),u=n(t),l=0,f=()=>{a.fill(1),u.fill(0),l=0},d=(...m)=>r(u,st(a,...m)),h=(m=i)=>{u=d(o,m),a=d(),m.length!==0&&(u=d(c,m),a=d())},y=()=>{if(l++>=s)throw new Error("drbg: tried max amount of iterations");let m=0,E=[];for(;m<e;){a=d();let L=a.slice();E.push(L),m+=a.length}return st(...E)};return(m,E)=>{f(),h(m);let L;for(;(L=E(y()))===void 0;)h();return f(),L}}function Ct(t,e={},r={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function n(o,c,s){if(!s&&c!=="function"&&!Object.hasOwn(t,o))throw new TypeError(`param "${o}" is invalid: expected own property`);let a=t[o];if(s&&a===void 0)return;let u=typeof a;if(u!==c||a===null)throw new TypeError(`param "${o}" is invalid: expected ${c}, got ${u}`)}let i=(o,c)=>Object.entries(o).forEach(([s,a])=>n(s,a,c));i(e,!1),i(r,!0)}var be=BigInt(0),oe=BigInt(1),Bt=BigInt(2),sa=BigInt(3),ia=BigInt(4),ca=BigInt(5),Pf=BigInt(7),aa=BigInt(8),Nf=BigInt(9),ua=BigInt(16);function qe(t,e){if(e<=be)throw new Error("mod: expected positive modulus, got "+e);let r=t%e;return r>=be?r:e+r}function Re(t,e,r){if(e<be)throw new Error("pow2: expected non-negative exponent, got "+e);let n=t;for(;e-- >be;)n*=n,n%=r;return n}function ra(t,e){if(t===be)throw new Error("invert: expected non-zero number");if(e<=be)throw new Error("invert: expected positive modulus, got "+e);let r=qe(t,e),n=e,i=be,o=oe,c=oe,s=be;for(;r!==be;){let u=n/r,l=n-r*u,f=i-c*u,d=o-s*u;n=r,r=l,i=c,o=s,c=f,s=d}if(n!==oe)throw new Error("invert: does not exist");return qe(i,e)}function Ms(t,e,r){let n=t;if(!n.eql(n.sqr(e),r))throw new Error("Cannot find square root")}function la(t,e){let r=t,n=(r.ORDER+oe)/ia,i=r.pow(e,n);return Ms(r,i,e),i}function Rf(t,e){let r=t,n=(r.ORDER-ca)/aa,i=r.mul(e,Bt),o=r.pow(i,n),c=r.mul(e,o),s=r.mul(r.mul(c,Bt),o),a=r.mul(c,r.sub(s,r.ONE));return Ms(r,a,e),a}function Uf(t){let e=Xt(t),r=fa(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),c=(t+Pf)/ua;return((s,a)=>{let u=s,l=u.pow(a,c),f=u.mul(l,n),d=u.mul(l,i),h=u.mul(l,o),y=u.eql(u.sqr(f),a),v=u.eql(u.sqr(d),a);l=u.cmov(l,f,y),f=u.cmov(h,d,v);let m=u.eql(u.sqr(f),a),E=u.cmov(l,f,m);return Ms(u,E,a),E})}function fa(t){if(t<sa)throw new Error("sqrt is not defined for small field");let e=t-oe,r=0;for(;e%Bt===be;)e/=Bt,r++;let n=Bt,i=Xt(t);for(;na(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return la;let o=i.pow(n,e),c=(e+oe)/Bt;return function(a,u){let l=a;if(l.is0(u))return u;if(na(l,u)!==1)throw new Error("Cannot find square root");let f=r,d=l.mul(l.ONE,o),h=l.pow(u,e),y=l.pow(u,c);for(;!l.eql(h,l.ONE);){if(l.is0(h))return l.ZERO;let v=1,m=l.sqr(h);for(;!l.eql(m,l.ONE);)if(v++,m=l.sqr(m),v===f)throw new Error("Cannot find square root");let E=oe<<BigInt(f-v-1),L=l.pow(d,E);f=v,d=l.sqr(L),h=l.mul(h,d),y=l.mul(y,L)}return y}}function Ff(t){return t%ia===sa?la:t%aa===ca?Rf:t%ua===Nf?Uf(t):fa(t)}var Mf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function $s(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=Mf.reduce((n,i)=>(n[i]="function",n),e);if(Ct(t,r),Pr(t.BYTES,"BYTES"),Pr(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=oe)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function $f(t,e,r){let n=t;if(r<be)throw new Error("invalid exponent, negatives unsupported");if(r===be)return n.ONE;if(r===oe)return e;let i=n.ONE,o=e;for(;r>be;)r&oe&&(i=n.mul(i,o)),o=n.sqr(o),r>>=oe;return i}function _n(t,e,r=!1){let n=t,i=new Array(e.length).fill(r?n.ZERO:void 0),o=e.reduce((s,a,u)=>n.is0(a)?s:(i[u]=s,n.mul(s,a)),n.ONE),c=n.inv(o);return e.reduceRight((s,a,u)=>n.is0(a)?s:(i[u]=n.mul(s,i[u]),n.mul(s,a)),c),i}function na(t,e){let r=t,n=(r.ORDER-oe)/Bt,i=r.pow(e,n),o=r.eql(i,r.ONE),c=r.eql(i,r.ZERO),s=r.eql(i,r.neg(r.ONE));if(!o&&!c&&!s)throw new Error("invalid Legendre symbol result");return o?1:c?0:-1}function Kf(t,e){if(e!==void 0&&_s(e),t<=be)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let r=jt(t);if(e!==void 0&&e<r)throw new Error(`invalid n length: expected bit length (${r}) >= n.length (${e})`);let n=e!==void 0?e:r,i=Math.ceil(n/8);return{nBitLength:n,nByteLength:i}}var oa=new WeakMap,On=class{ORDER;BITS;BYTES;isLE;ZERO=be;ONE=oe;_lengths;_mod;constructor(e,r={}){if(e<=oe)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:i,nByteLength:o}=Kf(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=i,this.BYTES=o,Object.freeze(this)}create(e){return qe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return be<=e&&e<this.ORDER}is0(e){return e===be}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&oe)===oe}neg(e){return qe(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return qe(e*e,this.ORDER)}add(e,r){return qe(e+r,this.ORDER)}sub(e,r){return qe(e-r,this.ORDER)}mul(e,r){return qe(e*r,this.ORDER)}pow(e,r){return $f(this,e,r)}div(e,r){return qe(e*ra(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return ra(e,this.ORDER)}sqrt(e){let r=oa.get(this);return r||oa.set(this,r=Ff(this.ORDER)),r(this,e)}toBytes(e){return this.isLE?Us(e,this.BYTES):Bn(e,this.BYTES)}fromBytes(e,r=!1){fe(e);let{_lengths:n,BYTES:i,isLE:o,ORDER:c,_mod:s}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>i)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(i);u.set(e,o?0:u.length-e.length),e=u}if(e.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+e.length);let a=o?Rs(e):Zt(e);if(s&&(a=qe(a,c)),!r&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(e){return _n(this,e)}cmov(e,r,n){return Lt(n,"condition"),n?r:e}};Object.freeze(On.prototype);function Xt(t,e={}){return new On(t,e)}function da(t){if(typeof t!="bigint")throw new Error("field order must be bigint");if(t<=oe)throw new Error("field order must be greater than 1");let e=jt(t-oe);return Math.ceil(e/8)}function Ks(t){let e=da(t);return e+Math.ceil(e/2)}function Hs(t,e,r=!1){fe(t);let n=t.length,i=da(e),o=Math.max(Ks(e),16);if(n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let c=r?Rs(t):Zt(t),s=qe(c,e-oe)+oe;return r?Us(s,i):Bn(s,i)}var Qt=BigInt(0),Ot=BigInt(1);function Ur(t,e){let r=e.negate();return t?r:e}function Ws(t,e){let r=_n(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function ya(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Vs(t,e){ya(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=Rr(t),c=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:c}}function ha(t,e,r){let{windowSize:n,mask:i,maxNumber:o,shiftBy:c}=r,s=Number(t&i),a=t>>c;s>n&&(s-=o,a+=Ot);let u=e*n,l=u+Math.abs(s)-1,f=s===0,d=s<0,h=e%2!==0;return{nextN:a,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}var Gs=new WeakMap,ba=new WeakMap;function zs(t){return ba.get(t)||1}function pa(t){if(t!==Qt)throw new Error("invalid wNAF")}var kn=class{BASE;ZERO;Fn;bits;constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let i=e;for(;r>Qt;)r&Ot&&(n=n.add(i)),i=i.double(),r>>=Ot;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=Vs(r,this.bits),o=[],c=e,s=c;for(let a=0;a<n;a++){s=c,o.push(s);for(let u=1;u<i;u++)s=s.add(c),o.push(s);c=s.double()}return o}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let i=this.ZERO,o=this.BASE,c=Vs(e,this.bits);for(let s=0;s<c.windows;s++){let{nextN:a,offset:u,isZero:l,isNeg:f,isNegF:d,offsetF:h}=ha(n,s,c);n=a,l?o=o.add(Ur(d,r[h])):i=i.add(Ur(f,r[u]))}return pa(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=Vs(e,this.bits);for(let c=0;c<o.windows&&n!==Qt;c++){let{nextN:s,offset:a,isZero:u,isNeg:l}=ha(n,c,o);if(n=s,!u){let f=r[a];i=i.add(l?f.negate():f)}}return pa(n),i}getPrecomputes(e,r,n){let i=Gs.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),Gs.set(r,i))),i}cached(e,r,n){let i=zs(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=zs(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){ya(r,this.bits),ba.set(e,r),Gs.delete(e)}hasCache(e){return zs(e)!==1}};function ga(t,e,r,n){let i=e,o=t.ZERO,c=t.ZERO;for(;r>Qt||n>Qt;)r&Ot&&(o=o.add(i)),n&Ot&&(c=c.add(i)),i=i.double(),r>>=Ot,n>>=Ot;return{p1:o,p2:c}}function ma(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return $s(e),e}else return Xt(t,{isLE:r})}function wa(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let a of["p","n","h"]){let u=e[a];if(!(typeof u=="bigint"&&u>Qt))throw new Error(`CURVE.${a} must be positive bigint`)}let i=ma(e.p,r.Fp,n),o=ma(e.n,r.Fn,n),s=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let a of s)if(!i.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:o}}function Ea(t,e){return function(n){let i=t(n);return{secretKey:i,publicKey:e(i)}}}var Pn=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(xn(e),Je(r,void 0,"key"),this.iHash=e.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 n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),Dt(i)}update(e){return qt(this),this.iHash.update(e),this}digestInto(e){qt(this),vn(e,this),this.finished=!0;let r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:i,destroyed:o,blockLen:c,outputLen:s}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=c,e.outputLen=s,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},xa=(()=>{let t=((e,r,n)=>new Pn(e,r).update(n).digest());return t.create=(e,r)=>new Pn(e,r),t})();var va=(t,e)=>(t+(t>=0?e:-e)/Sa)/e;function Hf(t,e,r){Fs("scalar",t,et,r);let[[n,i],[o,c]]=e,s=va(c*t,r),a=va(-i*t,r),u=t-s*n-a*o,l=-s*i-a*c,f=u<et,d=l<et;f&&(u=-u),d&&(l=-l);let h=Rr(Math.ceil(jt(r)/2))+gt;if(u<et||u>=h||l<et||l>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:u,k2neg:d,k2:l}}function qs(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Ys(t,e){Ct(t);let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Lt(r.lowS,"lowS"),Lt(r.prehash,"prehash"),r.format!==void 0&&qs(r.format),r}var Zs=class extends Error{constructor(e=""){super(e)}},Ze={Err:Zs,_tlv:{encode:(t,e)=>{let{Err:r}=Ze;if(Pr(t,"tag"),t<0||t>255)throw new r("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,i=Nr(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?Nr(i.length/2|128):"";return Nr(t)+o+i+e},decode(t,e){let{Err:r}=Ze;e=fe(e,void 0,"DER data");let n=0;if(t<0||t>255)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let i=e[n++],o=!!(i&128),c=0;if(!o)c=i;else{let a=i&127;if(!a)throw new r("tlv.decode(long): indefinite length not supported");if(a>4)throw new r("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+a);if(u.length!==a)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let l of u)c=c<<8|l;if(n+=a,c<128)throw new r("tlv.decode(long): not minimal encoding")}let s=e.subarray(n,n+c);if(s.length!==c)throw new r("tlv.decode: wrong value length");return{v:s,l:e.subarray(n+c)}}},_int:{encode(t){let{Err:e}=Ze;if(Cn(t),t<et)throw new e("integer: negative integers are not allowed");let r=Nr(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=Ze;if(t.length<1)throw new e("invalid signature integer: empty");if(t[0]&128)throw new e("invalid signature integer: negative");if(t.length>1&&t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Zt(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=Ze,i=fe(t,void 0,"signature"),{v:o,l:c}=n.decode(48,i);if(c.length)throw new e("invalid signature: left bytes after parsing");let{v:s,l:a}=n.decode(2,o),{v:u,l}=n.decode(2,a);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(s),s:r.decode(u)}},hexFromSig(t){let{_tlv:e,_int:r}=Ze,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}};Object.freeze(Ze._tlv);Object.freeze(Ze._int);Object.freeze(Ze);var et=BigInt(0),gt=BigInt(1),Sa=BigInt(2),Nn=BigInt(3),Vf=BigInt(4);function Ia(t,e={}){let r=wa("weierstrass",t,e),n=r.Fp,i=r.Fn,o=r.CURVE,{h:c,n:s}=o;Ct(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:a,allowInfinityPoint:u}=e;if(a&&(!n.is0(o.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Aa(n,i);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(J,b,T){if(u&&b.is0())return Uint8Array.of(0);let{x:D,y:g}=b.toAffine(),p=n.toBytes(D);if(Lt(T,"isCompressed"),T){f();let w=!n.isOdd(g);return st(Ta(w),p)}else return st(Uint8Array.of(4),p,n.toBytes(g))}function h(J){fe(J,void 0,"Point");let{publicKey:b,publicKeyUncompressed:T}=l,D=J.length,g=J[0],p=J.subarray(1);if(u&&D===1&&g===0)return{x:n.ZERO,y:n.ZERO};if(D===b&&(g===2||g===3)){let w=n.fromBytes(p);if(!n.isValid(w))throw new Error("bad point: is not on curve, wrong x");let S=m(w),x;try{x=n.sqrt(S)}catch($){let F=$ instanceof Error?": "+$.message:"";throw new Error("bad point: is not on curve, sqrt error"+F)}f();let A=n.isOdd(x);return(g&1)===1!==A&&(x=n.neg(x)),{x:w,y:x}}else if(D===T&&g===4){let w=n.BYTES,S=n.fromBytes(p.subarray(0,w)),x=n.fromBytes(p.subarray(w,w*2));if(!E(S,x))throw new Error("bad point: is not on curve");return{x:S,y:x}}else throw new Error(`bad point: got length ${D}, expected compressed=${b} or uncompressed=${T}`)}let y=e.toBytes===void 0?d:e.toBytes,v=e.fromBytes===void 0?h:e.fromBytes;function m(J){let b=n.sqr(J),T=n.mul(b,J);return n.add(n.add(T,n.mul(J,o.a)),o.b)}function E(J,b){let T=n.sqr(b),D=m(J);return n.eql(T,D)}if(!E(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let L=n.mul(n.pow(o.a,Nn),Vf),P=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(L,P)))throw new Error("bad curve params: a or b");function M(J,b,T=!1){if(!n.isValid(b)||T&&n.is0(b))throw new Error(`bad point coordinate ${J}`);return b}function _(J){if(!(J instanceof B))throw new Error("Weierstrass Point expected")}function ce(J){if(!a||!a.basises)throw new Error("no endo");return Hf(J,a.basises,i.ORDER)}function X(J,b,T,D,g){return T=new B(n.mul(T.X,J),T.Y,T.Z),b=Ur(D,b),T=Ur(g,T),b.add(T)}class B{static BASE=new B(o.Gx,o.Gy,n.ONE);static ZERO=new B(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=i;X;Y;Z;constructor(b,T,D){this.X=M("x",b),this.Y=M("y",T,!0),this.Z=M("z",D),Object.freeze(this)}static CURVE(){return o}static fromAffine(b){let{x:T,y:D}=b||{};if(!b||!n.isValid(T)||!n.isValid(D))throw new Error("invalid affine point");if(b instanceof B)throw new Error("projective point not allowed");return n.is0(T)&&n.is0(D)?B.ZERO:new B(T,D,n.ONE)}static fromBytes(b){let T=B.fromAffine(v(fe(b,void 0,"point")));return T.assertValidity(),T}static fromHex(b){return B.fromBytes(Ln(b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,T=!0){return He.createCache(this,b),T||this.multiply(Nn),this}assertValidity(){let b=this;if(b.is0()){if(e.allowInfinityPoint&&n.is0(b.X)&&n.eql(b.Y,n.ONE)&&n.is0(b.Z))return;throw new Error("bad point: ZERO")}let{x:T,y:D}=b.toAffine();if(!n.isValid(T)||!n.isValid(D))throw new Error("bad point: x or y not field elements");if(!E(T,D))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){_(b);let{X:T,Y:D,Z:g}=this,{X:p,Y:w,Z:S}=b,x=n.eql(n.mul(T,S),n.mul(p,g)),A=n.eql(n.mul(D,S),n.mul(w,g));return x&&A}negate(){return new B(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:T}=o,D=n.mul(T,Nn),{X:g,Y:p,Z:w}=this,S=n.ZERO,x=n.ZERO,A=n.ZERO,C=n.mul(g,g),$=n.mul(p,p),F=n.mul(w,w),k=n.mul(g,p);return k=n.add(k,k),A=n.mul(g,w),A=n.add(A,A),S=n.mul(b,A),x=n.mul(D,F),x=n.add(S,x),S=n.sub($,x),x=n.add($,x),x=n.mul(S,x),S=n.mul(k,S),A=n.mul(D,A),F=n.mul(b,F),k=n.sub(C,F),k=n.mul(b,k),k=n.add(k,A),A=n.add(C,C),C=n.add(A,C),C=n.add(C,F),C=n.mul(C,k),x=n.add(x,C),F=n.mul(p,w),F=n.add(F,F),C=n.mul(F,k),S=n.sub(S,C),A=n.mul(F,$),A=n.add(A,A),A=n.add(A,A),new B(S,x,A)}add(b){_(b);let{X:T,Y:D,Z:g}=this,{X:p,Y:w,Z:S}=b,x=n.ZERO,A=n.ZERO,C=n.ZERO,$=o.a,F=n.mul(o.b,Nn),k=n.mul(T,p),pe=n.mul(D,w),me=n.mul(g,S),ye=n.add(T,D),ee=n.add(p,w);ye=n.mul(ye,ee),ee=n.add(k,pe),ye=n.sub(ye,ee),ee=n.add(T,g);let De=n.add(p,S);return ee=n.mul(ee,De),De=n.add(k,me),ee=n.sub(ee,De),De=n.add(D,g),x=n.add(w,S),De=n.mul(De,x),x=n.add(pe,me),De=n.sub(De,x),C=n.mul($,ee),x=n.mul(F,me),C=n.add(x,C),x=n.sub(pe,C),C=n.add(pe,C),A=n.mul(x,C),pe=n.add(k,k),pe=n.add(pe,k),me=n.mul($,me),ee=n.mul(F,ee),pe=n.add(pe,me),me=n.sub(k,me),me=n.mul($,me),ee=n.add(ee,me),k=n.mul(pe,ee),A=n.add(A,k),k=n.mul(De,ee),x=n.mul(ye,x),x=n.sub(x,k),k=n.mul(ye,pe),C=n.mul(De,C),C=n.add(C,k),new B(x,A,C)}subtract(b){return _(b),this.add(b.negate())}is0(){return this.equals(B.ZERO)}multiply(b){let{endo:T}=e;if(!i.isValidNot0(b))throw new RangeError("invalid scalar: out of range");let D,g,p=w=>He.cached(this,w,S=>Ws(B,S));if(T){let{k1neg:w,k1:S,k2neg:x,k2:A}=ce(b),{p:C,f:$}=p(S),{p:F,f:k}=p(A);g=$.add(k),D=X(T.beta,C,F,w,x)}else{let{p:w,f:S}=p(b);D=w,g=S}return Ws(B,[D,g])[0]}multiplyUnsafe(b){let{endo:T}=e,D=this,g=b;if(!i.isValid(g))throw new RangeError("invalid scalar: out of range");if(g===et||D.is0())return B.ZERO;if(g===gt)return D;if(He.hasCache(this))return this.multiply(g);if(T){let{k1neg:p,k1:w,k2neg:S,k2:x}=ce(g),{p1:A,p2:C}=ga(B,D,w,x);return X(T.beta,A,C,p,S)}else return He.unsafe(D,g)}toAffine(b){let T=this,D=b,{X:g,Y:p,Z:w}=T;if(n.eql(w,n.ONE))return{x:g,y:p};let S=T.is0();D==null&&(D=S?n.ONE:n.inv(w));let x=n.mul(g,D),A=n.mul(p,D),C=n.mul(w,D);if(S)return{x:n.ZERO,y:n.ZERO};if(!n.eql(C,n.ONE))throw new Error("invZ was invalid");return{x,y:A}}isTorsionFree(){let{isTorsionFree:b}=e;return c===gt?!0:b?b(B,this):He.unsafe(this,s).is0()}clearCofactor(){let{clearCofactor:b}=e;return c===gt?this:b?b(B,this):this.multiplyUnsafe(c)}isSmallOrder(){return c===gt?this.is0():this.clearCofactor().is0()}toBytes(b=!0){return Lt(b,"isCompressed"),this.assertValidity(),y(B,this,b)}toHex(b=!0){return ks(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let Ae=i.BITS,He=new kn(B,e.endo?Math.ceil(Ae/2):Ae);return Ae>=8&&B.BASE.precompute(8),Object.freeze(B.prototype),Object.freeze(B),B}function Ta(t){return Uint8Array.of(t?2:3)}function Aa(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Gf(t,e={}){let{Fn:r}=t,n=e.randomBytes===void 0?Ns:e.randomBytes,i=Object.assign(Aa(t.Fp,r),{seed:Math.max(Ks(r.ORDER),16)});function o(h){try{let y=r.fromBytes(h);return r.isValidNot0(y)}catch{return!1}}function c(h,y){let{publicKey:v,publicKeyUncompressed:m}=i;try{let E=h.length;return y===!0&&E!==v||y===!1&&E!==m?!1:!!t.fromBytes(h)}catch{return!1}}function s(h){return h=h===void 0?n(i.seed):h,Hs(fe(h,i.seed,"seed"),r.ORDER)}function a(h,y=!0){return t.BASE.multiply(r.fromBytes(h)).toBytes(y)}function u(h){let{secretKey:y,publicKey:v,publicKeyUncompressed:m}=i,E=r._lengths;if(!Ps(h))return;let L=fe(h,void 0,"key").length,P=L===v||L===m,M=L===y||!!E?.includes(L);if(!(P&&M))return P}function l(h,y,v=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(y)===!1)throw new Error("second arg must be public key");let m=r.fromBytes(h);return t.fromBytes(y).multiply(m).toBytes(v)}let f={isValidSecretKey:o,isValidPublicKey:c,randomSecretKey:s},d=Ea(s,a);return Object.freeze(f),Object.freeze(i),Object.freeze({getPublicKey:a,getSharedSecret:l,keygen:d,Point:t,utils:f,lengths:i})}function Da(t,e,r={}){let n=e;xn(n),Ct(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let i=r.randomBytes===void 0?Ns:r.randomBytes,o=r.hmac===void 0?(g,p)=>xa(n,g,p):r.hmac,{Fp:c,Fn:s}=t,{ORDER:a,BITS:u}=s,{keygen:l,getPublicKey:f,getSharedSecret:d,utils:h,lengths:y}=Gf(t,r),v={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},m=a*Sa+gt<c.ORDER;function E(g){let p=a>>gt;return g>p}function L(g,p){if(!s.isValidNot0(p))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return p}function P(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function M(g,p){qs(p);let w=y.signature,S=p==="compact"?w:p==="recovered"?w+1:void 0;return fe(g,S)}class _{r;s;recovery;constructor(p,w,S){if(this.r=L("r",p),this.s=L("s",w),S!=null){if(P(),![0,1,2,3].includes(S))throw new Error("invalid recovery id");this.recovery=S}Object.freeze(this)}static fromBytes(p,w=v.format){M(p,w);let S;if(w==="der"){let{r:$,s:F}=Ze.toSig(fe(p));return new _($,F)}w==="recovered"&&(S=p[0],w="compact",p=p.subarray(1));let x=y.signature/2,A=p.subarray(0,x),C=p.subarray(x,x*2);return new _(s.fromBytes(A),s.fromBytes(C),S)}static fromHex(p,w){return this.fromBytes(Ln(p),w)}assertRecovery(){let{recovery:p}=this;if(p==null)throw new Error("invalid recovery id: must be present");return p}addRecoveryBit(p){return new _(this.r,this.s,p)}recoverPublicKey(p){let{r:w,s:S}=this,x=this.assertRecovery(),A=x===2||x===3?w+a:w;if(!c.isValid(A))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let C=c.toBytes(A),$=t.fromBytes(st(Ta((x&1)===0),C)),F=s.inv(A),k=X(fe(p,void 0,"msgHash")),pe=s.create(-k*F),me=s.create(S*F),ye=t.BASE.multiplyUnsafe(pe).add($.multiplyUnsafe(me));if(ye.is0())throw new Error("invalid recovery: point at infinify");return ye.assertValidity(),ye}hasHighS(){return E(this.s)}toBytes(p=v.format){if(qs(p),p==="der")return Ln(Ze.hexFromSig(this));let{r:w,s:S}=this,x=s.toBytes(w),A=s.toBytes(S);return p==="recovered"?(P(),st(Uint8Array.of(this.assertRecovery()),x,A)):st(x,A)}toHex(p){return ks(this.toBytes(p))}}Object.freeze(_.prototype),Object.freeze(_);let ce=r.bits2int===void 0?function(p){if(p.length>8192)throw new Error("input is too large");let w=Zt(p),S=p.length*8-u;return S>0?w>>BigInt(S):w}:r.bits2int,X=r.bits2int_modN===void 0?function(p){return s.create(ce(p))}:r.bits2int_modN,B=Rr(u);function Ae(g){return Fs("num < 2^"+u,g,et,B),s.toBytes(g)}function He(g,p){return fe(g,void 0,"message"),p?fe(n(g),void 0,"prehashed message"):g}function J(g,p,w){let{lowS:S,prehash:x,extraEntropy:A}=Ys(w,v);g=He(g,x);let C=X(g),$=s.fromBytes(p);if(!s.isValidNot0($))throw new Error("invalid private key");let F=[Ae($),Ae(C)];if(A!=null&&A!==!1){let ye=A===!0?i(y.secretKey):A;F.push(fe(ye,void 0,"extraEntropy"))}let k=st(...F),pe=C;function me(ye){let ee=ce(ye);if(!s.isValidNot0(ee))return;let De=s.inv(ee),Rt=t.BASE.multiply(ee).toAffine(),ar=s.create(Rt.x);if(ar===et)return;let zr=s.create(De*s.create(pe+ar*$));if(zr===et)return;let Fi=(Rt.x===ar?0:2)|Number(Rt.y>),Mi=zr;return S&&E(zr)&&(Mi=s.neg(zr),Fi^=1),new _(ar,Mi,m?void 0:Fi)}return{seed:k,k2sig:me}}function b(g,p,w={}){let{seed:S,k2sig:x}=J(g,p,w);return ta(n.outputLen,s.BYTES,o)(S,x).toBytes(w.format)}function T(g,p,w,S={}){let{lowS:x,prehash:A,format:C}=Ys(S,v);if(w=fe(w,void 0,"publicKey"),p=He(p,A),!Ps(g)){let $=g instanceof _?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+$)}M(g,C);try{let $=_.fromBytes(g,C),F=t.fromBytes(w);if(x&&$.hasHighS())return!1;let{r:k,s:pe}=$,me=X(p),ye=s.inv(pe),ee=s.create(me*ye),De=s.create(k*ye),Rt=t.BASE.multiplyUnsafe(ee).add(F.multiplyUnsafe(De));return Rt.is0()?!1:s.create(Rt.x)===k}catch{return!1}}function D(g,p,w={}){let{prehash:S}=Ys(w,v);return p=He(p,S),_.fromBytes(g,"recovered").recoverPublicKey(p).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:d,utils:h,lengths:y,Point:t,sign:b,verify:T,recoverPublicKey:D,Signature:_,hash:n})}var Xs={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},zf={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var La=BigInt(2);function Wf(t){let e=Xs.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),c=BigInt(23),s=BigInt(44),a=BigInt(88),u=t*t*t%e,l=u*u*t%e,f=Re(l,r,e)*l%e,d=Re(f,r,e)*l%e,h=Re(d,La,e)*u%e,y=Re(h,i,e)*h%e,v=Re(y,o,e)*y%e,m=Re(v,s,e)*v%e,E=Re(m,a,e)*m%e,L=Re(E,s,e)*v%e,P=Re(L,r,e)*l%e,M=Re(P,c,e)*y%e,_=Re(M,n,e)*u%e,ce=Re(_,La,e);if(!js.eql(js.sqr(ce),t))throw new Error("Cannot find square root");return ce}var js=Xt(Xs.p,{sqrt:Wf}),Yf=Ia(Xs,{Fp:js,endo:zf}),Fr=Da(Yf,Jc);var Rn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}};function Ba(t,e,r,n){n?.signal?.throwIfAborted();let i=Ca.default.createHash("sha256");if(r instanceof Uint8Array)i.update(r);else for(let c of r)i.update(c);let o=i.digest();try{return Fr.verify(e,o,t,{prehash:!1,format:"der"})}catch(c){throw new Rn(String(c))}}var Un=class{type="secp256k1";raw;_key;constructor(e){this._key=_a(e),this.raw=Oa(this._key)}toMultihash(){return Ge.digest(mt(this))}toCID(){return ie.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ne(this.raw,e.raw)}verify(e,r,n){return Ba(this._key,r,e,n)}};function ka(t){return new Un(t)}function Oa(t){return Fr.Point.fromBytes(t).toBytes()}function _a(t){try{return Fr.Point.fromBytes(t),t}catch(e){throw new an(String(e))}}function Pa(t){let{Type:e,Data:r}=kr.decode(t.digest),n=r??new Uint8Array;switch(e){case Ie.Ed25519:return Gc(n);case Ie.secp256k1:return ka(n);case Ie.ECDSA:return Fc(n);default:throw new Cr}}function mt(t){return kr.encode({Type:Ie[t.type],Data:t.raw})}var Na=Symbol.for("nodejs.util.inspect.custom"),qf=114,Mr=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[bs]=!0;toString(){return this.string==null&&(this.string=te.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ie.createV1(qf,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Ne(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Ne(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Na](){return`PeerId(${this.toString()})`}},Fn=class extends Mr{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Mn=class extends Mr{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},$n=class extends Mr{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Zf=2336,Kn=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ge.digest(xe(this.url))}[Na](){return`PeerId(${this.url})`}[bs]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ie.createV1(Zf,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=ne(e)),e.toString()===this.toString())}};function Jt(t){if(Xf(t))return new Fn({multihash:t});if(jf(t))try{let e=Pa(t);if(e.type==="Ed25519")return new Mn({multihash:t,publicKey:e});if(e.type==="secp256k1")return new $n({multihash:t,publicKey:e})}catch{let r=ne(t.digest);return new Kn(new URL(r))}throw new ln("Supplied PeerID Multihash is invalid")}function jf(t){return t.code===Ge.code}function Xf(t){return t.code===ss.code}var bu=_e(se("net"),1);var ge=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},it=class extends Error{static name="ValidationError";name="ValidationError"},Hn=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Vn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Ue=se("node:net");function Js(t){return e=>ne(e,t)}function ei(t){return e=>xe(e,t)}function er(t){return new DataView(t.buffer).getUint16(t.byteOffset).toString()}function _t(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof t=="string"?parseInt(t):t),new Uint8Array(e)}function Ra(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let r=xe(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=_t(n);return Qe([r,i],r.length+i.length)}function Ua(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let r=je.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=_t(n);return Qe([r,i],r.length+i.length)}function ti(t){let e=t.subarray(0,t.length-2),r=t.subarray(t.length-2),n=ne(e,"base32"),i=er(r);return`${n}:${i}`}var ri=function(t){t=t.toString().trim();let e=new Uint8Array(4);return t.split(/\./g).forEach((r,n)=>{let i=parseInt(r,10);if(isNaN(i)||i<0||i>255)throw new ge("Invalid byte value in IP address");e[n]=i}),e},Fa=function(t){let e=0;t=t.toString().trim();let r=t.split(":",8),n;for(n=0;n<r.length;n++){let o=(0,Ue.isIPv4)(r[n]),c;o&&(c=ri(r[n]),r[n]=ne(c.subarray(0,2),"base16")),c!=null&&++n<8&&r.splice(n,0,ne(c.subarray(2,4),"base16"))}if(r[0]==="")for(;r.length<8;)r.unshift("0");else if(r[r.length-1]==="")for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&r[n]!=="";n++);let o=[n,1];for(n=9-r.length;n>0;n--)o.push("0");r.splice.apply(r,o)}let i=new Uint8Array(e+16);for(n=0;n<r.length;n++){r[n]===""&&(r[n]="0");let o=parseInt(r[n],16);if(isNaN(o)||o<0||o>65535)throw new ge("Invalid byte value in IP address");i[e++]=o>>8&255,i[e++]=o&255}return i},Ma=function(t){if(t.byteLength!==4)throw new ge("IPv4 address was incorrect length");let e=[];for(let r=0;r<t.byteLength;r++)e.push(t[r]);return e.join(".")},$a=function(t){if(t.byteLength!==16)throw new ge("IPv6 address was incorrect length");let e=[];for(let n=0;n<t.byteLength;n+=2){let i=t[n],o=t[n+1],c=`${i.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(c)}let r=e.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new ge(`Invalid IPv6 address "${r}"`)}};function Ka(t){try{let e=new URL(`http://[${t}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new ge(`Invalid IPv6 address "${t}"`)}}var Qs=Object.values(pr).map(t=>t.decoder),Qf=(function(){let t=Qs[0].or(Qs[1]);return Qs.slice(2).forEach(e=>t=t.or(e)),t})();function Ha(t){return Qf.decode(t)}function Va(t){return e=>t.encoder.encode(e)}function Jf(t){if(parseInt(t).toString()!==t)throw new it("Value must be an integer")}function ed(t){if(t<0)throw new it("Value must be a positive integer, or zero")}function td(t){return e=>{if(e>t)throw new it(`Value must be smaller than or equal to ${t}`)}}function rd(...t){return e=>{for(let r of t)r(e)}}var $r=rd(Jf,ed,td(65535));var de=-1,ni=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let r;if(typeof e=="string"?r=this.protocolsByName.get(e):r=this.protocolsByCode.get(e),r==null)throw new Vn(`Protocol ${e} was unknown`);return r}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(r=>{this.protocolsByName.set(r,e)})}removeProtocol(e){let r=this.protocolsByCode.get(e);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},at=new ni,yd=[{code:4,name:"ip4",size:32,valueToBytes:ri,bytesToValue:Ma,validate:t=>{if(!(0,Ue.isIPv4)(t))throw new it(`Invalid IPv4 address "${t}"`)}},{code:6,name:"tcp",size:16,valueToBytes:_t,bytesToValue:er,validate:$r},{code:273,name:"udp",size:16,valueToBytes:_t,bytesToValue:er,validate:$r},{code:33,name:"dccp",size:16,valueToBytes:_t,bytesToValue:er,validate:$r},{code:41,name:"ip6",size:128,valueToBytes:Fa,bytesToValue:$a,stringToValue:Ka,validate:t=>{if(!(0,Ue.isIPv6)(t))throw new it(`Invalid IPv6 address "${t}"`)}},{code:42,name:"ip6zone",size:de},{code:43,name:"ipcidr",size:8,bytesToValue:Js("base10"),valueToBytes:ei("base10")},{code:53,name:"dns",size:de},{code:54,name:"dns4",size:de},{code:55,name:"dns6",size:de},{code:56,name:"dnsaddr",size:de},{code:132,name:"sctp",size:16,valueToBytes:_t,bytesToValue:er,validate:$r},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:de,stringToValue:t=>decodeURIComponent(t),valueToString:t=>encodeURIComponent(t)},{code:421,name:"p2p",aliases:["ipfs"],size:de,bytesToValue:Js("base58btc"),valueToBytes:t=>t.startsWith("Q")||t.startsWith("1")?ei("base58btc")(t):ie.parse(t).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:ti,valueToBytes:Ra},{code:445,name:"onion3",size:296,bytesToValue:ti,valueToBytes:Ua},{code:446,name:"garlic64",size:de},{code:447,name:"garlic32",size:de},{code:448,name:"tls"},{code:449,name:"sni",size:de},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:de,bytesToValue:Va(jo),valueToBytes:Ha},{code:480,name:"http"},{code:481,name:"http-path",size:de,stringToValue:t=>`/${decodeURIComponent(t)}`,valueToString:t=>encodeURIComponent(t.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:de}];yd.forEach(t=>{at.addProtocol(t)});function Ga(t){let e=[],r=0;for(;r<t.length;){let n=xt(t,r),i=at.getProtocol(n),o=ue(n),c=bd(i,t,r+o),s=0;c>0&&i.size===de&&(s=ue(c));let a=o+s+c,u={code:n,name:i.name,bytes:t.subarray(r,r+a)};if(c>0){let l=r+o+s,f=t.subarray(l,l+c);u.value=i.bytesToValue?.(f)??ne(f)}e.push(u),r+=a}return e}function za(t){let e=0,r=[];for(let n of t){if(n.bytes==null){let i=at.getProtocol(n.code),o=ue(n.code),c,s=0,a=0;n.value!=null&&(c=i.valueToBytes?.(n.value)??xe(n.value),s=c.byteLength,i.size===de&&(a=ue(s)));let u=new Uint8Array(o+a+s),l=0;Ut(n.code,u,l),l+=o,c!=null&&(i.size===de&&(Ut(s,u,l),l+=a),u.set(c,l)),n.bytes=u}r.push(n.bytes),e+=n.bytes.byteLength}return Qe(r,e)}function Wa(t){if(t.charAt(0)!=="/")throw new ge('String multiaddr must start with "/"');let e=[],r="protocol",n="",i="";for(let o=1;o<t.length;o++){let c=t.charAt(o);c!=="/"&&(r==="protocol"?i+=t.charAt(o):n+=t.charAt(o));let s=o===t.length-1;if(c==="/"||s){let a=at.getProtocol(i);if(r==="protocol"){if(a.size==null||a.size===0){e.push({code:a.code,name:a.name}),n="",i="",r="protocol";continue}else if(s)throw new ge(`Component ${i} was missing value`);r="value"}else if(r==="value"){let u={code:a.code,name:a.name};if(a.size!=null&&a.size!==0){if(n==="")throw new ge(`Component ${i} was missing value`);u.value=a.stringToValue?.(n)??n}e.push(u),n="",i="",r="protocol"}}}if(i!==""&&n!=="")throw new ge("Incomplete multiaddr");return e}function Ya(t){return`/${t.flatMap(e=>{if(e.value==null)return e.name;let r=at.getProtocol(e.code);if(r==null)throw new ge(`Unknown protocol code ${e.code}`);return[e.name,r.valueToString?.(e.value)??e.value]}).join("/")}`}function bd(t,e,r){return t.size==null||t.size===0?0:t.size>0?t.size/8:xt(e,r)}var gd=Symbol.for("nodejs.util.inspect.custom"),yi=Symbol.for("@multiformats/multiaddr");function wd(t){if(t==null&&(t="/"),qa(t))return t.getComponents();if(t instanceof Uint8Array)return Ga(t);if(typeof t=="string")return t=t.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),t===""&&(t="/"),Wa(t);if(Array.isArray(t))return t;throw new ge("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Qn=class t{[yi]=!0;#e;#t;#r;constructor(e="/",r={}){this.#e=wd(e),r.validate!==!1&&Ed(this)}get bytes(){return this.#r==null&&(this.#r=za(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Ya(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let r=new t(e);return new t([...this.#e,...r.getComponents()],{validate:!1})}decapsulate(e){let r=e.toString(),n=this.toString(),i=n.lastIndexOf(r);if(i<0)throw new Hn(`Address ${this.toString()} does not contain subaddress: ${r}`);return new t(n.slice(0,i),{validate:!1})}decapsulateCode(e){let r;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){r=n;break}return new t(this.#e.slice(0,r),{validate:!1})}equals(e){return Ne(this.bytes,e.bytes)}[gd](){return`Multiaddr(${this.toString()})`}};function Ed(t){t.getComponents().forEach(e=>{let r=at.getProtocol(e.code);e.value!=null&&r.validate?.(e.value)})}function qa(t){return!!t?.[yi]}function tt(t){return new Qn(t)}var V=t=>({match:e=>{let r=e[0];return r==null||r.code!==t||r.value!=null?!1:e.slice(1)}}),I=(t,e)=>({match:r=>{let n=r[0];return n?.code!==t||n.value==null||e!=null&&n.value!==e?!1:r.slice(1)}}),Za=t=>({match:e=>t.match(e)===!1?e:!1}),O=t=>({match:e=>{let r=t.match(e);return r===!1?e:r}}),ve=(...t)=>({match:e=>{let r;for(let n of t){let i=n.match(e);i!==!1&&(r==null||i.length<r.length)&&(r=i)}return r??!1}}),N=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e}});function G(...t){function e(i){if(i==null)return!1;let o=i.getComponents();for(let c of t){let s=c.match(o);if(s===!1)return!1;o=s}return o}function r(i){return e(i)!==!1}function n(i){let o=e(i);return o===!1?!1:o.length===0}return{matchers:t,matches:r,exactMatch:n}}var xd=I(421),jg=G(xd),eo=I(54),to=I(55),ro=I(56),gi=I(53),Xg=G(eo,O(I(421))),Qg=G(to,O(I(421))),Jg=G(ro,O(I(421))),e0=G(ve(gi,ro,eo,to),O(I(421))),ja=N(I(4),O(I(43))),Xa=N(O(I(42)),I(41),O(I(43))),wi=ve(ja,Xa),or=ve(wi,gi,eo,to,ro),t0=G(ve(wi,N(ve(gi,ro,eo,to),O(I(421))))),r0=G(ja),n0=G(Xa),o0=G(wi),Ei=N(or,I(6)),Hr=N(or,I(273)),Qa=G(N(Ei,O(I(421)))),s0=G(Hr),xi=N(Hr,V(460),O(I(421))),no=N(Hr,V(461),O(I(421))),vd=ve(xi,no),i0=G(xi),c0=G(no),bi=ve(or,Ei,Hr,xi,no),Ja=ve(N(bi,V(477),O(I(421)))),a0=G(Ja),eu=ve(N(bi,V(478),O(I(421))),N(bi,V(448),O(I(449)),V(477),O(I(421)))),u0=G(eu),tu=N(Hr,V(280),O(I(466)),O(I(466)),O(I(421))),l0=G(tu),ru=N(no,V(465),O(I(466)),O(I(466)),O(I(421))),f0=G(ru),Jn=ve(Ja,eu,N(Ei,O(I(421))),N(vd,O(I(421))),N(or,O(I(421))),tu,ru,I(421)),d0=G(Jn),Sd=N(O(Jn),V(290),Za(V(281)),O(I(421))),h0=G(Sd),Id=ve(N(Jn,V(290),V(281),O(I(421))),N(Jn,V(281),O(I(421))),N(V(281),O(I(421)))),p0=G(Id),Td=N(or,ve(N(I(6,"80")),N(I(6),V(480)),V(480)),O(I(481)),O(I(421))),m0=G(Td),Ad=N(or,ve(N(I(6,"443")),N(I(6,"443"),V(480)),N(I(6),V(443)),N(I(6),V(448),V(480)),N(V(448),V(480)),V(448),V(443)),O(I(481)),O(I(421))),y0=G(Ad),Dd=ve(N(I(777),O(I(421)))),b0=G(Dd),Ld=ve(N(I(400),O(I(421)))),oo=G(Ld);var so=class extends Event{type;detail;constructor(e,r){super(e),this.type=e,this.detail=r}};var yu=_e(se("node:net"),1);function io(t){let e=t.getComponents(),r={},n=0;if(e[n]?.name==="ip6zone"&&(r.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(r.type=e[n].name,r.host=e[n].value,n++):e[n].name==="dnsaddr"&&(r.type=e[n].name,r.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(r.protocol=e[n].name==="tcp"?"tcp":"udp",r.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(r.type==="ip4"?r.cidr=parseInt(`${e[n].value}`):r.type==="ip6"&&(r.cidr=`${e[n].value}`),n++),r.type==null||r.host==null)throw new j(`Multiaddr ${t} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(r.sni=e[n+1].value,n+=2),r}function ut(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var co=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},sr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new co(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new co(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var vi=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function wt(t={}){return Cd(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function Cd(t,e){e=e??{};let r=e.onEnd,n=new sr,i,o,c,s=ut(),a=async()=>{try{return n.isEmpty()?c?{done:!0}:await new Promise((m,E)=>{o=L=>{o=null,n.push(L);try{m(t(n))}catch(P){E(P)}return i}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{s.resolve(),s=ut()})}},u=m=>o!=null?o(m):(n.push(m),i),l=m=>(n=new sr,o!=null?o({error:m}):(n.push({error:m}),i)),f=m=>{if(c)return i;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:m})},d=m=>c?i:(c=!0,m!=null?l(m):u({done:!0})),h=()=>(n=new sr,d(),{done:!0}),y=m=>(d(m),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:a,return:h,throw:y,push:f,end:d,get readableLength(){return n.size},onEmpty:async m=>{let E=m?.signal;if(E?.throwIfAborted(),n.isEmpty())return;let L,P;E!=null&&(L=new Promise((M,_)=>{P=()=>{_(new vi)},E.addEventListener("abort",P)}));try{await Promise.race([s.promise,L])}finally{P!=null&&E!=null&&E?.removeEventListener("abort",P)}}},r==null)return i;let v=i;return i={[Symbol.asyncIterator](){return this},next(){return v.next()},throw(m){return v.throw(m),r!=null&&(r(m),r=void 0),{done:!0}},return(){return v.return(),r!=null&&(r(),r=void 0),{done:!0}},push:f,end(m){return v.end(m),r!=null&&(r(m),r=void 0),i},get readableLength(){return v.readableLength},onEmpty:m=>v.onEmpty(m)},i}var Si=class t extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,t)}},nu=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function Ii(t,e){let{milliseconds:r,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout},signal:c}=e,s,a,l=new Promise((f,d)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(c?.aborted){d(nu(c));return}if(c&&(a=()=>{d(nu(c))},c.addEventListener("abort",a,{once:!0})),t.then(f,d),r===Number.POSITIVE_INFINITY)return;let h=new Si;s=o.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(y){d(y)}return}typeof t.cancel=="function"&&t.cancel(),i===!1?f():i instanceof Error?d(i):(h.message=i??`Promise timed out after ${r} milliseconds`,d(h))},r)}).finally(()=>{l.clear(),a&&c&&c.removeEventListener("abort",a)});return l.clear=()=>{o.clearTimeout.call(void 0,s),s=void 0},l}var Bd=t=>{let e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function Od(t,e,r){let n,i=new Promise((o,c)=>{if(r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let s=[e].flat(),a=[],{addListener:u,removeListener:l}=Bd(t),f=async(...h)=>{let y=r.multiArgs?h:h[0];if(r.filter)try{if(!await r.filter(y))return}catch(v){n(),c(v);return}a.push(y),r.count===a.length&&(n(),o(a))},d=(...h)=>{n(),c(r.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of s)l(h,f);for(let h of r.rejectionEvents)s.includes(h)||l(h,d)};for(let h of s)u(h,f);for(let h of r.rejectionEvents)s.includes(h)||u(h,d);r.signal&&r.signal.addEventListener("abort",()=>{d(r.signal.reason)},{once:!0}),r.resolveImmediately&&o(a)});if(i.cancel=n,typeof r.timeout=="number"){let o=Ii(i,{milliseconds:r.timeout});return o.cancel=()=>{n(),o.clear()},o}return i}function Fe(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Od(t,e,r),i=n.then(o=>o[0]);return i.cancel=n.cancel,i}var Pt=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};var ao=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function _d(t){return t.reason}async function ir(t,e,r){if(e==null)return t;let n=r?.translateError??_d;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let i;try{return await Promise.race([t,new Promise((o,c)=>{i=()=>{c(n(e))},e.addEventListener("abort",i)})])}finally{i!=null&&e.removeEventListener("abort",i)}}var kd=Math.pow(2,20)*4,uo=class extends Wt{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??kd,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new K,this.writeBuffer=new K,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let r=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",r);let n=i=>{this.onDrainPromise?.reject(i.error??new ao)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),ir(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=wt(),r=o=>{e.push(o.data)};this.addEventListener("message",r);let n=o=>{e.end(o.error)};this.addEventListener("close",n);let i=()=>{e.end()};this.addEventListener("remoteCloseWrite",i);try{yield*e}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",i)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new pt(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new pn(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new pt("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new pt("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new pt(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new pt(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new un;this.dispatchEvent(new mn(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new zt))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,r=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let i=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(i===0){e=!1;break}let o=this.writeBuffer.sublist(0,i),c=new K(o);this.writeBuffer.consume(o.byteLength);let s=this.sendData(o);if(e=s.canSendMore,n+=s.sentBytes,s.sentBytes!==c.byteLength&&(c.consume(s.sentBytes),this.writeBuffer.prepend(c)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,r,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new hn(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Lr(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Lr(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var lo=class extends uo{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",r=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),r.error!=null?r.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):r.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Fe(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Fe(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};var su=_e(se("node:os"),1);function ou(t){return!!(t.startsWith("169.254.")||t.toLowerCase().startsWith("fe80"))}function Ti(t,e,r){let n=[t.type,r??t.host];if(t.protocol!=null){let i=e??t.port;i!=null&&n.push(t.protocol,i)}return t.type==="ip6"&&t.zone!=null&&n.unshift("ip6zone",t.zone),t.cidr!=null&&n.push("ipcidr",t.cidr),tt(`/${n.join("/")}`)}var Pd={4:"IPv4",6:"IPv6"};function Nd(t){return["0.0.0.0","::"].includes(t)}function Rd(t){let e=[],r=su.default.networkInterfaces();for(let[,n]of Object.entries(r))if(n!=null)for(let i of n)ou(i.address)||i.family===Pd[t]&&e.push(i.address);return e}function iu(t,e){if(t==null)return[];let r=io(t);return(r.type==="ip4"||r.type==="ip6")&&Nd(r.host)?Rd(r.type==="ip4"?4:6).map(n=>Ti(r,e,n)):[Ti(r,e)]}function cu(t,e){if(typeof t!="string")throw new j(`invalid ip provided: ${t}`);if(typeof e=="string"&&(e=parseInt(e)),isNaN(e))throw new j(`invalid port provided: ${e}`);if((0,Ue.isIPv4)(t))return tt(`/ip4/${t}/tcp/${e}`);if((0,Ue.isIPv6)(t))return tt(`/ip6/${t}/tcp/${e}`);throw new j(`invalid ip:port for creating a multiaddr: ${t}:${e}`)}var Ai=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ut(),this.haveNext=ut()}[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 e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ut(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,r){await this._push(e,r)}async end(e,r){e!=null?await this.throw(e):await this._push(void 0,r)}async _push(e,r){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ut(),await ir(this.readNext.promise,r?.signal,r)}};function au(){return new Ai}function Ud(t){return t[Symbol.asyncIterator]!=null}async function Fd(t,e,r){try{await Promise.all(t.map(async n=>{for await(let i of n)await e.push(i,{signal:r}),r.throwIfAborted()})),await e.end(void 0,{signal:r})}catch(n){await e.end(n,{signal:r}).catch(()=>{})}}async function*Md(t){let e=new AbortController,r=au();Fd(t,r,e.signal).catch(()=>{});try{yield*r}finally{e.abort()}}function*$d(t){for(let e of t)yield*e}function Kd(...t){let e=[];for(let r of t)Ud(r)||e.push(r);return e.length===t.length?$d(e):Md(t)}var uu=Kd;function lu(t,...e){if(t==null)throw new Error("Empty pipeline");if(Di(t)){let n=t;t=()=>n.source}else if(du(t)||fu(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&Di(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)Di(r[n])&&(r[n]=Vd(r[n]));return Hd(...r)}var Hd=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},fu=t=>t?.[Symbol.asyncIterator]!=null,du=t=>t?.[Symbol.iterator]!=null,Di=t=>t==null?!1:t.sink!=null&&t.source!=null,Vd=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=wt({objectMode:!0});r.then(()=>{n.end()},c=>{n.end(c)});let i,o=t.source;if(fu(o))i=async function*(){yield*o,n.end()};else if(du(o))i=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return uu(n,i())}return t.source};var Gd=4194304,fo=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Ci=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Bi=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Oi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function zd(t){return typeof t?.closeRead=="function"}function Wd(t){return typeof t?.close=="function"}function Li(t){return zd(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:Wd(t)?t.status!=="open":!1}function Yd(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function qd(t,e){let r=e?.maxBufferSize??Gd,n=new K,i,o=!1;if(!Yd(t))throw new j("Argument should be a Stream or a Multiaddr");let c=l=>{if(n.append(l.data),n.byteLength>r){let f=n.byteLength;n.consume(n.byteLength),i?.reject(new Error(`Read buffer overflow - ${f} > ${r}`))}i?.resolve()};t.addEventListener("message",c);let s=l=>{l.error!=null?i?.reject(l.error):i?.resolve()};t.addEventListener("close",s);let a=()=>{i?.resolve()};t.addEventListener("remoteCloseWrite",a);let u={readBuffer:n,async read(l){if(o===!0)throw new fo("Stream was unwrapped");if(Li(t)){if(n.byteLength===0&&l?.bytes==null)return null;if(l?.bytes!=null&&n.byteLength<l.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,l.bytes),new Pt(`Unexpected EOF - stream closed after reading ${n.byteLength}/${l.bytes} bytes`)}let f=l?.bytes??1;for(i=Promise.withResolvers();;){if(n.byteLength>=f){i.resolve();break}if(await ir(i.promise,l?.signal),Li(t)){if(n.byteLength===0&&l?.bytes==null)return null;break}i=Promise.withResolvers()}let d=l?.bytes??n.byteLength;if(n.byteLength<d){if(Li(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,d),new Pt(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return u.read(l)}let h=n.sublist(0,d);return n.consume(d),h},async write(l,f){if(o===!0)throw new fo("Stream was unwrapped");t.send(l)||await Fe(t,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!0,t.removeEventListener("message",c),t.removeEventListener("close",s),t.removeEventListener("remoteCloseWrite",a),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.push(n))),t}};return u}function Vr(t,e={}){let r=qd(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=ue(e.maxDataLength));let n=e?.lengthDecoder??xt,i=e?.lengthEncoder??Yr;return{async read(c){let s=-1,a=new K;for(;;){let l=await r.read({...c,bytes:1});if(l==null)break;a.append(l);try{s=n(a)}catch(f){if(f instanceof RangeError)continue;throw f}if(s<0)throw new Ci("Invalid message length");if(e?.maxLengthLength!=null&&a.byteLength>e.maxLengthLength)throw new Oi(`Message length length too long - ${a.byteLength} > ${e.maxLengthLength}`);if(s>-1)break}if(e?.maxDataLength!=null&&s>e.maxDataLength)throw new Bi(`Message length too long - ${s} > ${e.maxDataLength}`);let u=await r.read({...c,bytes:s});if(u==null)throw t.log.error("tried to read %d bytes but the stream closed",s),new Pt(`Unexpected EOF - tried to read ${s} bytes but the stream closed`);if(u.byteLength!==s)throw t.log.error("read %d/%d bytes before the stream closed",u.byteLength,s),new Pt(`Unexpected EOF - read ${u.byteLength}/${s} bytes before the stream closed`);return u},async write(c,s){await r.write(new K(i(c.byteLength),c),s)},async writeV(c,s){let a=new K(...c.flatMap(u=>[i(u.byteLength),u]));await r.write(a,s)},unwrap(){return r.unwrap()}}}function _i(t,e){let r=Vr(t,e),n={read:async(i,o)=>{let c=await r.read(o);return i.decode(c)},write:async(i,o,c)=>{await r.write(o.encode(i),c)},writeV:async(i,o,c)=>{await r.writeV(i.map(s=>o.encode(s)),c)},pb:i=>({read:async o=>n.read(i,o),write:async(o,c)=>n.write(o,i,c),writeV:async(o,c)=>n.writeV(o,i,c),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}function Zd(t){return t?.addEventListener!=null}function jd(t){let e=wt(),r,n=c=>{e.push(c.data)},i=()=>{e.end(),t.removeEventListener("message",n),t.removeEventListener("close",o),t.removeEventListener("remoteCloseWrite",i)},o=c=>{e.end(c.error),c.error!=null&&r?.reject(c.error),t.removeEventListener("message",n),t.removeEventListener("close",o),t.removeEventListener("remoteCloseWrite",i)};return t.addEventListener("message",n),t.addEventListener("close",o,{once:!0}),t.addEventListener("remoteCloseWrite",i,{once:!0}),{source:e,async sink(c){async function*s(){yield*c}let a=s();for(;;){r=Promise.withResolvers();let{done:u,value:l}=await Promise.race([a.next(),r.promise]);if(t.writeStatus==="closing"||t.writeStatus==="closed"||(l!=null&&(t.send(l)||await Promise.race([Fe(t,"drain",{rejectionEvents:["close"]})])),u===!0))break}await t.close()}}}function ki(...t){let e=t.map(r=>Zd(r)?jd(r):r);return lu(...e)}var ho=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},cr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},po=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Gr=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function mo(t){return t[Symbol.asyncIterator]!=null}function hu(t,e){if(t.byteLength>e)throw new cr("Message length too long")}var bo=t=>{let e=ue(t),r=Le(e);return Yr(t,r),bo.bytes=e,r};bo.bytes=0;function go(t,e){e=e??{};let r=e.lengthEncoder??bo,n=e?.maxDataLength??4194304;function*i(o){hu(o,n);let c=r(o.byteLength);c instanceof Uint8Array?yield c:yield*c,o instanceof Uint8Array?yield o:yield*o}return mo(t)?(async function*(){for await(let o of t)yield*i(o)})():(function*(){for(let o of t)yield*i(o)})()}go.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??bo,n=e?.maxDataLength??4194304;return hu(t,n),new K(r(t.byteLength),t)};var Nt;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(Nt||(Nt={}));var Ni=t=>{let e=xt(t);return Ni.bytes=ue(e),e};Ni.bytes=0;function Pi(t,e){let r=new K,n=Nt.LENGTH,i=-1,o=e?.lengthDecoder??Ni,c=e?.maxLengthLength??8,s=e?.maxDataLength??4194304;function*a(){for(;r.byteLength>0;){if(n===Nt.LENGTH)try{if(i=o(r),i<0)throw new ho("Invalid message length");if(i>s)throw new cr("Message length too long");let u=o.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=Nt.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>c)throw new po("Message length length too long");break}throw u}if(n===Nt.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=Nt.LENGTH}}}return mo(t)?(async function*(){for await(let u of t)r.append(u),yield*a();if(r.byteLength>0)throw new Gr("Unexpected end of input")})():(function*(){for(let u of t)r.append(u),yield*a();if(r.byteLength>0)throw new Gr("Unexpected end of input")})()}Pi.fromReader=(t,e)=>{let r=1,n=(async function*(){for(;;)try{let{done:o,value:c}=await t.next(r);if(o===!0)return;c!=null&&(yield c)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{r=1}})();return Pi(n,{...e??{},onLength:o=>{r=o}})};var Ri=class extends lo{socket;constructor(e){let r=e.remoteAddr;if(e.localAddr!=null&&oo.matches(e.localAddr))r=e.localAddr;else if(r==null){if(e.socket.remoteAddress==null||e.socket.remotePort==null)throw new j("Could not determine remote address or port");r=cu(e.socket.remoteAddress,e.socket.remotePort)}super({...e,remoteAddr:r}),this.socket=e.socket,this.socket.on("data",n=>{this.onData(n)}),this.socket.on("error",n=>{this.log("tcp error",r,n),this.abort(n)}),this.socket.setTimeout(e.inactivityTimeout??120*1e3),this.socket.once("timeout",()=>{this.log("tcp timeout",r),this.abort(new Gt)}),this.socket.once("end",()=>{this.log("tcp end",r),this.onTransportClosed()}),this.socket.once("close",n=>{if(this.log("tcp close",r),n){this.abort(new Error("TCP transmission error"));return}this.onTransportClosed()}),this.socket.on("drain",()=>{this.log("tcp drain"),this.safeDispatchEvent("drain")})}sendData(e){let r=0,n=!0;for(let i of e)if(r+=i.byteLength,n=this.socket.write(i),!n)break;return{sentBytes:r,canSendMore:n}}async sendClose(e){this.socket.destroyed||(this.socket.destroySoon(),await Fe(this.socket,"close",e))}sendReset(){this.socket.resetAndDestroy()}sendPause(){this.socket.pause()}sendResume(){this.socket.resume()}},wo=t=>new Ri(t);var pu=_e(se("os"),1),mu=_e(se("path"),1);function Eo(t,e={}){if(oo.exactMatch(t)){let o=t.getComponents().find(c=>c.code===400)?.value;if(o==null)throw new j(`Multiaddr ${t} was not a Unix address`);return pu.default.platform()==="win32"?{path:mu.default.join("\\\\.\\pipe\\",o)}:{path:o}}let r=io(t),n=r.host,i=r.port;return{host:n,port:i,ipv6Only:r.type==="ip6",...e}}var he;(function(t){t[t.INACTIVE=0]="INACTIVE",t[t.ACTIVE=1]="ACTIVE",t[t.PAUSED=2]="PAUSED"})(he||(he={}));var xo=class extends Wt{context;server;sockets=new Set;status={code:he.INACTIVE};metrics;addr;log;shutdownController;constructor(e){if(super(),this.context=e,e.keepAlive=e.keepAlive??!0,e.noDelay=e.noDelay??!0,e.allowHalfOpen=e.allowHalfOpen??!1,this.shutdownController=new AbortController,yn(1/0,this.shutdownController.signal),this.log=e.logger.forComponent("libp2p:tcp:listener"),this.addr="unknown",this.server=yu.default.createServer(e,this.onSocket.bind(this)),e.maxConnections!==void 0&&(this.server.maxConnections=e.maxConnections),e.closeServerOnMaxConnections!=null&&e.closeServerOnMaxConnections.closeAbove<e.closeServerOnMaxConnections.listenBelow)throw new j("closeAbove must be >= listenBelow");e.metrics?.registerMetricGroup("libp2p_tcp_inbound_connections_total",{label:"address",help:"Current active connections in TCP listener",calculate:()=>({[this.addr]:this.sockets.size})}),this.metrics={status:e.metrics?.registerMetricGroup("libp2p_tcp_listener_status_info",{label:"address",help:"Current status of the TCP listener socket"}),errors:e.metrics?.registerMetricGroup("libp2p_tcp_listener_errors_total",{label:"address",help:"Total count of TCP listener errors by type"}),events:e.metrics?.registerMetricGroup("libp2p_tcp_listener_events_total",{label:"address",help:"Total count of TCP listener events by type"})},this.server.on("listening",()=>{let r=this.server.address();r==null?this.addr="unknown":typeof r=="string"?this.addr=r:this.addr=`${r.address}:${r.port}`,this.metrics.status?.update({[this.addr]:he.ACTIVE}),this.safeDispatchEvent("listening")}).on("error",r=>{this.metrics.errors?.increment({[`${this.addr} listen_error`]:!0}),this.safeDispatchEvent("error",{detail:r})}).on("close",()=>{this.metrics.status?.update({[this.addr]:this.status.code}),this.status.code!==he.PAUSED&&this.safeDispatchEvent("close")}).on("drop",()=>{this.metrics.events?.increment({[`${this.addr} drop`]:!0})})}onSocket(e){if(this.metrics.events?.increment({[`${this.addr} connection`]:!0}),this.status.code!==he.ACTIVE)throw e.destroy(),new fn("Server is not listening yet");let r;try{r=wo({socket:e,inactivityTimeout:this.context.inactivityTimeout,metrics:this.metrics?.events,metricPrefix:`${this.addr} `,direction:"inbound",localAddr:this.status.listeningAddr,log:this.context.logger.forComponent("libp2p:tcp:connection")})}catch(n){this.log.error("inbound connection failed - %e",n),this.metrics.errors?.increment({[`${this.addr} inbound_to_connection`]:!0}),e.destroy();return}this.log("new inbound connection %s",r.remoteAddr),this.sockets.add(e),this.context.upgrader.upgradeInbound(r,{signal:this.shutdownController.signal}).then(()=>{this.log("inbound connection upgraded %s",r.remoteAddr),e.once("close",()=>{this.sockets.delete(e),this.context.closeServerOnMaxConnections!=null&&this.sockets.size<this.context.closeServerOnMaxConnections.listenBelow&&this.resume().catch(n=>{this.log.error("error attempting to listen server once connection count under limit - %e",n),this.context.closeServerOnMaxConnections?.onListenError?.(n)})}),this.context.closeServerOnMaxConnections!=null&&this.sockets.size>=this.context.closeServerOnMaxConnections.closeAbove&&(this.log("pausing incoming connections as limit is exceeded - %d/%d",this.sockets.size,this.context.closeServerOnMaxConnections.closeAbove),this.pause())}).catch(async n=>{this.log.error("inbound connection upgrade failed - %e",n),this.metrics.errors?.increment({[`${this.addr} inbound_upgrade`]:!0}),this.sockets.delete(e),r.abort(n)})}getAddrs(){if(this.status.code===he.INACTIVE)return[];let e=this.server.address();return e==null?[]:typeof e=="string"?[tt(`/unix/${encodeURIComponent(e)}`)]:iu(this.status.listeningAddr,e.port)}updateAnnounceAddrs(){}async listen(e){if(this.status.code===he.ACTIVE||this.status.code===he.PAUSED)throw new dn("server is already listening");try{this.status={code:he.ACTIVE,listeningAddr:e,netConfig:Eo(e,this.context)},await this.resume()}catch(r){throw this.status={code:he.INACTIVE},r}}async close(e){let r=[];this.server.listening&&r.push(Fe(this.server,"close",e)),this.pause(!0),this.shutdownController.abort(),this.sockets.forEach(n=>{n.readable&&(r.push(Fe(n,"close",e)),n.destroy())}),await Promise.all(r)}async resume(){if(this.server.listening||this.status.code===he.INACTIVE)return;let e=this.status.netConfig;await new Promise((r,n)=>{this.server.once("error",n),this.server.listen(e,r)}),this.status={...this.status,code:he.ACTIVE},this.log("listening on %s",this.server.address())}pause(e=!1){if(!this.server.listening&&this.status.code===he.PAUSED&&e){this.status={code:he.INACTIVE};return}!this.server.listening||this.status.code!==he.ACTIVE||(this.log("%s server on %s",e?"closing":"pausing",this.server.address()),this.status=e?{code:he.INACTIVE}:{...this.status,code:he.PAUSED},this.server.close())}};var vo=class{opts;metrics;components;log;constructor(e,r={}){this.log=e.logger.forComponent("libp2p:tcp"),this.opts=r,this.components=e,e.metrics!=null&&(this.metrics={events:e.metrics.registerCounterGroup("libp2p_tcp_dialer_events_total",{label:"event",help:"Total count of TCP dialer events by type"}),errors:e.metrics.registerCounterGroup("libp2p_tcp_dialer_errors_total",{label:"event",help:"Total count of TCP dialer events by type"})})}[Dc]=!0;[Symbol.toStringTag]="@libp2p/tcp";[Cc]=["@libp2p/transport"];async dial(e,r){r.keepAlive=r.keepAlive??!0,r.noDelay=r.noDelay??!0,r.allowHalfOpen=r.allowHalfOpen??!1;let n=await this._connect(e,r),i;try{i=wo({socket:n,inactivityTimeout:this.opts.outboundSocketInactivityTimeout,metrics:this.metrics?.events,direction:"outbound",remoteAddr:e,log:this.log.newScope("connection")})}catch(o){throw this.metrics?.errors.increment({outbound_to_connection:!0}),n.destroy(o),o}try{return this.log("new outbound connection %s",i.remoteAddr),await r.upgrader.upgradeOutbound(i,r)}catch(o){throw this.metrics?.errors.increment({outbound_upgrade:!0}),this.log.error("error upgrading outbound connection - %e",o),i.abort(o),o}}async _connect(e,r){r.signal.throwIfAborted(),r.onProgress?.(new so("tcp:open-connection"));let n;return new Promise((i,o)=>{let c=Date.now(),s=Eo(e,{...this.opts.dialOpts??{},...r});this.log("dialing %a with opts %o",e,s),n=bu.default.connect(s);let a=h=>{this.log.error("dial to %a errored - %e",e,h);let y=s.path??`${s.host??""}:${s.port}`;h.message=`connection error ${y}: ${h.message}`,this.metrics?.events.increment({error:!0}),d(h)},u=()=>{this.log("connection timeout %a",e),this.metrics?.events.increment({timeout:!0});let h=new Gt(`Connection timeout after ${Date.now()-c}ms`);n.emit("error",h)},l=()=>{this.log("connection opened %a",e),this.metrics?.events.increment({connect:!0}),d()},f=()=>{this.log("connection aborted %a",e),this.metrics?.events.increment({abort:!0}),d(new cn)},d=h=>{if(n.removeListener("error",a),n.removeListener("timeout",u),n.removeListener("connect",l),r.signal!=null&&r.signal.removeEventListener("abort",f),h!=null){o(h);return}i(n)};n.on("error",a),n.on("timeout",u),n.on("connect",l),r.signal.addEventListener("abort",f)}).catch(i=>{throw n?.destroy(),i})}createListener(e){return new xo({...this.opts.listenOpts??{},...e,maxConnections:this.opts.maxConnections,backlog:this.opts.backlog,closeServerOnMaxConnections:this.opts.closeServerOnMaxConnections,inactivityTimeout:this.opts.inboundSocketInactivityTimeout,metrics:this.components.metrics,logger:this.components.logger})}listenFilter(e){return e.filter(r=>Qa.exactMatch(r)||r.toString().startsWith("/unix/"))}dialFilter(e){return this.listenFilter(e)}};function gu(t={}){return e=>new vo(e,t)}function Jd(t){return t[Symbol.asyncIterator]!=null}function eh(t){if(Jd(t))return(async()=>{for await(let e of t);})();for(let e of t);}var Ui=eh;function Be(t){return re.encode({type:re.Type.OK,peers:[],...t}).subarray()}function Se(t){return re.encode({type:re.Type.ERROR,error:{msg:t.message},peers:[]}).subarray()}var So=ht("libp2p:daemon-server:dht"),Io=class{dht;constructor(e){let{dht:r}=e;this.dht=r}async*provide(e){try{await Ui(this.dht.provide(e)),yield Be()}catch(r){So.error("failed to provide CID %s - %e",e,r),yield Se(r)}}async*getClosestPeers(e){yield Be({dht:{type:le.Type.BEGIN}});for await(let r of this.dht.getClosestPeers(e))r.name==="PEER_RESPONSE"&&(yield*r.closer.map(n=>le.encode({type:le.Type.VALUE,value:n.id.toMultihash().bytes})));yield le.encode({type:le.Type.END})}async*getPublicKey(e){yield Se(new Error("FIX ME: not implemented"))}async*getValue(e){try{for await(let r of this.dht.get(e))r.name==="VALUE"&&(yield Be({dht:{type:le.Type.VALUE,value:r.value}}))}catch(r){So.error("error getting value for key %b - %e",e,r),yield Se(r)}}async*putValue(e,r){try{await Ui(this.dht.put(e,r)),yield Be()}catch(n){So.error("error putting value %b for key %b - %e",r,e,n),yield Se(n)}}async*findPeer(e){try{for await(let r of this.dht.findPeer(e))r.name==="FINAL_PEER"&&(yield Be({dht:{type:le.Type.VALUE,peer:{id:r.peer.id.toMultihash().bytes,addrs:r.peer.multiaddrs.map(n=>n.bytes)}}}));throw new Error("Peer not found")}catch(r){So.error("peer not found %p - %e",e,r),yield Se(r)}}async*findProviders(e,r){yield Be({dht:{type:le.Type.BEGIN}});try{let n=r,i=0;for await(let o of this.dht.findProviders(e))if(o.name==="PEER_RESPONSE"){for(let c of o.providers)i++,yield le.encode({type:le.Type.VALUE,peer:{id:c.id.toMultihash().bytes,addrs:(c.multiaddrs??[]).map(s=>s.bytes)}});if(n===i)break}}catch(n){yield Se(n)}yield le.encode({type:le.Type.END})}};var To=ht("libp2p:daemon-server:pubsub"),Ao=class{pubsub;constructor(e){let{pubsub:r}=e;this.pubsub=r}async*getTopics(){try{yield Be({pubsub:{topics:this.pubsub.getTopics(),peerIDs:[]}})}catch(e){To.error("failed to get pubsub topics - %e",e),yield Se(e)}}async*subscribe(e){try{let r=wt();this.pubsub.subscribe(e),this.pubsub.addEventListener("message",n=>{let i=n.detail;i.topic===e&&(i.type==="signed"?r.push(Ar.encode({from:i.from.toMultihash().bytes,data:i.data,seqno:i.sequenceNumber==null?void 0:xe(i.sequenceNumber.toString(16).padStart(16,"0"),"base16"),topicIDs:[i.topic],signature:i.signature,key:mt(i.key)}).subarray()):r.push(Ar.encode({data:i.data,topicIDs:[i.topic]}).subarray()))}),yield Be(),yield*r}catch(r){To.error("failed to subscribe to topic %s - %e",e,r),yield Se(r)}}async*publish(e,r){try{await this.pubsub.publish(e,r),yield Be()}catch(n){To.error("failed to publish message to topic %s - %e",e,n),yield Se(n)}}async*listPeers(e){try{yield Be({pubsub:{topics:[e],peerIDs:this.pubsub.getSubscribers(e).map(r=>r.toMultihash().bytes)}})}catch(r){To.error("failed to list peers for topic %s - %e",e,r),yield Se(r)}}};var wu=1<<22,Te=ht("libp2p:daemon-server"),Do=class{multiaddr;libp2p;tcp;listener;dhtOperations;pubsubOperations;constructor(e){let{multiaddr:r,libp2pNode:n}=e;this.multiaddr=r,this.libp2p=n,this.tcp=gu()({logger:Tc()}),this.listener=this.tcp.createListener({upgrader:new Dr(this.handleConnection.bind(this))}),this._onExit=this._onExit.bind(this),n.services.dht!=null&&(this.dhtOperations=new Io({dht:n.services.dht})),n.services.pubsub!=null&&(this.pubsubOperations=new Ao({pubsub:n.services.pubsub}))}async connect(e){if(e.connect?.addrs==null)throw new Error("Invalid request");let r=e.connect.peer,n=e.connect.addrs.map(o=>tt(o)),i=Jt(rt(r));return Te("connect - adding multiaddrs %a to peer %p",n,i),await this.libp2p.peerStore.merge(i,{multiaddrs:n}),Te("connect - dial %p",i),this.libp2p.dial(i)}async openStream(e){if(e.streamOpen?.proto==null)throw new Error("Invalid request");let{peer:r,proto:n}=e.streamOpen,i=Jt(rt(r));Te("openStream - dial %p",i);let o=await this.libp2p.dial(i);Te("openStream - open stream for protocol(s) %s",n);let c=await o.newStream(n,{runOnLimitedConnection:!0});return{streamInfo:{peer:i.toMultihash().bytes,addr:o.remoteAddr.bytes,proto:c.protocol??""},connection:c}}async registerStreamHandler(e){if(e.streamHandler?.proto==null)throw new Error("Invalid request");let r=e.streamHandler.proto,n=tt(e.streamHandler.addr),i;Te("registerStreamHandler - handle %s at %a",r,n),await this.libp2p.handle(r,async(o,c)=>{try{Te("open stream for protocol %o to %a",r,n);let s=AbortSignal.timeout(1e4);i=await this.tcp.dial(n,{upgrader:new Dr,signal:s});let a=Tt.encode({peer:c.remotePeer.toMultihash().bytes,addr:c.remoteAddr.bytes,proto:o.protocol??""}),u=go.single(a);i.send(u)||await Fe(i,"drain",{rejectionEvents:["close"],signal:s}),await ki(o,i,o)}catch(s){Te.error("error handling stream handler - %e",s),i?.abort(s)}finally{try{await i?.close()}catch(s){i?.abort(s)}}},{runOnLimitedConnection:!0})}_listen(){process.on("SIGTERM",this._onExit),process.on("SIGINT",this._onExit),process.on("SIGHUP",this._onExit)}_onExit(){this.stop({exit:!0}).catch(e=>{Te.error("failed to stop daemon during exit - %e",e)})}async start(){this._listen(),await this.libp2p.start(),await this.listener.listen(this.multiaddr)}getMultiaddr(){let e=this.listener.getAddrs();if(e.length>0)return e[0];throw new Error("Not started")}async stop(e={exit:!1}){await this.libp2p.stop(),await this.listener.close(),e.exit&&Te("server closed, exiting"),process.removeListener("SIGTERM",this._onExit),process.removeListener("SIGINT",this._onExit),process.removeListener("SIGHUP",this._onExit)}async*handlePeerStoreRequest(e){try{switch(e.type){case dt.Type.GET_PROTOCOLS:if(e.id==null)throw new Error("Invalid request");let r=Jt(rt(e.id)),i=(await this.libp2p.peerStore.get(r)).protocols;yield Be({peerStore:{protos:i}});return;case dt.Type.GET_PEER_INFO:throw new Error("ERR_NOT_IMPLEMENTED");default:throw new Error("ERR_INVALID_REQUEST_TYPE")}}catch(r){Te.error("error handling peerstore request - %e",r),yield Se(r)}}async*handlePubsubRequest(e){try{if(this.libp2p.services.pubsub==null||this.pubsubOperations==null)throw new Error("PubSub not configured");switch(e.type){case Xe.Type.GET_TOPICS:yield*this.pubsubOperations.getTopics();return;case Xe.Type.SUBSCRIBE:if(e.topic==null)throw new Error("Invalid request");yield*this.pubsubOperations.subscribe(e.topic);return;case Xe.Type.PUBLISH:if(e.topic==null||e.data==null)throw new Error("Invalid request");yield*this.pubsubOperations.publish(e.topic,e.data);return;case Xe.Type.LIST_PEERS:if(e.topic==null)throw new Error("Invalid request");yield*this.pubsubOperations.listPeers(e.topic);return;default:throw new Error("ERR_INVALID_REQUEST_TYPE")}}catch(r){Te.error("error handling pubsub request - %e",r),yield Se(r)}}async*handleDHTRequest(e){try{if(this.libp2p.services.dht==null||this.dhtOperations==null)throw new Error("DHT not configured");switch(e.type){case Pe.Type.FIND_PEER:if(e.peer==null)throw new Error("Invalid request");yield*this.dhtOperations.findPeer(Jt(rt(e.peer)));return;case Pe.Type.FIND_PROVIDERS:if(e.cid==null)throw new Error("Invalid request");yield*this.dhtOperations.findProviders(ie.decode(e.cid),e.count??20);return;case Pe.Type.PROVIDE:if(e.cid==null)throw new Error("Invalid request");yield*this.dhtOperations.provide(ie.decode(e.cid));return;case Pe.Type.GET_CLOSEST_PEERS:if(e.key==null)throw new Error("Invalid request");yield*this.dhtOperations.getClosestPeers(e.key);return;case Pe.Type.GET_PUBLIC_KEY:if(e.peer==null)throw new Error("Invalid request");yield*this.dhtOperations.getPublicKey(Jt(rt(e.peer)));return;case Pe.Type.GET_VALUE:if(e.key==null)throw new Error("Invalid request");yield*this.dhtOperations.getValue(e.key);return;case Pe.Type.PUT_VALUE:if(e.key==null||e.value==null)throw new Error("Invalid request");yield*this.dhtOperations.putValue(e.key,e.value);return;default:throw new Error("ERR_INVALID_REQUEST_TYPE")}}catch(r){Te.error("error handling DHT request - %e",r),yield Se(r)}}handleConnection(e){Promise.resolve().then(async()=>{let r=this,n=_i(e,{maxDataLength:wu}),i=await n.read($e);Te("read",i);try{switch(i.type){case $e.Type.CONNECT:{await r.connect(i),await n.write({type:re.Type.OK},re);break}case $e.Type.IDENTIFY:{await n.write({type:re.Type.OK,identify:{id:r.libp2p.peerId.toMultihash().bytes,addrs:r.libp2p.getMultiaddrs().map(o=>o.decapsulateCode(421)).map(o=>o.bytes)}},re);break}case $e.Type.LIST_PEERS:{let o=[],c=new Set;for(let s of r.libp2p.getConnections()){let a=s.remotePeer.toString();c.has(a)||(c.add(a),o.push({id:s.remotePeer.toMultihash().bytes,addrs:[s.remoteAddr.bytes]}))}await n.write({type:re.Type.OK,peers:o},re);break}case $e.Type.STREAM_OPEN:{let o=await r.openStream(i);await n.write({type:re.Type.OK,streamInfo:o.streamInfo},re);let c=n.unwrap();await ki(c,o.connection,c);break}case $e.Type.STREAM_HANDLER:{await r.registerStreamHandler(i),await n.write({type:re.Type.OK},re);break}case $e.Type.PEERSTORE:{if(i.peerStore==null)throw new Error("ERR_INVALID_REQUEST");let o=n.unwrap(),c=Vr(o);for await(let s of r.handlePeerStoreRequest(i.peerStore))await c.write(s);break}case $e.Type.PUBSUB:{if(i.pubsub==null)throw new Error("ERR_INVALID_REQUEST");let o=n.unwrap(),c=Vr(o);for await(let s of r.handlePubsubRequest(i.pubsub))await c.write(s);break}case $e.Type.DHT:{if(i.dht==null)throw new Error("ERR_INVALID_REQUEST");let o=n.unwrap(),c=Vr(o);for await(let s of r.handleDHTRequest(i.dht))await c.write(s);break}default:throw new Error("ERR_INVALID_REQUEST_TYPE")}}catch(o){Te.error("error handling incoming connection - %e",o);let c=n.unwrap();if(c.status!=="open")return;n=_i(c,{maxDataLength:wu}),await n.write({type:re.Type.ERROR,error:{msg:o.message},peers:[]},re)}finally{await n.unwrap().close()}}).catch(r=>{Te.error("error handling incoming connection - %e",r)})}},th=(t,e)=>new Do({multiaddr:t,libp2pNode:e});return Tu(rh);})();
|
|
16
|
+
${e}[Error list was empty]`,r.trim()}return vc(t,e)}Ce.formatters.e=t=>t==null?"undefined":Ic(t);function uf(t){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=t,e.destroy=()=>!0,e.extend=()=>e,e}function Tc(t){return{forComponent(e){return ht(e,t)}}}function ht(t,e){let r=uf(`${t}:trace`);return Ce.enabled(`${t}:trace`)&&Ce.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(r=Ce(`${t}:trace`,e)),Object.assign(Ce(t,e),{error:Ce(`${t}:error`,e),trace:r,newScope:n=>ht(`${t}:${n}`,e)})}function Sc(t){if(t!=null&&(t=t.trim(),t.length!==0))return t}var cn=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var j=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},an=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var un=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var pt=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Lr=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var ln=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Gt=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},fn=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}},dn=class extends Error{static name="AlreadyStartedError";constructor(e="Already started"){super(e),this.name="AlreadyStartedError"}};var Cr=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var hn=class extends Event{data;constructor(e,r){super("message",r),this.data=e}},zt=class extends Event{error;local;constructor(e,r,n){super("close",n),this.error=r,this.local=e}},pn=class extends zt{constructor(e,r){super(!0,e,r)}},mn=class extends zt{constructor(e,r){super(!1,e,r)}};var bs=Symbol.for("@libp2p/peer-id");var Dc=Symbol.for("@libp2p/transport");var Ac;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Ac||(Ac={}));var Lc=se("node:events"),yn=(t,...e)=>{try{(0,Lc.setMaxListeners)(t,...e)}catch{}};function lf(t){return typeof t?.handleEvent=="function"}function ff(t){return(t!==!0&&t!==!1&&t?.once)??!1}var Wt=class extends EventTarget{#e=new Map;constructor(){super(),yn(1/0,this)}listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){let i=ff(n);super.addEventListener(e,c=>{if(i){let s=this.#e.get(c.type);s!=null&&(s=s.filter(({callback:a})=>a!==r),this.#e.set(c.type,s))}lf(r)?r.handleEvent(c):r(c)},n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:r,once:i})}removeEventListener(e,r,n){super.removeEventListener(e.toString(),r??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:o})=>o!==r),this.#e.set(e,i))}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}};var Cc=Symbol.for("@libp2p/service-capabilities");function Ne(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}async function Bc(t,e,r,n){let i=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},i,e,r.subarray());return n?.signal?.throwIfAborted(),o}var Oc=se("node:buffer");function Qe(t,e){return Et(Oc.Buffer.concat(t,e))}var kc=Symbol.for("@achingbrain/uint8arraylist");function _c(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(let n of t){let i=r+n.byteLength;if(e<i)return{buf:n,index:e-r};r=i}throw new RangeError("index is out of bounds")}function bn(t){return!!t?.[kc]}var K=class t{bufs;length;[kc]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let r=0;for(let n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(bn(n)){r+=n.byteLength;for(let i of n.bufs)this.bufs.push(i)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...e){this.prependAll(e)}prependAll(e){let r=0;for(let n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(bn(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(e){let r=_c(this.bufs,e);return r.buf[r.index]}set(e,r){let n=_c(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(bn(e))for(let n=0;n<e.length;n++)this.set(r+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,r){let{bufs:n,length:i}=this._subList(e,r);return Qe(n,i)}subarray(e,r){let{bufs:n,length:i}=this._subList(e,r);return n.length===1?n[0]:Qe(n,i)}sublist(e,r){let{bufs:n,length:i}=this._subList(e,r),o=new t;return o.length=i,o.bufs=n,o}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],i=0;for(let o=0;o<this.bufs.length;o++){let c=this.bufs[o],s=i,a=s+c.byteLength;if(i=a,e>=a)continue;let u=e>=s&&e<a,l=r>s&&r<=a;if(u&&l){if(e===s&&r===a){n.push(c);break}let f=e-s;n.push(c.subarray(f,f+(r-e)));break}if(u){if(e===0){n.push(c);continue}n.push(c.subarray(e-s));continue}if(l){if(r===a){n.push(c);break}n.push(c.subarray(0,r-s));break}n.push(c)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!bn(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.length===0)return r>this.length?this.length:r;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let o=256,c=new Int32Array(o);for(let f=0;f<o;f++)c[f]=-1;for(let f=0;f<i;f++)c[n[f]]=f;let s=c,a=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=r;f<=a;f+=l){l=0;for(let d=u;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){l=Math.max(1,d-s[h]);break}}if(l===0)return f}return-1}getInt8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){let n=Le(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){let i=ae(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,r,n),this.write(i,e)}getInt32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){let i=ae(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,r,n),this.write(i,e)}getBigInt64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){let i=ae(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,r,n),this.write(i,e)}getUint8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){let n=Le(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){let i=ae(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,r,n),this.write(i,e)}getUint32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){let i=ae(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,r,n),this.write(i,e)}getBigUint64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){let i=ae(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,r,n),this.write(i,e)}getFloat32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){let i=ae(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,r,n),this.write(i,e)}getFloat64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){let i=ae(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,r,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof t)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!Ne(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){let n=new t;return n.bufs=e,r==null&&(r=e.reduce((i,o)=>i+o.byteLength,0)),n.length=r,n}};var Pc=se("node:buffer");function ne(t,e="utf8"){let r=Xr[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?Pc.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}var df=parseInt("11111",2),gs=parseInt("10000000",2),hf=parseInt("01111111",2),Nc={0:Br,1:Br,2:pf,3:bf,4:gf,5:yf,6:mf,16:Br,22:Br,48:Br};function ws(t,e={offset:0}){let r=t[e.offset]&df;if(e.offset++,Nc[r]!=null)return Nc[r](t,e);throw new Error("No decoder for tag "+r)}function Or(t,e){let r=0;if((t[e.offset]&gs)===gs){let n=t[e.offset]&hf,i="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)i+=t[e.offset].toString(16).padStart(2,"0");r=parseInt(i,16)}else r=t[e.offset],e.offset++;return r}function Br(t,e){Or(t,e);let r=[];for(;!(e.offset>=t.byteLength);){let n=ws(t,e);if(n===null)break;r.push(n)}return r}function pf(t,e){let r=Or(t,e),n=e.offset,i=e.offset+r,o=[];for(let c=n;c<i;c++)c===n&&t[c]===0||o.push(t[c]);return e.offset+=r,Uint8Array.from(o)}function mf(t,e){let r=Or(t,e),n=e.offset+r,i=t[e.offset];e.offset++;let o=0,c=0;i<40?(o=0,c=i):i<80?(o=1,c=i-40):(o=2,c=i-80);let s=`${o}.${c}`,a=[];for(;e.offset<n;){let u=t[e.offset];if(e.offset++,a.push(u&127),u<128){a.reverse();let l=0;for(let f=0;f<a.length;f++)l+=a[f]<<f*7;s+=`.${l}`,a=[]}}return s}function yf(t,e){return e.offset++,null}function bf(t,e){let r=Or(t,e),n=t[e.offset];e.offset++;let i=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return i}function gf(t,e){let r=Or(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function wf(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);let r=new K;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function Es(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);let e=wf(t.byteLength);return new K(Uint8Array.from([e.byteLength|gs]),e)}function Rc(t){let e=new K,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new K(Uint8Array.from([2]),Es(e),e)}function Uc(t){let e=Uint8Array.from([0]),r=new K(e,t);return new K(Uint8Array.from([3]),Es(r),r)}function gn(t,e=48){let r=new K;for(let n of t)r.append(n);return new K(Uint8Array.from([e]),Es(r),r)}var Ef=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),xf=Uint8Array.from([6,5,43,129,4,0,34]),vf=Uint8Array.from([6,5,43,129,4,0,35]),Sf={ext:!0,kty:"EC",crv:"P-256"},If={ext:!0,kty:"EC",crv:"P-384"},Tf={ext:!0,kty:"EC",crv:"P-521"},xs=32,vs=48,Ss=66;function Fc(t){let e=ws(t);return Mc(e)}function Mc(t){let e=t[1][1][0],r=1,n,i;if(e.byteLength===xs*2+1)return n=ne(e.subarray(r,r+xs),"base64url"),i=ne(e.subarray(r+xs),"base64url"),new Yt({...Sf,key_ops:["verify"],x:n,y:i});if(e.byteLength===vs*2+1)return n=ne(e.subarray(r,r+vs),"base64url"),i=ne(e.subarray(r+vs),"base64url"),new Yt({...If,key_ops:["verify"],x:n,y:i});if(e.byteLength===Ss*2+1)return n=ne(e.subarray(r,r+Ss),"base64url"),i=ne(e.subarray(r+Ss),"base64url"),new Yt({...Tf,key_ops:["verify"],x:n,y:i});throw new j(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function $c(t){return gn([Rc(Uint8Array.from([1])),gn([Af(t.crv)],160),gn([Uc(new K(Uint8Array.from([4]),xe(t.x??"","base64url"),xe(t.y??"","base64url")))],161)]).subarray()}function Af(t){if(t==="P-256")return Ef;if(t==="P-384")return xf;if(t==="P-521")return vf;throw new j(`Invalid curve ${t}`)}var Yt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=$c(this.jwk)),this._raw}toMultihash(){return Ge.digest(mt(this))}toCID(){return ie.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ne(this.raw,e.raw)}async verify(e,r,n){return Bc(this.jwk,r,e,n)}};var wn=_e(se("crypto"),1);var my=wn.default.generateKeyPairSync,_r=32;var Df=64;function Kc(t,e,r){if(t.byteLength!==_r)throw new TypeError('"key" must be 32 bytes in length.');if(!(t instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');if(e.byteLength!==Df)throw new TypeError('"sig" must be 64 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"sig" must be a node.js Buffer, or Uint8Array.');let n=wn.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:ne(t,"base64url"),kty:"OKP"}});return wn.default.verify(null,r instanceof Uint8Array?r:r.subarray(),n,e)}function Vc(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var En=class{type="Ed25519";raw;constructor(e){this.raw=Is(e,_r)}toMultihash(){return Ge.digest(mt(this))}toCID(){return ie.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ne(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();let i=Kc(this.raw,r,e);return Vc(i)?i.then(o=>(n?.signal?.throwIfAborted(),o)):i}};function Gc(t){return t=Is(t,_r),new En(t)}function Is(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new j(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}var Ie;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(Ie||(Ie={}));var Ts;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(Ts||(Ts={}));(function(t){t.codec=()=>ze(Ts)})(Ie||(Ie={}));var kr;(function(t){let e;t.codec=()=>(e==null&&(e=Z((o,c,s={})=>{s.lengthDelimited!==!1&&c.fork(),o.Type!=null&&(c.uint32(8),Ie.codec().encode(o.Type,c)),o.Data!=null&&(c.uint32(18),c.bytes(o.Data)),s.lengthDelimited!==!1&&c.ldelim()},(o,c,s={})=>{let a={},u=c==null?o.len:o.pos+c;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{a.Type=Ie.codec().decode(o);break}case 2:{a.Data=o.bytes();break}default:{o.skipType(l&7);break}}}return a},function*(o,c,s,a={}){let u=c==null?o.len:o.pos+c;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${s}.Type`,value:Ie.codec().decode(o)};break}case 2:{yield{field:`${s}.Data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function r(o){return Y(o,t.codec())}t.encode=r;function n(o,c){return W(o,t.codec(),c)}t.decode=n;function i(o,c){return q(o,t.codec(),c)}t.stream=i})(kr||(kr={}));var As;(function(t){let e;t.codec=()=>(e==null&&(e=Z((o,c,s={})=>{s.lengthDelimited!==!1&&c.fork(),o.Type!=null&&(c.uint32(8),Ie.codec().encode(o.Type,c)),o.Data!=null&&(c.uint32(18),c.bytes(o.Data)),s.lengthDelimited!==!1&&c.ldelim()},(o,c,s={})=>{let a={},u=c==null?o.len:o.pos+c;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{a.Type=Ie.codec().decode(o);break}case 2:{a.Data=o.bytes();break}default:{o.skipType(l&7);break}}}return a},function*(o,c,s,a={}){let u=c==null?o.len:o.pos+c;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:{yield{field:`${s}.Type`,value:Ie.codec().decode(o)};break}case 2:{yield{field:`${s}.Data`,value:o.bytes()};break}default:{o.skipType(l&7);break}}}})),e);function r(o){return Y(o,t.codec())}t.encode=r;function n(o,c){return W(o,t.codec(),c)}t.decode=n;function i(o,c){return q(o,t.codec(),c)}t.stream=i})(As||(As={}));function Ds(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function yt(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(`${r}expected number, got ${typeof t}`)}if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new RangeError(`${r}expected integer >= 0, got ${t}`)}}function Je(t,e,r=""){let n=Ds(t),i=t?.length,o=e!==void 0;if(!n||o&&i!==e){let c=r&&`"${r}" `,s=o?` of length ${e}`:"",a=n?`length=${i}`:`type=${typeof t}`,u=c+"expected Uint8Array"+s+", got "+a;throw n?new RangeError(u):new TypeError(u)}return t}function xn(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(yt(t.outputLen),yt(t.blockLen),t.outputLen<1)throw new Error('"outputLen" must be >= 1');if(t.blockLen<1)throw new Error('"blockLen" must be >= 1')}function qt(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function vn(t,e){Je(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function Dt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Sn(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Ye(t,e){return t<<32-e|t>>>e}var Wc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Bf=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function In(t){if(Je(t),Wc)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Bf[t[r]];return e}var nt={_0:48,_9:57,A:65,F:70,a:97,f:102};function zc(t){if(t>=nt._0&&t<=nt._9)return t-nt._0;if(t>=nt.A&&t<=nt.F)return t-(nt.A-10);if(t>=nt.a&&t<=nt.f)return t-(nt.a-10)}function Ls(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Wc)try{return Uint8Array.fromHex(t)}catch(i){throw i instanceof SyntaxError?new RangeError(i.message):i}let e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let c=zc(t.charCodeAt(o)),s=zc(t.charCodeAt(o+1));if(c===void 0||s===void 0){let a=t[o]+t[o+1];throw new RangeError('hex string expected, got non-hex character "'+a+'" at index '+o)}n[i]=c*16+s}return n}function Yc(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];Je(i),e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}function qc(t,e={}){let r=(i,o)=>t(o).update(i).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=i=>t(i),Object.assign(r,e),Object.freeze(r)}function Zc(t=32){yt(t,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var jc=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Xc(t,e,r){return t&e^~t&r}function Qc(t,e,r){return t&e^t&r^e&r}var Tn=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,i){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Sn(this.buffer)}update(e){qt(this),Je(e);let{view:r,buffer:n,blockLen:i}=this,o=e.length;for(let c=0;c<o;){let s=Math.min(i-this.pos,o-c);if(s===i){let a=Sn(e);for(;i<=o-c;c+=i)this.process(a,c);continue}n.set(e.subarray(c,c+s),this.pos),this.pos+=s,c+=s,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){qt(this),vn(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:c}=this;r[c++]=128,Dt(this.buffer.subarray(c)),this.padOffset>i-c&&(this.process(n,0),c=0);for(let f=c;f<i;f++)r[f]=0;n.setBigUint64(i-8,BigInt(this.length*8),o),this.process(n,0);let s=Sn(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=a/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)s.setUint32(4*f,l[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:c,pos:s}=this;return e.destroyed=c,e.finished=o,e.length=i,e.pos=s,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},ot=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Of=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),bt=new Uint32Array(64),Cs=class extends Tn{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:i,E:o,F:c,G:s,H:a}=this;return[e,r,n,i,o,c,s,a]}set(e,r,n,i,o,c,s,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=c|0,this.G=s|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)bt[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let d=bt[f-15],h=bt[f-2],y=Ye(d,7)^Ye(d,18)^d>>>3,v=Ye(h,17)^Ye(h,19)^h>>>10;bt[f]=v+bt[f-7]+y+bt[f-16]|0}let{A:n,B:i,C:o,D:c,E:s,F:a,G:u,H:l}=this;for(let f=0;f<64;f++){let d=Ye(s,6)^Ye(s,11)^Ye(s,25),h=l+d+Xc(s,a,u)+Of[f]+bt[f]|0,v=(Ye(n,2)^Ye(n,13)^Ye(n,22))+Qc(n,i,o)|0;l=u,u=a,a=s,s=c+h|0,c=o,o=i,i=n,n=h+v|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,c=c+this.D|0,s=s+this.E|0,a=a+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,i,o,c,s,a,u,l)}roundClean(){Dt(bt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Dt(this.buffer)}},Bs=class extends Cs{A=ot[0]|0;B=ot[1]|0;C=ot[2]|0;D=ot[3]|0;E=ot[4]|0;F=ot[5]|0;G=ot[6]|0;H=ot[7]|0;constructor(){super(32)}};var Jc=qc(()=>new Bs,jc(1));var Ca=_e(se("node:crypto"),1);var fe=(t,e,r)=>Je(t,e,r),_s=yt,ks=In,st=(...t)=>Yc(...t),Ln=t=>Ls(t),Ps=Ds,Ns=t=>Zc(t),Dn=BigInt(0),Os=BigInt(1);function Lt(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new TypeError(r+"expected boolean, got type="+typeof t)}return t}function Cn(t){if(typeof t=="bigint"){if(!An(t))throw new RangeError("positive bigint expected, got "+t)}else _s(t);return t}function Pr(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(r+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){let r=e&&`"${e}" `;throw new RangeError(r+"expected safe integer, got "+t)}}function Nr(t){let e=Cn(t).toString(16);return e.length&1?"0"+e:e}function ea(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Dn:BigInt("0x"+t)}function Zt(t){return ea(In(t))}function Rs(t){return ea(In(_f(Je(t)).reverse()))}function Bn(t,e){if(yt(e),e===0)throw new RangeError("zero length");t=Cn(t);let r=t.toString(16);if(r.length>e*2)throw new RangeError("number too large");return Ls(r.padStart(e*2,"0"))}function Us(t,e){return Bn(t,e).reverse()}function _f(t){return Uint8Array.from(fe(t))}var An=t=>typeof t=="bigint"&&Dn<=t;function kf(t,e,r){return An(t)&&An(e)&&An(r)&&e<=t&&t<r}function Fs(t,e,r,n){if(!kf(e,r,n))throw new RangeError("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function jt(t){if(t<Dn)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>Dn;t>>=Os,e+=1);return e}var Rr=t=>(Os<<BigInt(t))-Os;function ta(t,e,r){if(yt(t,"hashLen"),yt(e,"qByteLen"),typeof r!="function")throw new TypeError("hmacFn must be a function");let n=m=>new Uint8Array(m),i=Uint8Array.of(),o=Uint8Array.of(0),c=Uint8Array.of(1),s=1e3,a=n(t),u=n(t),l=0,f=()=>{a.fill(1),u.fill(0),l=0},d=(...m)=>r(u,st(a,...m)),h=(m=i)=>{u=d(o,m),a=d(),m.length!==0&&(u=d(c,m),a=d())},y=()=>{if(l++>=s)throw new Error("drbg: tried max amount of iterations");let m=0,E=[];for(;m<e;){a=d();let L=a.slice();E.push(L),m+=a.length}return st(...E)};return(m,E)=>{f(),h(m);let L;for(;(L=E(y()))===void 0;)h();return f(),L}}function Ct(t,e={},r={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function n(o,c,s){if(!s&&c!=="function"&&!Object.hasOwn(t,o))throw new TypeError(`param "${o}" is invalid: expected own property`);let a=t[o];if(s&&a===void 0)return;let u=typeof a;if(u!==c||a===null)throw new TypeError(`param "${o}" is invalid: expected ${c}, got ${u}`)}let i=(o,c)=>Object.entries(o).forEach(([s,a])=>n(s,a,c));i(e,!1),i(r,!0)}var be=BigInt(0),oe=BigInt(1),Bt=BigInt(2),sa=BigInt(3),ia=BigInt(4),ca=BigInt(5),Pf=BigInt(7),aa=BigInt(8),Nf=BigInt(9),ua=BigInt(16);function qe(t,e){if(e<=be)throw new Error("mod: expected positive modulus, got "+e);let r=t%e;return r>=be?r:e+r}function Re(t,e,r){if(e<be)throw new Error("pow2: expected non-negative exponent, got "+e);let n=t;for(;e-- >be;)n*=n,n%=r;return n}function ra(t,e){if(t===be)throw new Error("invert: expected non-zero number");if(e<=be)throw new Error("invert: expected positive modulus, got "+e);let r=qe(t,e),n=e,i=be,o=oe,c=oe,s=be;for(;r!==be;){let u=n/r,l=n-r*u,f=i-c*u,d=o-s*u;n=r,r=l,i=c,o=s,c=f,s=d}if(n!==oe)throw new Error("invert: does not exist");return qe(i,e)}function Ms(t,e,r){let n=t;if(!n.eql(n.sqr(e),r))throw new Error("Cannot find square root")}function la(t,e){let r=t,n=(r.ORDER+oe)/ia,i=r.pow(e,n);return Ms(r,i,e),i}function Rf(t,e){let r=t,n=(r.ORDER-ca)/aa,i=r.mul(e,Bt),o=r.pow(i,n),c=r.mul(e,o),s=r.mul(r.mul(c,Bt),o),a=r.mul(c,r.sub(s,r.ONE));return Ms(r,a,e),a}function Uf(t){let e=Xt(t),r=fa(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),c=(t+Pf)/ua;return((s,a)=>{let u=s,l=u.pow(a,c),f=u.mul(l,n),d=u.mul(l,i),h=u.mul(l,o),y=u.eql(u.sqr(f),a),v=u.eql(u.sqr(d),a);l=u.cmov(l,f,y),f=u.cmov(h,d,v);let m=u.eql(u.sqr(f),a),E=u.cmov(l,f,m);return Ms(u,E,a),E})}function fa(t){if(t<sa)throw new Error("sqrt is not defined for small field");let e=t-oe,r=0;for(;e%Bt===be;)e/=Bt,r++;let n=Bt,i=Xt(t);for(;na(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return la;let o=i.pow(n,e),c=(e+oe)/Bt;return function(a,u){let l=a;if(l.is0(u))return u;if(na(l,u)!==1)throw new Error("Cannot find square root");let f=r,d=l.mul(l.ONE,o),h=l.pow(u,e),y=l.pow(u,c);for(;!l.eql(h,l.ONE);){if(l.is0(h))return l.ZERO;let v=1,m=l.sqr(h);for(;!l.eql(m,l.ONE);)if(v++,m=l.sqr(m),v===f)throw new Error("Cannot find square root");let E=oe<<BigInt(f-v-1),L=l.pow(d,E);f=v,d=l.sqr(L),h=l.mul(h,d),y=l.mul(y,L)}return y}}function Ff(t){return t%ia===sa?la:t%aa===ca?Rf:t%ua===Nf?Uf(t):fa(t)}var Mf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function $s(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=Mf.reduce((n,i)=>(n[i]="function",n),e);if(Ct(t,r),Pr(t.BYTES,"BYTES"),Pr(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=oe)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function $f(t,e,r){let n=t;if(r<be)throw new Error("invalid exponent, negatives unsupported");if(r===be)return n.ONE;if(r===oe)return e;let i=n.ONE,o=e;for(;r>be;)r&oe&&(i=n.mul(i,o)),o=n.sqr(o),r>>=oe;return i}function _n(t,e,r=!1){let n=t,i=new Array(e.length).fill(r?n.ZERO:void 0),o=e.reduce((s,a,u)=>n.is0(a)?s:(i[u]=s,n.mul(s,a)),n.ONE),c=n.inv(o);return e.reduceRight((s,a,u)=>n.is0(a)?s:(i[u]=n.mul(s,i[u]),n.mul(s,a)),c),i}function na(t,e){let r=t,n=(r.ORDER-oe)/Bt,i=r.pow(e,n),o=r.eql(i,r.ONE),c=r.eql(i,r.ZERO),s=r.eql(i,r.neg(r.ONE));if(!o&&!c&&!s)throw new Error("invalid Legendre symbol result");return o?1:c?0:-1}function Kf(t,e){if(e!==void 0&&_s(e),t<=be)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let r=jt(t);if(e!==void 0&&e<r)throw new Error(`invalid n length: expected bit length (${r}) >= n.length (${e})`);let n=e!==void 0?e:r,i=Math.ceil(n/8);return{nBitLength:n,nByteLength:i}}var oa=new WeakMap,On=class{ORDER;BITS;BYTES;isLE;ZERO=be;ONE=oe;_lengths;_mod;constructor(e,r={}){if(e<=oe)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:i,nByteLength:o}=Kf(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=i,this.BYTES=o,Object.freeze(this)}create(e){return qe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return be<=e&&e<this.ORDER}is0(e){return e===be}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&oe)===oe}neg(e){return qe(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return qe(e*e,this.ORDER)}add(e,r){return qe(e+r,this.ORDER)}sub(e,r){return qe(e-r,this.ORDER)}mul(e,r){return qe(e*r,this.ORDER)}pow(e,r){return $f(this,e,r)}div(e,r){return qe(e*ra(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return ra(e,this.ORDER)}sqrt(e){let r=oa.get(this);return r||oa.set(this,r=Ff(this.ORDER)),r(this,e)}toBytes(e){return this.isLE?Us(e,this.BYTES):Bn(e,this.BYTES)}fromBytes(e,r=!1){fe(e);let{_lengths:n,BYTES:i,isLE:o,ORDER:c,_mod:s}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>i)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(i);u.set(e,o?0:u.length-e.length),e=u}if(e.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+e.length);let a=o?Rs(e):Zt(e);if(s&&(a=qe(a,c)),!r&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(e){return _n(this,e)}cmov(e,r,n){return Lt(n,"condition"),n?r:e}};Object.freeze(On.prototype);function Xt(t,e={}){return new On(t,e)}function da(t){if(typeof t!="bigint")throw new Error("field order must be bigint");if(t<=oe)throw new Error("field order must be greater than 1");let e=jt(t-oe);return Math.ceil(e/8)}function Ks(t){let e=da(t);return e+Math.ceil(e/2)}function Hs(t,e,r=!1){fe(t);let n=t.length,i=da(e),o=Math.max(Ks(e),16);if(n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let c=r?Rs(t):Zt(t),s=qe(c,e-oe)+oe;return r?Us(s,i):Bn(s,i)}var Qt=BigInt(0),Ot=BigInt(1);function Ur(t,e){let r=e.negate();return t?r:e}function Ws(t,e){let r=_n(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function ya(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Vs(t,e){ya(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=Rr(t),c=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:c}}function ha(t,e,r){let{windowSize:n,mask:i,maxNumber:o,shiftBy:c}=r,s=Number(t&i),a=t>>c;s>n&&(s-=o,a+=Ot);let u=e*n,l=u+Math.abs(s)-1,f=s===0,d=s<0,h=e%2!==0;return{nextN:a,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}var Gs=new WeakMap,ba=new WeakMap;function zs(t){return ba.get(t)||1}function pa(t){if(t!==Qt)throw new Error("invalid wNAF")}var kn=class{BASE;ZERO;Fn;bits;constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let i=e;for(;r>Qt;)r&Ot&&(n=n.add(i)),i=i.double(),r>>=Ot;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=Vs(r,this.bits),o=[],c=e,s=c;for(let a=0;a<n;a++){s=c,o.push(s);for(let u=1;u<i;u++)s=s.add(c),o.push(s);c=s.double()}return o}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let i=this.ZERO,o=this.BASE,c=Vs(e,this.bits);for(let s=0;s<c.windows;s++){let{nextN:a,offset:u,isZero:l,isNeg:f,isNegF:d,offsetF:h}=ha(n,s,c);n=a,l?o=o.add(Ur(d,r[h])):i=i.add(Ur(f,r[u]))}return pa(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=Vs(e,this.bits);for(let c=0;c<o.windows&&n!==Qt;c++){let{nextN:s,offset:a,isZero:u,isNeg:l}=ha(n,c,o);if(n=s,!u){let f=r[a];i=i.add(l?f.negate():f)}}return pa(n),i}getPrecomputes(e,r,n){let i=Gs.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),Gs.set(r,i))),i}cached(e,r,n){let i=zs(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=zs(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){ya(r,this.bits),ba.set(e,r),Gs.delete(e)}hasCache(e){return zs(e)!==1}};function ga(t,e,r,n){let i=e,o=t.ZERO,c=t.ZERO;for(;r>Qt||n>Qt;)r&Ot&&(o=o.add(i)),n&Ot&&(c=c.add(i)),i=i.double(),r>>=Ot,n>>=Ot;return{p1:o,p2:c}}function ma(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return $s(e),e}else return Xt(t,{isLE:r})}function wa(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let a of["p","n","h"]){let u=e[a];if(!(typeof u=="bigint"&&u>Qt))throw new Error(`CURVE.${a} must be positive bigint`)}let i=ma(e.p,r.Fp,n),o=ma(e.n,r.Fn,n),s=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let a of s)if(!i.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:o}}function Ea(t,e){return function(n){let i=t(n);return{secretKey:i,publicKey:e(i)}}}var Pn=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(xn(e),Je(r,void 0,"key"),this.iHash=e.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 n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),Dt(i)}update(e){return qt(this),this.iHash.update(e),this}digestInto(e){qt(this),vn(e,this),this.finished=!0;let r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:i,destroyed:o,blockLen:c,outputLen:s}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=c,e.outputLen=s,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},xa=(()=>{let t=((e,r,n)=>new Pn(e,r).update(n).digest());return t.create=(e,r)=>new Pn(e,r),t})();var va=(t,e)=>(t+(t>=0?e:-e)/Sa)/e;function Hf(t,e,r){Fs("scalar",t,et,r);let[[n,i],[o,c]]=e,s=va(c*t,r),a=va(-i*t,r),u=t-s*n-a*o,l=-s*i-a*c,f=u<et,d=l<et;f&&(u=-u),d&&(l=-l);let h=Rr(Math.ceil(jt(r)/2))+gt;if(u<et||u>=h||l<et||l>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:u,k2neg:d,k2:l}}function qs(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Ys(t,e){Ct(t);let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Lt(r.lowS,"lowS"),Lt(r.prehash,"prehash"),r.format!==void 0&&qs(r.format),r}var Zs=class extends Error{constructor(e=""){super(e)}},Ze={Err:Zs,_tlv:{encode:(t,e)=>{let{Err:r}=Ze;if(Pr(t,"tag"),t<0||t>255)throw new r("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,i=Nr(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?Nr(i.length/2|128):"";return Nr(t)+o+i+e},decode(t,e){let{Err:r}=Ze;e=fe(e,void 0,"DER data");let n=0;if(t<0||t>255)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let i=e[n++],o=!!(i&128),c=0;if(!o)c=i;else{let a=i&127;if(!a)throw new r("tlv.decode(long): indefinite length not supported");if(a>4)throw new r("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+a);if(u.length!==a)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let l of u)c=c<<8|l;if(n+=a,c<128)throw new r("tlv.decode(long): not minimal encoding")}let s=e.subarray(n,n+c);if(s.length!==c)throw new r("tlv.decode: wrong value length");return{v:s,l:e.subarray(n+c)}}},_int:{encode(t){let{Err:e}=Ze;if(Cn(t),t<et)throw new e("integer: negative integers are not allowed");let r=Nr(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=Ze;if(t.length<1)throw new e("invalid signature integer: empty");if(t[0]&128)throw new e("invalid signature integer: negative");if(t.length>1&&t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Zt(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=Ze,i=fe(t,void 0,"signature"),{v:o,l:c}=n.decode(48,i);if(c.length)throw new e("invalid signature: left bytes after parsing");let{v:s,l:a}=n.decode(2,o),{v:u,l}=n.decode(2,a);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(s),s:r.decode(u)}},hexFromSig(t){let{_tlv:e,_int:r}=Ze,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}};Object.freeze(Ze._tlv);Object.freeze(Ze._int);Object.freeze(Ze);var et=BigInt(0),gt=BigInt(1),Sa=BigInt(2),Nn=BigInt(3),Vf=BigInt(4);function Ia(t,e={}){let r=wa("weierstrass",t,e),n=r.Fp,i=r.Fn,o=r.CURVE,{h:c,n:s}=o;Ct(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:a,allowInfinityPoint:u}=e;if(a&&(!n.is0(o.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Aa(n,i);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(J,b,T){if(u&&b.is0())return Uint8Array.of(0);let{x:D,y:g}=b.toAffine(),p=n.toBytes(D);if(Lt(T,"isCompressed"),T){f();let w=!n.isOdd(g);return st(Ta(w),p)}else return st(Uint8Array.of(4),p,n.toBytes(g))}function h(J){fe(J,void 0,"Point");let{publicKey:b,publicKeyUncompressed:T}=l,D=J.length,g=J[0],p=J.subarray(1);if(u&&D===1&&g===0)return{x:n.ZERO,y:n.ZERO};if(D===b&&(g===2||g===3)){let w=n.fromBytes(p);if(!n.isValid(w))throw new Error("bad point: is not on curve, wrong x");let S=m(w),x;try{x=n.sqrt(S)}catch($){let F=$ instanceof Error?": "+$.message:"";throw new Error("bad point: is not on curve, sqrt error"+F)}f();let A=n.isOdd(x);return(g&1)===1!==A&&(x=n.neg(x)),{x:w,y:x}}else if(D===T&&g===4){let w=n.BYTES,S=n.fromBytes(p.subarray(0,w)),x=n.fromBytes(p.subarray(w,w*2));if(!E(S,x))throw new Error("bad point: is not on curve");return{x:S,y:x}}else throw new Error(`bad point: got length ${D}, expected compressed=${b} or uncompressed=${T}`)}let y=e.toBytes===void 0?d:e.toBytes,v=e.fromBytes===void 0?h:e.fromBytes;function m(J){let b=n.sqr(J),T=n.mul(b,J);return n.add(n.add(T,n.mul(J,o.a)),o.b)}function E(J,b){let T=n.sqr(b),D=m(J);return n.eql(T,D)}if(!E(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let L=n.mul(n.pow(o.a,Nn),Vf),P=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(L,P)))throw new Error("bad curve params: a or b");function M(J,b,T=!1){if(!n.isValid(b)||T&&n.is0(b))throw new Error(`bad point coordinate ${J}`);return b}function _(J){if(!(J instanceof B))throw new Error("Weierstrass Point expected")}function ce(J){if(!a||!a.basises)throw new Error("no endo");return Hf(J,a.basises,i.ORDER)}function X(J,b,T,D,g){return T=new B(n.mul(T.X,J),T.Y,T.Z),b=Ur(D,b),T=Ur(g,T),b.add(T)}class B{static BASE=new B(o.Gx,o.Gy,n.ONE);static ZERO=new B(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=i;X;Y;Z;constructor(b,T,D){this.X=M("x",b),this.Y=M("y",T,!0),this.Z=M("z",D),Object.freeze(this)}static CURVE(){return o}static fromAffine(b){let{x:T,y:D}=b||{};if(!b||!n.isValid(T)||!n.isValid(D))throw new Error("invalid affine point");if(b instanceof B)throw new Error("projective point not allowed");return n.is0(T)&&n.is0(D)?B.ZERO:new B(T,D,n.ONE)}static fromBytes(b){let T=B.fromAffine(v(fe(b,void 0,"point")));return T.assertValidity(),T}static fromHex(b){return B.fromBytes(Ln(b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,T=!0){return He.createCache(this,b),T||this.multiply(Nn),this}assertValidity(){let b=this;if(b.is0()){if(e.allowInfinityPoint&&n.is0(b.X)&&n.eql(b.Y,n.ONE)&&n.is0(b.Z))return;throw new Error("bad point: ZERO")}let{x:T,y:D}=b.toAffine();if(!n.isValid(T)||!n.isValid(D))throw new Error("bad point: x or y not field elements");if(!E(T,D))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){_(b);let{X:T,Y:D,Z:g}=this,{X:p,Y:w,Z:S}=b,x=n.eql(n.mul(T,S),n.mul(p,g)),A=n.eql(n.mul(D,S),n.mul(w,g));return x&&A}negate(){return new B(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:T}=o,D=n.mul(T,Nn),{X:g,Y:p,Z:w}=this,S=n.ZERO,x=n.ZERO,A=n.ZERO,C=n.mul(g,g),$=n.mul(p,p),F=n.mul(w,w),k=n.mul(g,p);return k=n.add(k,k),A=n.mul(g,w),A=n.add(A,A),S=n.mul(b,A),x=n.mul(D,F),x=n.add(S,x),S=n.sub($,x),x=n.add($,x),x=n.mul(S,x),S=n.mul(k,S),A=n.mul(D,A),F=n.mul(b,F),k=n.sub(C,F),k=n.mul(b,k),k=n.add(k,A),A=n.add(C,C),C=n.add(A,C),C=n.add(C,F),C=n.mul(C,k),x=n.add(x,C),F=n.mul(p,w),F=n.add(F,F),C=n.mul(F,k),S=n.sub(S,C),A=n.mul(F,$),A=n.add(A,A),A=n.add(A,A),new B(S,x,A)}add(b){_(b);let{X:T,Y:D,Z:g}=this,{X:p,Y:w,Z:S}=b,x=n.ZERO,A=n.ZERO,C=n.ZERO,$=o.a,F=n.mul(o.b,Nn),k=n.mul(T,p),pe=n.mul(D,w),me=n.mul(g,S),ye=n.add(T,D),ee=n.add(p,w);ye=n.mul(ye,ee),ee=n.add(k,pe),ye=n.sub(ye,ee),ee=n.add(T,g);let De=n.add(p,S);return ee=n.mul(ee,De),De=n.add(k,me),ee=n.sub(ee,De),De=n.add(D,g),x=n.add(w,S),De=n.mul(De,x),x=n.add(pe,me),De=n.sub(De,x),C=n.mul($,ee),x=n.mul(F,me),C=n.add(x,C),x=n.sub(pe,C),C=n.add(pe,C),A=n.mul(x,C),pe=n.add(k,k),pe=n.add(pe,k),me=n.mul($,me),ee=n.mul(F,ee),pe=n.add(pe,me),me=n.sub(k,me),me=n.mul($,me),ee=n.add(ee,me),k=n.mul(pe,ee),A=n.add(A,k),k=n.mul(De,ee),x=n.mul(ye,x),x=n.sub(x,k),k=n.mul(ye,pe),C=n.mul(De,C),C=n.add(C,k),new B(x,A,C)}subtract(b){return _(b),this.add(b.negate())}is0(){return this.equals(B.ZERO)}multiply(b){let{endo:T}=e;if(!i.isValidNot0(b))throw new RangeError("invalid scalar: out of range");let D,g,p=w=>He.cached(this,w,S=>Ws(B,S));if(T){let{k1neg:w,k1:S,k2neg:x,k2:A}=ce(b),{p:C,f:$}=p(S),{p:F,f:k}=p(A);g=$.add(k),D=X(T.beta,C,F,w,x)}else{let{p:w,f:S}=p(b);D=w,g=S}return Ws(B,[D,g])[0]}multiplyUnsafe(b){let{endo:T}=e,D=this,g=b;if(!i.isValid(g))throw new RangeError("invalid scalar: out of range");if(g===et||D.is0())return B.ZERO;if(g===gt)return D;if(He.hasCache(this))return this.multiply(g);if(T){let{k1neg:p,k1:w,k2neg:S,k2:x}=ce(g),{p1:A,p2:C}=ga(B,D,w,x);return X(T.beta,A,C,p,S)}else return He.unsafe(D,g)}toAffine(b){let T=this,D=b,{X:g,Y:p,Z:w}=T;if(n.eql(w,n.ONE))return{x:g,y:p};let S=T.is0();D==null&&(D=S?n.ONE:n.inv(w));let x=n.mul(g,D),A=n.mul(p,D),C=n.mul(w,D);if(S)return{x:n.ZERO,y:n.ZERO};if(!n.eql(C,n.ONE))throw new Error("invZ was invalid");return{x,y:A}}isTorsionFree(){let{isTorsionFree:b}=e;return c===gt?!0:b?b(B,this):He.unsafe(this,s).is0()}clearCofactor(){let{clearCofactor:b}=e;return c===gt?this:b?b(B,this):this.multiplyUnsafe(c)}isSmallOrder(){return c===gt?this.is0():this.clearCofactor().is0()}toBytes(b=!0){return Lt(b,"isCompressed"),this.assertValidity(),y(B,this,b)}toHex(b=!0){return ks(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let Ae=i.BITS,He=new kn(B,e.endo?Math.ceil(Ae/2):Ae);return Ae>=8&&B.BASE.precompute(8),Object.freeze(B.prototype),Object.freeze(B),B}function Ta(t){return Uint8Array.of(t?2:3)}function Aa(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Gf(t,e={}){let{Fn:r}=t,n=e.randomBytes===void 0?Ns:e.randomBytes,i=Object.assign(Aa(t.Fp,r),{seed:Math.max(Ks(r.ORDER),16)});function o(h){try{let y=r.fromBytes(h);return r.isValidNot0(y)}catch{return!1}}function c(h,y){let{publicKey:v,publicKeyUncompressed:m}=i;try{let E=h.length;return y===!0&&E!==v||y===!1&&E!==m?!1:!!t.fromBytes(h)}catch{return!1}}function s(h){return h=h===void 0?n(i.seed):h,Hs(fe(h,i.seed,"seed"),r.ORDER)}function a(h,y=!0){return t.BASE.multiply(r.fromBytes(h)).toBytes(y)}function u(h){let{secretKey:y,publicKey:v,publicKeyUncompressed:m}=i,E=r._lengths;if(!Ps(h))return;let L=fe(h,void 0,"key").length,P=L===v||L===m,M=L===y||!!E?.includes(L);if(!(P&&M))return P}function l(h,y,v=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(y)===!1)throw new Error("second arg must be public key");let m=r.fromBytes(h);return t.fromBytes(y).multiply(m).toBytes(v)}let f={isValidSecretKey:o,isValidPublicKey:c,randomSecretKey:s},d=Ea(s,a);return Object.freeze(f),Object.freeze(i),Object.freeze({getPublicKey:a,getSharedSecret:l,keygen:d,Point:t,utils:f,lengths:i})}function Da(t,e,r={}){let n=e;xn(n),Ct(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let i=r.randomBytes===void 0?Ns:r.randomBytes,o=r.hmac===void 0?(g,p)=>xa(n,g,p):r.hmac,{Fp:c,Fn:s}=t,{ORDER:a,BITS:u}=s,{keygen:l,getPublicKey:f,getSharedSecret:d,utils:h,lengths:y}=Gf(t,r),v={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},m=a*Sa+gt<c.ORDER;function E(g){let p=a>>gt;return g>p}function L(g,p){if(!s.isValidNot0(p))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return p}function P(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function M(g,p){qs(p);let w=y.signature,S=p==="compact"?w:p==="recovered"?w+1:void 0;return fe(g,S)}class _{r;s;recovery;constructor(p,w,S){if(this.r=L("r",p),this.s=L("s",w),S!=null){if(P(),![0,1,2,3].includes(S))throw new Error("invalid recovery id");this.recovery=S}Object.freeze(this)}static fromBytes(p,w=v.format){M(p,w);let S;if(w==="der"){let{r:$,s:F}=Ze.toSig(fe(p));return new _($,F)}w==="recovered"&&(S=p[0],w="compact",p=p.subarray(1));let x=y.signature/2,A=p.subarray(0,x),C=p.subarray(x,x*2);return new _(s.fromBytes(A),s.fromBytes(C),S)}static fromHex(p,w){return this.fromBytes(Ln(p),w)}assertRecovery(){let{recovery:p}=this;if(p==null)throw new Error("invalid recovery id: must be present");return p}addRecoveryBit(p){return new _(this.r,this.s,p)}recoverPublicKey(p){let{r:w,s:S}=this,x=this.assertRecovery(),A=x===2||x===3?w+a:w;if(!c.isValid(A))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let C=c.toBytes(A),$=t.fromBytes(st(Ta((x&1)===0),C)),F=s.inv(A),k=X(fe(p,void 0,"msgHash")),pe=s.create(-k*F),me=s.create(S*F),ye=t.BASE.multiplyUnsafe(pe).add($.multiplyUnsafe(me));if(ye.is0())throw new Error("invalid recovery: point at infinify");return ye.assertValidity(),ye}hasHighS(){return E(this.s)}toBytes(p=v.format){if(qs(p),p==="der")return Ln(Ze.hexFromSig(this));let{r:w,s:S}=this,x=s.toBytes(w),A=s.toBytes(S);return p==="recovered"?(P(),st(Uint8Array.of(this.assertRecovery()),x,A)):st(x,A)}toHex(p){return ks(this.toBytes(p))}}Object.freeze(_.prototype),Object.freeze(_);let ce=r.bits2int===void 0?function(p){if(p.length>8192)throw new Error("input is too large");let w=Zt(p),S=p.length*8-u;return S>0?w>>BigInt(S):w}:r.bits2int,X=r.bits2int_modN===void 0?function(p){return s.create(ce(p))}:r.bits2int_modN,B=Rr(u);function Ae(g){return Fs("num < 2^"+u,g,et,B),s.toBytes(g)}function He(g,p){return fe(g,void 0,"message"),p?fe(n(g),void 0,"prehashed message"):g}function J(g,p,w){let{lowS:S,prehash:x,extraEntropy:A}=Ys(w,v);g=He(g,x);let C=X(g),$=s.fromBytes(p);if(!s.isValidNot0($))throw new Error("invalid private key");let F=[Ae($),Ae(C)];if(A!=null&&A!==!1){let ye=A===!0?i(y.secretKey):A;F.push(fe(ye,void 0,"extraEntropy"))}let k=st(...F),pe=C;function me(ye){let ee=ce(ye);if(!s.isValidNot0(ee))return;let De=s.inv(ee),Rt=t.BASE.multiply(ee).toAffine(),ar=s.create(Rt.x);if(ar===et)return;let zr=s.create(De*s.create(pe+ar*$));if(zr===et)return;let Fi=(Rt.x===ar?0:2)|Number(Rt.y>),Mi=zr;return S&&E(zr)&&(Mi=s.neg(zr),Fi^=1),new _(ar,Mi,m?void 0:Fi)}return{seed:k,k2sig:me}}function b(g,p,w={}){let{seed:S,k2sig:x}=J(g,p,w);return ta(n.outputLen,s.BYTES,o)(S,x).toBytes(w.format)}function T(g,p,w,S={}){let{lowS:x,prehash:A,format:C}=Ys(S,v);if(w=fe(w,void 0,"publicKey"),p=He(p,A),!Ps(g)){let $=g instanceof _?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+$)}M(g,C);try{let $=_.fromBytes(g,C),F=t.fromBytes(w);if(x&&$.hasHighS())return!1;let{r:k,s:pe}=$,me=X(p),ye=s.inv(pe),ee=s.create(me*ye),De=s.create(k*ye),Rt=t.BASE.multiplyUnsafe(ee).add(F.multiplyUnsafe(De));return Rt.is0()?!1:s.create(Rt.x)===k}catch{return!1}}function D(g,p,w={}){let{prehash:S}=Ys(w,v);return p=He(p,S),_.fromBytes(g,"recovered").recoverPublicKey(p).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:d,utils:h,lengths:y,Point:t,sign:b,verify:T,recoverPublicKey:D,Signature:_,hash:n})}var Xs={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},zf={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var La=BigInt(2);function Wf(t){let e=Xs.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),c=BigInt(23),s=BigInt(44),a=BigInt(88),u=t*t*t%e,l=u*u*t%e,f=Re(l,r,e)*l%e,d=Re(f,r,e)*l%e,h=Re(d,La,e)*u%e,y=Re(h,i,e)*h%e,v=Re(y,o,e)*y%e,m=Re(v,s,e)*v%e,E=Re(m,a,e)*m%e,L=Re(E,s,e)*v%e,P=Re(L,r,e)*l%e,M=Re(P,c,e)*y%e,_=Re(M,n,e)*u%e,ce=Re(_,La,e);if(!js.eql(js.sqr(ce),t))throw new Error("Cannot find square root");return ce}var js=Xt(Xs.p,{sqrt:Wf}),Yf=Ia(Xs,{Fp:js,endo:zf}),Fr=Da(Yf,Jc);var Rn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}};function Ba(t,e,r,n){n?.signal?.throwIfAborted();let i=Ca.default.createHash("sha256");if(r instanceof Uint8Array)i.update(r);else for(let c of r)i.update(c);let o=i.digest();try{return Fr.verify(e,o,t,{prehash:!1,format:"der"})}catch(c){throw new Rn(String(c))}}var Un=class{type="secp256k1";raw;_key;constructor(e){this._key=_a(e),this.raw=Oa(this._key)}toMultihash(){return Ge.digest(mt(this))}toCID(){return ie.createV1(114,this.toMultihash())}toString(){return te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ne(this.raw,e.raw)}verify(e,r,n){return Ba(this._key,r,e,n)}};function ka(t){return new Un(t)}function Oa(t){return Fr.Point.fromBytes(t).toBytes()}function _a(t){try{return Fr.Point.fromBytes(t),t}catch(e){throw new an(String(e))}}function Pa(t){let{Type:e,Data:r}=kr.decode(t.digest),n=r??new Uint8Array;switch(e){case Ie.Ed25519:return Gc(n);case Ie.secp256k1:return ka(n);case Ie.ECDSA:return Fc(n);default:throw new Cr}}function mt(t){return kr.encode({Type:Ie[t.type],Data:t.raw})}var Na=Symbol.for("nodejs.util.inspect.custom"),qf=114,Mr=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[bs]=!0;toString(){return this.string==null&&(this.string=te.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ie.createV1(qf,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Ne(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Ne(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Na](){return`PeerId(${this.toString()})`}},Fn=class extends Mr{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Mn=class extends Mr{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},$n=class extends Mr{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Zf=2336,Kn=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ge.digest(xe(this.url))}[Na](){return`PeerId(${this.url})`}[bs]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ie.createV1(Zf,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=ne(e)),e.toString()===this.toString())}};function Jt(t){if(Xf(t))return new Fn({multihash:t});if(jf(t))try{let e=Pa(t);if(e.type==="Ed25519")return new Mn({multihash:t,publicKey:e});if(e.type==="secp256k1")return new $n({multihash:t,publicKey:e})}catch{let r=ne(t.digest);return new Kn(new URL(r))}throw new ln("Supplied PeerID Multihash is invalid")}function jf(t){return t.code===Ge.code}function Xf(t){return t.code===ss.code}var bu=_e(se("net"),1);var ge=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},it=class extends Error{static name="ValidationError";name="ValidationError"},Hn=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Vn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Ue=se("node:net");function Js(t){return e=>ne(e,t)}function ei(t){return e=>xe(e,t)}function er(t){return new DataView(t.buffer).getUint16(t.byteOffset).toString()}function _t(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof t=="string"?parseInt(t):t),new Uint8Array(e)}function Ra(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let r=xe(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=_t(n);return Qe([r,i],r.length+i.length)}function Ua(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let r=je.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=_t(n);return Qe([r,i],r.length+i.length)}function ti(t){let e=t.subarray(0,t.length-2),r=t.subarray(t.length-2),n=ne(e,"base32"),i=er(r);return`${n}:${i}`}var ri=function(t){t=t.toString().trim();let e=new Uint8Array(4);return t.split(/\./g).forEach((r,n)=>{let i=parseInt(r,10);if(isNaN(i)||i<0||i>255)throw new ge("Invalid byte value in IP address");e[n]=i}),e},Fa=function(t){let e=0;t=t.toString().trim();let r=t.split(":",8),n;for(n=0;n<r.length;n++){let o=(0,Ue.isIPv4)(r[n]),c;o&&(c=ri(r[n]),r[n]=ne(c.subarray(0,2),"base16")),c!=null&&++n<8&&r.splice(n,0,ne(c.subarray(2,4),"base16"))}if(r[0]==="")for(;r.length<8;)r.unshift("0");else if(r[r.length-1]==="")for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&r[n]!=="";n++);let o=[n,1];for(n=9-r.length;n>0;n--)o.push("0");r.splice.apply(r,o)}let i=new Uint8Array(e+16);for(n=0;n<r.length;n++){r[n]===""&&(r[n]="0");let o=parseInt(r[n],16);if(isNaN(o)||o<0||o>65535)throw new ge("Invalid byte value in IP address");i[e++]=o>>8&255,i[e++]=o&255}return i},Ma=function(t){if(t.byteLength!==4)throw new ge("IPv4 address was incorrect length");let e=[];for(let r=0;r<t.byteLength;r++)e.push(t[r]);return e.join(".")},$a=function(t){if(t.byteLength!==16)throw new ge("IPv6 address was incorrect length");let e=[];for(let n=0;n<t.byteLength;n+=2){let i=t[n],o=t[n+1],c=`${i.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(c)}let r=e.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new ge(`Invalid IPv6 address "${r}"`)}};function Ka(t){try{let e=new URL(`http://[${t}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new ge(`Invalid IPv6 address "${t}"`)}}var Qs=Object.values(pr).map(t=>t.decoder),Qf=(function(){let t=Qs[0].or(Qs[1]);return Qs.slice(2).forEach(e=>t=t.or(e)),t})();function Ha(t){return Qf.decode(t)}function Va(t){return e=>t.encoder.encode(e)}function Jf(t){if(parseInt(t).toString()!==t)throw new it("Value must be an integer")}function ed(t){if(t<0)throw new it("Value must be a positive integer, or zero")}function td(t){return e=>{if(e>t)throw new it(`Value must be smaller than or equal to ${t}`)}}function rd(...t){return e=>{for(let r of t)r(e)}}var $r=rd(Jf,ed,td(65535));var de=-1,ni=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let r;if(typeof e=="string"?r=this.protocolsByName.get(e):r=this.protocolsByCode.get(e),r==null)throw new Vn(`Protocol ${e} was unknown`);return r}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(r=>{this.protocolsByName.set(r,e)})}removeProtocol(e){let r=this.protocolsByCode.get(e);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},at=new ni,yd=[{code:4,name:"ip4",size:32,valueToBytes:ri,bytesToValue:Ma,validate:t=>{if(!(0,Ue.isIPv4)(t))throw new it(`Invalid IPv4 address "${t}"`)}},{code:6,name:"tcp",size:16,valueToBytes:_t,bytesToValue:er,validate:$r},{code:273,name:"udp",size:16,valueToBytes:_t,bytesToValue:er,validate:$r},{code:33,name:"dccp",size:16,valueToBytes:_t,bytesToValue:er,validate:$r},{code:41,name:"ip6",size:128,valueToBytes:Fa,bytesToValue:$a,stringToValue:Ka,validate:t=>{if(!(0,Ue.isIPv6)(t))throw new it(`Invalid IPv6 address "${t}"`)}},{code:42,name:"ip6zone",size:de},{code:43,name:"ipcidr",size:8,bytesToValue:Js("base10"),valueToBytes:ei("base10")},{code:53,name:"dns",size:de},{code:54,name:"dns4",size:de},{code:55,name:"dns6",size:de},{code:56,name:"dnsaddr",size:de},{code:132,name:"sctp",size:16,valueToBytes:_t,bytesToValue:er,validate:$r},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:de,stringToValue:t=>decodeURIComponent(t),valueToString:t=>encodeURIComponent(t)},{code:421,name:"p2p",aliases:["ipfs"],size:de,bytesToValue:Js("base58btc"),valueToBytes:t=>t.startsWith("Q")||t.startsWith("1")?ei("base58btc")(t):ie.parse(t).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:ti,valueToBytes:Ra},{code:445,name:"onion3",size:296,bytesToValue:ti,valueToBytes:Ua},{code:446,name:"garlic64",size:de},{code:447,name:"garlic32",size:de},{code:448,name:"tls"},{code:449,name:"sni",size:de},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:de,bytesToValue:Va(jo),valueToBytes:Ha},{code:480,name:"http"},{code:481,name:"http-path",size:de,stringToValue:t=>`/${decodeURIComponent(t)}`,valueToString:t=>encodeURIComponent(t.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:de}];yd.forEach(t=>{at.addProtocol(t)});function Ga(t){let e=[],r=0;for(;r<t.length;){let n=xt(t,r),i=at.getProtocol(n),o=ue(n),c=bd(i,t,r+o),s=0;c>0&&i.size===de&&(s=ue(c));let a=o+s+c,u={code:n,name:i.name,bytes:t.subarray(r,r+a)};if(c>0){let l=r+o+s,f=t.subarray(l,l+c);u.value=i.bytesToValue?.(f)??ne(f)}e.push(u),r+=a}return e}function za(t){let e=0,r=[];for(let n of t){if(n.bytes==null){let i=at.getProtocol(n.code),o=ue(n.code),c,s=0,a=0;n.value!=null&&(c=i.valueToBytes?.(n.value)??xe(n.value),s=c.byteLength,i.size===de&&(a=ue(s)));let u=new Uint8Array(o+a+s),l=0;Ut(n.code,u,l),l+=o,c!=null&&(i.size===de&&(Ut(s,u,l),l+=a),u.set(c,l)),n.bytes=u}r.push(n.bytes),e+=n.bytes.byteLength}return Qe(r,e)}function Wa(t){if(t.charAt(0)!=="/")throw new ge('String multiaddr must start with "/"');let e=[],r="protocol",n="",i="";for(let o=1;o<t.length;o++){let c=t.charAt(o);c!=="/"&&(r==="protocol"?i+=t.charAt(o):n+=t.charAt(o));let s=o===t.length-1;if(c==="/"||s){let a=at.getProtocol(i);if(r==="protocol"){if(a.size==null||a.size===0){e.push({code:a.code,name:a.name}),n="",i="",r="protocol";continue}else if(s)throw new ge(`Component ${i} was missing value`);r="value"}else if(r==="value"){let u={code:a.code,name:a.name};if(a.size!=null&&a.size!==0){if(n==="")throw new ge(`Component ${i} was missing value`);u.value=a.stringToValue?.(n)??n}e.push(u),n="",i="",r="protocol"}}}if(i!==""&&n!=="")throw new ge("Incomplete multiaddr");return e}function Ya(t){return`/${t.flatMap(e=>{if(e.value==null)return e.name;let r=at.getProtocol(e.code);if(r==null)throw new ge(`Unknown protocol code ${e.code}`);return[e.name,r.valueToString?.(e.value)??e.value]}).join("/")}`}function bd(t,e,r){return t.size==null||t.size===0?0:t.size>0?t.size/8:xt(e,r)}var gd=Symbol.for("nodejs.util.inspect.custom"),yi=Symbol.for("@multiformats/multiaddr");function wd(t){if(t==null&&(t="/"),qa(t))return t.getComponents();if(t instanceof Uint8Array)return Ga(t);if(typeof t=="string")return t=t.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),t===""&&(t="/"),Wa(t);if(Array.isArray(t))return t;throw new ge("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Qn=class t{[yi]=!0;#e;#t;#r;constructor(e="/",r={}){this.#e=wd(e),r.validate!==!1&&Ed(this)}get bytes(){return this.#r==null&&(this.#r=za(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Ya(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let r=new t(e);return new t([...this.#e,...r.getComponents()],{validate:!1})}decapsulate(e){let r=e.toString(),n=this.toString(),i=n.lastIndexOf(r);if(i<0)throw new Hn(`Address ${this.toString()} does not contain subaddress: ${r}`);return new t(n.slice(0,i),{validate:!1})}decapsulateCode(e){let r;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){r=n;break}return new t(this.#e.slice(0,r),{validate:!1})}equals(e){return Ne(this.bytes,e.bytes)}[gd](){return`Multiaddr(${this.toString()})`}};function Ed(t){t.getComponents().forEach(e=>{let r=at.getProtocol(e.code);e.value!=null&&r.validate?.(e.value)})}function qa(t){return!!t?.[yi]}function tt(t){return new Qn(t)}var V=t=>({match:e=>{let r=e[0];return r==null||r.code!==t||r.value!=null?!1:e.slice(1)}}),I=(t,e)=>({match:r=>{let n=r[0];return n?.code!==t||n.value==null||e!=null&&n.value!==e?!1:r.slice(1)}}),Za=t=>({match:e=>t.match(e)===!1?e:!1}),O=t=>({match:e=>{let r=t.match(e);return r===!1?e:r}}),ve=(...t)=>({match:e=>{let r;for(let n of t){let i=n.match(e);i!==!1&&(r==null||i.length<r.length)&&(r=i)}return r??!1}}),N=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e}});function G(...t){function e(i){if(i==null)return!1;let o=i.getComponents();for(let c of t){let s=c.match(o);if(s===!1)return!1;o=s}return o}function r(i){return e(i)!==!1}function n(i){let o=e(i);return o===!1?!1:o.length===0}return{matchers:t,matches:r,exactMatch:n}}var xd=I(421),jg=G(xd),eo=I(54),to=I(55),ro=I(56),gi=I(53),Xg=G(eo,O(I(421))),Qg=G(to,O(I(421))),Jg=G(ro,O(I(421))),e0=G(ve(gi,ro,eo,to),O(I(421))),ja=N(I(4),O(I(43))),Xa=N(O(I(42)),I(41),O(I(43))),wi=ve(ja,Xa),or=ve(wi,gi,eo,to,ro),t0=G(ve(wi,N(ve(gi,ro,eo,to),O(I(421))))),r0=G(ja),n0=G(Xa),o0=G(wi),Ei=N(or,I(6)),Hr=N(or,I(273)),Qa=G(N(Ei,O(I(421)))),s0=G(Hr),xi=N(Hr,V(460),O(I(421))),no=N(Hr,V(461),O(I(421))),vd=ve(xi,no),i0=G(xi),c0=G(no),bi=ve(or,Ei,Hr,xi,no),Ja=ve(N(bi,V(477),O(I(421)))),a0=G(Ja),eu=ve(N(bi,V(478),O(I(421))),N(bi,V(448),O(I(449)),V(477),O(I(421)))),u0=G(eu),tu=N(Hr,V(280),O(I(466)),O(I(466)),O(I(421))),l0=G(tu),ru=N(no,V(465),O(I(466)),O(I(466)),O(I(421))),f0=G(ru),Jn=ve(Ja,eu,N(Ei,O(I(421))),N(vd,O(I(421))),N(or,O(I(421))),tu,ru,I(421)),d0=G(Jn),Sd=N(O(Jn),V(290),Za(V(281)),O(I(421))),h0=G(Sd),Id=ve(N(Jn,V(290),V(281),O(I(421))),N(Jn,V(281),O(I(421))),N(V(281),O(I(421)))),p0=G(Id),Td=N(or,ve(N(I(6,"80")),N(I(6),V(480)),V(480)),O(I(481)),O(I(421))),m0=G(Td),Ad=N(or,ve(N(I(6,"443")),N(I(6,"443"),V(480)),N(I(6),V(443)),N(I(6),V(448),V(480)),N(V(448),V(480)),V(448),V(443)),O(I(481)),O(I(421))),y0=G(Ad),Dd=ve(N(I(777),O(I(421)))),b0=G(Dd),Ld=ve(N(I(400),O(I(421)))),oo=G(Ld);var so=class extends Event{type;detail;constructor(e,r){super(e),this.type=e,this.detail=r}};var yu=_e(se("node:net"),1);function io(t){let e=t.getComponents(),r={},n=0;if(e[n]?.name==="ip6zone"&&(r.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(r.type=e[n].name,r.host=e[n].value,n++):e[n].name==="dnsaddr"&&(r.type=e[n].name,r.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(r.protocol=e[n].name==="tcp"?"tcp":"udp",r.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(r.type==="ip4"?r.cidr=parseInt(`${e[n].value}`):r.type==="ip6"&&(r.cidr=`${e[n].value}`),n++),r.type==null||r.host==null)throw new j(`Multiaddr ${t} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(r.sni=e[n+1].value,n+=2),r}function ut(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var co=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},sr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new co(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new co(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var vi=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function wt(t={}){return Cd(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function Cd(t,e){e=e??{};let r=e.onEnd,n=new sr,i,o,c,s=ut(),a=async()=>{try{return n.isEmpty()?c?{done:!0}:await new Promise((m,E)=>{o=L=>{o=null,n.push(L);try{m(t(n))}catch(P){E(P)}return i}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{s.resolve(),s=ut()})}},u=m=>o!=null?o(m):(n.push(m),i),l=m=>(n=new sr,o!=null?o({error:m}):(n.push({error:m}),i)),f=m=>{if(c)return i;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:m})},d=m=>c?i:(c=!0,m!=null?l(m):u({done:!0})),h=()=>(n=new sr,d(),{done:!0}),y=m=>(d(m),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:a,return:h,throw:y,push:f,end:d,get readableLength(){return n.size},onEmpty:async m=>{let E=m?.signal;if(E?.throwIfAborted(),n.isEmpty())return;let L,P;E!=null&&(L=new Promise((M,_)=>{P=()=>{_(new vi)},E.addEventListener("abort",P)}));try{await Promise.race([s.promise,L])}finally{P!=null&&E!=null&&E?.removeEventListener("abort",P)}}},r==null)return i;let v=i;return i={[Symbol.asyncIterator](){return this},next(){return v.next()},throw(m){return v.throw(m),r!=null&&(r(m),r=void 0),{done:!0}},return(){return v.return(),r!=null&&(r(),r=void 0),{done:!0}},push:f,end(m){return v.end(m),r!=null&&(r(m),r=void 0),i},get readableLength(){return v.readableLength},onEmpty:m=>v.onEmpty(m)},i}var Si=class t extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,t)}},nu=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function Ii(t,e){let{milliseconds:r,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout},signal:c}=e,s,a,l=new Promise((f,d)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(c?.aborted){d(nu(c));return}if(c&&(a=()=>{d(nu(c))},c.addEventListener("abort",a,{once:!0})),t.then(f,d),r===Number.POSITIVE_INFINITY)return;let h=new Si;s=o.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(y){d(y)}return}typeof t.cancel=="function"&&t.cancel(),i===!1?f():i instanceof Error?d(i):(h.message=i??`Promise timed out after ${r} milliseconds`,d(h))},r)}).finally(()=>{l.clear(),a&&c&&c.removeEventListener("abort",a)});return l.clear=()=>{o.clearTimeout.call(void 0,s),s=void 0},l}var Bd=t=>{let e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function Od(t,e,r){let n,i=new Promise((o,c)=>{if(r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let s=[e].flat(),a=[],{addListener:u,removeListener:l}=Bd(t),f=async(...h)=>{let y=r.multiArgs?h:h[0];if(r.filter)try{if(!await r.filter(y))return}catch(v){n(),c(v);return}a.push(y),r.count===a.length&&(n(),o(a))},d=(...h)=>{n(),c(r.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of s)l(h,f);for(let h of r.rejectionEvents)s.includes(h)||l(h,d)};for(let h of s)u(h,f);for(let h of r.rejectionEvents)s.includes(h)||u(h,d);r.signal&&r.signal.addEventListener("abort",()=>{d(r.signal.reason)},{once:!0}),r.resolveImmediately&&o(a)});if(i.cancel=n,typeof r.timeout=="number"){let o=Ii(i,{milliseconds:r.timeout});return o.cancel=()=>{n(),o.clear()},o}return i}function Fe(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Od(t,e,r),i=n.then(o=>o[0]);return i.cancel=n.cancel,i}var Pt=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};var ao=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function _d(t){return t.reason}async function ir(t,e,r){if(e==null)return t;let n=r?.translateError??_d;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let i;try{return await Promise.race([t,new Promise((o,c)=>{i=()=>{c(n(e))},e.addEventListener("abort",i)})])}finally{i!=null&&e.removeEventListener("abort",i)}}var kd=Math.pow(2,20)*4,uo=class extends Wt{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??kd,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new K,this.writeBuffer=new K,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let r=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{this.processSendQueue()})),this.onDrainPromise?.resolve()};this.addEventListener("drain",r);let n=i=>{this.onDrainPromise?.reject(i.error??new ao)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),ir(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=wt(),r=o=>{e.push(o.data)};this.addEventListener("message",r);let n=o=>{e.end(o.error)};this.addEventListener("close",n);let i=()=>{e.end()};this.addEventListener("remoteCloseWrite",i);try{yield*e}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",i)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new pt(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new pn(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new pt("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new pt("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new pt(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new pt(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new un;this.dispatchEvent(new mn(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new zt))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,r=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let i=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(i===0){e=!1;break}let o=this.writeBuffer.sublist(0,i),c=new K(o);this.writeBuffer.consume(o.byteLength);let s=this.sendData(o);if(e=s.canSendMore,n+=s.sentBytes,s.sentBytes!==c.byteLength&&(c.consume(s.sentBytes),this.writeBuffer.prepend(c)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,r,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new hn(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Lr(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Lr(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var lo=class extends uo{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",r=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),r.error!=null?r.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):r.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Fe(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Fe(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};var su=_e(se("node:os"),1);function ou(t){return!!(t.startsWith("169.254.")||t.toLowerCase().startsWith("fe80"))}function Ti(t,e,r){let n=[t.type,r??t.host];if(t.protocol!=null){let i=e??t.port;i!=null&&n.push(t.protocol,i)}return t.type==="ip6"&&t.zone!=null&&n.unshift("ip6zone",t.zone),t.cidr!=null&&n.push("ipcidr",t.cidr),tt(`/${n.join("/")}`)}var Pd={4:"IPv4",6:"IPv6"};function Nd(t){return["0.0.0.0","::"].includes(t)}function Rd(t){let e=[],r=su.default.networkInterfaces();for(let[,n]of Object.entries(r))if(n!=null)for(let i of n)ou(i.address)||i.family===Pd[t]&&e.push(i.address);return e}function iu(t,e){if(t==null)return[];let r=io(t);return(r.type==="ip4"||r.type==="ip6")&&Nd(r.host)?Rd(r.type==="ip4"?4:6).map(n=>Ti(r,e,n)):[Ti(r,e)]}function cu(t,e){if(typeof t!="string")throw new j(`invalid ip provided: ${t}`);if(typeof e=="string"&&(e=parseInt(e)),isNaN(e))throw new j(`invalid port provided: ${e}`);if((0,Ue.isIPv4)(t))return tt(`/ip4/${t}/tcp/${e}`);if((0,Ue.isIPv6)(t))return tt(`/ip6/${t}/tcp/${e}`);throw new j(`invalid ip:port for creating a multiaddr: ${t}:${e}`)}var Ai=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ut(),this.haveNext=ut()}[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 e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ut(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,r){await this._push(e,r)}async end(e,r){e!=null?await this.throw(e):await this._push(void 0,r)}async _push(e,r){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ut(),await ir(this.readNext.promise,r?.signal,r)}};function au(){return new Ai}function Ud(t){return t[Symbol.asyncIterator]!=null}async function Fd(t,e,r){try{await Promise.all(t.map(async n=>{for await(let i of n)await e.push(i,{signal:r}),r.throwIfAborted()})),await e.end(void 0,{signal:r})}catch(n){await e.end(n,{signal:r}).catch(()=>{})}}async function*Md(t){let e=new AbortController,r=au();Fd(t,r,e.signal).catch(()=>{});try{yield*r}finally{e.abort()}}function*$d(t){for(let e of t)yield*e}function Kd(...t){let e=[];for(let r of t)Ud(r)||e.push(r);return e.length===t.length?$d(e):Md(t)}var uu=Kd;function lu(t,...e){if(t==null)throw new Error("Empty pipeline");if(Di(t)){let n=t;t=()=>n.source}else if(du(t)||fu(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&Di(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)Di(r[n])&&(r[n]=Vd(r[n]));return Hd(...r)}var Hd=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},fu=t=>t?.[Symbol.asyncIterator]!=null,du=t=>t?.[Symbol.iterator]!=null,Di=t=>t==null?!1:t.sink!=null&&t.source!=null,Vd=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=wt({objectMode:!0});r.then(()=>{n.end()},c=>{n.end(c)});let i,o=t.source;if(fu(o))i=async function*(){yield*o,n.end()};else if(du(o))i=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return uu(n,i())}return t.source};var Gd=4194304,fo=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Ci=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Bi=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Oi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function zd(t){return typeof t?.closeRead=="function"}function Wd(t){return typeof t?.close=="function"}function Li(t){return zd(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:Wd(t)?t.status!=="open":!1}function Yd(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function qd(t,e){let r=e?.maxBufferSize??Gd,n=new K,i,o=!1;if(!Yd(t))throw new j("Argument should be a Stream or a Multiaddr");let c=l=>{if(n.append(l.data),n.byteLength>r){let f=n.byteLength;n.consume(n.byteLength),i?.reject(new Error(`Read buffer overflow - ${f} > ${r}`))}i?.resolve()};t.addEventListener("message",c);let s=l=>{l.error!=null?i?.reject(l.error):i?.resolve()};t.addEventListener("close",s);let a=()=>{i?.resolve()};t.addEventListener("remoteCloseWrite",a);let u={readBuffer:n,async read(l){if(o===!0)throw new fo("Stream was unwrapped");if(Li(t)){if(n.byteLength===0&&l?.bytes==null)return null;if(l?.bytes!=null&&n.byteLength<l.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,l.bytes),new Pt(`Unexpected EOF - stream closed after reading ${n.byteLength}/${l.bytes} bytes`)}let f=l?.bytes??1;for(i=Promise.withResolvers();;){if(n.byteLength>=f){i.resolve();break}if(await ir(i.promise,l?.signal),Li(t)){if(n.byteLength===0&&l?.bytes==null)return null;break}i=Promise.withResolvers()}let d=l?.bytes??n.byteLength;if(n.byteLength<d){if(Li(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,d),new Pt(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return u.read(l)}let h=n.sublist(0,d);return n.consume(d),h},async write(l,f){if(o===!0)throw new fo("Stream was unwrapped");t.send(l)||await Fe(t,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!0,t.removeEventListener("message",c),t.removeEventListener("close",s),t.removeEventListener("remoteCloseWrite",a),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.push(n))),t}};return u}function Vr(t,e={}){let r=qd(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=ue(e.maxDataLength));let n=e?.lengthDecoder??xt,i=e?.lengthEncoder??Yr;return{async read(c){let s=-1,a=new K;for(;;){let l=await r.read({...c,bytes:1});if(l==null)break;a.append(l);try{s=n(a)}catch(f){if(f instanceof RangeError)continue;throw f}if(s<0)throw new Ci("Invalid message length");if(e?.maxLengthLength!=null&&a.byteLength>e.maxLengthLength)throw new Oi(`Message length length too long - ${a.byteLength} > ${e.maxLengthLength}`);if(s>-1)break}if(e?.maxDataLength!=null&&s>e.maxDataLength)throw new Bi(`Message length too long - ${s} > ${e.maxDataLength}`);let u=await r.read({...c,bytes:s});if(u==null)throw t.log.error("tried to read %d bytes but the stream closed",s),new Pt(`Unexpected EOF - tried to read ${s} bytes but the stream closed`);if(u.byteLength!==s)throw t.log.error("read %d/%d bytes before the stream closed",u.byteLength,s),new Pt(`Unexpected EOF - read ${u.byteLength}/${s} bytes before the stream closed`);return u},async write(c,s){await r.write(new K(i(c.byteLength),c),s)},async writeV(c,s){let a=new K(...c.flatMap(u=>[i(u.byteLength),u]));await r.write(a,s)},unwrap(){return r.unwrap()}}}function _i(t,e){let r=Vr(t,e),n={read:async(i,o)=>{let c=await r.read(o);return i.decode(c)},write:async(i,o,c)=>{await r.write(o.encode(i),c)},writeV:async(i,o,c)=>{await r.writeV(i.map(s=>o.encode(s)),c)},pb:i=>({read:async o=>n.read(i,o),write:async(o,c)=>n.write(o,i,c),writeV:async(o,c)=>n.writeV(o,i,c),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}function Zd(t){return t?.addEventListener!=null}function jd(t){let e=wt(),r,n=c=>{e.push(c.data)},i=()=>{e.end(),t.removeEventListener("message",n),t.removeEventListener("close",o),t.removeEventListener("remoteCloseWrite",i)},o=c=>{e.end(c.error),c.error!=null&&r?.reject(c.error),t.removeEventListener("message",n),t.removeEventListener("close",o),t.removeEventListener("remoteCloseWrite",i)};return t.addEventListener("message",n),t.addEventListener("close",o,{once:!0}),t.addEventListener("remoteCloseWrite",i,{once:!0}),{source:e,async sink(c){async function*s(){yield*c}let a=s();for(;;){r=Promise.withResolvers();let{done:u,value:l}=await Promise.race([a.next(),r.promise]);if(t.writeStatus==="closing"||t.writeStatus==="closed"||(l!=null&&(t.send(l)||await Promise.race([Fe(t,"drain",{rejectionEvents:["close"]})])),u===!0))break}await t.close()}}}function ki(...t){let e=t.map(r=>Zd(r)?jd(r):r);return lu(...e)}var ho=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},cr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},po=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Gr=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function mo(t){return t[Symbol.asyncIterator]!=null}function hu(t,e){if(t.byteLength>e)throw new cr("Message length too long")}var bo=t=>{let e=ue(t),r=Le(e);return Yr(t,r),bo.bytes=e,r};bo.bytes=0;function go(t,e){e=e??{};let r=e.lengthEncoder??bo,n=e?.maxDataLength??4194304;function*i(o){hu(o,n);let c=r(o.byteLength);c instanceof Uint8Array?yield c:yield*c,o instanceof Uint8Array?yield o:yield*o}return mo(t)?(async function*(){for await(let o of t)yield*i(o)})():(function*(){for(let o of t)yield*i(o)})()}go.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??bo,n=e?.maxDataLength??4194304;return hu(t,n),new K(r(t.byteLength),t)};var Nt;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(Nt||(Nt={}));var Ni=t=>{let e=xt(t);return Ni.bytes=ue(e),e};Ni.bytes=0;function Pi(t,e){let r=new K,n=Nt.LENGTH,i=-1,o=e?.lengthDecoder??Ni,c=e?.maxLengthLength??8,s=e?.maxDataLength??4194304;function*a(){for(;r.byteLength>0;){if(n===Nt.LENGTH)try{if(i=o(r),i<0)throw new ho("Invalid message length");if(i>s)throw new cr("Message length too long");let u=o.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=Nt.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>c)throw new po("Message length length too long");break}throw u}if(n===Nt.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=Nt.LENGTH}}}return mo(t)?(async function*(){for await(let u of t)r.append(u),yield*a();if(r.byteLength>0)throw new Gr("Unexpected end of input")})():(function*(){for(let u of t)r.append(u),yield*a();if(r.byteLength>0)throw new Gr("Unexpected end of input")})()}Pi.fromReader=(t,e)=>{let r=1,n=(async function*(){for(;;)try{let{done:o,value:c}=await t.next(r);if(o===!0)return;c!=null&&(yield c)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{r=1}})();return Pi(n,{...e??{},onLength:o=>{r=o}})};var Ri=class extends lo{socket;constructor(e){let r=e.remoteAddr;if(e.localAddr!=null&&oo.matches(e.localAddr))r=e.localAddr;else if(r==null){if(e.socket.remoteAddress==null||e.socket.remotePort==null)throw new j("Could not determine remote address or port");r=cu(e.socket.remoteAddress,e.socket.remotePort)}super({...e,remoteAddr:r}),this.socket=e.socket,this.socket.on("data",n=>{this.onData(n)}),this.socket.on("error",n=>{this.log("tcp error",r,n),this.abort(n)}),this.socket.setTimeout(e.inactivityTimeout??120*1e3),this.socket.once("timeout",()=>{this.log("tcp timeout",r),this.abort(new Gt)}),this.socket.once("end",()=>{this.log("tcp end",r),this.onTransportClosed()}),this.socket.once("close",n=>{if(this.log("tcp close",r),n){this.abort(new Error("TCP transmission error"));return}this.onTransportClosed()}),this.socket.on("drain",()=>{this.log("tcp drain"),this.safeDispatchEvent("drain")})}sendData(e){let r=0,n=!0;for(let i of e)if(r+=i.byteLength,n=this.socket.write(i),!n)break;return{sentBytes:r,canSendMore:n}}async sendClose(e){this.socket.destroyed||(this.socket.destroySoon(),await Fe(this.socket,"close",e))}sendReset(){this.socket.resetAndDestroy()}sendPause(){this.socket.pause()}sendResume(){this.socket.resume()}},wo=t=>new Ri(t);var pu=_e(se("os"),1),mu=_e(se("path"),1);function Eo(t,e={}){if(oo.exactMatch(t)){let o=t.getComponents().find(c=>c.code===400)?.value;if(o==null)throw new j(`Multiaddr ${t} was not a Unix address`);return pu.default.platform()==="win32"?{path:mu.default.join("\\\\.\\pipe\\",o)}:{path:o}}let r=io(t),n=r.host,i=r.port;return{host:n,port:i,ipv6Only:r.type==="ip6",...e}}var he;(function(t){t[t.INACTIVE=0]="INACTIVE",t[t.ACTIVE=1]="ACTIVE",t[t.PAUSED=2]="PAUSED"})(he||(he={}));var xo=class extends Wt{context;server;sockets=new Set;status={code:he.INACTIVE};metrics;addr;log;shutdownController;constructor(e){if(super(),this.context=e,e.keepAlive=e.keepAlive??!0,e.noDelay=e.noDelay??!0,e.allowHalfOpen=e.allowHalfOpen??!1,this.shutdownController=new AbortController,yn(1/0,this.shutdownController.signal),this.log=e.logger.forComponent("libp2p:tcp:listener"),this.addr="unknown",this.server=yu.default.createServer(e,this.onSocket.bind(this)),e.maxConnections!==void 0&&(this.server.maxConnections=e.maxConnections),e.closeServerOnMaxConnections!=null&&e.closeServerOnMaxConnections.closeAbove<e.closeServerOnMaxConnections.listenBelow)throw new j("closeAbove must be >= listenBelow");e.metrics?.registerMetricGroup("libp2p_tcp_inbound_connections_total",{label:"address",help:"Current active connections in TCP listener",calculate:()=>({[this.addr]:this.sockets.size})}),this.metrics={status:e.metrics?.registerMetricGroup("libp2p_tcp_listener_status_info",{label:"address",help:"Current status of the TCP listener socket"}),errors:e.metrics?.registerMetricGroup("libp2p_tcp_listener_errors_total",{label:"address",help:"Total count of TCP listener errors by type"}),events:e.metrics?.registerMetricGroup("libp2p_tcp_listener_events_total",{label:"address",help:"Total count of TCP listener events by type"})},this.server.on("listening",()=>{let r=this.server.address();r==null?this.addr="unknown":typeof r=="string"?this.addr=r:this.addr=`${r.address}:${r.port}`,this.metrics.status?.update({[this.addr]:he.ACTIVE}),this.safeDispatchEvent("listening")}).on("error",r=>{this.metrics.errors?.increment({[`${this.addr} listen_error`]:!0}),this.safeDispatchEvent("error",{detail:r})}).on("close",()=>{this.metrics.status?.update({[this.addr]:this.status.code}),this.status.code!==he.PAUSED&&this.safeDispatchEvent("close")}).on("drop",()=>{this.metrics.events?.increment({[`${this.addr} drop`]:!0})})}onSocket(e){if(this.metrics.events?.increment({[`${this.addr} connection`]:!0}),this.status.code!==he.ACTIVE)throw e.destroy(),new fn("Server is not listening yet");let r;try{r=wo({socket:e,inactivityTimeout:this.context.inactivityTimeout,metrics:this.metrics?.events,metricPrefix:`${this.addr} `,direction:"inbound",localAddr:this.status.listeningAddr,log:this.context.logger.forComponent("libp2p:tcp:connection")})}catch(n){this.log.error("inbound connection failed - %e",n),this.metrics.errors?.increment({[`${this.addr} inbound_to_connection`]:!0}),e.destroy();return}this.log("new inbound connection %s",r.remoteAddr),this.sockets.add(e),this.context.upgrader.upgradeInbound(r,{signal:this.shutdownController.signal}).then(()=>{this.log("inbound connection upgraded %s",r.remoteAddr),e.once("close",()=>{this.sockets.delete(e),this.context.closeServerOnMaxConnections!=null&&this.sockets.size<this.context.closeServerOnMaxConnections.listenBelow&&this.resume().catch(n=>{this.log.error("error attempting to listen server once connection count under limit - %e",n),this.context.closeServerOnMaxConnections?.onListenError?.(n)})}),this.context.closeServerOnMaxConnections!=null&&this.sockets.size>=this.context.closeServerOnMaxConnections.closeAbove&&(this.log("pausing incoming connections as limit is exceeded - %d/%d",this.sockets.size,this.context.closeServerOnMaxConnections.closeAbove),this.pause())}).catch(async n=>{this.log.error("inbound connection upgrade failed - %e",n),this.metrics.errors?.increment({[`${this.addr} inbound_upgrade`]:!0}),this.sockets.delete(e),r.abort(n)})}getAddrs(){if(this.status.code===he.INACTIVE)return[];let e=this.server.address();return e==null?[]:typeof e=="string"?[tt(`/unix/${encodeURIComponent(e)}`)]:iu(this.status.listeningAddr,e.port)}updateAnnounceAddrs(){}async listen(e){if(this.status.code===he.ACTIVE||this.status.code===he.PAUSED)throw new dn("server is already listening");try{this.status={code:he.ACTIVE,listeningAddr:e,netConfig:Eo(e,this.context)},await this.resume()}catch(r){throw this.status={code:he.INACTIVE},r}}async close(e){let r=[];this.server.listening&&r.push(Fe(this.server,"close",e)),this.pause(!0),this.shutdownController.abort(),this.sockets.forEach(n=>{n.readable&&(r.push(Fe(n,"close",e)),n.destroy())}),await Promise.all(r)}async resume(){if(this.server.listening||this.status.code===he.INACTIVE)return;let e=this.status.netConfig;await new Promise((r,n)=>{this.server.once("error",n),this.server.listen(e,r)}),this.status={...this.status,code:he.ACTIVE},this.log("listening on %s",this.server.address())}pause(e=!1){if(!this.server.listening&&this.status.code===he.PAUSED&&e){this.status={code:he.INACTIVE};return}!this.server.listening||this.status.code!==he.ACTIVE||(this.log("%s server on %s",e?"closing":"pausing",this.server.address()),this.status=e?{code:he.INACTIVE}:{...this.status,code:he.PAUSED},this.server.close())}};var vo=class{opts;metrics;components;log;constructor(e,r={}){this.log=e.logger.forComponent("libp2p:tcp"),this.opts=r,this.components=e,e.metrics!=null&&(this.metrics={events:e.metrics.registerCounterGroup("libp2p_tcp_dialer_events_total",{label:"event",help:"Total count of TCP dialer events by type"}),errors:e.metrics.registerCounterGroup("libp2p_tcp_dialer_errors_total",{label:"event",help:"Total count of TCP dialer events by type"})})}[Dc]=!0;[Symbol.toStringTag]="@libp2p/tcp";[Cc]=["@libp2p/transport"];async dial(e,r){r.keepAlive=r.keepAlive??!0,r.noDelay=r.noDelay??!0,r.allowHalfOpen=r.allowHalfOpen??!1;let n=await this._connect(e,r),i;try{i=wo({socket:n,inactivityTimeout:this.opts.outboundSocketInactivityTimeout,metrics:this.metrics?.events,direction:"outbound",remoteAddr:e,log:this.log.newScope("connection")})}catch(o){throw this.metrics?.errors.increment({outbound_to_connection:!0}),n.destroy(o),o}try{return this.log("new outbound connection %s",i.remoteAddr),await r.upgrader.upgradeOutbound(i,r)}catch(o){throw this.metrics?.errors.increment({outbound_upgrade:!0}),this.log.error("error upgrading outbound connection - %e",o),i.abort(o),o}}async _connect(e,r){r.signal.throwIfAborted(),r.onProgress?.(new so("tcp:open-connection"));let n;return new Promise((i,o)=>{let c=Date.now(),s=Eo(e,{...this.opts.dialOpts??{},...r});this.log("dialing %a with opts %o",e,s),n=bu.default.connect(s);let a=h=>{this.log.error("dial to %a errored - %e",e,h);let y=s.path??`${s.host??""}:${s.port}`;h.message=`connection error ${y}: ${h.message}`,this.metrics?.events.increment({error:!0}),d(h)},u=()=>{this.log("connection timeout %a",e),this.metrics?.events.increment({timeout:!0});let h=new Gt(`Connection timeout after ${Date.now()-c}ms`);n.emit("error",h)},l=()=>{this.log("connection opened %a",e),this.metrics?.events.increment({connect:!0}),d()},f=()=>{this.log("connection aborted %a",e),this.metrics?.events.increment({abort:!0}),d(new cn)},d=h=>{if(n.removeListener("error",a),n.removeListener("timeout",u),n.removeListener("connect",l),r.signal!=null&&r.signal.removeEventListener("abort",f),h!=null){o(h);return}i(n)};n.on("error",a),n.on("timeout",u),n.on("connect",l),r.signal.addEventListener("abort",f)}).catch(i=>{throw n?.destroy(),i})}createListener(e){return new xo({...this.opts.listenOpts??{},...e,maxConnections:this.opts.maxConnections,backlog:this.opts.backlog,closeServerOnMaxConnections:this.opts.closeServerOnMaxConnections,inactivityTimeout:this.opts.inboundSocketInactivityTimeout,metrics:this.components.metrics,logger:this.components.logger})}listenFilter(e){return e.filter(r=>Qa.exactMatch(r)||r.toString().startsWith("/unix/"))}dialFilter(e){return this.listenFilter(e)}};function gu(t={}){return e=>new vo(e,t)}function Jd(t){return t[Symbol.asyncIterator]!=null}function eh(t){if(Jd(t))return(async()=>{for await(let e of t);})();for(let e of t);}var Ui=eh;function Be(t){return re.encode({type:re.Type.OK,peers:[],...t}).subarray()}function Se(t){return re.encode({type:re.Type.ERROR,error:{msg:t.message},peers:[]}).subarray()}var So=ht("libp2p:daemon-server:dht"),Io=class{dht;constructor(e){let{dht:r}=e;this.dht=r}async*provide(e){try{await Ui(this.dht.provide(e)),yield Be()}catch(r){So.error("failed to provide CID %s - %e",e,r),yield Se(r)}}async*getClosestPeers(e){yield Be({dht:{type:le.Type.BEGIN}});for await(let r of this.dht.getClosestPeers(e))r.name==="PEER_RESPONSE"&&(yield*r.closer.map(n=>le.encode({type:le.Type.VALUE,value:n.id.toMultihash().bytes})));yield le.encode({type:le.Type.END})}async*getPublicKey(e){yield Se(new Error("FIX ME: not implemented"))}async*getValue(e){try{for await(let r of this.dht.get(e))r.name==="VALUE"&&(yield Be({dht:{type:le.Type.VALUE,value:r.value}}))}catch(r){So.error("error getting value for key %b - %e",e,r),yield Se(r)}}async*putValue(e,r){try{await Ui(this.dht.put(e,r)),yield Be()}catch(n){So.error("error putting value %b for key %b - %e",r,e,n),yield Se(n)}}async*findPeer(e){try{for await(let r of this.dht.findPeer(e))r.name==="FINAL_PEER"&&(yield Be({dht:{type:le.Type.VALUE,peer:{id:r.peer.id.toMultihash().bytes,addrs:r.peer.multiaddrs.map(n=>n.bytes)}}}));throw new Error("Peer not found")}catch(r){So.error("peer not found %p - %e",e,r),yield Se(r)}}async*findProviders(e,r){yield Be({dht:{type:le.Type.BEGIN}});try{let n=r,i=0;for await(let o of this.dht.findProviders(e))if(o.name==="PEER_RESPONSE"){for(let c of o.providers)i++,yield le.encode({type:le.Type.VALUE,peer:{id:c.id.toMultihash().bytes,addrs:(c.multiaddrs??[]).map(s=>s.bytes)}});if(n===i)break}}catch(n){yield Se(n)}yield le.encode({type:le.Type.END})}};var To=ht("libp2p:daemon-server:pubsub"),Ao=class{pubsub;constructor(e){let{pubsub:r}=e;this.pubsub=r}async*getTopics(){try{yield Be({pubsub:{topics:this.pubsub.getTopics(),peerIDs:[]}})}catch(e){To.error("failed to get pubsub topics - %e",e),yield Se(e)}}async*subscribe(e){try{let r=wt();this.pubsub.subscribe(e),this.pubsub.addEventListener("message",n=>{let i=n.detail;i.topic===e&&(i.type==="signed"?r.push(Ar.encode({from:i.from.toMultihash().bytes,data:i.data,seqno:i.sequenceNumber==null?void 0:xe(i.sequenceNumber.toString(16).padStart(16,"0"),"base16"),topicIDs:[i.topic],signature:i.signature,key:mt(i.key)}).subarray()):r.push(Ar.encode({data:i.data,topicIDs:[i.topic]}).subarray()))}),yield Be(),yield*r}catch(r){To.error("failed to subscribe to topic %s - %e",e,r),yield Se(r)}}async*publish(e,r){try{await this.pubsub.publish(e,r),yield Be()}catch(n){To.error("failed to publish message to topic %s - %e",e,n),yield Se(n)}}async*listPeers(e){try{yield Be({pubsub:{topics:[e],peerIDs:this.pubsub.getSubscribers(e).map(r=>r.toMultihash().bytes)}})}catch(r){To.error("failed to list peers for topic %s - %e",e,r),yield Se(r)}}};var wu=1<<22,Te=ht("libp2p:daemon-server"),Do=class{multiaddr;libp2p;tcp;listener;dhtOperations;pubsubOperations;constructor(e){let{multiaddr:r,libp2pNode:n}=e;this.multiaddr=r,this.libp2p=n,this.tcp=gu()({logger:Tc()}),this.listener=this.tcp.createListener({upgrader:new Dr(this.handleConnection.bind(this))}),this._onExit=this._onExit.bind(this),n.services.dht!=null&&(this.dhtOperations=new Io({dht:n.services.dht})),n.services.pubsub!=null&&(this.pubsubOperations=new Ao({pubsub:n.services.pubsub}))}async connect(e){if(e.connect?.addrs==null)throw new Error("Invalid request");let r=e.connect.peer,n=e.connect.addrs.map(o=>tt(o)),i=Jt(rt(r));return Te("connect - adding multiaddrs %a to peer %p",n,i),await this.libp2p.peerStore.merge(i,{multiaddrs:n}),Te("connect - dial %p",i),this.libp2p.dial(i)}async openStream(e){if(e.streamOpen?.proto==null)throw new Error("Invalid request");let{peer:r,proto:n}=e.streamOpen,i=Jt(rt(r));Te("openStream - dial %p",i);let o=await this.libp2p.dial(i);Te("openStream - open stream for protocol(s) %s",n);let c=await o.newStream(n,{runOnLimitedConnection:!0});return{streamInfo:{peer:i.toMultihash().bytes,addr:o.remoteAddr.bytes,proto:c.protocol??""},connection:c}}async registerStreamHandler(e){if(e.streamHandler?.proto==null)throw new Error("Invalid request");let r=e.streamHandler.proto,n=tt(e.streamHandler.addr),i;Te("registerStreamHandler - handle %s at %a",r,n),await this.libp2p.handle(r,async(o,c)=>{try{Te("open stream for protocol %o to %a",r,n);let s=AbortSignal.timeout(1e4);i=await this.tcp.dial(n,{upgrader:new Dr,signal:s});let a=Tt.encode({peer:c.remotePeer.toMultihash().bytes,addr:c.remoteAddr.bytes,proto:o.protocol??""}),u=go.single(a);i.send(u)||await Fe(i,"drain",{rejectionEvents:["close"],signal:s}),await ki(o,i,o)}catch(s){Te.error("error handling stream handler - %e",s),i?.abort(s)}finally{try{await i?.close()}catch(s){i?.abort(s)}}},{runOnLimitedConnection:!0})}_listen(){process.on("SIGTERM",this._onExit),process.on("SIGINT",this._onExit),process.on("SIGHUP",this._onExit)}_onExit(){this.stop({exit:!0}).catch(e=>{Te.error("failed to stop daemon during exit - %e",e)})}async start(){this._listen(),await this.libp2p.start(),await this.listener.listen(this.multiaddr)}getMultiaddr(){let e=this.listener.getAddrs();if(e.length>0)return e[0];throw new Error("Not started")}async stop(e={exit:!1}){await this.libp2p.stop(),await this.listener.close(),e.exit&&Te("server closed, exiting"),process.removeListener("SIGTERM",this._onExit),process.removeListener("SIGINT",this._onExit),process.removeListener("SIGHUP",this._onExit)}async*handlePeerStoreRequest(e){try{switch(e.type){case dt.Type.GET_PROTOCOLS:if(e.id==null)throw new Error("Invalid request");let r=Jt(rt(e.id)),i=(await this.libp2p.peerStore.get(r)).protocols;yield Be({peerStore:{protos:i}});return;case dt.Type.GET_PEER_INFO:throw new Error("ERR_NOT_IMPLEMENTED");default:throw new Error("ERR_INVALID_REQUEST_TYPE")}}catch(r){Te.error("error handling peerstore request - %e",r),yield Se(r)}}async*handlePubsubRequest(e){try{if(this.libp2p.services.pubsub==null||this.pubsubOperations==null)throw new Error("PubSub not configured");switch(e.type){case Xe.Type.GET_TOPICS:yield*this.pubsubOperations.getTopics();return;case Xe.Type.SUBSCRIBE:if(e.topic==null)throw new Error("Invalid request");yield*this.pubsubOperations.subscribe(e.topic);return;case Xe.Type.PUBLISH:if(e.topic==null||e.data==null)throw new Error("Invalid request");yield*this.pubsubOperations.publish(e.topic,e.data);return;case Xe.Type.LIST_PEERS:if(e.topic==null)throw new Error("Invalid request");yield*this.pubsubOperations.listPeers(e.topic);return;default:throw new Error("ERR_INVALID_REQUEST_TYPE")}}catch(r){Te.error("error handling pubsub request - %e",r),yield Se(r)}}async*handleDHTRequest(e){try{if(this.libp2p.services.dht==null||this.dhtOperations==null)throw new Error("DHT not configured");switch(e.type){case Pe.Type.FIND_PEER:if(e.peer==null)throw new Error("Invalid request");yield*this.dhtOperations.findPeer(Jt(rt(e.peer)));return;case Pe.Type.FIND_PROVIDERS:if(e.cid==null)throw new Error("Invalid request");yield*this.dhtOperations.findProviders(ie.decode(e.cid),e.count??20);return;case Pe.Type.PROVIDE:if(e.cid==null)throw new Error("Invalid request");yield*this.dhtOperations.provide(ie.decode(e.cid));return;case Pe.Type.GET_CLOSEST_PEERS:if(e.key==null)throw new Error("Invalid request");yield*this.dhtOperations.getClosestPeers(e.key);return;case Pe.Type.GET_PUBLIC_KEY:if(e.peer==null)throw new Error("Invalid request");yield*this.dhtOperations.getPublicKey(Jt(rt(e.peer)));return;case Pe.Type.GET_VALUE:if(e.key==null)throw new Error("Invalid request");yield*this.dhtOperations.getValue(e.key);return;case Pe.Type.PUT_VALUE:if(e.key==null||e.value==null)throw new Error("Invalid request");yield*this.dhtOperations.putValue(e.key,e.value);return;default:throw new Error("ERR_INVALID_REQUEST_TYPE")}}catch(r){Te.error("error handling DHT request - %e",r),yield Se(r)}}handleConnection(e){Promise.resolve().then(async()=>{let r=this,n=_i(e,{maxDataLength:wu}),i=await n.read($e);Te("read",i);try{switch(i.type){case $e.Type.CONNECT:{await r.connect(i),await n.write({type:re.Type.OK},re);break}case $e.Type.IDENTIFY:{await n.write({type:re.Type.OK,identify:{id:r.libp2p.peerId.toMultihash().bytes,addrs:r.libp2p.getMultiaddrs().map(o=>o.decapsulateCode(421)).map(o=>o.bytes)}},re);break}case $e.Type.LIST_PEERS:{let o=[],c=new Set;for(let s of r.libp2p.getConnections()){let a=s.remotePeer.toString();c.has(a)||(c.add(a),o.push({id:s.remotePeer.toMultihash().bytes,addrs:[s.remoteAddr.bytes]}))}await n.write({type:re.Type.OK,peers:o},re);break}case $e.Type.STREAM_OPEN:{let o=await r.openStream(i);await n.write({type:re.Type.OK,streamInfo:o.streamInfo},re);let c=n.unwrap();await ki(c,o.connection,c);break}case $e.Type.STREAM_HANDLER:{await r.registerStreamHandler(i),await n.write({type:re.Type.OK},re);break}case $e.Type.PEERSTORE:{if(i.peerStore==null)throw new Error("ERR_INVALID_REQUEST");let o=n.unwrap(),c=Vr(o);for await(let s of r.handlePeerStoreRequest(i.peerStore))await c.write(s);break}case $e.Type.PUBSUB:{if(i.pubsub==null)throw new Error("ERR_INVALID_REQUEST");let o=n.unwrap(),c=Vr(o);for await(let s of r.handlePubsubRequest(i.pubsub))await c.write(s);break}case $e.Type.DHT:{if(i.dht==null)throw new Error("ERR_INVALID_REQUEST");let o=n.unwrap(),c=Vr(o);for await(let s of r.handleDHTRequest(i.dht))await c.write(s);break}default:throw new Error("ERR_INVALID_REQUEST_TYPE")}}catch(o){Te.error("error handling incoming connection - %e",o);let c=n.unwrap();if(c.status!=="open")return;n=_i(c,{maxDataLength:wu}),await n.write({type:re.Type.ERROR,error:{msg:o.message},peers:[]},re)}finally{await n.unwrap().close()}}).catch(r=>{Te.error("error handling incoming connection - %e",r)})}},th=(t,e)=>new Do({multiaddr:t,libp2pNode:e});return Tu(rh);})();
|
|
17
17
|
/*! Bundled license information:
|
|
18
18
|
|
|
19
19
|
@noble/curves/utils.js:
|