@libp2p/webrtc 6.0.15 → 6.0.16-2151144c3
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 +6 -6
- package/dist/index.min.js.map +4 -4
- package/dist/src/private-to-public/transport.d.ts +1 -0
- package/dist/src/private-to-public/transport.d.ts.map +1 -1
- package/dist/src/private-to-public/transport.js +1 -0
- package/dist/src/private-to-public/transport.js.map +1 -1
- package/dist/src/private-to-public/utils/generate-certificates.d.ts +1 -0
- package/dist/src/private-to-public/utils/generate-certificates.d.ts.map +1 -1
- package/dist/src/private-to-public/utils/generate-certificates.js +1 -0
- package/dist/src/private-to-public/utils/generate-certificates.js.map +1 -1
- package/package.json +14 -12
- package/src/private-to-public/transport.ts +1 -0
- package/src/private-to-public/utils/generate-certificates.ts +1 -0
- package/dist/typedoc-urls.json +0 -14
package/dist/index.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PWebrtc = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2PWebrtc=(()=>{var Ss=Object.defineProperty;var eh=Object.getOwnPropertyDescriptor;var rh=Object.getOwnPropertyNames;var nh=Object.prototype.hasOwnProperty;var Bt=(e,t)=>{for(var r in t)Ss(e,r,{get:t[r],enumerable:!0})},oh=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of rh(t))!nh.call(e,o)&&o!==r&&Ss(e,o,{get:()=>t[o],enumerable:!(n=eh(t,o))||n.enumerable});return e};var sh=e=>oh(Ss({},"__esModule",{value:!0}),e);var _0={};Bt(_0,{webRTC:()=>C0,webRTCDirect:()=>v0});var Vn=class extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}},$n=class extends Error{static name="InvalidCryptoExchangeError";constructor(t="Invalid crypto exchange"){super(t),this.name="InvalidCryptoExchangeError"}},Y=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},cr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Wn=class extends Error{static name="ConnectionFailedError";constructor(t="Connection failed"){super(t),this.name="ConnectionFailedError"}},qn=class extends Error{static name="MuxerClosedError";constructor(t="The muxer is closed"){super(t),this.name="MuxerClosedError"}},ur=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}};var jt=class extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}},Gr=class extends Error{static name="StreamBufferError";constructor(t="The stream buffer was full"){super(t),this.name="StreamBufferError"}};var Gn=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},zn=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},jn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var Xn=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var Me=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Yn=class extends Event{data;constructor(t,r){super("message",r),this.data=t}},fr=class extends Event{error;local;constructor(t,r,n){super("close",n),this.error=r,this.local=t}},Zn=class extends fr{constructor(t,r){super(!0,t,r)}},Qn=class extends fr{constructor(t,r){super(!1,t,r)}};var As=Symbol.for("@libp2p/peer-id");var Jn=Symbol.for("@libp2p/transport");var _c;(function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"})(_c||(_c={}));var me=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let r=this.#t.get(t);return r==null?0:r.length}addEventListener(t,r,n){super.addEventListener(t,r,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:r,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,r,n){super.removeEventListener(t.toString(),r??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==r),this.#t.set(t,o))}dispatchEvent(t){let r=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),r}safeDispatchEvent(t,r={}){return this.dispatchEvent(new CustomEvent(t,r))}};var lr=Symbol.for("@libp2p/service-capabilities"),Ic=Symbol.for("@libp2p/service-dependencies");var Ls={};Bt(Ls,{base58btc:()=>ft,base58flickr:()=>hh});var og=new Uint8Array(0);function Lc(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function te(e){if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}function Bc(e){return new TextEncoder().encode(e)}function Dc(e){return new TextDecoder().decode(e)}function ih(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<e.length;o++){var s=e.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=e.length,c=e.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var E=0,h=0,b=0,v=p.length;b!==v&&p[b]===0;)b++,E++;for(var x=(v-b)*f+1>>>0,D=new Uint8Array(x);b!==v;){for(var k=p[b],O=0,K=x-1;(k!==0||O<h)&&K!==-1;K--,O++)k+=256*D[K]>>>0,D[K]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");h=O,b++}for(var _=x-h;_!==x&&D[_]===0;)_++;for(var A=c.repeat(E);_<x;++_)A+=e.charAt(D[_]);return A}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var E=0;if(p[E]!==" "){for(var h=0,b=0;p[E]===c;)h++,E++;for(var v=(p.length-E)*u+1>>>0,x=new Uint8Array(v);p[E];){var D=r[p.charCodeAt(E)];if(D===255)return;for(var k=0,O=v-1;(D!==0||k<b)&&O!==-1;O--,k++)D+=a*x[O]>>>0,x[O]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");b=k,E++}if(p[E]!==" "){for(var K=v-b;K!==v&&x[K]===0;)K++;for(var _=new Uint8Array(h+(v-K)),A=h;K!==v;)_[A++]=x[K++];return _}}}function m(p){var E=d(p);if(E)return E;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:d,decode:m}}var ah=ih,ch=ah,Rc=ch;var vs=class{name;prefix;baseEncode;constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Cs=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,r,n){this.name=t,this.prefix=r;let o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Pc(this,t)}},_s=class{decoders;constructor(t){this.decoders=t}or(t){return Pc(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Pc(e,t){return new _s({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var Is=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new vs(t,r,n),this.decoder=new Cs(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function hr({name:e,prefix:t,encode:r,decode:n}){return new Is(e,t,r,n)}function ge({name:e,prefix:t,alphabet:r}){let{encode:n,decode:o}=Rc(r,e);return hr({prefix:t,name:e,encode:n,decode:s=>te(o(s))})}function uh(e,t,r,n){let o=e.length;for(;e[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let f=t[e[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|f,i+=r,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function fh(e,t,r){let n=t[t.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],i+=8;i>r;)i-=r,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function lh(e){let t={};for(let r=0;r<e.length;++r)t[e[r]]=r;return t}function ut({name:e,prefix:t,bitsPerChar:r,alphabet:n}){let o=lh(n);return hr({prefix:t,name:e,encode(s){return fh(s,n,r)},decode(s){return uh(s,o,r,e)}})}var ft=ge({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),hh=ge({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Bs={};Bt(Bs,{base32:()=>ye,base32hex:()=>gh,base32hexpad:()=>bh,base32hexpadupper:()=>wh,base32hexupper:()=>yh,base32pad:()=>ph,base32padupper:()=>mh,base32upper:()=>dh,base32z:()=>xh});var ye=ut({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),dh=ut({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ph=ut({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),mh=ut({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),gh=ut({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),yh=ut({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),bh=ut({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),wh=ut({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),xh=ut({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ds={};Bt(Ds,{base36:()=>zr,base36upper:()=>Eh});var zr=ge({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Eh=ge({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Vt={};Bt(Vt,{Digest:()=>Ke,create:()=>Dt,decode:()=>mr,equals:()=>Rs,hasCode:()=>Hh});var Sh=Uc,Oc=128,Ah=127,vh=~Ah,Ch=Math.pow(2,31);function Uc(e,t,r){t=t||[],r=r||0;for(var n=r;e>=Ch;)t[r++]=e&255|Oc,e/=128;for(;e&vh;)t[r++]=e&255|Oc,e>>>=7;return t[r]=e|0,Uc.bytes=r-n+1,t}var _h=Ts,Ih=128,Nc=127;function Ts(e,n){var r=0,n=n||0,o=0,s=n,i,a=e.length;do{if(s>=a)throw Ts.bytes=0,new RangeError("Could not decode varint");i=e[s++],r+=o<28?(i&Nc)<<o:(i&Nc)*Math.pow(2,o),o+=7}while(i>=Ih);return Ts.bytes=s-n,r}var Lh=Math.pow(2,7),Bh=Math.pow(2,14),Dh=Math.pow(2,21),Th=Math.pow(2,28),Rh=Math.pow(2,35),Ph=Math.pow(2,42),Oh=Math.pow(2,49),Nh=Math.pow(2,56),Uh=Math.pow(2,63),kh=function(e){return e<Lh?1:e<Bh?2:e<Dh?3:e<Th?4:e<Rh?5:e<Ph?6:e<Oh?7:e<Nh?8:e<Uh?9:10},Mh={encode:Sh,decode:_h,encodingLength:kh},Kh=Mh,jr=Kh;function Xr(e,t=0){return[jr.decode(e,t),jr.decode.bytes]}function dr(e,t,r=0){return jr.encode(e,t,r),t}function pr(e){return jr.encodingLength(e)}function Dt(e,t){let r=t.byteLength,n=pr(e),o=n+pr(r),s=new Uint8Array(o+r);return dr(e,s,0),dr(r,s,n),s.set(t,o),new Ke(e,r,t,s)}function mr(e){let t=te(e),[r,n]=Xr(t),[o,s]=Xr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Ke(r,o,i,t)}function Rs(e,t){if(e===t)return!0;{let r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&Lc(e.bytes,r.bytes)}}var Ke=class{code;size;digest;bytes;constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}};function Hh(e,t){return e.code===t}function kc(e,t){let{bytes:r,version:n}=e;switch(n){case 0:return Vh(r,Ps(e),t??ft.encoder);default:return $h(r,Ps(e),t??ye.encoder)}}var Mc=new WeakMap;function Ps(e){let t=Mc.get(e);if(t==null){let r=new Map;return Mc.set(e,r),r}return t}var dt=class e{code;version;multihash;bytes;"/";constructor(t,r,n,o){this.code=r,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:r}=this;if(t!==Yr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Wh)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return e.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:r}=this.multihash,n=Dt(t,r);return e.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return e.equals(this,t)}static equals(t,r){let n=r;return n!=null&&t.code===n.code&&t.version===n.version&&Rs(t.multihash,n.multihash)}toString(t){return kc(this,t)}toJSON(){return{"/":kc(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let r=t;if(r instanceof e)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new e(n,o,s,i??Kc(n,o,s.bytes))}else if(r[qh]===!0){let{version:n,multihash:o,code:s}=r,i=mr(o);return e.create(n,s,i)}else return null}static create(t,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(r!==Yr)throw new Error(`Version 0 CID must use dag-pb (code: ${Yr}) block encoding`);return new e(t,r,n,n.bytes)}case 1:{let o=Kc(t,r,n.bytes);return new e(t,r,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return e.create(0,Yr,t)}static createV1(t,r){return e.create(1,t,r)}static decode(t){let[r,n]=e.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(t){let r=e.inspectBytes(t),n=r.size-r.multihashSize,o=te(t.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new Ke(r.multihashCode,r.digestSize,s,o);return[r.version===0?e.createV0(i):e.createV1(r.codec,i),t.subarray(r.size)]}static inspectBytes(t){let r=0,n=()=>{let[l,d]=Xr(t.subarray(r));return r+=d,l},o=n(),s=Yr;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,a=n(),c=n(),u=r+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(t,r){let[n,o]=Fh(t,r),s=e.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ps(s).set(n,t),s}};function Fh(e,t){switch(e[0]){case"Q":{let r=t??ft;return[ft.prefix,r.decode(`${ft.prefix}${e}`)]}case ft.prefix:{let r=t??ft;return[ft.prefix,r.decode(e)]}case ye.prefix:{let r=t??ye;return[ye.prefix,r.decode(e)]}case zr.prefix:{let r=t??zr;return[zr.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}}function Vh(e,t,r){let{prefix:n}=r;if(n!==ft.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=t.get(n);if(o==null){let s=r.encode(e).slice(1);return t.set(n,s),s}else return o}function $h(e,t,r){let{prefix:n}=r,o=t.get(n);if(o==null){let s=r.encode(e);return t.set(n,s),s}else return o}var Yr=112,Wh=18;function Kc(e,t,r){let n=pr(e),o=n+pr(t),s=new Uint8Array(o+r.byteLength);return dr(e,s,0),dr(t,s,n),s.set(r,o),s}var qh=Symbol.for("@ipld/js-cid/CID");var Os={};Bt(Os,{identity:()=>$t});var Hc=0,Gh="identity",Fc=te;function zh(e,t){if(t?.truncate!=null&&t.truncate!==e.byteLength){if(t.truncate<0||t.truncate>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,t.truncate)}return Dt(Hc,Fc(e))}var $t={code:Hc,name:Gh,encode:Fc,digest:zh};function wt(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function pt(e=0){return new Uint8Array(e)}function it(e=0){return new Uint8Array(e)}function Tt(e,t){t==null&&(t=e.reduce((o,s)=>o+s.length,0));let r=it(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}var $c=Symbol.for("@achingbrain/uint8arraylist");function Vc(e,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let r=0;for(let n of e){let o=r+n.byteLength;if(t<o)return{buf:n,index:t-r};r=o}throw new RangeError("index is out of bounds")}function eo(e){return!!e?.[$c]}var W=class e{bufs;length;[$c]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let r=0;for(let n of t)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(eo(n))r+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...t){this.prependAll(t)}prependAll(t){let r=0;for(let n of t.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(eo(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(t){let r=Vc(this.bufs,t);return r.buf[r.index]}set(t,r){let n=Vc(this.bufs,t);n.buf[n.index]=r}write(t,r=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(r+n,t[n]);else if(eo(t))for(let n=0;n<t.length;n++)this.set(r+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,r){let{bufs:n,length:o}=this._subList(t,r);return Tt(n,o)}subarray(t,r){let{bufs:n,length:o}=this._subList(t,r);return n.length===1?n[0]:Tt(n,o)}sublist(t,r){let{bufs:n,length:o}=this._subList(t,r),s=new e;return s.length=o,s.bufs=[...n],s}_subList(t,r){if(t=t??0,r=r??this.length,t<0&&(t=this.length+t),r<0&&(r=this.length+r),t<0||r>this.length)throw new RangeError("index is out of bounds");if(t===r)return{bufs:[],length:0};if(t===0&&r===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let u=t>=a&&t<c,f=r>a&&r<=c;if(u&&f){if(t===a&&r===c){n.push(i);break}let l=t-a;n.push(i.subarray(l,l+(r-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(f){if(r===c){n.push(i);break}n.push(i.subarray(0,r-a));break}n.push(i)}return{bufs:n,length:r-t}}indexOf(t,r=0){if(!eo(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),t.length===0)return r>this.length?this.length:r;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=r;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let m=this.get(l+d);if(n[d]!==m){f=Math.max(1,d-a[m]);break}}if(f===0)return l}return-1}getInt8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(t,r){let n=it(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,t)}getInt16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(t,r,n){let o=pt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,t)}getInt32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(t,r,n){let o=pt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,t)}getBigInt64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(t,r,n){let o=pt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,t)}getUint8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(t,r){let n=it(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,t)}getUint16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(t,r,n){let o=pt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,t)}getUint32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(t,r,n){let o=pt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,t)}getBigUint64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(t,r,n){let o=pt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,t)}getFloat32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(t,r,n){let o=pt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,t)}getFloat64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(t,r,n){let o=pt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof e)||t.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!wt(this.bufs[r],t.bufs[r]))return!1;return!0}static fromUint8Arrays(t,r){let n=new e;return n.bufs=t,r==null&&(r=t.reduce((o,s)=>o+s.byteLength,0)),n.length=r,n}};var Ns={};Bt(Ns,{base10:()=>Xh});var Xh=ge({prefix:"9",name:"base10",alphabet:"0123456789"});var Us={};Bt(Us,{base16:()=>Yh,base16upper:()=>Zh});var Yh=ut({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Zh=ut({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ks={};Bt(ks,{base2:()=>Qh});var Qh=ut({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ms={};Bt(Ms,{base256emoji:()=>nd});var Wc=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Jh=Wc.reduce((e,t,r)=>(e[r]=t,e),[]),td=Wc.reduce((e,t,r)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return e[n]=r,e},[]);function ed(e){return e.reduce((t,r)=>(t+=Jh[r],t),"")}function rd(e){let t=[];for(let r of e){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=td[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);t.push(o)}return new Uint8Array(t)}var nd=hr({prefix:"\u{1F680}",name:"base256emoji",encode:ed,decode:rd});var Ks={};Bt(Ks,{base64:()=>od,base64pad:()=>sd,base64url:()=>Zr,base64urlpad:()=>id});var od=ut({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),sd=ut({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Zr=ut({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),id=ut({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Hs={};Bt(Hs,{base8:()=>ad});var ad=ut({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Fs={};Bt(Fs,{identity:()=>cd});var cd=hr({prefix:"\0",name:"identity",encode:e=>Dc(e),decode:e=>Bc(e)});var Hg=new TextEncoder,Fg=new TextDecoder;var Ws={};Bt(Ws,{sha256:()=>ee,sha512:()=>hd});var ld=20;function $s({name:e,code:t,encode:r,minDigestLength:n,maxDigestLength:o}){return new Vs(e,t,r,n,o)}var Vs=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,r,n,o,s){this.name=t,this.code=r,this.encode=n,this.minDigestLength=o??ld,this.maxDigestLength=s}digest(t,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?qc(n,this.code,r?.truncate):n.then(o=>qc(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function qc(e,t,r){if(r!=null&&r!==e.byteLength){if(r>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,r)}return Dt(t,e)}function zc(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}var ee=$s({name:"sha2-256",code:18,encode:zc("SHA-256")}),hd=$s({name:"sha2-512",code:19,encode:zc("SHA-512")});var He={...Fs,...ks,...Hs,...Ns,...Us,...Bs,...Ds,...Ls,...Ks,...Ms},Jg={...Ws,...Os};function Xc(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}var jc=Xc("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),qs=Xc("ascii","a",e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},e=>{e=e.substring(1);let t=it(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}),dd={utf8:jc,"utf-8":jc,hex:He.base16,latin1:qs,ascii:qs,binary:qs,...He},ro=dd;function q(e,t="utf8"){let r=ro[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}function $(e,t="utf8"){let r=ro[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}var pd=parseInt("11111",2),Gs=parseInt("10000000",2),md=parseInt("01111111",2),Yc={0:Qr,1:Qr,2:gd,3:wd,4:xd,5:bd,6:yd,16:Qr,22:Qr,48:Qr};function re(e,t={offset:0}){let r=e[t.offset]&pd;if(t.offset++,Yc[r]!=null)return Yc[r](e,t);throw new Error("No decoder for tag "+r)}function Jr(e,t){let r=0;if((e[t.offset]&Gs)===Gs){let n=e[t.offset]&md,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(o,16)}else r=e[t.offset],t.offset++;return r}function Qr(e,t){Jr(e,t);let r=[];for(;!(t.offset>=e.byteLength);){let n=re(e,t);if(n===null)break;r.push(n)}return r}function gd(e,t){let r=Jr(e,t),n=t.offset,o=t.offset+r,s=[];for(let i=n;i<o;i++)i===n&&e[i]===0||s.push(e[i]);return t.offset+=r,Uint8Array.from(s)}function yd(e,t){let r=Jr(e,t),n=t.offset+r,o=e[t.offset];t.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;t.offset<n;){let u=e[t.offset];if(t.offset++,c.push(u&127),u<128){c.reverse();let f=0;for(let l=0;l<c.length;l++)f+=c[l]<<l*7;a+=`.${f}`,c=[]}}return a}function bd(e,t){return t.offset++,null}function wd(e,t){let r=Jr(e,t),n=e[t.offset];t.offset++;let o=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function xd(e,t){let r=Jr(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n}function Ed(e){let t=e.toString(16);t.length%2===1&&(t="0"+t);let r=new W;for(let n=0;n<t.length;n+=2)r.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return r}function zs(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);let t=Ed(e.byteLength);return new W(Uint8Array.from([t.byteLength|Gs]),t)}function Pt(e){let t=new W,r=128;return(e.subarray()[0]&r)===r&&t.append(Uint8Array.from([0])),t.append(e),new W(Uint8Array.from([2]),zs(t),t)}function no(e){let t=Uint8Array.from([0]),r=new W(t,e);return new W(Uint8Array.from([3]),zs(r),r)}function be(e,t=48){let r=new W;for(let n of e)r.append(n);return new W(Uint8Array.from([t]),zs(r),r)}async function Zc(e,t,r,n){let o=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,r.subarray());return n?.signal?.throwIfAborted(),s}var Sd=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Ad=Uint8Array.from([6,5,43,129,4,0,34]),vd=Uint8Array.from([6,5,43,129,4,0,35]),Cd={ext:!0,kty:"EC",crv:"P-256"},_d={ext:!0,kty:"EC",crv:"P-384"},Id={ext:!0,kty:"EC",crv:"P-521"},js=32,Xs=48,Ys=66;function Zs(e){let t=re(e);return Qc(t)}function Qc(e){let t=e[1][1][0],r=1,n,o;if(t.byteLength===js*2+1)return n=$(t.subarray(r,r+js),"base64url"),o=$(t.subarray(r+js),"base64url"),new gr({...Cd,key_ops:["verify"],x:n,y:o});if(t.byteLength===Xs*2+1)return n=$(t.subarray(r,r+Xs),"base64url"),o=$(t.subarray(r+Xs),"base64url"),new gr({..._d,key_ops:["verify"],x:n,y:o});if(t.byteLength===Ys*2+1)return n=$(t.subarray(r,r+Ys),"base64url"),o=$(t.subarray(r+Ys),"base64url"),new gr({...Id,key_ops:["verify"],x:n,y:o});throw new Y(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Jc(e){return be([Pt(Uint8Array.from([1])),be([Ld(e.crv)],160),be([no(new W(Uint8Array.from([4]),q(e.x??"","base64url"),q(e.y??"","base64url")))],161)]).subarray()}function Ld(e){if(e==="P-256")return Sd;if(e==="P-384")return Ad;if(e==="P-521")return vd;throw new Y(`Invalid curve ${e}`)}var gr=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Jc(this.jwk)),this._raw}toMultihash(){return $t.digest(we(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return ft.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}async verify(t,r,n){return Zc(this.jwk,r,t,n)}};function Fe(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Kt(e,t=""){if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw new Error(`${r}expected integer >= 0, got ${e}`)}}function F(e,t,r=""){let n=Fe(e),o=e?.length,s=t!==void 0;if(!n||s&&o!==t){let i=r&&`"${r}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function Ve(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Kt(e.outputLen),Kt(e.blockLen)}function yr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function eu(e,t){F(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Wt(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function oo(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function qt(e,t){return e<<32-t|e>>>t}var ru=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Bd=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function oe(e){if(F(e),ru)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Bd[e[r]];return t}var ne={_0:48,_9:57,A:65,F:70,a:97,f:102};function tu(e){if(e>=ne._0&&e<=ne._9)return e-ne._0;if(e>=ne.A&&e<=ne.F)return e-(ne.A-10);if(e>=ne.a&&e<=ne.f)return e-(ne.a-10)}function se(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(ru)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=tu(e.charCodeAt(s)),a=tu(e.charCodeAt(s+1));if(i===void 0||a===void 0){let c=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ot(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];F(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let s=e[n];r.set(s,o),o+=s.length}return r}function Qs(e,t={}){let r=(o,s)=>e(s).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.create=o=>e(o),Object.assign(r,t),Object.freeze(r)}function xe(e=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}var Js=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function nu(e,t,r){return e&t^~e&r}function ou(e,t,r){return e&t^e&r^t&r}var tn=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,r,n,o){this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=oo(this.buffer)}update(t){yr(this),F(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=oo(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){yr(this),eu(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,Wt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)r[l]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=oo(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ie=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var xt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var so=BigInt(4294967295),su=BigInt(32);function Dd(e,t=!1){return t?{h:Number(e&so),l:Number(e>>su&so)}:{h:Number(e>>su&so)|0,l:Number(e&so)|0}}function iu(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=Dd(e[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var ti=(e,t,r)=>e>>>r,ei=(e,t,r)=>e<<32-r|t>>>r,$e=(e,t,r)=>e>>>r|t<<32-r,We=(e,t,r)=>e<<32-r|t>>>r,en=(e,t,r)=>e<<64-r|t>>>r-32,rn=(e,t,r)=>e>>>r-32|t<<64-r;function Xt(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var au=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),cu=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,uu=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),fu=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,lu=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),hu=(e,t,r,n,o,s)=>t+r+n+o+s+(e/2**32|0)|0;var Rd=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]),Ee=new Uint32Array(64),ri=class extends tn{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,r,n,o,s,i,a,c]}set(t,r,n,o,s,i,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,r){for(let l=0;l<16;l++,r+=4)Ee[l]=t.getUint32(r,!1);for(let l=16;l<64;l++){let d=Ee[l-15],m=Ee[l-2],p=qt(d,7)^qt(d,18)^d>>>3,E=qt(m,17)^qt(m,19)^m>>>10;Ee[l]=E+Ee[l-7]+p+Ee[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let d=qt(a,6)^qt(a,11)^qt(a,25),m=f+d+nu(a,c,u)+Rd[l]+Ee[l]|0,E=(qt(n,2)^qt(n,13)^qt(n,22))+ou(n,o,s)|0;f=u,u=c,c=a,a=i+m|0,i=s,s=o,o=n,n=m+E|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){Wt(Ee)}destroy(){this.set(0,0,0,0,0,0,0,0),Wt(this.buffer)}},ni=class extends ri{A=ie[0]|0;B=ie[1]|0;C=ie[2]|0;D=ie[3]|0;E=ie[4]|0;F=ie[5]|0;G=ie[6]|0;H=ie[7]|0;constructor(){super(32)}};var du=iu(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Pd=du[0],Od=du[1],Se=new Uint32Array(80),Ae=new Uint32Array(80),oi=class extends tn{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:d,Gh:m,Gl:p,Hh:E,Hl:h}=this;return[t,r,n,o,s,i,a,c,u,f,l,d,m,p,E,h]}set(t,r,n,o,s,i,a,c,u,f,l,d,m,p,E,h){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=m|0,this.Gl=p|0,this.Hh=E|0,this.Hl=h|0}process(t,r){for(let x=0;x<16;x++,r+=4)Se[x]=t.getUint32(r),Ae[x]=t.getUint32(r+=4);for(let x=16;x<80;x++){let D=Se[x-15]|0,k=Ae[x-15]|0,O=$e(D,k,1)^$e(D,k,8)^ti(D,k,7),K=We(D,k,1)^We(D,k,8)^ei(D,k,7),_=Se[x-2]|0,A=Ae[x-2]|0,N=$e(_,A,19)^en(_,A,61)^ti(_,A,6),M=We(_,A,19)^rn(_,A,61)^ei(_,A,6),T=uu(K,M,Ae[x-7],Ae[x-16]),w=fu(T,O,N,Se[x-7],Se[x-16]);Se[x]=w|0,Ae[x]=T|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:m,Fl:p,Gh:E,Gl:h,Hh:b,Hl:v}=this;for(let x=0;x<80;x++){let D=$e(l,d,14)^$e(l,d,18)^en(l,d,41),k=We(l,d,14)^We(l,d,18)^rn(l,d,41),O=l&m^~l&E,K=d&p^~d&h,_=lu(v,k,K,Od[x],Ae[x]),A=hu(_,b,D,O,Pd[x],Se[x]),N=_|0,M=$e(n,o,28)^en(n,o,34)^en(n,o,39),T=We(n,o,28)^rn(n,o,34)^rn(n,o,39),w=n&s^n&a^s&a,g=o&i^o&c^i&c;b=E|0,v=h|0,E=m|0,h=p|0,m=l|0,p=d|0,{h:l,l:d}=Xt(u|0,f|0,A|0,N|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let y=au(N,T,g);n=cu(y,A,M,w),o=y|0}({h:n,l:o}=Xt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Xt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Xt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=Xt(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=Xt(this.Eh|0,this.El|0,l|0,d|0),{h:m,l:p}=Xt(this.Fh|0,this.Fl|0,m|0,p|0),{h:E,l:h}=Xt(this.Gh|0,this.Gl|0,E|0,h|0),{h:b,l:v}=Xt(this.Hh|0,this.Hl|0,b|0,v|0),this.set(n,o,s,i,a,c,u,f,l,d,m,p,E,h,b,v)}roundClean(){Wt(Se,Ae)}destroy(){Wt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},si=class extends oi{Ah=xt[0]|0;Al=xt[1]|0;Bh=xt[2]|0;Bl=xt[3]|0;Ch=xt[4]|0;Cl=xt[5]|0;Dh=xt[6]|0;Dl=xt[7]|0;Eh=xt[8]|0;El=xt[9]|0;Fh=xt[10]|0;Fl=xt[11]|0;Gh=xt[12]|0;Gl=xt[13]|0;Hh=xt[14]|0;Hl=xt[15]|0;constructor(){super(64)}};var Yt=Qs(()=>new ni,Js(1));var pu=Qs(()=>new si,Js(3));var ai=BigInt(0),ii=BigInt(1);function ae(e,t=""){if(typeof e!="boolean"){let r=t&&`"${t}" `;throw new Error(r+"expected boolean, got type="+typeof e)}return e}function mu(e){if(typeof e=="bigint"){if(!io(e))throw new Error("positive bigint expected, got "+e)}else Kt(e);return e}function nn(e){let t=mu(e).toString(16);return t.length&1?"0"+t:t}function gu(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?ai:BigInt("0x"+e)}function br(e){return gu(oe(e))}function Zt(e){return gu(oe(qe(F(e)).reverse()))}function ao(e,t){Kt(t),e=mu(e);let r=se(e.toString(16).padStart(t*2,"0"));if(r.length!==t)throw new Error("number too large");return r}function on(e,t){return ao(e,t).reverse()}function qe(e){return Uint8Array.from(e)}var io=e=>typeof e=="bigint"&&ai<=e;function Nd(e,t,r){return io(e)&&io(t)&&io(r)&&t<=e&&e<r}function ve(e,t,r,n){if(!Nd(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function ci(e){let t;for(t=0;e>ai;e>>=ii,t+=1);return t}var sn=e=>(ii<<BigInt(e))-ii;function yu(e,t,r){if(Kt(e,"hashLen"),Kt(t,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");let n=h=>new Uint8Array(h),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(e),u=n(e),f=0,l=()=>{c.fill(1),u.fill(0),f=0},d=(...h)=>r(u,Ot(c,...h)),m=(h=o)=>{u=d(s,h),c=d(),h.length!==0&&(u=d(i,h),c=d())},p=()=>{if(f++>=a)throw new Error("drbg: tried max amount of iterations");let h=0,b=[];for(;h<t;){c=d();let v=c.slice();b.push(v),h+=c.length}return Ot(...b)};return(h,b)=>{l(),m(h);let v;for(;!(v=b(p()));)m();return l(),v}}function Qt(e,t={},r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(s,i,a){let c=e[s];if(a&&c===void 0)return;let u=typeof c;if(u!==i||c===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${u}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(t,!1),o(r,!0)}function wr(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}var Rt=BigInt(0),mt=BigInt(1),Ge=BigInt(2),xu=BigInt(3),Eu=BigInt(4),Su=BigInt(5),Ud=BigInt(7),Au=BigInt(8),kd=BigInt(9),vu=BigInt(16);function at(e,t){let r=e%t;return r>=Rt?r:t+r}function st(e,t,r){let n=e;for(;t-- >Rt;)n*=n,n%=r;return n}function bu(e,t){if(e===Rt)throw new Error("invert: expected non-zero number");if(t<=Rt)throw new Error("invert: expected positive modulus, got "+t);let r=at(e,t),n=t,o=Rt,s=mt,i=mt,a=Rt;for(;r!==Rt;){let u=n/r,f=n%r,l=o-i*u,d=s-a*u;n=r,r=f,o=i,s=a,i=l,a=d}if(n!==mt)throw new Error("invert: does not exist");return at(o,t)}function fi(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function Cu(e,t){let r=(e.ORDER+mt)/Eu,n=e.pow(t,r);return fi(e,n,t),n}function Md(e,t){let r=(e.ORDER-Su)/Au,n=e.mul(t,Ge),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,Ge),o),a=e.mul(s,e.sub(i,e.ONE));return fi(e,a,t),a}function Kd(e){let t=xr(e),r=_u(e),n=r(t,t.neg(t.ONE)),o=r(t,n),s=r(t,t.neg(n)),i=(e+Ud)/vu;return(a,c)=>{let u=a.pow(c,i),f=a.mul(u,n),l=a.mul(u,o),d=a.mul(u,s),m=a.eql(a.sqr(f),c),p=a.eql(a.sqr(l),c);u=a.cmov(u,f,m),f=a.cmov(d,l,p);let E=a.eql(a.sqr(f),c),h=a.cmov(u,f,E);return fi(a,h,c),h}}function _u(e){if(e<xu)throw new Error("sqrt is not defined for small field");let t=e-mt,r=0;for(;t%Ge===Rt;)t/=Ge,r++;let n=Ge,o=xr(e);for(;wu(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Cu;let s=o.pow(n,t),i=(t+mt)/Ge;return function(c,u){if(c.is0(u))return u;if(wu(c,u)!==1)throw new Error("Cannot find square root");let f=r,l=c.mul(c.ONE,s),d=c.pow(u,t),m=c.pow(u,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,E=c.sqr(d);for(;!c.eql(E,c.ONE);)if(p++,E=c.sqr(E),p===f)throw new Error("Cannot find square root");let h=mt<<BigInt(f-p-1),b=c.pow(l,h);f=p,l=c.sqr(b),d=c.mul(d,l),m=c.mul(m,b)}return m}}function Hd(e){return e%Eu===xu?Cu:e%Au===Su?Md:e%vu===kd?Kd(e):_u(e)}var Iu=(e,t)=>(at(e,t)&mt)===mt,Fd=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function li(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=Fd.reduce((n,o)=>(n[o]="function",n),t);return Qt(e,r),e}function Vd(e,t,r){if(r<Rt)throw new Error("invalid exponent, negatives unsupported");if(r===Rt)return e.ONE;if(r===mt)return t;let n=e.ONE,o=t;for(;r>Rt;)r&mt&&(n=e.mul(n,o)),o=e.sqr(o),r>>=mt;return n}function an(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function wu(e,t){let r=(e.ORDER-mt)/Ge,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function $d(e,t){t!==void 0&&Kt(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var ui=class{ORDER;BITS;BYTES;isLE;ZERO=Rt;ONE=mt;_lengths;_sqrt;_mod;constructor(t,r={}){if(t<=Rt)throw new Error("invalid field: expected ORDER > 0, got "+t);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=r.allowedLengths?.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:o,nByteLength:s}=$d(t,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(t){return at(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof t);return Rt<=t&&t<this.ORDER}is0(t){return t===Rt}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&mt)===mt}neg(t){return at(-t,this.ORDER)}eql(t,r){return t===r}sqr(t){return at(t*t,this.ORDER)}add(t,r){return at(t+r,this.ORDER)}sub(t,r){return at(t-r,this.ORDER)}mul(t,r){return at(t*r,this.ORDER)}pow(t,r){return Vd(this,t,r)}div(t,r){return at(t*bu(r,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,r){return t+r}subN(t,r){return t-r}mulN(t,r){return t*r}inv(t){return bu(t,this.ORDER)}sqrt(t){return this._sqrt||(this._sqrt=Hd(this.ORDER)),this._sqrt(this,t)}toBytes(t){return this.isLE?on(t,this.BYTES):ao(t,this.BYTES)}fromBytes(t,r=!1){F(t);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let u=new Uint8Array(o);u.set(t,s?0:u.length-t.length),t=u}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=s?Zt(t):br(t);if(a&&(c=at(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return an(this,t)}cmov(t,r,n){return n?r:t}};function xr(e,t={}){return new ui(e,t)}function Lu(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function hi(e){let t=Lu(e);return t+Math.ceil(t/2)}function di(e,t,r=!1){F(e);let n=e.length,o=Lu(t),s=hi(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?Zt(e):br(e),a=at(i,t-mt)+mt;return r?on(a,o):ao(a,o)}var Er=BigInt(0),ze=BigInt(1);function cn(e,t){let r=t.negate();return e?r:t}function je(e,t){let r=an(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function Ru(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function pi(e,t){Ru(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=sn(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Bu(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=ze);let u=t*n,f=u+Math.abs(a)-1,l=a===0,d=a<0,m=t%2!==0;return{nextN:c,offset:f,isZero:l,isNeg:d,isNegF:m,offsetF:u}}var mi=new WeakMap,Pu=new WeakMap;function gi(e){return Pu.get(e)||1}function Du(e){if(e!==Er)throw new Error("invalid wNAF")}var Sr=class{BASE;ZERO;Fn;bits;constructor(t,r){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=r}_unsafeLadder(t,r,n=this.ZERO){let o=t;for(;r>Er;)r&ze&&(n=n.add(o)),o=o.double(),r>>=ze;return n}precomputeWindow(t,r){let{windows:n,windowSize:o}=pi(r,this.bits),s=[],i=t,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let u=1;u<o;u++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(t,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=pi(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:f,isNeg:l,isNegF:d,offsetF:m}=Bu(n,a,i);n=c,f?s=s.add(cn(d,r[m])):o=o.add(cn(l,r[u]))}return Du(n),{p:o,f:s}}wNAFUnsafe(t,r,n,o=this.ZERO){let s=pi(t,this.bits);for(let i=0;i<s.windows&&n!==Er;i++){let{nextN:a,offset:c,isZero:u,isNeg:f}=Bu(n,i,s);if(n=a,!u){let l=r[c];o=o.add(f?l.negate():l)}}return Du(n),o}getPrecomputes(t,r,n){let o=mi.get(r);return o||(o=this.precomputeWindow(r,t),t!==1&&(typeof n=="function"&&(o=n(o)),mi.set(r,o))),o}cached(t,r,n){let o=gi(t);return this.wNAF(o,this.getPrecomputes(o,t,n),r)}unsafe(t,r,n,o){let s=gi(t);return s===1?this._unsafeLadder(t,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),r,o)}createCache(t,r){Ru(r,this.bits),Pu.set(t,r),mi.delete(t)}hasCache(t){return gi(t)!==1}};function Ou(e,t,r,n){let o=t,s=e.ZERO,i=e.ZERO;for(;r>Er||n>Er;)r&ze&&(s=s.add(o)),n&ze&&(i=i.add(o)),o=o.double(),r>>=ze,n>>=ze;return{p1:s,p2:i}}function Tu(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return li(t),t}else return xr(e,{isLE:r})}function co(e,t,r={},n){if(n===void 0&&(n=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let u=t[c];if(!(typeof u=="bigint"&&u>Er))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Tu(t.p,r.Fp,n),s=Tu(t.n,r.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function Ar(e,t){return function(n){let o=e(n);return{secretKey:o,publicKey:t(o)}}}var Ce=BigInt(0),gt=BigInt(1),yi=BigInt(2),Wd=BigInt(8);function qd(e,t,r,n){let o=e.sqr(r),s=e.sqr(n),i=e.add(e.mul(t.a,o),s),a=e.add(e.ONE,e.mul(t.d,e.mul(o,s)));return e.eql(i,a)}function Nu(e,t={}){let r=co("edwards",e,t,t.FpFnLE),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i}=s;Qt(t,{},{uvRatio:"function"});let a=yi<<BigInt(o.BYTES*8)-gt,c=h=>n.create(h),u=t.uvRatio||((h,b)=>{try{return{isValid:!0,value:n.sqrt(n.div(h,b))}}catch{return{isValid:!1,value:Ce}}});if(!qd(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function f(h,b,v=!1){let x=v?gt:Ce;return ve("coordinate "+h,b,x,a),b}function l(h){if(!(h instanceof p))throw new Error("EdwardsPoint expected")}let d=wr((h,b)=>{let{X:v,Y:x,Z:D}=h,k=h.is0();b==null&&(b=k?Wd:n.inv(D));let O=c(v*b),K=c(x*b),_=n.mul(D,b);if(k)return{x:Ce,y:gt};if(_!==gt)throw new Error("invZ was invalid");return{x:O,y:K}}),m=wr(h=>{let{a:b,d:v}=s;if(h.is0())throw new Error("bad point: ZERO");let{X:x,Y:D,Z:k,T:O}=h,K=c(x*x),_=c(D*D),A=c(k*k),N=c(A*A),M=c(K*b),T=c(A*c(M+_)),w=c(N+c(v*c(K*_)));if(T!==w)throw new Error("bad point: equation left != right (1)");let g=c(x*D),y=c(k*O);if(g!==y)throw new Error("bad point: equation left != right (2)");return!0});class p{static BASE=new p(s.Gx,s.Gy,gt,c(s.Gx*s.Gy));static ZERO=new p(Ce,gt,gt,Ce);static Fp=n;static Fn=o;X;Y;Z;T;constructor(b,v,x,D){this.X=f("x",b),this.Y=f("y",v),this.Z=f("z",x,!0),this.T=f("t",D),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){if(b instanceof p)throw new Error("extended point not allowed");let{x:v,y:x}=b||{};return f("x",v),f("y",x),new p(v,x,gt,c(v*x))}static fromBytes(b,v=!1){let x=n.BYTES,{a:D,d:k}=s;b=qe(F(b,x,"point")),ae(v,"zip215");let O=qe(b),K=b[x-1];O[x-1]=K&-129;let _=Zt(O),A=v?a:n.ORDER;ve("point.y",_,Ce,A);let N=c(_*_),M=c(N-gt),T=c(k*N-D),{isValid:w,value:g}=u(M,T);if(!w)throw new Error("bad point: invalid y coordinate");let y=(g>)===gt,C=(K&128)!==0;if(!v&&g===Ce&&C)throw new Error("bad point: x=0 and x_0=1");return C!==y&&(g=c(-g)),p.fromAffine({x:g,y:_})}static fromHex(b,v=!1){return p.fromBytes(se(b),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,v=!0){return E.createCache(this,b),v||this.multiply(yi),this}assertValidity(){m(this)}equals(b){l(b);let{X:v,Y:x,Z:D}=this,{X:k,Y:O,Z:K}=b,_=c(v*K),A=c(k*D),N=c(x*K),M=c(O*D);return _===A&&N===M}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:b}=s,{X:v,Y:x,Z:D}=this,k=c(v*v),O=c(x*x),K=c(yi*c(D*D)),_=c(b*k),A=v+x,N=c(c(A*A)-k-O),M=_+O,T=M-K,w=_-O,g=c(N*T),y=c(M*w),C=c(N*w),L=c(T*M);return new p(g,y,L,C)}add(b){l(b);let{a:v,d:x}=s,{X:D,Y:k,Z:O,T:K}=this,{X:_,Y:A,Z:N,T:M}=b,T=c(D*_),w=c(k*A),g=c(K*x*M),y=c(O*N),C=c((D+k)*(_+A)-T-w),L=y-g,I=y+g,S=c(w-v*T),B=c(C*L),R=c(I*S),P=c(C*S),j=c(L*I);return new p(B,R,j,P)}subtract(b){return this.add(b.negate())}multiply(b){if(!o.isValidNot0(b))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:x}=E.cached(this,b,D=>je(p,D));return je(p,[v,x])[0]}multiplyUnsafe(b,v=p.ZERO){if(!o.isValid(b))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return b===Ce?p.ZERO:this.is0()||b===gt?this:E.unsafe(this,b,x=>je(p,x),v)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return E.unsafe(this,s.n).is0()}toAffine(b){return d(this,b)}clearCofactor(){return i===gt?this:this.multiplyUnsafe(i)}toBytes(){let{x:b,y:v}=this.toAffine(),x=n.toBytes(v);return x[x.length-1]|=b>?128:0,x}toHex(){return oe(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let E=new Sr(p,o.BITS);return p.BASE.precompute(8),p}function Uu(e,t,r={}){if(typeof t!="function")throw new Error('"hash" function param is required');Qt(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=r,{BASE:o,Fp:s,Fn:i}=e,a=r.randomBytes||xe,c=r.adjustScalarBytes||(_=>_),u=r.domain||((_,A,N)=>{if(ae(N,"phflag"),A.length||N)throw new Error("Contexts/pre-hash are not supported");return _});function f(_){return i.create(Zt(_))}function l(_){let A=x.secretKey;F(_,x.secretKey,"secretKey");let N=F(t(_),2*A,"hashedSecretKey"),M=c(N.slice(0,A)),T=N.slice(A,2*A),w=f(M);return{head:M,prefix:T,scalar:w}}function d(_){let{head:A,prefix:N,scalar:M}=l(_),T=o.multiply(M),w=T.toBytes();return{head:A,prefix:N,scalar:M,point:T,pointBytes:w}}function m(_){return d(_).pointBytes}function p(_=Uint8Array.of(),...A){let N=Ot(...A);return f(t(u(N,F(_,void 0,"context"),!!n)))}function E(_,A,N={}){_=F(_,void 0,"message"),n&&(_=n(_));let{prefix:M,scalar:T,pointBytes:w}=d(A),g=p(N.context,M,_),y=o.multiply(g).toBytes(),C=p(N.context,y,w,_),L=i.create(g+C*T);if(!i.isValid(L))throw new Error("sign failed: invalid s");let I=Ot(y,i.toBytes(L));return F(I,x.signature,"result")}let h={zip215:!0};function b(_,A,N,M=h){let{context:T,zip215:w}=M,g=x.signature;_=F(_,g,"signature"),A=F(A,void 0,"message"),N=F(N,x.publicKey,"publicKey"),w!==void 0&&ae(w,"zip215"),n&&(A=n(A));let y=g/2,C=_.subarray(0,y),L=Zt(_.subarray(y,g)),I,S,B;try{I=e.fromBytes(N,w),S=e.fromBytes(C,w),B=o.multiplyUnsafe(L)}catch{return!1}if(!w&&I.isSmallOrder())return!1;let R=p(T,S.toBytes(),I.toBytes(),A);return S.add(I.multiplyUnsafe(R)).subtract(B).clearCofactor().is0()}let v=s.BYTES,x={secretKey:v,publicKey:v,signature:2*v,seed:v};function D(_=a(x.seed)){return F(_,x.seed,"seed")}function k(_){return Fe(_)&&_.length===i.BYTES}function O(_,A){try{return!!e.fromBytes(_,A)}catch{return!1}}let K={getExtendedPublicKey:d,randomSecretKey:D,isValidSecretKey:k,isValidPublicKey:O,toMontgomery(_){let{y:A}=e.fromBytes(_),N=x.publicKey,M=N===32;if(!M&&N!==57)throw new Error("only defined for 25519 and 448");let T=M?s.div(gt+A,gt-A):s.div(A-gt,A+gt);return s.toBytes(T)},toMontgomerySecret(_){let A=x.secretKey;F(_,A);let N=t(_.subarray(0,A));return c(N).subarray(0,A)}};return Object.freeze({keygen:Ar(D,m),getPublicKey:m,sign:E,verify:b,utils:K,Point:e,lengths:x})}var un=BigInt(0),vr=BigInt(1),uo=BigInt(2);function Gd(e){return Qt(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function ku(e){let t=Gd(e),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=t,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||xe,u=a?255:448,f=a?32:56,l=BigInt(a?9:5),d=BigInt(a?121665:39081),m=a?uo**BigInt(254):uo**BigInt(447),p=a?BigInt(8)*uo**BigInt(251)-vr:BigInt(4)*uo**BigInt(445)-vr,E=m+p+vr,h=g=>at(g,r),b=v(l);function v(g){return on(h(g),f)}function x(g){let y=qe(F(g,f,"uCoordinate"));return a&&(y[31]&=127),h(Zt(y))}function D(g){return Zt(o(qe(F(g,f,"scalar"))))}function k(g,y){let C=N(x(y),D(g));if(C===un)throw new Error("invalid private or public key received");return v(C)}function O(g){return k(g,b)}let K=O,_=k;function A(g,y,C){let L=h(g*(y-C));return y=h(y-L),C=h(C+L),{x_2:y,x_3:C}}function N(g,y){ve("u",g,un,r),ve("scalar",y,m,E);let C=y,L=g,I=vr,S=un,B=g,R=vr,P=un;for(let G=BigInt(u-1);G>=un;G--){let V=C>>G&vr;P^=V,{x_2:I,x_3:B}=A(P,I,B),{x_2:S,x_3:R}=A(P,S,R),P=V;let X=I+S,rt=h(X*X),lt=I-S,Z=h(lt*lt),ht=rt-Z,ar=B+R,Fn=B-R,qr=h(Fn*X),Ac=h(ar*lt),vc=qr+Ac,Cc=qr-Ac;B=h(vc*vc),R=h(L*h(Cc*Cc)),I=h(rt*Z),S=h(ht*(rt+h(d*ht)))}({x_2:I,x_3:B}=A(P,I,B)),{x_2:S,x_3:R}=A(P,S,R);let j=s(S);return h(I*j)}let M={secretKey:f,publicKey:f,seed:f},T=(g=c(f))=>(F(g,M.seed,"seed"),g),w={randomSecretKey:T};return Object.freeze({keygen:Ar(T,K),getSharedSecret:_,getPublicKey:K,scalarMult:k,scalarMultBase:O,utils:w,GuBytes:b.slice(),lengths:M})}var zd=BigInt(1),Mu=BigInt(2),jd=BigInt(3),Xd=BigInt(5),Yd=BigInt(8),fo=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Zd={p:fo,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Yd,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Hu(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=fo,a=e*e%s*e%s,c=st(a,Mu,s)*a%s,u=st(c,zd,s)*e%s,f=st(u,Xd,s)*u%s,l=st(f,t,s)*f%s,d=st(l,r,s)*l%s,m=st(d,n,s)*d%s,p=st(m,o,s)*m%s,E=st(p,o,s)*m%s,h=st(E,t,s)*f%s;return{pow_p_5_8:st(h,Mu,s)*e%s,b2:a}}function Fu(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var Ku=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Qd(e,t){let r=fo,n=at(t*t*t,r),o=at(n*n*t,r),s=Hu(e*o).pow_p_5_8,i=at(e*n*s,r),a=at(t*i*i,r),c=i,u=at(i*Ku,r),f=a===e,l=a===at(-e,r),d=a===at(-e*Ku,r);return f&&(i=c),(l||d)&&(i=u),Iu(i,r)&&(i=at(-i,r)),{isValid:f||l,value:i}}var Jd=Nu(Zd,{uvRatio:Qd});function tp(e){return Uu(Jd,pu,Object.assign({adjustScalarBytes:Fu},e))}var Vu=tp({});var fn=(()=>{let e=fo;return ku({P:e,type:"x25519",powPminus2:t=>{let{pow_p_5_8:r,b2:n}=Hu(t);return at(st(r,jd,e)*n,e)},adjustScalarBytes:Fu})})();var ln=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},lo=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var $u={get(e=globalThis){let t=e.crypto;if(t?.subtle==null)throw new lo("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Ht=$u;var ho=32;var bi,ep=(async()=>{try{return await Ht.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function rp(e,t,r){if(e.buffer instanceof ArrayBuffer){let n=await Ht.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Ht.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function np(e,t,r){return Vu.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}async function Wu(e,t,r){return bi==null&&(bi=await ep),bi?rp(e,t,r):np(e,t,r)}function po(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}var mo=class{type="Ed25519";raw;constructor(t){this.raw=wi(t,ho)}toMultihash(){return $t.digest(we(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return ft.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}verify(t,r,n){n?.signal?.throwIfAborted();let o=Wu(this.raw,r,t);return po(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function xi(e){return e=wi(e,ho),new mo(e)}function wi(e,t){if(e=Uint8Array.from(e??[]),e.length!==t)throw new Y(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var sp=Math.pow(2,7),ip=Math.pow(2,14),ap=Math.pow(2,21),Ei=Math.pow(2,28),Si=Math.pow(2,35),Ai=Math.pow(2,42),vi=Math.pow(2,49),J=128,vt=127;function et(e){if(e<sp)return 1;if(e<ip)return 2;if(e<ap)return 3;if(e<Ei)return 4;if(e<Si)return 5;if(e<Ai)return 6;if(e<vi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function _e(e,t,r=0){switch(et(e)){case 8:t[r++]=e&255|J,e/=128;case 7:t[r++]=e&255|J,e/=128;case 6:t[r++]=e&255|J,e/=128;case 5:t[r++]=e&255|J,e/=128;case 4:t[r++]=e&255|J,e>>>=7;case 3:t[r++]=e&255|J,e>>>=7;case 2:t[r++]=e&255|J,e>>>=7;case 1:{t[r++]=e&255,e>>>=7;break}default:throw new Error("unreachable")}return t}function cp(e,t,r=0){switch(et(e)){case 8:t.set(r++,e&255|J),e/=128;case 7:t.set(r++,e&255|J),e/=128;case 6:t.set(r++,e&255|J),e/=128;case 5:t.set(r++,e&255|J),e/=128;case 4:t.set(r++,e&255|J),e>>>=7;case 3:t.set(r++,e&255|J),e>>>=7;case 2:t.set(r++,e&255|J),e>>>=7;case 1:{t.set(r++,e&255),e>>>=7;break}default:throw new Error("unreachable")}return t}function hn(e,t){let r=e[t],n=0;if(n+=r&vt,r<J||(r=e[t+1],n+=(r&vt)<<7,r<J)||(r=e[t+2],n+=(r&vt)<<14,r<J)||(r=e[t+3],n+=(r&vt)<<21,r<J)||(r=e[t+4],n+=(r&vt)*Ei,r<J)||(r=e[t+5],n+=(r&vt)*Si,r<J)||(r=e[t+6],n+=(r&vt)*Ai,r<J)||(r=e[t+7],n+=(r&vt)*vi,r<J))return n;throw new RangeError("Could not decode varint")}function up(e,t){let r=e.get(t),n=0;if(n+=r&vt,r<J||(r=e.get(t+1),n+=(r&vt)<<7,r<J)||(r=e.get(t+2),n+=(r&vt)<<14,r<J)||(r=e.get(t+3),n+=(r&vt)<<21,r<J)||(r=e.get(t+4),n+=(r&vt)*Ei,r<J)||(r=e.get(t+5),n+=(r&vt)*Si,r<J)||(r=e.get(t+6),n+=(r&vt)*Ai,r<J)||(r=e.get(t+7),n+=(r&vt)*vi,r<J))return n;throw new RangeError("Could not decode varint")}function go(e,t,r=0){return t==null&&(t=it(et(e))),t instanceof Uint8Array?_e(e,t,r):cp(e,t,r)}function ce(e,t=0){return e instanceof Uint8Array?hn(e,t):up(e,t)}var Ci=new Float32Array([-0]),Ie=new Uint8Array(Ci.buffer);function Gu(e,t,r){Ci[0]=e,t[r]=Ie[0],t[r+1]=Ie[1],t[r+2]=Ie[2],t[r+3]=Ie[3]}function zu(e,t){return Ie[0]=e[t],Ie[1]=e[t+1],Ie[2]=e[t+2],Ie[3]=e[t+3],Ci[0]}var _i=new Float64Array([-0]),Ct=new Uint8Array(_i.buffer);function ju(e,t,r){_i[0]=e,t[r]=Ct[0],t[r+1]=Ct[1],t[r+2]=Ct[2],t[r+3]=Ct[3],t[r+4]=Ct[4],t[r+5]=Ct[5],t[r+6]=Ct[6],t[r+7]=Ct[7]}function Xu(e,t){return Ct[0]=e[t],Ct[1]=e[t+1],Ct[2]=e[t+2],Ct[3]=e[t+3],Ct[4]=e[t+4],Ct[5]=e[t+5],Ct[6]=e[t+6],Ct[7]=e[t+7],_i[0]}var fp=BigInt(Number.MAX_SAFE_INTEGER),lp=BigInt(Number.MIN_SAFE_INTEGER),Ut=class e{lo;hi;constructor(t,r){this.lo=t|0,this.hi=r|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?t<16384?t<128?1:2:t<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return Xe;if(t<fp&&t>lp)return this.fromNumber(Number(t));let r=t<0n;r&&(t=-t);let n=t>>32n,o=t-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>Yu&&(o=0n,++n>Yu&&(n=0n))),new e(Number(o),Number(n))}static fromNumber(t){if(t===0)return Xe;let r=t<0;r&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new e(n,o)}static from(t){return typeof t=="number"?e.fromNumber(t):typeof t=="bigint"?e.fromBigInt(t):typeof t=="string"?e.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new e(t.low>>>0,t.high>>>0):Xe}},Xe=new Ut(0,0);Xe.toBigInt=function(){return 0n};Xe.zzEncode=Xe.zzDecode=function(){return this};Xe.length=function(){return 1};var Yu=4294967296n;function Zu(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:(r&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Qu(e,t,r){if(r-t<1)return"";let o,s=[],i=0,a;for(;t<r;)a=e[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(e[t++]&63)<<6|e[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Ii(e,t,r){let n=r,o,s;for(let i=0;i<e.length;++i)o=e.charCodeAt(i),o<128?t[r++]=o:o<2048?(t[r++]=o>>6|192,t[r++]=o&63|128):(o&64512)===55296&&((s=e.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[r++]=o>>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=o&63|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=o&63|128);return r-n}function Gt(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function yo(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}var Li=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Gt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Gt(this,4);return yo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Gt(this,4);return yo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Gt(this,4);let t=zu(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Gt(this,4);let t=Xu(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),r=this.pos,n=this.pos+t;if(n>this.len)throw Gt(this,t);return this.pos+=t,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let t=this.bytes();return Qu(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Gt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Gt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Ut(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw Gt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,t}if(this.len-this.pos>4){for(;r<5;++r)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;r<5;++r){if(this.pos>=this.len)throw Gt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Gt(this,8);let t=yo(this.buf,this.pos+=4),r=yo(this.buf,this.pos+=4);return new Ut(t,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=hn(this.buf,this.pos);return this.pos+=et(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function pn(e){return new Li(e instanceof Uint8Array?e:e.subarray())}function Le(e,t,r){let n=pn(e);return t.decode(n,void 0,r)}function Bi(e){let t=e??8192,r=t>>>1,n,o=t;return function(i){if(i<1||i>r)return it(i);o+i>t&&(n=it(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Ye=class{fn;len;next;val;constructor(t,r,n){this.fn=t,this.len=r,this.next=void 0,this.val=n}};function Di(){}var Ri=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},hp=Bi();function dp(e){return globalThis.Buffer!=null?it(e):hp(e)}var gn=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ye(Di,0,0),this.tail=this.head,this.states=null}_push(t,r,n){return this.tail=this.tail.next=new Ye(t,r,n),this.len+=r,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Pi((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(bo,10,Ut.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let r=Ut.fromBigInt(t);return this._push(bo,r.length(),r)}uint64Number(t){return this._push(_e,et(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let r=Ut.fromBigInt(t).zzEncode();return this._push(bo,r.length(),r)}sint64Number(t){let r=Ut.fromNumber(t).zzEncode();return this._push(bo,r.length(),r)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Ti,1,t?1:0)}fixed32(t){return this._push(mn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let r=Ut.fromBigInt(t);return this._push(mn,4,r.lo)._push(mn,4,r.hi)}fixed64Number(t){let r=Ut.fromNumber(t);return this._push(mn,4,r.lo)._push(mn,4,r.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Gu,4,t)}double(t){return this._push(ju,8,t)}bytes(t){let r=t.length>>>0;return r===0?this._push(Ti,1,0):this.uint32(r)._push(mp,r,t)}string(t){let r=Zu(t);return r!==0?this.uint32(r)._push(Ii,r,t):this._push(Ti,1,0)}fork(){return this.states=new Ri(this),this.head=this.tail=new Ye(Di,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Ye(Di,0,0),this.len=0),this}ldelim(){let t=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=r,this.len+=n),this}finish(){let t=this.head.next,r=dp(this.len),n=0;for(;t!=null;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}};function Ti(e,t,r){t[r]=e&255}function pp(e,t,r){for(;e>127;)t[r++]=e&127|128,e>>>=7;t[r]=e}var Pi=class extends Ye{next;constructor(t,r){super(pp,t,r),this.next=void 0}};function bo(e,t,r){for(;e.hi!==0;)t[r++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=e.lo&127|128,e.lo=e.lo>>>7;t[r++]=e.lo}function mn(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function mp(e,t,r){t.set(e,r)}globalThis.Buffer!=null&&(gn.prototype.bytes=function(e){let t=e.length>>>0;return this.uint32(t),t>0&&this._push(gp,t,e),this},gn.prototype.string=function(e){let t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(yp,t,e),this});function gp(e,t,r){t.set(e,r)}function yp(e,t,r){e.length<40?Ii(e,t,r):t.utf8Write!=null?t.utf8Write(e,r):t.set(q(e),r)}function Oi(){return new gn}function Be(e,t){let r=Oi();return t.encode(e,r,{lengthDelimited:!1}),r.finish()}function*De(e,t,r){let n=pn(e);yield*t.stream(n,void 0,"$",r)}var wo={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function xo(e,t,r,n,o){return{name:e,type:t,encode:r,decode:n,stream:o}}function Ze(e){function t(s){if(e[s.toString()]==null)throw new Error("Invalid enum value");return e[s]}let r=function(i,a){let c=t(i);a.int32(c)},n=function(i){let a=i.int32();return t(a)},o=function*(i){let a=i.int32();yield t(a)};return xo("enum",wo.VARINT,r,n,o)}function Te(e,t,r){return xo("message",wo.LENGTH_DELIMITED,e,t,r)}var ct;(function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(ct||(ct={}));var Ni;(function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(Ni||(Ni={}));(function(e){e.codec=()=>Ze(Ni)})(ct||(ct={}));var Jt;(function(e){let t;e.codec=()=>(t==null&&(t=Te((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ct.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.Type=ct.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.Type`,value:ct.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(f&7);break}}}})),t);function r(s){return Be(s,e.codec())}e.encode=r;function n(s,i){return Le(s,e.codec(),i)}e.decode=n;function o(s,i){return De(s,e.codec(),i)}e.stream=o})(Jt||(Jt={}));var Ui;(function(e){let t;e.codec=()=>(t==null&&(t=Te((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ct.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.Type=ct.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.Type`,value:ct.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(f&7);break}}}})),t);function r(s){return Be(s,e.codec())}e.encode=r;function n(s,i){return Le(s,e.codec(),i)}e.decode=n;function o(s,i){return De(s,e.codec(),i)}e.stream=o})(Ui||(Ui={}));var bn={};Bt(bn,{MAX_RSA_KEY_SIZE:()=>ki,generateRSAKeyPair:()=>of,jwkToJWKKeyPair:()=>sf,jwkToPkcs1:()=>Ep,jwkToPkix:()=>Fi,jwkToRSAPrivateKey:()=>qi,pkcs1MessageToJwk:()=>Ki,pkcs1MessageToRSAPrivateKey:()=>Vi,pkcs1ToJwk:()=>xp,pkcs1ToRSAPrivateKey:()=>nf,pkixMessageToJwk:()=>Hi,pkixMessageToRSAPublicKey:()=>Wi,pkixToJwk:()=>Sp,pkixToRSAPublicKey:()=>$i});var Cr=class{type="RSA";jwk;_raw;_multihash;constructor(t,r){this.jwk=t,this._multihash=r}get raw(){return this._raw==null&&(this._raw=bn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return dt.createV1(114,this._multihash)}toString(){return ft.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}verify(t,r,n){return rf(this.jwk,r,t,n)}},yn=class{type="RSA";jwk;_raw;publicKey;constructor(t,r){this.jwk=t,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=bn.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}sign(t,r){return ef(this.jwk,t,r)}};var ki=8192,Mi=18,bp=1062,wp=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function xp(e){let t=re(e);return Ki(t)}function Ki(e){return{n:$(e[1],"base64url"),e:$(e[2],"base64url"),d:$(e[3],"base64url"),p:$(e[4],"base64url"),q:$(e[5],"base64url"),dp:$(e[6],"base64url"),dq:$(e[7],"base64url"),qi:$(e[8],"base64url"),kty:"RSA"}}function Ep(e){if(e.n==null||e.e==null||e.d==null||e.p==null||e.q==null||e.dp==null||e.dq==null||e.qi==null)throw new Y("JWK was missing components");return be([Pt(Uint8Array.from([0])),Pt(q(e.n,"base64url")),Pt(q(e.e,"base64url")),Pt(q(e.d,"base64url")),Pt(q(e.p,"base64url")),Pt(q(e.q,"base64url")),Pt(q(e.dp,"base64url")),Pt(q(e.dq,"base64url")),Pt(q(e.qi,"base64url"))]).subarray()}function Sp(e){let t=re(e,{offset:0});return Hi(t)}function Hi(e){let t=re(e[1],{offset:0});return{kty:"RSA",n:$(t[0],"base64url"),e:$(t[1],"base64url")}}function Fi(e){if(e.n==null||e.e==null)throw new Y("JWK was missing components");return be([wp,no(be([Pt(q(e.n,"base64url")),Pt(q(e.e,"base64url"))]))]).subarray()}function nf(e){let t=re(e);return Vi(t)}function Vi(e){let t=Ki(e);return qi(t)}function $i(e,t){if(e.byteLength>=bp)throw new cr("Key size is too large");let r=re(e,{offset:0});return Wi(r,e,t)}function Wi(e,t,r){let n=Hi(e);if(r==null){let o=Yt(Jt.encode({Type:ct.RSA,Data:t}));r=Dt(Mi,o)}return new Cr(n,r)}function qi(e){if(cf(e)>ki)throw new Y("Key size is too large");let t=sf(e),r=Yt(Jt.encode({Type:ct.RSA,Data:Fi(t.publicKey)})),n=Dt(Mi,r);return new yn(t.privateKey,new Cr(t.publicKey,n))}async function of(e){if(e>ki)throw new Y("Key size is too large");let t=await af(e),r=Yt(Jt.encode({Type:ct.RSA,Data:Fi(t.publicKey)})),n=Dt(Mi,r);return new yn(t.privateKey,new Cr(t.publicKey,n))}function sf(e){if(e==null)throw new Y("Missing key parameter");return{privateKey:e,publicKey:{kty:e.kty,n:e.n,e:e.e}}}async function af(e,t){let r=await Ht.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);t?.signal?.throwIfAborted();let n=await Ap(r,t);return{privateKey:n[0],publicKey:n[1]}}async function ef(e,t,r){let n=await Ht.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let o=await Ht.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,t instanceof Uint8Array?t:t.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function rf(e,t,r,n){let o=await Ht.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ht.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),s}async function Ap(e,t){if(e.privateKey==null||e.publicKey==null)throw new Y("Private and public key are required");let r=await Promise.all([Ht.get().subtle.exportKey("jwk",e.privateKey),Ht.get().subtle.exportKey("jwk",e.publicKey)]);return t?.signal?.throwIfAborted(),r}function cf(e){if(e.kty!=="RSA")throw new Y("invalid key type");if(e.n==null)throw new Y("invalid key modulus");return q(e.n,"base64url").length*8}var Eo=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,r){if(Ve(t),F(r,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?t.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Wt(o)}update(t){return yr(this),this.iHash.update(t),this}digestInto(t){yr(this),F(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},_r=(e,t,r)=>new Eo(e,t).update(r).digest();_r.create=(e,t)=>new Eo(e,t);var uf=(e,t)=>(e+(e>=0?t:-t)/ff)/t;function vp(e,t,r){let[[n,o],[s,i]]=t,a=uf(i*e,r),c=uf(-o*e,r),u=e-a*n-c*s,f=-a*o-c*i,l=u<ue,d=f<ue;l&&(u=-u),d&&(f=-f);let m=sn(Math.ceil(ci(r)/2))+Ir;if(u<ue||u>=m||f<ue||f>=m)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:l,k1:u,k2neg:d,k2:f}}function zi(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Gi(e,t){let r={};for(let n of Object.keys(t))r[n]=e[n]===void 0?t[n]:e[n];return ae(r.lowS,"lowS"),ae(r.prehash,"prehash"),r.format!==void 0&&zi(r.format),r}var ji=class extends Error{constructor(t=""){super(t)}},Re={Err:ji,_tlv:{encode:(e,t)=>{let{Err:r}=Re;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=nn(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?nn(o.length/2|128):"";return nn(e)+s+o+t},decode(e,t){let{Err:r}=Re,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let f of u)i=i<<8|f;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=Re;if(e<ue)throw new t("integer: negative integers are not allowed");let r=nn(e);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=Re;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return br(e)}},toSig(e){let{Err:t,_int:r,_tlv:n}=Re,o=F(e,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l:f}=n.decode(2,c);if(f.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:r}=Re,n=t.encode(2,r.encode(e.r)),o=t.encode(2,r.encode(e.s)),s=n+o;return t.encode(48,s)}},ue=BigInt(0),Ir=BigInt(1),ff=BigInt(2),So=BigInt(3),Cp=BigInt(4);function lf(e,t={}){let r=co("weierstrass",e,t),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i,n:a}=s;Qt(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=t;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=df(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(T,w,g){let{x:y,y:C}=w.toAffine(),L=n.toBytes(y);if(ae(g,"isCompressed"),g){f();let I=!n.isOdd(C);return Ot(hf(I),L)}else return Ot(Uint8Array.of(4),L,n.toBytes(C))}function d(T){F(T,void 0,"Point");let{publicKey:w,publicKeyUncompressed:g}=u,y=T.length,C=T[0],L=T.subarray(1);if(y===w&&(C===2||C===3)){let I=n.fromBytes(L);if(!n.isValid(I))throw new Error("bad point: is not on curve, wrong x");let S=E(I),B;try{B=n.sqrt(S)}catch(j){let G=j instanceof Error?": "+j.message:"";throw new Error("bad point: is not on curve, sqrt error"+G)}f();let R=n.isOdd(B);return(C&1)===1!==R&&(B=n.neg(B)),{x:I,y:B}}else if(y===g&&C===4){let I=n.BYTES,S=n.fromBytes(L.subarray(0,I)),B=n.fromBytes(L.subarray(I,I*2));if(!h(S,B))throw new Error("bad point: is not on curve");return{x:S,y:B}}else throw new Error(`bad point: got length ${y}, expected compressed=${w} or uncompressed=${g}`)}let m=t.toBytes||l,p=t.fromBytes||d;function E(T){let w=n.sqr(T),g=n.mul(w,T);return n.add(n.add(g,n.mul(T,s.a)),s.b)}function h(T,w){let g=n.sqr(w),y=E(T);return n.eql(g,y)}if(!h(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let b=n.mul(n.pow(s.a,So),Cp),v=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(b,v)))throw new Error("bad curve params: a or b");function x(T,w,g=!1){if(!n.isValid(w)||g&&n.is0(w))throw new Error(`bad point coordinate ${T}`);return w}function D(T){if(!(T instanceof A))throw new Error("Weierstrass Point expected")}function k(T){if(!c||!c.basises)throw new Error("no endo");return vp(T,c.basises,o.ORDER)}let O=wr((T,w)=>{let{X:g,Y:y,Z:C}=T;if(n.eql(C,n.ONE))return{x:g,y};let L=T.is0();w==null&&(w=L?n.ONE:n.inv(C));let I=n.mul(g,w),S=n.mul(y,w),B=n.mul(C,w);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(B,n.ONE))throw new Error("invZ was invalid");return{x:I,y:S}}),K=wr(T=>{if(T.is0()){if(t.allowInfinityPoint&&!n.is0(T.Y))return;throw new Error("bad point: ZERO")}let{x:w,y:g}=T.toAffine();if(!n.isValid(w)||!n.isValid(g))throw new Error("bad point: x or y not field elements");if(!h(w,g))throw new Error("bad point: equation left != right");if(!T.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function _(T,w,g,y,C){return g=new A(n.mul(g.X,T),g.Y,g.Z),w=cn(y,w),g=cn(C,g),w.add(g)}class A{static BASE=new A(s.Gx,s.Gy,n.ONE);static ZERO=new A(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(w,g,y){this.X=x("x",w),this.Y=x("y",g,!0),this.Z=x("z",y),Object.freeze(this)}static CURVE(){return s}static fromAffine(w){let{x:g,y}=w||{};if(!w||!n.isValid(g)||!n.isValid(y))throw new Error("invalid affine point");if(w instanceof A)throw new Error("projective point not allowed");return n.is0(g)&&n.is0(y)?A.ZERO:new A(g,y,n.ONE)}static fromBytes(w){let g=A.fromAffine(p(F(w,void 0,"point")));return g.assertValidity(),g}static fromHex(w){return A.fromBytes(se(w))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,g=!0){return M.createCache(this,w),g||this.multiply(So),this}assertValidity(){K(this)}hasEvenY(){let{y:w}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(w)}equals(w){D(w);let{X:g,Y:y,Z:C}=this,{X:L,Y:I,Z:S}=w,B=n.eql(n.mul(g,S),n.mul(L,C)),R=n.eql(n.mul(y,S),n.mul(I,C));return B&&R}negate(){return new A(this.X,n.neg(this.Y),this.Z)}double(){let{a:w,b:g}=s,y=n.mul(g,So),{X:C,Y:L,Z:I}=this,S=n.ZERO,B=n.ZERO,R=n.ZERO,P=n.mul(C,C),j=n.mul(L,L),G=n.mul(I,I),V=n.mul(C,L);return V=n.add(V,V),R=n.mul(C,I),R=n.add(R,R),S=n.mul(w,R),B=n.mul(y,G),B=n.add(S,B),S=n.sub(j,B),B=n.add(j,B),B=n.mul(S,B),S=n.mul(V,S),R=n.mul(y,R),G=n.mul(w,G),V=n.sub(P,G),V=n.mul(w,V),V=n.add(V,R),R=n.add(P,P),P=n.add(R,P),P=n.add(P,G),P=n.mul(P,V),B=n.add(B,P),G=n.mul(L,I),G=n.add(G,G),P=n.mul(G,V),S=n.sub(S,P),R=n.mul(G,j),R=n.add(R,R),R=n.add(R,R),new A(S,B,R)}add(w){D(w);let{X:g,Y:y,Z:C}=this,{X:L,Y:I,Z:S}=w,B=n.ZERO,R=n.ZERO,P=n.ZERO,j=s.a,G=n.mul(s.b,So),V=n.mul(g,L),X=n.mul(y,I),rt=n.mul(C,S),lt=n.add(g,y),Z=n.add(L,I);lt=n.mul(lt,Z),Z=n.add(V,X),lt=n.sub(lt,Z),Z=n.add(g,C);let ht=n.add(L,S);return Z=n.mul(Z,ht),ht=n.add(V,rt),Z=n.sub(Z,ht),ht=n.add(y,C),B=n.add(I,S),ht=n.mul(ht,B),B=n.add(X,rt),ht=n.sub(ht,B),P=n.mul(j,Z),B=n.mul(G,rt),P=n.add(B,P),B=n.sub(X,P),P=n.add(X,P),R=n.mul(B,P),X=n.add(V,V),X=n.add(X,V),rt=n.mul(j,rt),Z=n.mul(G,Z),X=n.add(X,rt),rt=n.sub(V,rt),rt=n.mul(j,rt),Z=n.add(Z,rt),V=n.mul(X,Z),R=n.add(R,V),V=n.mul(ht,Z),B=n.mul(lt,B),B=n.sub(B,V),V=n.mul(lt,X),P=n.mul(ht,P),P=n.add(P,V),new A(B,R,P)}subtract(w){return this.add(w.negate())}is0(){return this.equals(A.ZERO)}multiply(w){let{endo:g}=t;if(!o.isValidNot0(w))throw new Error("invalid scalar: out of range");let y,C,L=I=>M.cached(this,I,S=>je(A,S));if(g){let{k1neg:I,k1:S,k2neg:B,k2:R}=k(w),{p:P,f:j}=L(S),{p:G,f:V}=L(R);C=j.add(V),y=_(g.beta,P,G,I,B)}else{let{p:I,f:S}=L(w);y=I,C=S}return je(A,[y,C])[0]}multiplyUnsafe(w){let{endo:g}=t,y=this;if(!o.isValid(w))throw new Error("invalid scalar: out of range");if(w===ue||y.is0())return A.ZERO;if(w===Ir)return y;if(M.hasCache(this))return this.multiply(w);if(g){let{k1neg:C,k1:L,k2neg:I,k2:S}=k(w),{p1:B,p2:R}=Ou(A,y,L,S);return _(g.beta,B,R,C,I)}else return M.unsafe(y,w)}toAffine(w){return O(this,w)}isTorsionFree(){let{isTorsionFree:w}=t;return i===Ir?!0:w?w(A,this):M.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:w}=t;return i===Ir?this:w?w(A,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(w=!0){return ae(w,"isCompressed"),this.assertValidity(),m(A,this,w)}toHex(w=!0){return oe(this.toBytes(w))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=o.BITS,M=new Sr(A,t.endo?Math.ceil(N/2):N);return A.BASE.precompute(8),A}function hf(e){return Uint8Array.of(e?2:3)}function df(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function _p(e,t={}){let{Fn:r}=e,n=t.randomBytes||xe,o=Object.assign(df(e.Fp,r),{seed:hi(r.ORDER)});function s(m){try{let p=r.fromBytes(m);return r.isValidNot0(p)}catch{return!1}}function i(m,p){let{publicKey:E,publicKeyUncompressed:h}=o;try{let b=m.length;return p===!0&&b!==E||p===!1&&b!==h?!1:!!e.fromBytes(m)}catch{return!1}}function a(m=n(o.seed)){return di(F(m,o.seed,"seed"),r.ORDER)}function c(m,p=!0){return e.BASE.multiply(r.fromBytes(m)).toBytes(p)}function u(m){let{secretKey:p,publicKey:E,publicKeyUncompressed:h}=o;if(!Fe(m)||"_lengths"in r&&r._lengths||p===E)return;let b=F(m,void 0,"key").length;return b===E||b===h}function f(m,p,E=!0){if(u(m)===!0)throw new Error("first arg must be private key");if(u(p)===!1)throw new Error("second arg must be public key");let h=r.fromBytes(m);return e.fromBytes(p).multiply(h).toBytes(E)}let l={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=Ar(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:d,Point:e,utils:l,lengths:o})}function pf(e,t,r={}){Ve(t),Qt(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes||xe,o=r.hmac||((g,y)=>_r(t,g,y)),{Fp:s,Fn:i}=e,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:f,getSharedSecret:l,utils:d,lengths:m}=_p(e,r),p={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},E=a*ff<s.ORDER;function h(g){let y=a>>Ir;return g>y}function b(g,y){if(!i.isValidNot0(y))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return y}function v(){if(E)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function x(g,y){zi(y);let C=m.signature,L=y==="compact"?C:y==="recovered"?C+1:void 0;return F(g,L)}class D{r;s;recovery;constructor(y,C,L){if(this.r=b("r",y),this.s=b("s",C),L!=null){if(v(),![0,1,2,3].includes(L))throw new Error("invalid recovery id");this.recovery=L}Object.freeze(this)}static fromBytes(y,C=p.format){x(y,C);let L;if(C==="der"){let{r:R,s:P}=Re.toSig(F(y));return new D(R,P)}C==="recovered"&&(L=y[0],C="compact",y=y.subarray(1));let I=m.signature/2,S=y.subarray(0,I),B=y.subarray(I,I*2);return new D(i.fromBytes(S),i.fromBytes(B),L)}static fromHex(y,C){return this.fromBytes(se(y),C)}assertRecovery(){let{recovery:y}=this;if(y==null)throw new Error("invalid recovery id: must be present");return y}addRecoveryBit(y){return new D(this.r,this.s,y)}recoverPublicKey(y){let{r:C,s:L}=this,I=this.assertRecovery(),S=I===2||I===3?C+a:C;if(!s.isValid(S))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let B=s.toBytes(S),R=e.fromBytes(Ot(hf((I&1)===0),B)),P=i.inv(S),j=O(F(y,void 0,"msgHash")),G=i.create(-j*P),V=i.create(L*P),X=e.BASE.multiplyUnsafe(G).add(R.multiplyUnsafe(V));if(X.is0())throw new Error("invalid recovery: point at infinify");return X.assertValidity(),X}hasHighS(){return h(this.s)}toBytes(y=p.format){if(zi(y),y==="der")return se(Re.hexFromSig(this));let{r:C,s:L}=this,I=i.toBytes(C),S=i.toBytes(L);return y==="recovered"?(v(),Ot(Uint8Array.of(this.assertRecovery()),I,S)):Ot(I,S)}toHex(y){return oe(this.toBytes(y))}}let k=r.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");let C=br(y),L=y.length*8-c;return L>0?C>>BigInt(L):C},O=r.bits2int_modN||function(y){return i.create(k(y))},K=sn(c);function _(g){return ve("num < 2^"+c,g,ue,K),i.toBytes(g)}function A(g,y){return F(g,void 0,"message"),y?F(t(g),void 0,"prehashed message"):g}function N(g,y,C){let{lowS:L,prehash:I,extraEntropy:S}=Gi(C,p);g=A(g,I);let B=O(g),R=i.fromBytes(y);if(!i.isValidNot0(R))throw new Error("invalid private key");let P=[_(R),_(B)];if(S!=null&&S!==!1){let X=S===!0?n(m.secretKey):S;P.push(F(X,void 0,"extraEntropy"))}let j=Ot(...P),G=B;function V(X){let rt=k(X);if(!i.isValidNot0(rt))return;let lt=i.inv(rt),Z=e.BASE.multiply(rt).toAffine(),ht=i.create(Z.x);if(ht===ue)return;let ar=i.create(lt*i.create(G+ht*R));if(ar===ue)return;let Fn=(Z.x===ht?0:2)|Number(Z.y&Ir),qr=ar;return L&&h(ar)&&(qr=i.neg(ar),Fn^=1),new D(ht,qr,E?void 0:Fn)}return{seed:j,k2sig:V}}function M(g,y,C={}){let{seed:L,k2sig:I}=N(g,y,C);return yu(t.outputLen,i.BYTES,o)(L,I).toBytes(C.format)}function T(g,y,C,L={}){let{lowS:I,prehash:S,format:B}=Gi(L,p);if(C=F(C,void 0,"publicKey"),y=A(y,S),!Fe(g)){let R=g instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+R)}x(g,B);try{let R=D.fromBytes(g,B),P=e.fromBytes(C);if(I&&R.hasHighS())return!1;let{r:j,s:G}=R,V=O(y),X=i.inv(G),rt=i.create(V*X),lt=i.create(j*X),Z=e.BASE.multiplyUnsafe(rt).add(P.multiplyUnsafe(lt));return Z.is0()?!1:i.create(Z.x)===j}catch{return!1}}function w(g,y,C={}){let{prehash:L}=Gi(C,p);return y=A(y,L),D.fromBytes(g,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:u,getPublicKey:f,getSharedSecret:l,utils:d,lengths:m,Point:e,sign:M,verify:T,recoverPublicKey:w,Signature:D,hash:t})}var Yi={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Ip={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var mf=BigInt(2);function Lp(e){let t=Yi.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,f=u*u*e%t,l=st(f,r,t)*f%t,d=st(l,r,t)*f%t,m=st(d,mf,t)*u%t,p=st(m,o,t)*m%t,E=st(p,s,t)*p%t,h=st(E,a,t)*E%t,b=st(h,c,t)*h%t,v=st(b,a,t)*E%t,x=st(v,r,t)*f%t,D=st(x,i,t)*p%t,k=st(D,n,t)*u%t,O=st(k,mf,t);if(!Xi.eql(Xi.sqr(O),e))throw new Error("Cannot find square root");return O}var Xi=xr(Yi.p,{sqrt:Lp}),Bp=lf(Yi,{Fp:Xi,endo:Ip}),Lr=pf(Bp,Yt);function gf(e,t,r,n){let o=ee.digest(r instanceof Uint8Array?r:r.subarray());if(po(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Lr.verify(t,s,e,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new ln(String(s))});try{return n?.signal?.throwIfAborted(),Lr.verify(t,o.digest,e,{prehash:!1,format:"der"})}catch(s){throw new ln(String(s))}}var Ao=class{type="secp256k1";raw;_key;constructor(t){this._key=bf(t),this.raw=yf(this._key)}toMultihash(){return $t.digest(we(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return ft.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}verify(t,r,n){return gf(this._key,r,t,n)}};function Zi(e){return new Ao(e)}function yf(e){return Lr.Point.fromBytes(e).toBytes()}function bf(e){try{return Lr.Point.fromBytes(e),e}catch(t){throw new cr(String(t))}}function wn(e,t){let{Type:r,Data:n}=Jt.decode(e),o=n??new Uint8Array;switch(r){case ct.RSA:return $i(o,t);case ct.Ed25519:return xi(o);case ct.secp256k1:return Zi(o);case ct.ECDSA:return Zs(o);default:throw new Me}}function wf(e){let{Type:t,Data:r}=Jt.decode(e.digest),n=r??new Uint8Array;switch(t){case ct.Ed25519:return xi(n);case ct.secp256k1:return Zi(n);case ct.ECDSA:return Zs(n);default:throw new Me}}function we(e){return Jt.encode({Type:ct[e.type],Data:e.raw})}var xf=Symbol.for("nodejs.util.inspect.custom"),Dp=114,xn=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[As]=!0;toString(){return this.string==null&&(this.string=ft.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return dt.createV1(Dp,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return wt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return wt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[xf](){return`PeerId(${this.toString()})`}},En=class extends xn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Sn=class extends xn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},An=class extends xn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Tp=2336,vn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=$t.digest(q(this.url))}[xf](){return`PeerId(${this.url})`}[As]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return dt.createV1(Tp,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=$(t)),t.toString()===this.toString())}};var Rp=114,Ef=2336;function Br(e,t){let r;if(e.charAt(0)==="1"||e.charAt(0)==="Q")r=mr(ft.decode(`z${e}`));else{if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return Pp(dt.parse(e));if(t==null)throw new Y('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=mr(t.decode(e))}return Sf(r)}function Qi(e){if(e.type==="Ed25519")return new Sn({multihash:e.toCID().multihash,publicKey:e});if(e.type==="secp256k1")return new An({multihash:e.toCID().multihash,publicKey:e});if(e.type==="RSA")return new En({multihash:e.toCID().multihash,publicKey:e});throw new Me}function Sf(e){if(Np(e))return new En({multihash:e});if(Op(e))try{let t=wf(e);if(t.type==="Ed25519")return new Sn({multihash:e,publicKey:t});if(t.type==="secp256k1")return new An({multihash:e,publicKey:t})}catch{let r=$(e.digest);return new vn(new URL(r))}throw new jn("Supplied PeerID Multihash is invalid")}function Pp(e){if(e?.multihash==null||e.version==null||e.version===1&&e.code!==Rp&&e.code!==Ef)throw new zn("Supplied PeerID CID is invalid");if(e.code===Ef){let t=$(e.multihash.digest);return new vn(new URL(t))}return Sf(e.multihash)}function Op(e){return e.code===$t.code}function Np(e){return e.code===ee.code}var Et=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},fe=class extends Error{static name="ValidationError";name="ValidationError"},vo=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Co=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var _o=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let r=this.index,n=t();return n===void 0&&(this.index=r),n}parseWith(t){let r=t();if(this.index===this.input.length)return r}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let r=this.readChar();if(r===t)return r})}readSeparator(t,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,r,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,t);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=t,s+=f,s>u||(i+=1,r!==void 0&&i>r))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let r=0;r<t.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[r]=n}return t})}readIPv6Addr(){let t=r=>{for(let n=0;n<r.length/2;n++){let o=n*2;if(n<r.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return r[o]=i[0],r[o+1]=i[1],r[o+2]=i[2],r[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];r[o]=s>>8,r[o+1]=s&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,o]=t(r);if(n===16)return r;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Up=45,kp=15,Io=new _o;function Af(e){if(!(e.length>kp))return Io.new(e).parseWith(()=>Io.readIPv4Addr())}function vf(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>Up))return Io.new(e).parseWith(()=>Io.readIPv6Addr())}function Lo(e){return!!Af(e)}function Cf(e){return!!vf(e)}function ta(e){return t=>$(t,e)}function ea(e){return t=>q(t,e)}function Dr(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function Qe(e){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof e=="string"?parseInt(e):e),new Uint8Array(t)}function _f(e){let t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let r=q(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Qe(n);return Tt([r,o],r.length+o.length)}function If(e){let t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let r=ye.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Qe(n);return Tt([r,o],r.length+o.length)}function ra(e){let t=e.subarray(0,e.length-2),r=e.subarray(e.length-2),n=$(t,"base32"),o=Dr(r);return`${n}:${o}`}var na=function(e){e=e.toString().trim();let t=new Uint8Array(4);return e.split(/\./g).forEach((r,n)=>{let o=parseInt(r,10);if(isNaN(o)||o<0||o>255)throw new Et("Invalid byte value in IP address");t[n]=o}),t},Lf=function(e){let t=0;e=e.toString().trim();let r=e.split(":",8),n;for(n=0;n<r.length;n++){let s=Lo(r[n]),i;s&&(i=na(r[n]),r[n]=$(i.subarray(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,$(i.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 s=[n,1];for(n=9-r.length;n>0;n--)s.push("0");r.splice.apply(r,s)}let o=new Uint8Array(t+16);for(n=0;n<r.length;n++){r[n]===""&&(r[n]="0");let s=parseInt(r[n],16);if(isNaN(s)||s<0||s>65535)throw new Et("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},Bf=function(e){if(e.byteLength!==4)throw new Et("IPv4 address was incorrect length");let t=[];for(let r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},Df=function(e){if(e.byteLength!==16)throw new Et("IPv6 address was incorrect length");let t=[];for(let n=0;n<e.byteLength;n+=2){let o=e[n],s=e[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}let r=t.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Et(`Invalid IPv6 address "${r}"`)}};function Tf(e){try{let t=new URL(`http://[${e}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new Et(`Invalid IPv6 address "${e}"`)}}var Ji=Object.values(He).map(e=>e.decoder),Mp=(function(){let e=Ji[0].or(Ji[1]);return Ji.slice(2).forEach(t=>e=e.or(t)),e})();function Rf(e){return Mp.decode(e)}function Pf(e){return t=>e.encoder.encode(t)}function Kp(e){if(parseInt(e).toString()!==e)throw new fe("Value must be an integer")}function Hp(e){if(e<0)throw new fe("Value must be a positive integer, or zero")}function Fp(e){return t=>{if(t>e)throw new fe(`Value must be smaller than or equal to ${e}`)}}function Vp(...e){return t=>{for(let r of e)r(t)}}var Cn=Vp(Kp,Hp,Fp(65535));var yt=-1,oa=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let r;if(typeof t=="string"?r=this.protocolsByName.get(t):r=this.protocolsByCode.get(t),r==null)throw new Co(`Protocol ${t} was unknown`);return r}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(r=>{this.protocolsByName.set(r,t)})}removeProtocol(t){let r=this.protocolsByCode.get(t);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},le=new oa,nm=[{code:4,name:"ip4",size:32,valueToBytes:na,bytesToValue:Bf,validate:e=>{if(!Lo(e))throw new fe(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Qe,bytesToValue:Dr,validate:Cn},{code:273,name:"udp",size:16,valueToBytes:Qe,bytesToValue:Dr,validate:Cn},{code:33,name:"dccp",size:16,valueToBytes:Qe,bytesToValue:Dr,validate:Cn},{code:41,name:"ip6",size:128,valueToBytes:Lf,bytesToValue:Df,stringToValue:Tf,validate:e=>{if(!Cf(e))throw new fe(`Invalid IPv6 address "${e}"`)}},{code:42,name:"ip6zone",size:yt},{code:43,name:"ipcidr",size:8,bytesToValue:ta("base10"),valueToBytes:ea("base10")},{code:53,name:"dns",size:yt},{code:54,name:"dns4",size:yt},{code:55,name:"dns6",size:yt},{code:56,name:"dnsaddr",size:yt},{code:132,name:"sctp",size:16,valueToBytes:Qe,bytesToValue:Dr,validate:Cn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:yt,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:yt,bytesToValue:ta("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?ea("base58btc")(e):dt.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:ra,valueToBytes:_f},{code:445,name:"onion3",size:296,bytesToValue:ra,valueToBytes:If},{code:446,name:"garlic64",size:yt},{code:447,name:"garlic32",size:yt},{code:448,name:"tls"},{code:449,name:"sni",size:yt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:yt,bytesToValue:Pf(Zr),valueToBytes:Rf},{code:480,name:"http"},{code:481,name:"http-path",size:yt,stringToValue:e=>`/${decodeURIComponent(e)}`,valueToString:e=>encodeURIComponent(e.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:yt}];nm.forEach(e=>{le.addProtocol(e)});function Of(e){let t=[],r=0;for(;r<e.length;){let n=ce(e,r),o=le.getProtocol(n),s=et(n),i=om(o,e,r+s),a=0;i>0&&o.size===yt&&(a=et(i));let c=s+a+i,u={code:n,name:o.name,bytes:e.subarray(r,r+c)};if(i>0){let f=r+s+a,l=e.subarray(f,f+i);u.value=o.bytesToValue?.(l)??$(l)}t.push(u),r+=c}return t}function Nf(e){let t=0,r=[];for(let n of e){if(n.bytes==null){let o=le.getProtocol(n.code),s=et(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??q(n.value),a=i.byteLength,o.size===yt&&(c=et(a)));let u=new Uint8Array(s+c+a),f=0;_e(n.code,u,f),f+=s,i!=null&&(o.size===yt&&(_e(a,u,f),f+=c),u.set(i,f)),n.bytes=u}r.push(n.bytes),t+=n.bytes.byteLength}return Tt(r,t)}function Uf(e){if(e.charAt(0)!=="/")throw new Et('String multiaddr must start with "/"');let t=[],r="protocol",n="",o="";for(let s=1;s<e.length;s++){let i=e.charAt(s);i!=="/"&&(r==="protocol"?o+=e.charAt(s):n+=e.charAt(s));let a=s===e.length-1;if(i==="/"||a){let c=le.getProtocol(o);if(r==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",r="protocol";continue}else if(a)throw new Et(`Component ${o} was missing value`);r="value"}else if(r==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Et(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}t.push(u),n="",o="",r="protocol"}}}if(o!==""&&n!=="")throw new Et("Incomplete multiaddr");return t}function kf(e){return`/${e.flatMap(t=>{if(t.value==null)return t.name;let r=le.getProtocol(t.code);if(r==null)throw new Et(`Unknown protocol code ${t.code}`);return[t.name,r.valueToString?.(t.value)??t.value]}).join("/")}`}function om(e,t,r){return e.size==null||e.size===0?0:e.size>0?e.size/8:ce(t,r)}var sm=Symbol.for("nodejs.util.inspect.custom"),Ea=Symbol.for("@multiformats/multiaddr");function im(e){if(e==null&&(e="/"),Mf(e))return e.getComponents();if(e instanceof Uint8Array)return Of(e);if(typeof e=="string")return e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),e===""&&(e="/"),Uf(e);if(Array.isArray(e))return e;throw new Et("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Ro=class e{[Ea]=!0;#t;#e;#r;constructor(t="/",r={}){this.#t=im(t),r.validate!==!1&&am(this)}get bytes(){return this.#r==null&&(this.#r=Nf(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=kf(this.#t)),this.#e}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let r=new e(t);return new e([...this.#t,...r.getComponents()],{validate:!1})}decapsulate(t){let r=t.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new vo(`Address ${this.toString()} does not contain subaddress: ${r}`);return new e(n.slice(0,o),{validate:!1})}decapsulateCode(t){let r;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){r=n;break}return new e(this.#t.slice(0,r),{validate:!1})}equals(t){return wt(this.bytes,t.bytes)}[sm](){return`Multiaddr(${this.toString()})`}};function am(e){e.getComponents().forEach(t=>{let r=le.getProtocol(t.code);t.value!=null&&r.validate?.(t.value)})}function Mf(e){return!!e?.[Ea]}function Or(e){return new Ro(e)}var nt=e=>({match:t=>{let r=t[0];return r==null||r.code!==e||r.value!=null?!1:t.slice(1)}}),H=(e,t)=>({match:r=>{let n=r[0];return n?.code!==e||n.value==null||t!=null&&n.value!==t?!1:r.slice(1)}}),Kf=e=>({match:t=>e.match(t)===!1?t:!1}),z=e=>({match:t=>{let r=e.match(t);return r===!1?t:r}}),_t=(...e)=>({match:t=>{let r;for(let n of e){let o=n.match(t);o!==!1&&(r==null||o.length<r.length)&&(r=o)}return r??!1}}),tt=(...e)=>({match:t=>{for(let r of e){let n=r.match(t);if(n===!1)return!1;t=n}return t}});function ot(...e){function t(o){if(o==null)return!1;let s=o.getComponents();for(let i of e){let a=i.match(s);if(a===!1)return!1;s=a}return s}function r(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:e,matches:r,exactMatch:n}}var cm=H(421),U1=ot(cm),Oo=H(54),No=H(55),Uo=H(56),Aa=H(53),k1=ot(Oo,z(H(421))),M1=ot(No,z(H(421))),K1=ot(Uo,z(H(421))),H1=ot(_t(Aa,Uo,Oo,No),z(H(421))),Hf=tt(H(4),z(H(43))),Ff=tt(z(H(42)),H(41),z(H(43))),va=_t(Hf,Ff),er=_t(va,Aa,Oo,No,Uo),F1=ot(_t(va,tt(_t(Aa,Uo,Oo,No),z(H(421))))),V1=ot(Hf),$1=ot(Ff),W1=ot(va),Ca=tt(er,H(6)),_n=tt(er,H(273)),q1=ot(tt(Ca,z(H(421)))),G1=ot(_n),_a=tt(_n,nt(460),z(H(421))),ko=tt(_n,nt(461),z(H(421))),um=_t(_a,ko),z1=ot(_a),j1=ot(ko),Sa=_t(er,Ca,_n,_a,ko),Vf=_t(tt(Sa,nt(477),z(H(421)))),X1=ot(Vf),$f=_t(tt(Sa,nt(478),z(H(421))),tt(Sa,nt(448),z(H(449)),nt(477),z(H(421)))),Y1=ot($f),Wf=tt(_n,nt(280),z(H(466)),z(H(466)),z(H(421))),qf=ot(Wf),Gf=tt(ko,nt(465),z(H(466)),z(H(466)),z(H(421))),Z1=ot(Gf),Po=_t(Vf,$f,tt(Ca,z(H(421))),tt(um,z(H(421))),tt(er,z(H(421))),Wf,Gf,H(421)),zf=ot(Po),fm=tt(z(Po),nt(290),Kf(nt(281)),z(H(421))),Q1=ot(fm),lm=_t(tt(Po,nt(290),nt(281),z(H(421))),tt(Po,nt(281),z(H(421))),tt(nt(281),z(H(421)))),jf=ot(lm),hm=_t(tt(er,H(6),nt(480),z(H(421))),tt(er,nt(480),z(H(421)))),J1=ot(hm),dm=tt(er,_t(tt(H(6,"443"),nt(480)),tt(H(6),nt(443)),tt(H(6),nt(448),nt(480)),tt(nt(448),nt(480)),nt(448),nt(443)),z(H(421))),t2=ot(dm),pm=_t(tt(H(777),z(H(421)))),e2=ot(pm),mm=_t(tt(H(400),z(H(421)))),r2=ot(mm);var It;(function(e){let t;(function(a){a.FIN="FIN",a.STOP_SENDING="STOP_SENDING",a.RESET="RESET",a.FIN_ACK="FIN_ACK"})(t=e.Flag||(e.Flag={}));let r;(function(a){a[a.FIN=0]="FIN",a[a.STOP_SENDING=1]="STOP_SENDING",a[a.RESET=2]="RESET",a[a.FIN_ACK=3]="FIN_ACK"})(r||(r={})),(function(a){a.codec=()=>Ze(r)})(t=e.Flag||(e.Flag={}));let n;e.codec=()=>(n==null&&(n=Te((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.flag!=null&&(c.uint32(8),e.Flag.codec().encode(a.flag,c)),a.message!=null&&(c.uint32(18),c.bytes(a.message)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let f={},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let d=a.uint32();switch(d>>>3){case 1:{f.flag=e.Flag.codec().decode(a);break}case 2:{f.message=a.bytes();break}default:{a.skipType(d&7);break}}}return f},function*(a,c,u,f={}){let l=c==null?a.len:a.pos+c;for(;a.pos<l;){let d=a.uint32();switch(d>>>3){case 1:{yield{field:`${u}.flag`,value:e.Flag.codec().decode(a)};break}case 2:{yield{field:`${u}.message`,value:a.bytes()};break}default:{a.skipType(d&7);break}}}})),n);function o(a){return Be(a,e.codec())}e.encode=o;function s(a,c){return Le(a,e.codec(),c)}e.decode=s;function i(a,c){return De(a,e.codec(),c)}e.stream=i})(It||(It={}));var Xf=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],Ia=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Yf="libp2p+webrtc+v1/",Zf=2*1024*1024,Nr=16*1024;function gm(e=Nr){let t=et(e-et(e)),r=1+et(Object.keys(It.Flag).length-1),n=1,o=e-t-r-n,s=et(o);return t+r+n+s}var Qf=gm();var Jf=1e4,La="/webrtc",In="/webrtc-signaling/0.0.1";function Ba(e){let t=e.getComponents(),r={},n=0;if(t[n]?.name==="ip6zone"&&(r.zone=`${t[n].value}`,n++),t[n].name==="ip4"||t[n].name==="ip6"||t[n].name==="dns"||t[n].name==="dns4"||t[n].name==="dns6"?(r.type=t[n].name,r.host=t[n].value,n++):t[n].name==="dnsaddr"&&(r.type=t[n].name,r.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(r.protocol=t[n].name==="tcp"?"tcp":"udp",r.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(r.type==="ip4"?r.cidr=parseInt(`${t[n].value}`):r.type==="ip6"&&(r.cidr=`${t[n].value}`),n++),r.type==null||r.host==null)throw new Y(`Multiaddr ${e} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(r.sni=t[n+1].value,n+=2),r}function Mo(){let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}var Ko=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Ur=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Ko(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let r=this.head;this.head=r.next=new Ko(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Da=class extends Error{type;code;constructor(t,r){super(t??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function kr(e={}){return ym(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}},e)}function ym(e,t){t=t??{};let r=t.onEnd,n=new Ur,o,s,i,a=Mo(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,b)=>{s=v=>{s=null,n.push(v);try{h(e(n))}catch(x){b(x)}return o}}):e(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Mo()})}},u=h=>s!=null?s(h):(n.push(h),o),f=h=>(n=new Ur,s!=null?s({error:h}):(n.push({error:h}),o)),l=h=>{if(i)return o;if(t?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:h})},d=h=>i?o:(i=!0,h!=null?f(h):u({done:!0})),m=()=>(n=new Ur,d(),{done:!0}),p=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:p,push:l,end:d,get readableLength(){return n.size},onEmpty:async h=>{let b=h?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let v,x;b!=null&&(v=new Promise((D,k)=>{x=()=>{k(new Da)},b.addEventListener("abort",x)}));try{await Promise.race([a.promise,v])}finally{x!=null&&b!=null&&b?.removeEventListener("abort",x)}}},r==null)return o;let E=o;return o={[Symbol.asyncIterator](){return this},next(){return E.next()},throw(h){return E.throw(h),r!=null&&(r(h),r=void 0),{done:!0}},return(){return E.return(),r!=null&&(r(),r=void 0),{done:!0}},push:l,end(h){return E.end(h),r!=null&&(r(h),r=void 0),o},get readableLength(){return E.readableLength},onEmpty:h=>E.onEmpty(h)},o}var Ta=class e extends Error{name="TimeoutError";constructor(t,r){super(t,r),Error.captureStackTrace?.(this,e)}},tl=e=>e.reason??new DOMException("This operation was aborted.","AbortError");function Ra(e,t){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=t,a,c,f=new Promise((l,d)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){d(tl(i));return}if(i&&(c=()=>{d(tl(i))},i.addEventListener("abort",c,{once:!0})),e.then(l,d),r===Number.POSITIVE_INFINITY)return;let m=new Ta;a=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(p){d(p)}return}typeof e.cancel=="function"&&e.cancel(),o===!1?l():o instanceof Error?d(o):(m.message=o??`Promise timed out after ${r} milliseconds`,d(m))},r)}).finally(()=>{f.clear(),c&&i&&i.removeEventListener("abort",c)});return f.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},f}var bm=e=>{let t=e.addEventListener||e.on||e.addListener,r=e.removeEventListener||e.off||e.removeListener;if(!t||!r)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}};function wm(e,t,r){let n,o=new Promise((s,i)=>{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 a=[t].flat(),c=[],{addListener:u,removeListener:f}=bm(e),l=async(...m)=>{let p=r.multiArgs?m:m[0];if(r.filter)try{if(!await r.filter(p))return}catch(E){n(),i(E);return}c.push(p),r.count===c.length&&(n(),s(c))},d=(...m)=>{n(),i(r.rejectionMultiArgs?m:m[0])};n=()=>{for(let m of a)f(m,l);for(let m of r.rejectionEvents)a.includes(m)||f(m,d)};for(let m of a)u(m,l);for(let m of r.rejectionEvents)a.includes(m)||u(m,d);r.signal&&r.signal.addEventListener("abort",()=>{d(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){let s=Ra(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function St(e,t,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=wm(e,t,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var rr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},Ho=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},Fo=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function xm(e){return e.reason}async function he(e,t,r){if(t==null)return e;let n=r?.translateError??xm;if(t.aborted)return e.catch(()=>{}),Promise.reject(n(t));let o;try{return await Promise.race([e,new Promise((s,i)=>{o=()=>{i(n(t))},t.addEventListener("abort",o)})])}finally{o!=null&&t.removeEventListener("abort",o)}}var Em=Math.pow(2,20)*4,Oe=class extends me{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(t){super(),this.status="open",this.log=t.log,this.direction=t.direction??"outbound",this.inactivityTimeout=t.inactivityTimeout??12e4,this.maxReadBufferLength=t.maxReadBufferLength??Em,this.maxWriteBufferLength=t.maxWriteBufferLength,this.maxMessageSize=t.maxMessageSize,this.readBuffer=new W,this.writeBuffer=new W,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=o=>{this.onDrainPromise?.reject(o.error??new Fo)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(t){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),he(this.onDrainPromise.promise,t?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let t=kr(),r=s=>{t.push(s.data)};this.addEventListener("message",r);let n=s=>{t.end(s.error)};this.addEventListener("close",n);let o=()=>{t.end()};this.addEventListener("remoteCloseWrite",o);try{yield*t}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(t){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new jt(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",t.byteLength),this.writeBuffer.append(t),this.processSendQueue()}abort(t){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",t),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(t)}catch(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new Zn(t))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new jt("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 jt("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new jt(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.append(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new jt(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.prepend(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(t){if(t.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(t),this.dispatchReadBuffer()}}addEventListener(...t){super.addEventListener.apply(this,t),t[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 t=new ur;this.dispatchEvent(new Qn(t))}onTransportClosed(t){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"),t!=null?this.abort(t):(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 fr))}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 t=!0,r=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){t=!1;break}let s=this.writeBuffer.sublist(0,o),i=new W(s);this.writeBuffer.consume(s.byteLength);let a=this.sendData(s);if(t=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!t)break}return t||(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"),t}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 t=this.readBuffer.sublist();this.readBuffer.consume(t.byteLength),this.dispatchEvent(new Yn(t))}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 Gr(`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 Gr(`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 Vo=class extends Oe{remoteAddr;metricPrefix;metrics;constructor(t){super(t),this.metricPrefix=t.metricPrefix??"",this.metrics=t.metrics,this.remoteAddr=t.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(t){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 St(this,"idle",{...t,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 St(this,"drain",{...t,rejectionEvents:["close"]})),await this.sendClose(t),this.onTransportClosed())}};function el(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}var $o=class extends me{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(t,r){super(),this.maConn=t,this.protocol=r.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=t.log.newScope(r.name),this.streamOptions=r.streamOptions,this.maxEarlyStreams=r.maxEarlyStreams??10,this.metrics=r.metrics;let n=i=>{try{this.onData(i.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let o=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",o);let s=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",s)}send(t){let r=this.maConn.send(t);return r===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),r}async close(t){this.status==="closed"||this.status==="closing"||(this.status="closing",await he(Promise.all([...this.streams].map(async r=>{await r.close(t)})),t?.signal),this.status="closed")}abort(t){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(r=>{r.abort(t)}),this.status="closed")}onTransportClosed(t){this.status="closing";try{[...this.streams].forEach(r=>{r.onTransportClosed(t)})}catch(r){this.abort(r)}this.status="closed"}async createStream(t){if(this.status!=="open")throw new qn;let r=this.onCreateStream({...this.streamOptions,...t});return el(r)&&(r=await r),this.streams.push(r),this.cleanUpStream(r),r}onRemoteStream(t){if(this.streams.push(t),this.cleanUpStream(t),this.listenerCount("stream")===0){this.earlyStreams.push(t),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new Ho(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:t})}cleanUpStream(t){let r=n=>{let o=this.streams.findIndex(s=>s===t);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${t.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${t.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${t.direction}_stream_end`]:!0})};t.addEventListener("close",r),this.metrics?.increment({[`${t.direction}_stream`]:!0})}addEventListener(...t){super.addEventListener.apply(this,t),t[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(r=>{this.safeDispatchEvent("stream",{detail:r})}),this.earlyStreams=[]})}};var Wo=class extends Oe{id;protocol;constructor(t){super(t),this.id=t.id,this.protocol=t.protocol??""}async close(t){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="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 St(this,"idle",{...t,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await St(this,"drain",{...t,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(t),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(t){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(t),this.readStatus="closed",this.log("closed readable end gracefully"))}};var Sm=4194304,qo=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Ln=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Oa=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Na=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Am(e){return typeof e?.closeRead=="function"}function vm(e){return typeof e?.close=="function"}function Pa(e){return Am(e)?e.remoteWriteStatus!=="writable"&&e.readBufferLength===0:vm(e)?e.status!=="open":!1}function Cm(e){return e?.addEventListener!=null&&e?.removeEventListener!=null&&e?.send!=null&&e?.push!=null&&e?.log!=null}function _m(e,t){let r=t?.maxBufferSize??Sm,n=new W,o,s=!1;if(!Cm(e))throw new Y("Argument should be a Stream or a Multiaddr");let i=f=>{if(n.append(f.data),n.byteLength>r){let l=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${l} > ${r}`))}o?.resolve()};e.addEventListener("message",i);let a=f=>{f.error!=null?o?.reject(f.error):o?.resolve()};e.addEventListener("close",a);let c=()=>{o?.resolve()};e.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(f){if(s===!0)throw new qo("Stream was unwrapped");if(Pa(e)){if(n.byteLength===0&&f?.bytes==null)return null;if(f?.bytes!=null&&n.byteLength<f.bytes)throw e.log.error("closed after reading %d/%d bytes",n.byteLength,f.bytes),new rr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${f.bytes} bytes`)}let l=f?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=l){o.resolve();break}if(await he(o.promise,f?.signal),Pa(e)){if(n.byteLength===0&&f?.bytes==null)return null;break}o=Promise.withResolvers()}let d=f?.bytes??n.byteLength;if(n.byteLength<d){if(Pa(e))throw e.log.error("closed while reading %d/%d bytes",n.byteLength,d),new rr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return u.read(f)}let m=n.sublist(0,d);return n.consume(d),m},async write(f,l){if(s===!0)throw new qo("Stream was unwrapped");e.send(f)||await St(e,"drain",{signal:l?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,e.removeEventListener("message",i),e.removeEventListener("close",a),e.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(e.log("stream unwrapped with %d unread bytes",n.byteLength),e.push(n))),e}};return u}function Go(e,t={}){let r=_m(e,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=et(t.maxDataLength));let n=t?.lengthDecoder??ce,o=t?.lengthEncoder??go;return{async read(i){let a=-1,c=new W;for(;;){let f=await r.read({...i,bytes:1});if(f==null)break;c.append(f);try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Ln("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Na(`Message length length too long - ${c.byteLength} > ${t.maxLengthLength}`);if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Oa(`Message length too long - ${a} > ${t.maxDataLength}`);let u=await r.read({...i,bytes:a});if(u==null)throw e.log.error("tried to read %d bytes but the stream closed",a),new rr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(u.byteLength!==a)throw e.log.error("read %d/%d bytes before the stream closed",u.byteLength,a),new rr(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await r.write(new W(o(i.byteLength),i),a)},async writeV(i,a){let c=new W(...i.flatMap(u=>[o(u.byteLength),u]));await r.write(c,a)},unwrap(){return r.unwrap()}}}function zo(e,t){let r=Go(e,t),n={read:async(o,s)=>{let i=await r.read(s);return o.decode(i)},write:async(o,s,i)=>{await r.write(s.encode(o),i)},writeV:async(o,s,i)=>{await r.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}var Im=1024*1024*4,Lm=1024*1024*4,jo=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(t={}){this.buffer=new W,this.maxBufferSize=t.maxBufferSize??Im,this.maxDataLength=t.maxDataLength??Lm,this.lengthDecoder=t.lengthDecoder??ce,this.encodingLength=t.encodingLength??et}*decode(t){if(this.buffer.append(t),this.buffer.byteLength>this.maxBufferSize)throw new Y(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let r;try{r=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(r<0||r>this.maxDataLength)throw new Ln("Invalid message length");let n=this.encodingLength(r),o=n+r;if(this.buffer.byteLength>=o){let s=this.buffer.sublist(n,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}};var Xo=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Mr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Yo=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Bn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Zo(e){return e[Symbol.asyncIterator]!=null}function rl(e,t){if(e.byteLength>t)throw new Mr("Message length too long")}var Jo=e=>{let t=et(e),r=it(t);return go(e,r),Jo.bytes=t,r};Jo.bytes=0;function Dn(e,t){t=t??{};let r=t.lengthEncoder??Jo,n=t?.maxDataLength??4194304;function*o(s){rl(s,n);let i=r(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Zo(e)?(async function*(){for await(let s of e)yield*o(s)})():(function*(){for(let s of e)yield*o(s)})()}Dn.single=(e,t)=>{t=t??{};let r=t.lengthEncoder??Jo,n=t?.maxDataLength??4194304;return rl(e,n),new W(r(e.byteLength),e)};var nr;(function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(nr||(nr={}));var Ua=e=>{let t=ce(e);return Ua.bytes=et(t),t};Ua.bytes=0;function Tn(e,t){let r=new W,n=nr.LENGTH,o=-1,s=t?.lengthDecoder??Ua,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===nr.LENGTH)try{if(o=s(r),o<0)throw new Xo("Invalid message length");if(o>a)throw new Mr("Message length too long");let u=s.bytes;r.consume(u),t?.onLength!=null&&t.onLength(o),n=nr.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>i)throw new Yo("Message length length too long");break}throw u}if(n===nr.DATA){if(r.byteLength<o)break;let u=r.sublist(0,o);r.consume(o),t?.onData!=null&&t.onData(u),yield u,n=nr.LENGTH}}}return Zo(e)?(async function*(){for await(let u of e)r.append(u),yield*c();if(r.byteLength>0)throw new Bn("Unexpected end of input")})():(function*(){for(let u of e)r.append(u),yield*c();if(r.byteLength>0)throw new Bn("Unexpected end of input")})()}Tn.fromReader=(e,t)=>{let r=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await e.next(r);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}})();return Tn(n,{...t??{},onLength:s=>{r=s}})};var nl=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},Tm=(function(){function e(t,r,n){this.name=t,this.version=r,this.os=n,this.type="browser"}return e})();var Rm=(function(){function e(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return e})();var Pm=(function(){function e(t,r,n,o){this.name=t,this.version=r,this.os=n,this.bot=o,this.type="bot-device"}return e})();var Om=(function(){function e(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return e})();var Nm=(function(){function e(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return e})();var Um=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,km=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,ol=3,Mm=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",Um]],sl=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function al(e){return e?il(e):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Nm:typeof navigator<"u"?il(navigator.userAgent):Fm()}function Km(e){return e!==""&&Mm.reduce(function(t,r){var n=r[0],o=r[1];if(t)return t;var s=o.exec(e);return!!s&&[n,s]},!1)}function il(e){var t=Km(e);if(!t)return null;var r=t[0],n=t[1];if(r==="searchbot")return new Om;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<ol&&(o=nl(nl([],o,!0),Vm(ol-o.length),!0)):o=[];var s=o.join("."),i=Hm(e),a=km.exec(e);return a&&a[1]?new Pm(r,s,i,a[1]):new Tm(r,s,i)}function Hm(e){for(var t=0,r=sl.length;t<r;t++){var n=sl[t],o=n[0],s=n[1],i=s.exec(e);if(i)return o}return null}function Fm(){var e=typeof process<"u"&&process.version;return e?new Rm(process.version.slice(1)):null}function Vm(e){for(var t=[],r=0;r<e;r++)t.push("0");return t}var cl=al(),ts=cl!=null&&cl.name==="firefox";async function ka(e){return e=e??{},typeof e=="function"&&(e=await e()),e.iceServers=e.iceServers??Xf.map(t=>({urls:[t]})),e}var ul=(e=32)=>Yf+[...Array(e)].map(()=>Ia.at(Math.floor(Math.random()*Ia.length))).join("");var Ma=class extends Wo{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(t){super({...t,maxMessageSize:(t.maxMessageSize??Nr)-Qf}),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=kr(),this.maxBufferedAmount=t.maxBufferedAmount??Zf,this.finAckTimeout=t.finAckTimeout??Jf,this.channel.onclose=()=>{this.log.trace("received datachannel close event"),this.onRemoteCloseWrite(),this.onTransportClosed()},this.channel.onerror=n=>{let o=n.error;this.log.trace("received datachannel error event - %e",o),this.abort(o)},this.channel.onmessage=async n=>{this.log("incoming message %d bytes",n.data.byteLength);let{data:o}=n;o===null||o.byteLength===0||this.incomingData.push(new Uint8Array(o,0,o.byteLength))},this.channel.bufferedAmountLowThreshold=0,this.channel.onbufferedamountlow=()=>{this.writableNeedsDrain&&this.safeDispatchEvent("drain")},Promise.resolve().then(async()=>{for await(let n of Tn(this.incomingData))this.processIncomingProtobuf(n)}).catch(n=>{this.log.error("error processing incoming data channel messages - %e",n)});let r=()=>{this.channel.readyState==="open"&&(this.log.trace("stream closed, closing underlying datachannel"),this.channel.close())};this.addEventListener("close",r),this.channel.readyState!=="open"&&(this.log('channel ready state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),St(this.channel,"open",{rejectionEvents:["close","error"]}).then(()=>{this.log('channel ready state is now "%s", dispatching drain',this.channel.readyState),this.safeDispatchEvent("drain")}).catch(n=>{this.abort(n.error??n)}))}sendNewStream(){}_sendMessage(t){if(this.channel.readyState!=="open")throw new jt(`Invalid datachannel state - ${this.channel.readyState}`);if(this.log.trace('sending message, channel state "%s"',this.channel.readyState),ts){this.channel.send(t.subarray());return}for(let r of t)this.channel.send(r)}sendData(t){return this.channel.readyState!=="open"?{sentBytes:0,canSendMore:!1}:(this._sendMessage(Dn.single(It.encode({message:t.subarray()}))),{sentBytes:t.byteLength,canSendMore:this.channel.bufferedAmount<this.maxBufferedAmount})}sendReset(t){try{this.log.error("sending reset - %e",t),this._sendFlag(It.Flag.RESET),this.receivedFinAck?.reject(t)}catch(r){this.log.error("failed to send reset - %e",r)}}async sendCloseWrite(t){this._sendFlag(It.Flag.FIN),t?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let r=t?.signal??AbortSignal.timeout(this.finAckTimeout),n=[St(this.channel,"close",{signal:r}),St(this.channel,"error",{signal:r})];await Promise.any([he(this.receivedFinAck.promise,r),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(t){this._sendFlag(It.Flag.STOP_SENDING),t?.signal?.throwIfAborted()}processIncomingProtobuf(t){let r=It.decode(t);r.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new W(r.message)),r.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',r.flag,this.writeStatus,this.readStatus),r.flag===It.Flag.FIN&&(this._sendFlag(It.Flag.FIN_ACK),this.onRemoteCloseWrite()),r.flag===It.Flag.RESET&&(this.receivedFinAck?.reject(new ur("The stream was reset")),this.onRemoteReset()),r.flag===It.Flag.STOP_SENDING&&this.onRemoteCloseRead(),r.flag===It.Flag.FIN_ACK&&this.receivedFinAck?.resolve())}_sendFlag(t){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',t.toString(),this.channel.readyState),!1;this.log.trace("sending flag %s",t.toString());let r=It.encode({flag:t}),n=Dn.single(r);try{return this._sendMessage(n),!0}catch(o){this.log.error("could not send flag %s - %e",t.toString(),o)}return!1}sendPause(){}sendResume(){}};function Rn(e){let{channel:t,direction:r,isHandshake:n}=e;return new Ma({...e,id:`${t.id}`,log:e.log.newScope(`${n===!0?"handshake":r}:${t.id}`),protocol:""})}var Ne=class{protocol;peerConnection;metrics;dataChannelOptions;earlyDataChannels;constructor(t){this.onEarlyDataChannel=this.onEarlyDataChannel.bind(this),this.peerConnection=t.peerConnection,this.metrics=t.metrics,this.protocol=t.protocol??La,this.dataChannelOptions=t.dataChannelOptions??{},this.peerConnection.addEventListener("datachannel",this.onEarlyDataChannel),this.earlyDataChannels=[]}onEarlyDataChannel(t){this.earlyDataChannels.push(t.channel)}createStreamMuxer(t){return this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel),new Ka(t,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,earlyDataChannels:this.earlyDataChannels})}},Ka=class extends $o{peerConnection;dataChannelOptions;constructor(t,r){super(t,{...r,name:"muxer"}),this.peerConnection=r.peerConnection,this.protocol=r.protocol??La,this.dataChannelOptions=r.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{this.onDataChannel(n)},queueMicrotask(()=>{if(this.status!=="open"){r.earlyDataChannels.forEach(n=>{n.close()});return}r.earlyDataChannels.forEach(n=>{this.onDataChannel(n)})})}onDataChannel(t){if(this.log("incoming datachannel with channel id %d, protocol %s and status %s",t.id,t.protocol,t.readyState),t.label==="init"){this.log.trace("closing init channel %d",t.id),t.close();return}let r=Rn({...this.streamOptions,...this.dataChannelOptions,channel:t,direction:"inbound",log:this.log});this.onRemoteStream(r)}async onCreateStream(t){let r=this.peerConnection.createDataChannel("",{});return this.log("open channel %d for protocol %s",r.id,t?.protocol),Rn({...t,...this.dataChannelOptions,channel:r,direction:"outbound",log:this.log})}onData(){}};var Ha=class extends Vo{peerConnection;constructor(t){super(t),this.peerConnection=t.peerConnection;let r=t.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change %s initial state %s",this.peerConnection.connectionState,r),(this.peerConnection.connectionState==="disconnected"||this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.onTransportClosed(),this.peerConnection.close())}}sendData(t){return{sentBytes:t.byteLength,canSendMore:!0}}async sendClose(t){this.peerConnection.close(),t?.signal?.throwIfAborted()}sendReset(){this.peerConnection.close()}sendPause(){}sendResume(){}},Pn=e=>new Ha(e);var es=globalThis.RTCPeerConnection,rs=globalThis.RTCSessionDescription,fl=globalThis.RTCIceCandidate;var kt=class extends Event{type;detail;constructor(t,r){super(t),this.type=t,this.detail=r}};var Ue=class extends Error{constructor(t){super(`WebRTC transport error: ${t}`),this.name="WebRTCTransportError"}},Ft=class extends Ue{constructor(t="SDP handshake failed"){super(t),this.name="SDPHandshakeFailedError"}};var ns=class extends Ue{constructor(t,r){super(`Invalid fingerprint "${t}" within ${r}`),this.name="WebRTC/InvalidFingerprintError"}};var os=class extends Ue{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},ss=class extends Ue{constructor(t){super(`unsupported hash algorithm code: ${t} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var Nt;(function(e){let t;(function(a){a.SDP_OFFER="SDP_OFFER",a.SDP_ANSWER="SDP_ANSWER",a.ICE_CANDIDATE="ICE_CANDIDATE"})(t=e.Type||(e.Type={}));let r;(function(a){a[a.SDP_OFFER=0]="SDP_OFFER",a[a.SDP_ANSWER=1]="SDP_ANSWER",a[a.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(r||(r={})),(function(a){a.codec=()=>Ze(r)})(t=e.Type||(e.Type={}));let n;e.codec=()=>(n==null&&(n=Te((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),e.Type.codec().encode(a.type,c)),a.data!=null&&(c.uint32(18),c.string(a.data)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let f={},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let d=a.uint32();switch(d>>>3){case 1:{f.type=e.Type.codec().decode(a);break}case 2:{f.data=a.string();break}default:{a.skipType(d&7);break}}}return f},function*(a,c,u,f={}){let l=c==null?a.len:a.pos+c;for(;a.pos<l;){let d=a.uint32();switch(d>>>3){case 1:{yield{field:`${u}.type`,value:e.Type.codec().decode(a)};break}case 2:{yield{field:`${u}.data`,value:a.string()};break}default:{a.skipType(d&7);break}}}})),n);function o(a){return Be(a,e.codec())}e.encode=o;function s(a,c){return Le(a,e.codec(),c)}e.decode=s;function i(a,c){return De(a,e.codec(),c)}e.stream=i})(Nt||(Nt={}));var is=async(e,t,r)=>{try{let n=Promise.withResolvers();for($m(e,n);;){let o=await Promise.race([n.promise,t.read({signal:r.signal})]);if(o==null){r.signal?.throwIfAborted();break}if(o.type!==Nt.Type.ICE_CANDIDATE)throw new Xn("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){r.onProgress?.(new kt("webrtc:end-of-ice-candidates")),r.log.trace("end-of-candidates received");continue}let i=new fl(s);r.log.trace("%s received new ICE candidate %o",r.direction,s);try{r.onProgress?.(new kt("webrtc:add-ice-candidate",i.candidate)),await e.addIceCandidate(i)}catch(a){r.log.error("%s bad candidate received %o - %e",r.direction,s,a)}}}catch(n){if(r.log.error("%s error parsing ICE candidate - %e",r.direction,n),r.signal?.aborted===!0&&e.connectionState!=="connected")throw n}};function $m(e,t){if(e.connectionState==="connected"){t.resolve();return}e.onconnectionstatechange=r=>{switch(e.connectionState){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new Wn(`RTCPeerConnection connection state became "${e.connectionState}"`));break;default:break}}}function as(e){let t;for(let r of e.getComponents())r.name==="p2p"&&(t=Br(r.value??""));if(t==null)throw new Gn("Remote peerId must be present in multiaddr");return t}async function ll({rtcConfiguration:e,dataChannel:t,signal:r,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:u}){let{circuitAddress:f,targetPeer:l}=hl(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing circuit address: %a",f);let d=s.getConnections(l),m;d.length===0?(u?.(new kt("webrtc:dial-relay")),m=await i.dial(f,{signal:r,onProgress:u})):(u?.(new kt("webrtc:reuse-relay-connection")),m=d[0]),u?.(new kt("webrtc:open-signaling-stream"));let p=await m.newStream(In,{signal:r,runOnLimitedConnection:!0}),E=zo(p).pb(Nt),h=new es(e);h.addEventListener("connectionstatechange",()=>{switch(h.connectionState){case"closed":h.close();break;default:break}});let b=new Ne({peerConnection:h,dataChannelOptions:t});try{let v=h.createDataChannel("init");h.onicecandidate=({candidate:O})=>{if(h.connectionState==="connected"){a.trace("ignore new ice candidate as peer connection is already connected");return}if(O==null||O?.candidate===""){a.trace("initiator detected end of ICE candidates");return}let K=JSON.stringify(O?.toJSON()??null);a.trace("initiator sending ICE candidate %o",O),E.write({type:Nt.Type.ICE_CANDIDATE,data:K},{signal:r}).catch(_=>{a.error("error sending ICE candidate - %e",_)})},h.onicecandidateerror=O=>{a.error("initiator ICE candidate error",O)};let x=await h.createOffer().catch(O=>{throw a.error("could not execute createOffer - %e",O),new Ft("Failed to set createOffer")});a.trace("initiator send SDP offer %s",x.sdp),u?.(new kt("webrtc:send-sdp-offer")),await E.write({type:Nt.Type.SDP_OFFER,data:x.sdp},{signal:r}),await h.setLocalDescription(x).catch(O=>{throw a.error("could not execute setLocalDescription - %e",O),new Ft("Failed to set localDescription")}),u?.(new kt("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let D=await E.read({signal:r});if(D.type!==Nt.Type.SDP_ANSWER)throw new Ft("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",D.data);let k=new rs({type:"answer",sdp:D.data});return await h.setRemoteDescription(k).catch(O=>{throw a.error("could not execute setRemoteDescription - %e",O),new Ft("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),u?.(new kt("webrtc:read-ice-candidates")),await is(h,E,{direction:"initiator",signal:r,log:a,onProgress:u}),a.trace("initiator connected"),v.readyState!=="open"&&(a.trace("wait for init channel to open"),await St(v,"open",{signal:r})),a.trace("closing init channel"),v.close(),a.trace("waiting for init channel to close"),await St(v,"close",{signal:r}),u?.(new kt("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await p.close({signal:r}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:h,muxerFactory:b}}catch(v){throw a.error("outgoing signaling error - %e",v),h.close(),p.abort(v),v}finally{h.onicecandidate=null,h.onicecandidateerror=null}}var dl=ot(zf.matchers[0],nt(290)),cs=class e extends me{transportManager;shutdownController;events;constructor(t,r){super(),this.transportManager=t.transportManager,this.events=t.events,this.shutdownController=r.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(t){t.detail.getAddrs().filter(n=>dl.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(t=>!(t instanceof e)).map(t=>t.getAddrs().filter(r=>dl.exactMatch(r)).map(r=>r.encapsulate("/webrtc"))).flat()}updateAnnounceAddrs(){}async close(){this.events.removeEventListener("transport:listening",this.onTransportListening),this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function pl(e,t,{peerConnection:r,signal:n,log:o}){o.trace("new inbound signaling stream");let s=zo(e).pb(Nt);try{r.onicecandidate=({candidate:l})=>{if(r.connectionState==="connected"){o.trace("ignore new ice candidate as peer connection is already connected");return}if(l==null||l?.candidate===""){o.trace("recipient detected end of ICE candidates");return}let d=JSON.stringify(l?.toJSON()??null);o.trace("recipient sending ICE candidate %s",d),s.write({type:Nt.Type.ICE_CANDIDATE,data:d},{signal:n}).catch(m=>{o.error("error sending ICE candidate - %e",m)})},o.trace("recipient read SDP offer");let c=await s.read({signal:n});if(c.type!==Nt.Type.SDP_OFFER)throw new Ft(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let u=new rs({type:"offer",sdp:c.data});await r.setRemoteDescription(u).catch(l=>{throw o.error("could not execute setRemoteDescription - %e",l),new Ft("Failed to set remoteDescription")});let f=await r.createAnswer().catch(l=>{throw o.error("could not execute createAnswer - %e",l),new Ft("Failed to create answer")});o.trace("recipient send SDP answer %s",f.sdp),await s.write({type:Nt.Type.SDP_ANSWER,data:f.sdp},{signal:n}),await r.setLocalDescription(f).catch(l=>{throw o.error("could not execute setLocalDescription - %e",l),new Ft("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await is(r,s,{direction:"recipient",signal:n,log:o})}catch(c){if(r.connectionState!=="connected")throw o.error("error while handling signaling stream from peer %a - %e",t.remoteAddr,c),r.close(),c;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",t.remoteAddr,c)}let i=as(t.remoteAddr),a=Or(`/webrtc/p2p/${i}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:i}}var us=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,r={}){this.components=t,this.init=r,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[Jn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[lr]=["@libp2p/transport"];[Ic]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(In,(t,r)=>{let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(t,r,n).catch(o=>{this.log.error("failed to handle incoming connect from %p - %e",r.remotePeer,o)}).finally(()=>{n.clear()})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(In),this._started=!1}createListener(t){return new cs(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(jf.exactMatch)}dialFilter(t){return this.listenFilter(t)}async dial(t,r){this.log.trace("dialing address: %a",t);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await ll({rtcConfiguration:await ka(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:t,dataChannelOptions:this.init.dataChannel,signal:r.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:r.onProgress}),i=Pn({peerConnection:o,remoteAddr:n,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")}),a=await r.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,remotePeer:as(t),muxerFactory:s,onProgress:r.onProgress,signal:r.signal});return this._closeOnShutdown(o,i),a}async _onProtocol(t,r,n){let o=new es(await ka(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{switch(o.connectionState){case"closed":o.close();break;default:break}});let s=new Ne({peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i,remotePeer:a}=await pl(t,r,{peerConnection:o,signal:n,log:this.log});await t.close({signal:n});let c=Pn({peerConnection:o,remoteAddr:i,metrics:this.metrics?.listenerEvents,direction:"inbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")});await this.components.upgrader.upgradeInbound(c,{skipEncryption:!0,skipProtection:!0,remotePeer:a,muxerFactory:s,signal:n}),this._closeOnShutdown(o,c)}catch(i){throw this.log.error("incoming signaling error - %e",i),o.close(),t.abort(i),i}}_closeOnShutdown(t,r){let n=()=>{r.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection - %e",o)})};this.shutdownController.signal.addEventListener("abort",n),t.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function hl(e){let t=e.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(t==null)throw new Y("Destination peer id was missing");return{circuitAddress:Or(e.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:Br(t)}}var Kr=!!globalThis.process?.env?.DUMP_SESSION_KEYS,Fa=16;function Wm(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function fs(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function ls(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function bt(e,t,r=""){let n=Wm(e),o=e?.length,s=t!==void 0;if(!n||s&&o!==t){let i=r&&`"${r}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function Va(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ml(e,t){bt(e,void 0,"output");let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function de(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function pe(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function qm(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var Gm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function gl(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function yl(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}var $a=(e,t)=>{function r(n,...o){if(bt(n,void 0,"key"),!Gm)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){let f=o[0];bt(f,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let s=e.tagLength;s&&o[1]!==void 0&&bt(o[1],void 0,"AAD");let i=t(n,...o),a=(f,l)=>{if(l!==void 0){if(f!==2)throw new Error("cipher output not supported");bt(l,void 0,"output")}},c=!1;return{encrypt(f,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,bt(f),a(i.encrypt.length,l),i.encrypt(f,l)},decrypt(f,l){if(bt(f),s&&f.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,l),i.decrypt(f,l)}}}return Object.assign(r,e),r};function Wa(e,t,r=!0){if(t===void 0)return new Uint8Array(e);if(t.length!==e)throw new Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(r&&!zm(t))throw new Error("invalid output, must be aligned");return t}function bl(e,t,r){fs(r);let n=new Uint8Array(16),o=qm(n);return o.setBigUint64(0,BigInt(t),r),o.setBigUint64(8,BigInt(e),r),n}function zm(e){return e.byteOffset%4===0}function Hr(e){return Uint8Array.from(e)}var xl=e=>Uint8Array.from(e.split(""),t=>t.charCodeAt(0)),jm=xl("expand 16-byte k"),Xm=xl("expand 32-byte k"),Ym=de(jm),Zm=de(Xm);function U(e,t){return e<<t|e>>>32-t}function qa(e){return e.byteOffset%4===0}var hs=64,Qm=16,El=2**32-1,wl=Uint32Array.of();function Jm(e,t,r,n,o,s,i,a){let c=o.length,u=new Uint8Array(hs),f=de(u),l=qa(o)&&qa(s),d=l?de(o):wl,m=l?de(s):wl;for(let p=0;p<c;i++){if(e(t,r,n,f,i,a),i>=El)throw new Error("arx: counter overflow");let E=Math.min(hs,c-p);if(l&&E===hs){let h=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let b=0,v;b<Qm;b++)v=h+b,m[v]=d[v]^f[b];p+=hs;continue}for(let h=0,b;h<E;h++)b=p+h,s[b]=o[b]^u[h];p+=E}}function Ga(e,t){let{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=gl({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return ls(o),ls(i),fs(s),fs(r),(a,c,u,f,l=0)=>{bt(a,void 0,"key"),bt(c,void 0,"nonce"),bt(u,void 0,"data");let d=u.length;if(f===void 0&&(f=new Uint8Array(d)),bt(f,void 0,"output"),ls(l),l<0||l>=El)throw new Error("arx: counter overflow");if(f.length<d)throw new Error(`arx: output (${f.length}) is shorter than data (${d})`);let m=[],p=a.length,E,h;if(p===32)m.push(E=Hr(a)),h=Zm;else if(p===16&&r)E=new Uint8Array(32),E.set(a),E.set(a,16),h=Ym,m.push(E);else throw bt(a,32,"arx key"),new Error("invalid key size");qa(c)||m.push(c=Hr(c));let b=de(E);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,b,de(c.subarray(0,16)),b),c=c.subarray(16)}let v=16-o;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let D=new Uint8Array(12);D.set(c,s?0:12-c.length),c=D,m.push(c)}let x=de(c);return Jm(e,h,b,x,u,f,l,i),pe(...m),f}}function At(e,t){return e[t++]&255|(e[t++]&255)<<8}var za=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;constructor(t){t=Hr(bt(t,32,"key"));let r=At(t,0),n=At(t,2),o=At(t,4),s=At(t,6),i=At(t,8),a=At(t,10),c=At(t,12),u=At(t,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let f=0;f<8;f++)this.pad[f]=At(t,16+2*f)}process(t,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],u=i[2],f=i[3],l=i[4],d=i[5],m=i[6],p=i[7],E=i[8],h=i[9],b=At(t,r+0),v=At(t,r+2),x=At(t,r+4),D=At(t,r+6),k=At(t,r+8),O=At(t,r+10),K=At(t,r+12),_=At(t,r+14),A=s[0]+(b&8191),N=s[1]+((b>>>13|v<<3)&8191),M=s[2]+((v>>>10|x<<6)&8191),T=s[3]+((x>>>7|D<<9)&8191),w=s[4]+((D>>>4|k<<12)&8191),g=s[5]+(k>>>1&8191),y=s[6]+((k>>>14|O<<2)&8191),C=s[7]+((O>>>11|K<<5)&8191),L=s[8]+((K>>>8|_<<8)&8191),I=s[9]+(_>>>5|o),S=0,B=S+A*a+N*(5*h)+M*(5*E)+T*(5*p)+w*(5*m);S=B>>>13,B&=8191,B+=g*(5*d)+y*(5*l)+C*(5*f)+L*(5*u)+I*(5*c),S+=B>>>13,B&=8191;let R=S+A*c+N*a+M*(5*h)+T*(5*E)+w*(5*p);S=R>>>13,R&=8191,R+=g*(5*m)+y*(5*d)+C*(5*l)+L*(5*f)+I*(5*u),S+=R>>>13,R&=8191;let P=S+A*u+N*c+M*a+T*(5*h)+w*(5*E);S=P>>>13,P&=8191,P+=g*(5*p)+y*(5*m)+C*(5*d)+L*(5*l)+I*(5*f),S+=P>>>13,P&=8191;let j=S+A*f+N*u+M*c+T*a+w*(5*h);S=j>>>13,j&=8191,j+=g*(5*E)+y*(5*p)+C*(5*m)+L*(5*d)+I*(5*l),S+=j>>>13,j&=8191;let G=S+A*l+N*f+M*u+T*c+w*a;S=G>>>13,G&=8191,G+=g*(5*h)+y*(5*E)+C*(5*p)+L*(5*m)+I*(5*d),S+=G>>>13,G&=8191;let V=S+A*d+N*l+M*f+T*u+w*c;S=V>>>13,V&=8191,V+=g*a+y*(5*h)+C*(5*E)+L*(5*p)+I*(5*m),S+=V>>>13,V&=8191;let X=S+A*m+N*d+M*l+T*f+w*u;S=X>>>13,X&=8191,X+=g*c+y*a+C*(5*h)+L*(5*E)+I*(5*p),S+=X>>>13,X&=8191;let rt=S+A*p+N*m+M*d+T*l+w*f;S=rt>>>13,rt&=8191,rt+=g*u+y*c+C*a+L*(5*h)+I*(5*E),S+=rt>>>13,rt&=8191;let lt=S+A*E+N*p+M*m+T*d+w*l;S=lt>>>13,lt&=8191,lt+=g*f+y*u+C*c+L*a+I*(5*h),S+=lt>>>13,lt&=8191;let Z=S+A*h+N*E+M*p+T*m+w*d;S=Z>>>13,Z&=8191,Z+=g*l+y*f+C*u+L*c+I*a,S+=Z>>>13,Z&=8191,S=(S<<2)+S|0,S=S+B|0,B=S&8191,S=S>>>13,R+=S,s[0]=B,s[1]=R,s[2]=P,s[3]=j,s[4]=G,s[5]=V,s[6]=X,s[7]=rt,s[8]=lt,s[9]=Z}finalize(){let{h:t,pad:r}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+r[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+r[a]|0)+(i>>>16)|0,t[a]=i&65535;pe(n)}update(t){Va(this),bt(t),t=Hr(t);let{buffer:r,blockLen:n}=this,o=t.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(t,s);continue}r.set(t.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){pe(this.h,this.r,this.buffer,this.pad)}digestInto(t){Va(this),ml(t,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:o}=this;if(o){for(r[o++]=1;o<16;o++)r[o]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)t[s++]=n[i]>>>0,t[s++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}};function t0(e){let t=(n,o)=>e(o).update(n).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}var Sl=t0(e=>new za(e));function Cl(e,t,r,n,o,s=20){let i=e[0],a=e[1],c=e[2],u=e[3],f=t[0],l=t[1],d=t[2],m=t[3],p=t[4],E=t[5],h=t[6],b=t[7],v=o,x=r[0],D=r[1],k=r[2],O=i,K=a,_=c,A=u,N=f,M=l,T=d,w=m,g=p,y=E,C=h,L=b,I=v,S=x,B=D,R=k;for(let j=0;j<s;j+=2)O=O+N|0,I=U(I^O,16),g=g+I|0,N=U(N^g,12),O=O+N|0,I=U(I^O,8),g=g+I|0,N=U(N^g,7),K=K+M|0,S=U(S^K,16),y=y+S|0,M=U(M^y,12),K=K+M|0,S=U(S^K,8),y=y+S|0,M=U(M^y,7),_=_+T|0,B=U(B^_,16),C=C+B|0,T=U(T^C,12),_=_+T|0,B=U(B^_,8),C=C+B|0,T=U(T^C,7),A=A+w|0,R=U(R^A,16),L=L+R|0,w=U(w^L,12),A=A+w|0,R=U(R^A,8),L=L+R|0,w=U(w^L,7),O=O+M|0,R=U(R^O,16),C=C+R|0,M=U(M^C,12),O=O+M|0,R=U(R^O,8),C=C+R|0,M=U(M^C,7),K=K+T|0,I=U(I^K,16),L=L+I|0,T=U(T^L,12),K=K+T|0,I=U(I^K,8),L=L+I|0,T=U(T^L,7),_=_+w|0,S=U(S^_,16),g=g+S|0,w=U(w^g,12),_=_+w|0,S=U(S^_,8),g=g+S|0,w=U(w^g,7),A=A+N|0,B=U(B^A,16),y=y+B|0,N=U(N^y,12),A=A+N|0,B=U(B^A,8),y=y+B|0,N=U(N^y,7);let P=0;n[P++]=i+O|0,n[P++]=a+K|0,n[P++]=c+_|0,n[P++]=u+A|0,n[P++]=f+N|0,n[P++]=l+M|0,n[P++]=d+T|0,n[P++]=m+w|0,n[P++]=p+g|0,n[P++]=E+y|0,n[P++]=h+C|0,n[P++]=b+L|0,n[P++]=v+I|0,n[P++]=x+S|0,n[P++]=D+B|0,n[P++]=k+R|0}function e0(e,t,r,n){let o=e[0],s=e[1],i=e[2],a=e[3],c=t[0],u=t[1],f=t[2],l=t[3],d=t[4],m=t[5],p=t[6],E=t[7],h=r[0],b=r[1],v=r[2],x=r[3];for(let k=0;k<20;k+=2)o=o+c|0,h=U(h^o,16),d=d+h|0,c=U(c^d,12),o=o+c|0,h=U(h^o,8),d=d+h|0,c=U(c^d,7),s=s+u|0,b=U(b^s,16),m=m+b|0,u=U(u^m,12),s=s+u|0,b=U(b^s,8),m=m+b|0,u=U(u^m,7),i=i+f|0,v=U(v^i,16),p=p+v|0,f=U(f^p,12),i=i+f|0,v=U(v^i,8),p=p+v|0,f=U(f^p,7),a=a+l|0,x=U(x^a,16),E=E+x|0,l=U(l^E,12),a=a+l|0,x=U(x^a,8),E=E+x|0,l=U(l^E,7),o=o+u|0,x=U(x^o,16),p=p+x|0,u=U(u^p,12),o=o+u|0,x=U(x^o,8),p=p+x|0,u=U(u^p,7),s=s+f|0,h=U(h^s,16),E=E+h|0,f=U(f^E,12),s=s+f|0,h=U(h^s,8),E=E+h|0,f=U(f^E,7),i=i+l|0,b=U(b^i,16),d=d+b|0,l=U(l^d,12),i=i+l|0,b=U(b^i,8),d=d+b|0,l=U(l^d,7),a=a+c|0,v=U(v^a,16),m=m+v|0,c=U(c^m,12),a=a+c|0,v=U(v^a,8),m=m+v|0,c=U(c^m,7);let D=0;n[D++]=o,n[D++]=s,n[D++]=i,n[D++]=a,n[D++]=h,n[D++]=b,n[D++]=v,n[D++]=x}var r0=Ga(Cl,{counterRight:!1,counterLength:4,allowShortKeys:!1}),n0=Ga(Cl,{counterRight:!1,counterLength:8,extendNonceFn:e0,allowShortKeys:!1});var o0=new Uint8Array(16),Al=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(o0.subarray(r))},s0=new Uint8Array(32);function vl(e,t,r,n,o){o!==void 0&&bt(o,void 0,"AAD");let s=e(t,r,s0),i=bl(n.length,o?o.length:0,!0),a=Sl.create(s);o&&Al(a,o),Al(a,n),a.update(i);let c=a.digest();return pe(s,i),c}var _l=e=>(t,r,n)=>({encrypt(s,i){let a=s.length;i=Wa(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);e(t,r,c,c,1);let u=vl(e,t,r,c,n);return i.set(u,a),pe(u),i},decrypt(s,i){i=Wa(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),u=vl(e,t,r,a,n);if(!yl(c,u))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),e(t,r,i,i,1),pe(u),i}}),ja=$a({blockSize:64,nonceLength:12,tagLength:16},_l(r0)),r6=$a({blockSize:64,nonceLength:24,tagLength:16},_l(n0));function Ll(e,t,r){return Ve(e),r===void 0&&(r=new Uint8Array(e.outputLen)),_r(e,r,t)}var Xa=Uint8Array.of(0),Il=Uint8Array.of();function Bl(e,t,r,n=32){Ve(e),Kt(n,"length");let o=e.outputLen;if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);r===void 0?r=Il:F(r,void 0,"info");let i=new Uint8Array(s*o),a=_r.create(e,t),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let f=0;f<s;f++)Xa[0]=f+1,c.update(f===0?Il:u).update(r).update(Xa).digestInto(u),i.set(u,o*f),a._cloneInto(c);return a.destroy(),c.destroy(),Wt(u,Xa),i.slice(0,n)}var Ya={hashSHA256(e){return Yt(e.subarray())},getHKDF(e,t){let r=Ll(Yt,t,e),o=Bl(Yt,r,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let e=fn.utils.randomSecretKey();return{publicKey:fn.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed(e){return{publicKey:fn.getPublicKey(e),privateKey:e}},generateX25519SharedKey(e,t){return fn.getSharedSecret(e.subarray(),t.subarray())},chaCha20Poly1305Encrypt(e,t,r,n){return ja(n,t,r).encrypt(e.subarray())},chaCha20Poly1305Decrypt(e,t,r,n,o){return ja(n,t,r).decrypt(e.subarray(),o)}};var Dl=Ya;function Tl(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}var Fr=e=>{let t=it(2);return t[0]=e>>8,t[1]=e,t};Fr.bytes=2;var Vr=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};Vr.bytes=2;function Rl(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Za(e,t){!t.enabled||!Kr||(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${$(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${$(e.privateKey,"hex")}`)):t("Missing local static keys."))}function Qa(e,t){!t.enabled||!Kr||(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${$(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${$(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function Pl(e,t){!t.enabled||!Kr||t(e?`REMOTE_STATIC_PUBLIC_KEY ${$(e.subarray(),"hex")}`:"Missing remote static public key.")}function Ja(e,t){!t.enabled||!Kr||t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${$(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function tc(e,t,r){!r.enabled||!Kr||(r(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&$(e.k,"hex")}`),r(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&$(t.k,"hex")}`))}var $r=class e extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=e.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var i0=0,a0=4294967295,c0="Cipherstate has reached maximum n, a new handshake must be performed",ds=class{n;bytes;view;constructor(t=i0){this.n=t,this.bytes=pt(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>a0)throw new Error(c0)}};var or=pt(0),Wr=class{k;n;crypto;constructor(t,r=void 0,n=0){this.crypto=t,this.k=r,this.n=new ds(n)}hasKey(){return!!this.k}encryptWithAd(t,r){if(!this.hasKey())return r;this.n.assertValue();let n=this.crypto.encrypt(r,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,r,n){if(!this.hasKey())return r;this.n.assertValue();let o=this.crypto.decrypt(r,this.n.getBytes(),t,this.k,n);return this.n.increment(),o}},ec=class{cs;ck;h;crypto;constructor(t,r){this.crypto=t;let n=q(r,"utf-8");this.h=u0(t,n),this.ck=this.h,this.cs=new Wr(t)}mixKey(t){let[r,n]=this.crypto.hkdf(this.ck,t);this.ck=r,this.cs=new Wr(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new W(this.h,t))}encryptAndHash(t){let r=this.cs.encryptWithAd(this.h,t);return this.mixHash(r),r}decryptAndHash(t){let r=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),r}split(){let[t,r]=this.crypto.hkdf(this.ck,or);return[new Wr(this.crypto,t),new Wr(this.crypto,r)]}},rc=class{ss;s;e;rs;re;initiator;crypto;constructor(t){let{crypto:r,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:u}=t;this.crypto=r,this.ss=new ec(r,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=u}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let t=this.crypto.generateKeypair();return this.ss.mixHash(t.publicKey),this.e=t,t.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(t,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<r+32)throw new Error("message is not long enough");this.re=t.sublist(r,r+32),this.ss.mixHash(this.re)}readS(t,r=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(t.byteLength<r+n)throw new Error("message is not long enough");let o=t.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},On=class extends rc{writeMessageA(t){return new W(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let r=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new W(r,n,this.ss.encryptAndHash(t))}writeMessageC(t){let r=this.writeS();return this.writeSE(),new W(r,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(r){throw new $r(`handshake stage 0 validation fail: ${r.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();let r=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+r))}catch(r){throw new $r(`handshake stage 1 validation fail: ${r.message}`)}}readMessageC(t){try{let r=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(r))}catch(r){throw new $r(`handshake stage 2 validation fail: ${r.message}`)}}};function u0(e,t){if(t.length<=32){let r=pt(32);return r.set(t),r}else return e.hash(t)}var nc=new Float32Array([-0]),ke=new Uint8Array(nc.buffer);function Ol(e,t,r){nc[0]=e,t[r]=ke[0],t[r+1]=ke[1],t[r+2]=ke[2],t[r+3]=ke[3]}function Nl(e,t){return ke[0]=e[t],ke[1]=e[t+1],ke[2]=e[t+2],ke[3]=e[t+3],nc[0]}var oc=new Float64Array([-0]),Lt=new Uint8Array(oc.buffer);function Ul(e,t,r){oc[0]=e,t[r]=Lt[0],t[r+1]=Lt[1],t[r+2]=Lt[2],t[r+3]=Lt[3],t[r+4]=Lt[4],t[r+5]=Lt[5],t[r+6]=Lt[6],t[r+7]=Lt[7]}function kl(e,t){return Lt[0]=e[t],Lt[1]=e[t+1],Lt[2]=e[t+2],Lt[3]=e[t+3],Lt[4]=e[t+4],Lt[5]=e[t+5],Lt[6]=e[t+6],Lt[7]=e[t+7],oc[0]}var f0=BigInt(Number.MAX_SAFE_INTEGER),l0=BigInt(Number.MIN_SAFE_INTEGER),Mt=class e{lo;hi;constructor(t,r){this.lo=t|0,this.hi=r|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?t<16384?t<128?1:2:t<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return sr;if(t<f0&&t>l0)return this.fromNumber(Number(t));let r=t<0n;r&&(t=-t);let n=t>>32n,o=t-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>Ml&&(o=0n,++n>Ml&&(n=0n))),new e(Number(o),Number(n))}static fromNumber(t){if(t===0)return sr;let r=t<0;r&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new e(n,o)}static from(t){return typeof t=="number"?e.fromNumber(t):typeof t=="bigint"?e.fromBigInt(t):typeof t=="string"?e.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new e(t.low>>>0,t.high>>>0):sr}},sr=new Mt(0,0);sr.toBigInt=function(){return 0n};sr.zzEncode=sr.zzDecode=function(){return this};sr.length=function(){return 1};var Ml=4294967296n;function Kl(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:(r&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Hl(e,t,r){if(r-t<1)return"";let o,s=[],i=0,a;for(;t<r;)a=e[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(e[t++]&63)<<6|e[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function sc(e,t,r){let n=r,o,s;for(let i=0;i<e.length;++i)o=e.charCodeAt(i),o<128?t[r++]=o:o<2048?(t[r++]=o>>6|192,t[r++]=o&63|128):(o&64512)===55296&&((s=e.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[r++]=o>>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=o&63|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=o&63|128);return r-n}function zt(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function ps(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}var ic=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,zt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw zt(this,4);return ps(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw zt(this,4);return ps(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw zt(this,4);let t=Nl(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw zt(this,4);let t=kl(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),r=this.pos,n=this.pos+t;if(n>this.len)throw zt(this,t);return this.pos+=t,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let t=this.bytes();return Hl(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw zt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw zt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Mt(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw zt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,t}if(this.len-this.pos>4){for(;r<5;++r)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;r<5;++r){if(this.pos>=this.len)throw zt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw zt(this,8);let t=ps(this.buf,this.pos+=4),r=ps(this.buf,this.pos+=4);return new Mt(t,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=hn(this.buf,this.pos);return this.pos+=et(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function ac(e){return new ic(e instanceof Uint8Array?e:e.subarray())}function ms(e,t,r){let n=ac(e);return t.decode(n,void 0,r)}function cc(e){let t=e??8192,r=t>>>1,n,o=t;return function(i){if(i<1||i>r)return it(i);o+i>t&&(n=it(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var ir=class{fn;len;next;val;constructor(t,r,n){this.fn=t,this.len=r,this.next=void 0,this.val=n}};function uc(){}var lc=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},h0=cc();function d0(e){return globalThis.Buffer!=null?it(e):h0(e)}var Un=class{len;head;tail;states;constructor(){this.len=0,this.head=new ir(uc,0,0),this.tail=this.head,this.states=null}_push(t,r,n){return this.tail=this.tail.next=new ir(t,r,n),this.len+=r,this}uint32(t){return this.len+=(this.tail=this.tail.next=new hc((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(gs,10,Mt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let r=Mt.fromBigInt(t);return this._push(gs,r.length(),r)}uint64Number(t){return this._push(_e,et(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let r=Mt.fromBigInt(t).zzEncode();return this._push(gs,r.length(),r)}sint64Number(t){let r=Mt.fromNumber(t).zzEncode();return this._push(gs,r.length(),r)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(fc,1,t?1:0)}fixed32(t){return this._push(Nn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let r=Mt.fromBigInt(t);return this._push(Nn,4,r.lo)._push(Nn,4,r.hi)}fixed64Number(t){let r=Mt.fromNumber(t);return this._push(Nn,4,r.lo)._push(Nn,4,r.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Ol,4,t)}double(t){return this._push(Ul,8,t)}bytes(t){let r=t.length>>>0;return r===0?this._push(fc,1,0):this.uint32(r)._push(m0,r,t)}string(t){let r=Kl(t);return r!==0?this.uint32(r)._push(sc,r,t):this._push(fc,1,0)}fork(){return this.states=new lc(this),this.head=this.tail=new ir(uc,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new ir(uc,0,0),this.len=0),this}ldelim(){let t=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=r,this.len+=n),this}finish(){let t=this.head.next,r=d0(this.len),n=0;for(;t!=null;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}};function fc(e,t,r){t[r]=e&255}function p0(e,t,r){for(;e>127;)t[r++]=e&127|128,e>>>=7;t[r]=e}var hc=class extends ir{next;constructor(t,r){super(p0,t,r),this.next=void 0}};function gs(e,t,r){for(;e.hi!==0;)t[r++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=e.lo&127|128,e.lo=e.lo>>>7;t[r++]=e.lo}function Nn(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function m0(e,t,r){t.set(e,r)}globalThis.Buffer!=null&&(Un.prototype.bytes=function(e){let t=e.length>>>0;return this.uint32(t),t>0&&this._push(g0,t,e),this},Un.prototype.string=function(e){let t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(y0,t,e),this});function g0(e,t,r){t.set(e,r)}function y0(e,t,r){e.length<40?sc(e,t,r):t.utf8Write!=null?t.utf8Write(e,r):t.set(q(e),r)}function dc(){return new Un}function ys(e,t){let r=dc();return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var kn;(function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(kn||(kn={}));function pc(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function bs(e,t){return pc("message",kn.LENGTH_DELIMITED,e,t)}var Mn=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ws;(function(e){let t;e.codec=()=>(t==null&&(t=bs((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.webtransportCerthashes!=null)for(let s of r.webtransportCerthashes)n.uint32(10),n.bytes(s);if(r.streamMuxers!=null)for(let s of r.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new Mn('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(r.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new Mn('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(r.string());break}default:{r.skipType(a&7);break}}}return s})),t),e.encode=r=>ys(r,e.codec()),e.decode=(r,n)=>ms(r,e.codec(),n)})(ws||(ws={}));var Kn;(function(e){let t;e.codec=()=>(t==null&&(t=bs((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.identityKey!=null&&r.identityKey.byteLength>0&&(n.uint32(10),n.bytes(r.identityKey)),r.identitySig!=null&&r.identitySig.byteLength>0&&(n.uint32(18),n.bytes(r.identitySig)),r.extensions!=null&&(n.uint32(34),ws.codec().encode(r.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={identityKey:pt(0),identitySig:pt(0)},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{s.identityKey=r.bytes();break}case 2:{s.identitySig=r.bytes();break}case 4:{s.extensions=ws.codec().decode(r,r.uint32(),{limits:o.limits?.extensions});break}default:{r.skipType(a&7);break}}}return s})),t),e.encode=r=>ys(r,e.codec()),e.decode=(r,n)=>ms(r,e.codec(),n)})(Kn||(Kn={}));async function gc(e,t,r){let n=await e.sign($l(t));return Kn.encode({identityKey:we(e.publicKey),identitySig:n,extensions:r})}async function yc(e,t,r){try{let n=Kn.decode(e),o=wn(n.identityKey);if(r?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${r}`);if(!t)throw new Error("Remote static does not exist");let s=$l(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Vn(n.message)}}function $l(e){let t=q("noise-libp2p-static-key:");return e instanceof Uint8Array?Tt([t,e],t.length+e.length):(e.prepend(t),e)}var mc=class extends Oe{stream;handshake;metrics;decoder;constructor(t,r,n){super({log:t.log,inactivityTimeout:t.inactivityTimeout,maxReadBufferLength:t.maxReadBufferLength,direction:t.direction}),this.stream=t,this.handshake=r,this.metrics=n,this.decoder=new jo({lengthDecoder:Vr,maxBufferSize:16*1024*1024,encodingLength:()=>2});let o=c=>{try{for(let u of this.decoder.decode(c.data))this.onData(this.decrypt(u))}catch(u){this.abort(u)}};this.stream.addEventListener("message",o);let s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(t){let r=new W;for(let n=0;n<t.byteLength;n+=65519){let o=n+65519;o>t.byteLength&&(o=t.byteLength);let s;t instanceof Uint8Array?s=this.handshake.encrypt(t.subarray(n,o)):s=this.handshake.encrypt(t.sublist(n,o)),this.metrics?.encryptedPackets.increment(),r.append(Fr(s.byteLength)),r.append(s)}return r}decrypt(t){let r=new W;for(let n=0;n<t.byteLength;n+=65535){let o=n+65535;if(o>t.byteLength&&(o=t.byteLength),o-Fa<n)throw new Error("Invalid chunk");let s;t instanceof Uint8Array?s=t.subarray(n,o):s=t.sublist(n,o);let i=t.subarray(n,o-Fa);try{let a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),r.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return r}close(t){return this.stream.close(t)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(t){this.stream.abort(t)}sendData(t){return{sentBytes:t.byteLength,canSendMore:this.stream.send(this.encrypt(t))}}};function bc(e,t,r){return new mc(e,t,r)}async function Wl(e,t){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:u}=e,f=await gc(s,a.publicKey,u),l=new On({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Za(l.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(l.writeMessageA(or),t),r.trace("Stage 0 - Initiator finished sending first message."),Qa(l.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");let d=l.readMessageB(await n.read(t));r.trace("Stage 1 - Initiator received the message."),Ja(l.re,r),Pl(l.rs,r),r.trace("Initiator going to check remote's signature...");let m=await yc(d,l.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(l.writeMessageC(f),t),r.trace("Stage 2 - Initiator sent message with signed payload.");let[p,E]=l.ss.split();return tc(p,E,r),{payload:m,encrypt:h=>p.encryptWithAd(or,h),decrypt:(h,b)=>E.decryptWithAd(or,h,b)}}async function ql(e,t){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:u}=e,f=await gc(s,a.publicKey,u),l=new On({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Za(l.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),l.readMessageA(await n.read(t)),r.trace("Stage 0 - Responder received first message."),Ja(l.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(l.writeMessageB(f),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Qa(l.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");let d=l.readMessageC(await n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");let m=await yc(d,l.rs,c),[p,E]=l.ss.split();return tc(p,E,r),{payload:m,encrypt:h=>E.encryptWithAd(or,h),decrypt:(h,b)=>p.decryptWithAd(or,h,b)}}var xs=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(t,r={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=r,{metrics:a}=t;this.components=t,this.log=t.logger.forComponent("libp2p:noise");let c=s??Dl;this.crypto=Tl(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?Rl(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??pt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[lr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,r){let n=t.log?.newScope("noise")??this.log,o=Go(t,{lengthEncoder:Fr,lengthDecoder:Vr,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=wn(s.payload.identityKey);return{connection:bc(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Qi(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(t){if(t==null||t.length===0)return;let r=this.components.upgrader.getStreamMuxers();if(r!=null)for(let n of t){let o=r.get(n);if(o!=null)return o}if(t.length)throw new $n("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(t,r){let n=t.log?.newScope("noise")??this.log,o=Go(t,{lengthEncoder:Fr,lengthDecoder:Vr,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=wn(s.payload.identityKey);return{connection:bc(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Qi(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(t,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Wl({connection:t,privateKey:r,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(t,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await ql({connection:t,privateKey:r,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function Gl(e={}){return t=>new xs(t,e)}var wc=Object.values(He).map(e=>e.decoder).reduce((e,t)=>e.or(t)),b0=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function zl(e){return e?.match(b0)?.groups?.fingerprint}function xc(e){let r=e.getComponents().find(n=>n.code===466)?.value;if(r===void 0||r==="")throw new Y(`Couldn't find a certhash component of multiaddr: ${e.toString()}`);return r}function w0(e){return Vt.decode(wc.decode(e))}function x0(e){let t=w0(xc(e)),r=E0(t.code),n=t.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new ns(n,e.toString());return`${r} ${o.join(":").toUpperCase()}`}function jl(e){let t=e.split(":").map(o=>parseInt(o,16)),r=Uint8Array.from(t),n=Dt(ee.code,r);return Or(`/certhash/${Zr.encode(n.bytes)}`)}function E0(e){switch(e){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new ss(e)}}function Xl(e,t){let{host:r,port:n,type:o}=Ba(e);if(o!=="ip4"&&o!=="ip6")throw new Y(`Multiaddr ${e} was not an IPv4 or IPv6 address`);let s=x0(e);return{type:"answer",sdp:`v=0
|
|
2
|
+
"use strict";var Libp2PWebrtc=(()=>{var Os=Object.defineProperty;var Sh=Object.getOwnPropertyDescriptor;var Ah=Object.getOwnPropertyNames;var vh=Object.prototype.hasOwnProperty;var Bt=(e,t)=>{for(var r in t)Os(e,r,{get:t[r],enumerable:!0})},Ch=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ah(t))!vh.call(e,o)&&o!==r&&Os(e,o,{get:()=>t[o],enumerable:!(n=Sh(t,o))||n.enumerable});return e};var _h=e=>Ch(Os({},"__esModule",{value:!0}),e);var Ym={};Bt(Ym,{webRTC:()=>Xm,webRTCDirect:()=>jm});var zn=class extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}},jn=class extends Error{static name="InvalidCryptoExchangeError";constructor(t="Invalid crypto exchange"){super(t),this.name="InvalidCryptoExchangeError"}},Y=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},lr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Xn=class extends Error{static name="ConnectionFailedError";constructor(t="Connection failed"){super(t),this.name="ConnectionFailedError"}},Yn=class extends Error{static name="MuxerClosedError";constructor(t="The muxer is closed"){super(t),this.name="MuxerClosedError"}},hr=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}};var zt=class extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}},Yr=class extends Error{static name="StreamBufferError";constructor(t="The stream buffer was full"){super(t),this.name="StreamBufferError"}};var Zn=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},Qn=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Jn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var to=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var We=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var eo=class extends Event{data;constructor(t,r){super("message",r),this.data=t}},dr=class extends Event{error;local;constructor(t,r,n){super("close",n),this.error=r,this.local=t}},ro=class extends dr{constructor(t,r){super(!0,t,r)}},no=class extends dr{constructor(t,r){super(!1,t,r)}};var Ns=Symbol.for("@libp2p/peer-id");var oo=Symbol.for("@libp2p/transport");var Vc;(function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"})(Vc||(Vc={}));function Lh(e){return typeof e?.handleEvent=="function"}function Ih(e){return(e!==!0&&e!==!1&&e?.once)??!1}var be=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let r=this.#t.get(t);return r==null?0:r.length}addEventListener(t,r,n){let o=Ih(n);super.addEventListener(t,i=>{if(o){let a=this.#t.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==r),this.#t.set(i.type,a))}Lh(r)?r.handleEvent(i):r(i)},n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:r,once:o})}removeEventListener(t,r,n){super.removeEventListener(t.toString(),r??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==r),this.#t.set(t,o))}safeDispatchEvent(t,r={}){return this.dispatchEvent(new CustomEvent(t,r))}};var pr=Symbol.for("@libp2p/service-capabilities"),$c=Symbol.for("@libp2p/service-dependencies");var Hs={};Bt(Hs,{base58btc:()=>ut,base58flickr:()=>Nh});var Ig=new Uint8Array(0);function Wc(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function Jt(e){if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}function Gc(e){return new TextEncoder().encode(e)}function qc(e){return new TextDecoder().decode(e)}function Bh(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<e.length;o++){var s=e.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=e.length,c=e.charAt(0),f=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var w=0,h=0,b=0,v=p.length;b!==v&&p[b]===0;)b++,w++;for(var E=(v-b)*l+1>>>0,D=new Uint8Array(E);b!==v;){for(var k=p[b],O=0,K=E-1;(k!==0||O<h)&&K!==-1;K--,O++)k+=256*D[K]>>>0,D[K]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");h=O,b++}for(var _=E-h;_!==E&&D[_]===0;)_++;for(var A=c.repeat(w);_<E;++_)A+=e.charAt(D[_]);return A}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var w=0;if(p[w]!==" "){for(var h=0,b=0;p[w]===c;)h++,w++;for(var v=(p.length-w)*f+1>>>0,E=new Uint8Array(v);p[w];){var D=r[p.charCodeAt(w)];if(D===255)return;for(var k=0,O=v-1;(D!==0||k<b)&&O!==-1;O--,k++)D+=a*E[O]>>>0,E[O]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");b=k,w++}if(p[w]!==" "){for(var K=v-b;K!==v&&E[K]===0;)K++;for(var _=new Uint8Array(h+(v-K)),A=h;K!==v;)_[A++]=E[K++];return _}}}function m(p){var w=d(p);if(w)return w;throw new Error(`Non-${t} character`)}return{encode:u,decodeUnsafe:d,decode:m}}var Dh=Bh,Th=Dh,jc=Th;var Us=class{name;prefix;baseEncode;constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},ks=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,r,n){this.name=t,this.prefix=r;let o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Xc(this,t)}},Ms=class{decoders;constructor(t){this.decoders=t}or(t){return Xc(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Xc(e,t){return new Ms({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var Ks=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Us(t,r,n),this.decoder=new ks(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function mr({name:e,prefix:t,encode:r,decode:n}){return new Ks(e,t,r,n)}function xe({name:e,prefix:t,alphabet:r}){let{encode:n,decode:o}=jc(r,e);return mr({prefix:t,name:e,encode:n,decode:s=>Jt(o(s))})}function Rh(e,t,r,n){let o=e.length;for(;e[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let l=t[e[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|l,i+=r,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Ph(e,t,r){let n=t[t.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],i+=8;i>r;)i-=r,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function Oh(e){let t={};for(let r=0;r<e.length;++r)t[e[r]]=r;return t}function ft({name:e,prefix:t,bitsPerChar:r,alphabet:n}){let o=Oh(n);return mr({prefix:t,name:e,encode(s){return Ph(s,n,r)},decode(s){return Rh(s,o,r,e)}})}var ut=xe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Nh=xe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Fs={};Bt(Fs,{base32:()=>we,base32hex:()=>Kh,base32hexpad:()=>Fh,base32hexpadupper:()=>Vh,base32hexupper:()=>Hh,base32pad:()=>kh,base32padupper:()=>Mh,base32upper:()=>Uh,base32z:()=>$h});var we=ft({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Uh=ft({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),kh=ft({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Mh=ft({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Kh=ft({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Hh=ft({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Fh=ft({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Vh=ft({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),$h=ft({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Vs={};Bt(Vs,{base36:()=>Zr,base36upper:()=>Wh});var Zr=xe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Wh=xe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ft={};Bt(Ft,{Digest:()=>Ge,create:()=>Dt,decode:()=>br,equals:()=>Ws,hasCode:()=>fd});var Gh=Qc,Yc=128,qh=127,zh=~qh,jh=Math.pow(2,31);function Qc(e,t,r){t=t||[],r=r||0;for(var n=r;e>=jh;)t[r++]=e&255|Yc,e/=128;for(;e&zh;)t[r++]=e&255|Yc,e>>>=7;return t[r]=e|0,Qc.bytes=r-n+1,t}var Xh=$s,Yh=128,Zc=127;function $s(e,n){var r=0,n=n||0,o=0,s=n,i,a=e.length;do{if(s>=a)throw $s.bytes=0,new RangeError("Could not decode varint");i=e[s++],r+=o<28?(i&Zc)<<o:(i&Zc)*Math.pow(2,o),o+=7}while(i>=Yh);return $s.bytes=s-n,r}var Zh=Math.pow(2,7),Qh=Math.pow(2,14),Jh=Math.pow(2,21),td=Math.pow(2,28),ed=Math.pow(2,35),rd=Math.pow(2,42),nd=Math.pow(2,49),od=Math.pow(2,56),sd=Math.pow(2,63),id=function(e){return e<Zh?1:e<Qh?2:e<Jh?3:e<td?4:e<ed?5:e<rd?6:e<nd?7:e<od?8:e<sd?9:10},ad={encode:Gh,decode:Xh,encodingLength:id},cd=ad,Qr=cd;function Jr(e,t=0){return[Qr.decode(e,t),Qr.decode.bytes]}function gr(e,t,r=0){return Qr.encode(e,t,r),t}function yr(e){return Qr.encodingLength(e)}function Dt(e,t){let r=t.byteLength,n=yr(e),o=n+yr(r),s=new Uint8Array(o+r);return gr(e,s,0),gr(r,s,n),s.set(t,o),new Ge(e,r,t,s)}function br(e){let t=Jt(e),[r,n]=Jr(t),[o,s]=Jr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Ge(r,o,i,t)}function Ws(e,t){if(e===t)return!0;{let r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&Wc(e.bytes,r.bytes)}}var Ge=class{code;size;digest;bytes;constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}};function fd(e,t){return e.code===t}function Jc(e,t){let{bytes:r,version:n}=e;return n===0?ld(r,Gs(e),t??ut.encoder):hd(r,Gs(e),t??we.encoder)}var tf=new WeakMap;function Gs(e){let t=tf.get(e);if(t==null){let r=new Map;return tf.set(e,r),r}return t}var dt=class e{code;version;multihash;bytes;"/";constructor(t,r,n,o){this.code=r,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:r}=this;if(t!==tn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==dd)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return e.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:r}=this.multihash,n=Dt(t,r);return e.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return e.equals(this,t)}static equals(t,r){let n=r;return n!=null&&t.code===n.code&&t.version===n.version&&Ws(t.multihash,n.multihash)}toString(t){return Jc(this,t)}toJSON(){return{"/":Jc(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let r=t;if(r instanceof e)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new e(n,o,s,i??ef(n,o,s.bytes))}else if(r[pd]===!0){let{version:n,multihash:o,code:s}=r,i=br(o);return e.create(n,s,i)}else return null}static create(t,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(r!==tn)throw new Error(`Version 0 CID must use dag-pb (code: ${tn}) block encoding`);return new e(t,r,n,n.bytes)}case 1:{let o=ef(t,r,n.bytes);return new e(t,r,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return e.create(0,tn,t)}static createV1(t,r){return e.create(1,t,r)}static decode(t){let[r,n]=e.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(t){let r=e.inspectBytes(t),n=r.size-r.multihashSize,o=Jt(t.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new Ge(r.multihashCode,r.digestSize,s,o);return[r.version===0?e.createV0(i):e.createV1(r.codec,i),t.subarray(r.size)]}static inspectBytes(t){let r=0,n=()=>{let[u,d]=Jr(t.subarray(r));return r+=d,u},o=n(),s=tn;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,a=n(),c=n(),f=r+c,l=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:f}}static parse(t,r){let[n,o]=ud(t,r),s=e.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Gs(s).set(n,t),s}};function ud(e,t){switch(e[0]){case"Q":{let r=t??ut;return[ut.prefix,r.decode(`${ut.prefix}${e}`)]}case ut.prefix:{let r=t??ut;return[ut.prefix,r.decode(e)]}case we.prefix:{let r=t??we;return[we.prefix,r.decode(e)]}case Zr.prefix:{let r=t??Zr;return[Zr.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}}function ld(e,t,r){let{prefix:n}=r;if(n!==ut.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=t.get(n);if(o==null){let s=r.encode(e).slice(1);return t.set(n,s),s}else return o}function hd(e,t,r){let{prefix:n}=r,o=t.get(n);if(o==null){let s=r.encode(e);return t.set(n,s),s}else return o}var tn=112,dd=18;function ef(e,t,r){let n=yr(e),o=n+yr(t),s=new Uint8Array(o+r.byteLength);return gr(e,s,0),gr(t,s,n),s.set(r,o),s}var pd=Symbol.for("@ipld/js-cid/CID");var qs={};Bt(qs,{identity:()=>Vt});var rf=0,md="identity",nf=Jt;function gd(e,t){if(t?.truncate!=null&&t.truncate!==e.byteLength){if(t.truncate<0||t.truncate>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,t.truncate)}return Dt(rf,nf(e))}var Vt={code:rf,name:md,encode:nf,digest:gd};function xt(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function pt(e=0){return new Uint8Array(e)}function it(e=0){return new Uint8Array(e)}function Tt(e,t){t==null&&(t=e.reduce((o,s)=>o+s.length,0));let r=it(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}var sf=Symbol.for("@achingbrain/uint8arraylist");function of(e,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let r=0;for(let n of e){let o=r+n.byteLength;if(t<o)return{buf:n,index:t-r};r=o}throw new RangeError("index is out of bounds")}function io(e){return!!e?.[sf]}var W=class e{bufs;length;[sf]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let r=0;for(let n of t)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(io(n))r+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...t){this.prependAll(t)}prependAll(t){let r=0;for(let n of t.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(io(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(t){let r=of(this.bufs,t);return r.buf[r.index]}set(t,r){let n=of(this.bufs,t);n.buf[n.index]=r}write(t,r=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(r+n,t[n]);else if(io(t))for(let n=0;n<t.length;n++)this.set(r+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,r){let{bufs:n,length:o}=this._subList(t,r);return Tt(n,o)}subarray(t,r){let{bufs:n,length:o}=this._subList(t,r);return n.length===1?n[0]:Tt(n,o)}sublist(t,r){let{bufs:n,length:o}=this._subList(t,r),s=new e;return s.length=o,s.bufs=[...n],s}_subList(t,r){if(t=t??0,r=r??this.length,t<0&&(t=this.length+t),r<0&&(r=this.length+r),t<0||r>this.length)throw new RangeError("index is out of bounds");if(t===r)return{bufs:[],length:0};if(t===0&&r===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let f=t>=a&&t<c,l=r>a&&r<=c;if(f&&l){if(t===a&&r===c){n.push(i);break}let u=t-a;n.push(i.subarray(u,u+(r-t)));break}if(f){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(l){if(r===c){n.push(i);break}n.push(i.subarray(0,r-a));break}n.push(i)}return{bufs:n,length:r-t}}indexOf(t,r=0){if(!io(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),t.length===0)return r>this.length?this.length:r;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let u=0;u<s;u++)i[u]=-1;for(let u=0;u<o;u++)i[n[u]]=u;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,l;for(let u=r;u<=c;u+=l){l=0;for(let d=f;d>=0;d--){let m=this.get(u+d);if(n[d]!==m){l=Math.max(1,d-a[m]);break}}if(l===0)return u}return-1}getInt8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(t,r){let n=it(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,t)}getInt16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(t,r,n){let o=pt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,t)}getInt32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(t,r,n){let o=pt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,t)}getBigInt64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(t,r,n){let o=pt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,t)}getUint8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(t,r){let n=it(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,t)}getUint16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(t,r,n){let o=pt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,t)}getUint32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(t,r,n){let o=pt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,t)}getBigUint64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(t,r,n){let o=pt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,t)}getFloat32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(t,r,n){let o=pt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,t)}getFloat64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(t,r,n){let o=pt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof e)||t.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!xt(this.bufs[r],t.bufs[r]))return!1;return!0}static fromUint8Arrays(t,r){let n=new e;return n.bufs=t,r==null&&(r=t.reduce((o,s)=>o+s.byteLength,0)),n.length=r,n}};var zs={};Bt(zs,{base10:()=>bd});var bd=xe({prefix:"9",name:"base10",alphabet:"0123456789"});var js={};Bt(js,{base16:()=>xd,base16upper:()=>wd});var xd=ft({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),wd=ft({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Xs={};Bt(Xs,{base2:()=>Ed});var Ed=ft({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ys={};Bt(Ys,{base256emoji:()=>_d});var af=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Sd=af.reduce((e,t,r)=>(e[r]=t,e),[]),Ad=af.reduce((e,t,r)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return e[n]=r,e},[]);function vd(e){return e.reduce((t,r)=>(t+=Sd[r],t),"")}function Cd(e){let t=[];for(let r of e){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=Ad[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);t.push(o)}return new Uint8Array(t)}var _d=mr({prefix:"\u{1F680}",name:"base256emoji",encode:vd,decode:Cd});var Zs={};Bt(Zs,{base64:()=>Ld,base64pad:()=>Id,base64url:()=>en,base64urlpad:()=>Bd});var Ld=ft({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Id=ft({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),en=ft({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Bd=ft({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Qs={};Bt(Qs,{base8:()=>Dd});var Dd=ft({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Js={};Bt(Js,{identity:()=>Td});var Td=mr({prefix:"\0",name:"identity",encode:e=>qc(e),decode:e=>Gc(e)});var uy=new TextEncoder,ly=new TextDecoder;var ri={};Bt(ri,{sha256:()=>te,sha512:()=>Nd});var Od=20;function ei({name:e,code:t,encode:r,minDigestLength:n,maxDigestLength:o}){return new ti(e,t,r,n,o)}var ti=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,r,n,o,s){this.name=t,this.code=r,this.encode=n,this.minDigestLength=o??Od,this.maxDigestLength=s}digest(t,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?cf(n,this.code,r?.truncate):n.then(o=>cf(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function cf(e,t,r){if(r!=null&&r!==e.byteLength){if(r>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,r)}return Dt(t,e)}function uf(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}var te=ei({name:"sha2-256",code:18,encode:uf("SHA-256")}),Nd=ei({name:"sha2-512",code:19,encode:uf("SHA-512")});var qe={...Js,...Xs,...Qs,...zs,...js,...Fs,...Vs,...Hs,...Zs,...Ys},Ay={...ri,...qs};function hf(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}var lf=hf("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),ni=hf("ascii","a",e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},e=>{e=e.substring(1);let t=it(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}),Ud={utf8:lf,"utf-8":lf,hex:qe.base16,latin1:ni,ascii:ni,binary:ni,...qe},ao=Ud;function G(e,t="utf8"){let r=ao[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}function $(e,t="utf8"){let r=ao[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}var kd=parseInt("11111",2),oi=parseInt("10000000",2),Md=parseInt("01111111",2),df={0:rn,1:rn,2:Kd,3:Vd,4:$d,5:Fd,6:Hd,16:rn,22:rn,48:rn};function ee(e,t={offset:0}){let r=e[t.offset]&kd;if(t.offset++,df[r]!=null)return df[r](e,t);throw new Error("No decoder for tag "+r)}function nn(e,t){let r=0;if((e[t.offset]&oi)===oi){let n=e[t.offset]&Md,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(o,16)}else r=e[t.offset],t.offset++;return r}function rn(e,t){nn(e,t);let r=[];for(;!(t.offset>=e.byteLength);){let n=ee(e,t);if(n===null)break;r.push(n)}return r}function Kd(e,t){let r=nn(e,t),n=t.offset,o=t.offset+r,s=[];for(let i=n;i<o;i++)i===n&&e[i]===0||s.push(e[i]);return t.offset+=r,Uint8Array.from(s)}function Hd(e,t){let r=nn(e,t),n=t.offset+r,o=e[t.offset];t.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;t.offset<n;){let f=e[t.offset];if(t.offset++,c.push(f&127),f<128){c.reverse();let l=0;for(let u=0;u<c.length;u++)l+=c[u]<<u*7;a+=`.${l}`,c=[]}}return a}function Fd(e,t){return t.offset++,null}function Vd(e,t){let r=nn(e,t),n=e[t.offset];t.offset++;let o=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function $d(e,t){let r=nn(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n}function Wd(e){let t=e.toString(16);t.length%2===1&&(t="0"+t);let r=new W;for(let n=0;n<t.length;n+=2)r.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return r}function si(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);let t=Wd(e.byteLength);return new W(Uint8Array.from([t.byteLength|oi]),t)}function Pt(e){let t=new W,r=128;return(e.subarray()[0]&r)===r&&t.append(Uint8Array.from([0])),t.append(e),new W(Uint8Array.from([2]),si(t),t)}function co(e){let t=Uint8Array.from([0]),r=new W(t,e);return new W(Uint8Array.from([3]),si(r),r)}function Ee(e,t=48){let r=new W;for(let n of e)r.append(n);return new W(Uint8Array.from([t]),si(r),r)}async function pf(e,t,r,n){let o=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,r.subarray());return n?.signal?.throwIfAborted(),s}var Gd=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),qd=Uint8Array.from([6,5,43,129,4,0,34]),zd=Uint8Array.from([6,5,43,129,4,0,35]),jd={ext:!0,kty:"EC",crv:"P-256"},Xd={ext:!0,kty:"EC",crv:"P-384"},Yd={ext:!0,kty:"EC",crv:"P-521"},ii=32,ai=48,ci=66;function fi(e){let t=ee(e);return mf(t)}function mf(e){let t=e[1][1][0],r=1,n,o;if(t.byteLength===ii*2+1)return n=$(t.subarray(r,r+ii),"base64url"),o=$(t.subarray(r+ii),"base64url"),new xr({...jd,key_ops:["verify"],x:n,y:o});if(t.byteLength===ai*2+1)return n=$(t.subarray(r,r+ai),"base64url"),o=$(t.subarray(r+ai),"base64url"),new xr({...Xd,key_ops:["verify"],x:n,y:o});if(t.byteLength===ci*2+1)return n=$(t.subarray(r,r+ci),"base64url"),o=$(t.subarray(r+ci),"base64url"),new xr({...Yd,key_ops:["verify"],x:n,y:o});throw new Y(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function gf(e){return Ee([Pt(Uint8Array.from([1])),Ee([Zd(e.crv)],160),Ee([co(new W(Uint8Array.from([4]),G(e.x??"","base64url"),G(e.y??"","base64url")))],161)]).subarray()}function Zd(e){if(e==="P-256")return Gd;if(e==="P-384")return qd;if(e==="P-521")return zd;throw new Y(`Invalid curve ${e}`)}var xr=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=gf(this.jwk)),this._raw}toMultihash(){return Vt.digest(Se(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return ut.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:xt(this.raw,t.raw)}async verify(t,r,n){return pf(this.jwk,r,t,n)}};function ze(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function jt(e,t=""){if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw new Error(`${r}expected integer >= 0, got ${e}`)}}function F(e,t,r=""){let n=ze(e),o=e?.length,s=t!==void 0;if(!n||s&&o!==t){let i=r&&`"${r}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function fo(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash must wrapped by utils.createHasher");jt(e.outputLen),jt(e.blockLen)}function wr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function bf(e,t){F(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function ne(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function uo(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function $t(e,t){return e<<32-t|e>>>t}var xf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qd=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function oe(e){if(F(e),xf)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Qd[e[r]];return t}var re={_0:48,_9:57,A:65,F:70,a:97,f:102};function yf(e){if(e>=re._0&&e<=re._9)return e-re._0;if(e>=re.A&&e<=re.F)return e-(re.A-10);if(e>=re.a&&e<=re.f)return e-(re.a-10)}function se(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(xf)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=yf(e.charCodeAt(s)),a=yf(e.charCodeAt(s+1));if(i===void 0||a===void 0){let c=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ot(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];F(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let s=e[n];r.set(s,o),o+=s.length}return r}function ui(e,t={}){let r=(o,s)=>e(s).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.create=o=>e(o),Object.assign(r,t),Object.freeze(r)}function Ae(e=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}var li=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function wf(e,t,r){return e&t^~e&r}function Ef(e,t,r){return e&t^e&r^t&r}var on=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,r,n,o){this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=uo(this.buffer)}update(t){wr(this),F(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=uo(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){wr(this),bf(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,ne(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let u=i;u<o;u++)r[u]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=uo(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,l=this.get();if(f>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<f;u++)a.setUint32(4*u,l[u],s)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ie=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var wt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var lo=BigInt(4294967295),Sf=BigInt(32);function Jd(e,t=!1){return t?{h:Number(e&lo),l:Number(e>>Sf&lo)}:{h:Number(e>>Sf&lo)|0,l:Number(e&lo)|0}}function Af(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=Jd(e[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var hi=(e,t,r)=>e>>>r,di=(e,t,r)=>e<<32-r|t>>>r,je=(e,t,r)=>e>>>r|t<<32-r,Xe=(e,t,r)=>e<<32-r|t>>>r,sn=(e,t,r)=>e<<64-r|t>>>r-32,an=(e,t,r)=>e>>>r-32|t<<64-r;function Xt(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var vf=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Cf=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,_f=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Lf=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,If=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),Bf=(e,t,r,n,o,s)=>t+r+n+o+s+(e/2**32|0)|0;var ep=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]),ve=new Uint32Array(64),pi=class extends on{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,r,n,o,s,i,a,c]}set(t,r,n,o,s,i,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,r){for(let u=0;u<16;u++,r+=4)ve[u]=t.getUint32(r,!1);for(let u=16;u<64;u++){let d=ve[u-15],m=ve[u-2],p=$t(d,7)^$t(d,18)^d>>>3,w=$t(m,17)^$t(m,19)^m>>>10;ve[u]=w+ve[u-7]+p+ve[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:f,H:l}=this;for(let u=0;u<64;u++){let d=$t(a,6)^$t(a,11)^$t(a,25),m=l+d+wf(a,c,f)+ep[u]+ve[u]|0,w=($t(n,2)^$t(n,13)^$t(n,22))+Ef(n,o,s)|0;l=f,f=c,c=a,a=i+m|0,i=s,s=o,o=n,n=m+w|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,f,l)}roundClean(){ne(ve)}destroy(){this.set(0,0,0,0,0,0,0,0),ne(this.buffer)}},mi=class extends pi{A=ie[0]|0;B=ie[1]|0;C=ie[2]|0;D=ie[3]|0;E=ie[4]|0;F=ie[5]|0;G=ie[6]|0;H=ie[7]|0;constructor(){super(32)}};var Df=Af(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),rp=Df[0],np=Df[1],Ce=new Uint32Array(80),_e=new Uint32Array(80),gi=class extends on{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:l,Fh:u,Fl:d,Gh:m,Gl:p,Hh:w,Hl:h}=this;return[t,r,n,o,s,i,a,c,f,l,u,d,m,p,w,h]}set(t,r,n,o,s,i,a,c,f,l,u,d,m,p,w,h){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=f|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=m|0,this.Gl=p|0,this.Hh=w|0,this.Hl=h|0}process(t,r){for(let E=0;E<16;E++,r+=4)Ce[E]=t.getUint32(r),_e[E]=t.getUint32(r+=4);for(let E=16;E<80;E++){let D=Ce[E-15]|0,k=_e[E-15]|0,O=je(D,k,1)^je(D,k,8)^hi(D,k,7),K=Xe(D,k,1)^Xe(D,k,8)^di(D,k,7),_=Ce[E-2]|0,A=_e[E-2]|0,N=je(_,A,19)^sn(_,A,61)^hi(_,A,6),M=Xe(_,A,19)^an(_,A,61)^di(_,A,6),T=_f(K,M,_e[E-7],_e[E-16]),x=Lf(T,O,N,Ce[E-7],Ce[E-16]);Ce[E]=x|0,_e[E]=T|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:l,Eh:u,El:d,Fh:m,Fl:p,Gh:w,Gl:h,Hh:b,Hl:v}=this;for(let E=0;E<80;E++){let D=je(u,d,14)^je(u,d,18)^sn(u,d,41),k=Xe(u,d,14)^Xe(u,d,18)^an(u,d,41),O=u&m^~u&w,K=d&p^~d&h,_=If(v,k,K,np[E],_e[E]),A=Bf(_,b,D,O,rp[E],Ce[E]),N=_|0,M=je(n,o,28)^sn(n,o,34)^sn(n,o,39),T=Xe(n,o,28)^an(n,o,34)^an(n,o,39),x=n&s^n&a^s&a,g=o&i^o&c^i&c;b=w|0,v=h|0,w=m|0,h=p|0,m=u|0,p=d|0,{h:u,l:d}=Xt(f|0,l|0,A|0,N|0),f=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let y=vf(N,T,g);n=Cf(y,A,M,x),o=y|0}({h:n,l:o}=Xt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Xt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Xt(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l}=Xt(this.Dh|0,this.Dl|0,f|0,l|0),{h:u,l:d}=Xt(this.Eh|0,this.El|0,u|0,d|0),{h:m,l:p}=Xt(this.Fh|0,this.Fl|0,m|0,p|0),{h:w,l:h}=Xt(this.Gh|0,this.Gl|0,w|0,h|0),{h:b,l:v}=Xt(this.Hh|0,this.Hl|0,b|0,v|0),this.set(n,o,s,i,a,c,f,l,u,d,m,p,w,h,b,v)}roundClean(){ne(Ce,_e)}destroy(){ne(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},yi=class extends gi{Ah=wt[0]|0;Al=wt[1]|0;Bh=wt[2]|0;Bl=wt[3]|0;Ch=wt[4]|0;Cl=wt[5]|0;Dh=wt[6]|0;Dl=wt[7]|0;Eh=wt[8]|0;El=wt[9]|0;Fh=wt[10]|0;Fl=wt[11]|0;Gh=wt[12]|0;Gl=wt[13]|0;Hh=wt[14]|0;Hl=wt[15]|0;constructor(){super(64)}};var Tf=ui(()=>new mi,li(1));var Rf=ui(()=>new yi,li(3));var xi=BigInt(0),bi=BigInt(1);function ae(e,t=""){if(typeof e!="boolean"){let r=t&&`"${t}" `;throw new Error(r+"expected boolean, got type="+typeof e)}return e}function Pf(e){if(typeof e=="bigint"){if(!ho(e))throw new Error("positive bigint expected, got "+e)}else jt(e);return e}function cn(e){let t=Pf(e).toString(16);return t.length&1?"0"+t:t}function Of(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?xi:BigInt("0x"+e)}function Er(e){return Of(oe(e))}function Yt(e){return Of(oe(Ye(F(e)).reverse()))}function po(e,t){jt(t),e=Pf(e);let r=se(e.toString(16).padStart(t*2,"0"));if(r.length!==t)throw new Error("number too large");return r}function fn(e,t){return po(e,t).reverse()}function Ye(e){return Uint8Array.from(e)}var ho=e=>typeof e=="bigint"&&xi<=e;function op(e,t,r){return ho(e)&&ho(t)&&ho(r)&&t<=e&&e<r}function Le(e,t,r,n){if(!op(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function wi(e){let t;for(t=0;e>xi;e>>=bi,t+=1);return t}var un=e=>(bi<<BigInt(e))-bi;function Nf(e,t,r){if(jt(e,"hashLen"),jt(t,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");let n=h=>new Uint8Array(h),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(e),f=n(e),l=0,u=()=>{c.fill(1),f.fill(0),l=0},d=(...h)=>r(f,Ot(c,...h)),m=(h=o)=>{f=d(s,h),c=d(),h.length!==0&&(f=d(i,h),c=d())},p=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let h=0,b=[];for(;h<t;){c=d();let v=c.slice();b.push(v),h+=c.length}return Ot(...b)};return(h,b)=>{u(),m(h);let v;for(;!(v=b(p()));)m();return u(),v}}function Zt(e,t={},r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(s,i,a){let c=e[s];if(a&&c===void 0)return;let f=typeof c;if(f!==i||c===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${f}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(t,!1),o(r,!0)}function Sr(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}var Rt=BigInt(0),mt=BigInt(1),Ze=BigInt(2),Mf=BigInt(3),Kf=BigInt(4),Hf=BigInt(5),sp=BigInt(7),Ff=BigInt(8),ip=BigInt(9),Vf=BigInt(16);function at(e,t){let r=e%t;return r>=Rt?r:t+r}function st(e,t,r){let n=e;for(;t-- >Rt;)n*=n,n%=r;return n}function Uf(e,t){if(e===Rt)throw new Error("invert: expected non-zero number");if(t<=Rt)throw new Error("invert: expected positive modulus, got "+t);let r=at(e,t),n=t,o=Rt,s=mt,i=mt,a=Rt;for(;r!==Rt;){let f=n/r,l=n%r,u=o-i*f,d=s-a*f;n=r,r=l,o=i,s=a,i=u,a=d}if(n!==mt)throw new Error("invert: does not exist");return at(o,t)}function Si(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function $f(e,t){let r=(e.ORDER+mt)/Kf,n=e.pow(t,r);return Si(e,n,t),n}function ap(e,t){let r=(e.ORDER-Hf)/Ff,n=e.mul(t,Ze),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,Ze),o),a=e.mul(s,e.sub(i,e.ONE));return Si(e,a,t),a}function cp(e){let t=Ar(e),r=Wf(e),n=r(t,t.neg(t.ONE)),o=r(t,n),s=r(t,t.neg(n)),i=(e+sp)/Vf;return(a,c)=>{let f=a.pow(c,i),l=a.mul(f,n),u=a.mul(f,o),d=a.mul(f,s),m=a.eql(a.sqr(l),c),p=a.eql(a.sqr(u),c);f=a.cmov(f,l,m),l=a.cmov(d,u,p);let w=a.eql(a.sqr(l),c),h=a.cmov(f,l,w);return Si(a,h,c),h}}function Wf(e){if(e<Mf)throw new Error("sqrt is not defined for small field");let t=e-mt,r=0;for(;t%Ze===Rt;)t/=Ze,r++;let n=Ze,o=Ar(e);for(;kf(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return $f;let s=o.pow(n,t),i=(t+mt)/Ze;return function(c,f){if(c.is0(f))return f;if(kf(c,f)!==1)throw new Error("Cannot find square root");let l=r,u=c.mul(c.ONE,s),d=c.pow(f,t),m=c.pow(f,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,w=c.sqr(d);for(;!c.eql(w,c.ONE);)if(p++,w=c.sqr(w),p===l)throw new Error("Cannot find square root");let h=mt<<BigInt(l-p-1),b=c.pow(u,h);l=p,u=c.sqr(b),d=c.mul(d,u),m=c.mul(m,b)}return m}}function fp(e){return e%Kf===Mf?$f:e%Ff===Hf?ap:e%Vf===ip?cp(e):Wf(e)}var Gf=(e,t)=>(at(e,t)&mt)===mt,up=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ai(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=up.reduce((n,o)=>(n[o]="function",n),t);return Zt(e,r),e}function lp(e,t,r){if(r<Rt)throw new Error("invalid exponent, negatives unsupported");if(r===Rt)return e.ONE;if(r===mt)return t;let n=e.ONE,o=t;for(;r>Rt;)r&mt&&(n=e.mul(n,o)),o=e.sqr(o),r>>=mt;return n}function ln(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function kf(e,t){let r=(e.ORDER-mt)/Ze,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function hp(e,t){t!==void 0&&jt(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var Ei=class{ORDER;BITS;BYTES;isLE;ZERO=Rt;ONE=mt;_lengths;_sqrt;_mod;constructor(t,r={}){if(t<=Rt)throw new Error("invalid field: expected ORDER > 0, got "+t);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=r.allowedLengths?.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:o,nByteLength:s}=hp(t,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(t){return at(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof t);return Rt<=t&&t<this.ORDER}is0(t){return t===Rt}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&mt)===mt}neg(t){return at(-t,this.ORDER)}eql(t,r){return t===r}sqr(t){return at(t*t,this.ORDER)}add(t,r){return at(t+r,this.ORDER)}sub(t,r){return at(t-r,this.ORDER)}mul(t,r){return at(t*r,this.ORDER)}pow(t,r){return lp(this,t,r)}div(t,r){return at(t*Uf(r,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,r){return t+r}subN(t,r){return t-r}mulN(t,r){return t*r}inv(t){return Uf(t,this.ORDER)}sqrt(t){return this._sqrt||(this._sqrt=fp(this.ORDER)),this._sqrt(this,t)}toBytes(t){return this.isLE?fn(t,this.BYTES):po(t,this.BYTES)}fromBytes(t,r=!1){F(t);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let f=new Uint8Array(o);f.set(t,s?0:f.length-t.length),t=f}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=s?Yt(t):Er(t);if(a&&(c=at(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return ln(this,t)}cmov(t,r,n){return n?r:t}};function Ar(e,t={}){return new Ei(e,t)}function qf(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function vi(e){let t=qf(e);return t+Math.ceil(t/2)}function Ci(e,t,r=!1){F(e);let n=e.length,o=qf(t),s=vi(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?Yt(e):Er(e),a=at(i,t-mt)+mt;return r?fn(a,o):po(a,o)}var vr=BigInt(0),Qe=BigInt(1);function hn(e,t){let r=t.negate();return e?r:t}function Je(e,t){let r=ln(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function Yf(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function _i(e,t){Yf(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=un(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function zf(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=Qe);let f=t*n,l=f+Math.abs(a)-1,u=a===0,d=a<0,m=t%2!==0;return{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:m,offsetF:f}}var Li=new WeakMap,Zf=new WeakMap;function Ii(e){return Zf.get(e)||1}function jf(e){if(e!==vr)throw new Error("invalid wNAF")}var Cr=class{BASE;ZERO;Fn;bits;constructor(t,r){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=r}_unsafeLadder(t,r,n=this.ZERO){let o=t;for(;r>vr;)r&Qe&&(n=n.add(o)),o=o.double(),r>>=Qe;return n}precomputeWindow(t,r){let{windows:n,windowSize:o}=_i(r,this.bits),s=[],i=t,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let f=1;f<o;f++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(t,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=_i(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:l,isNeg:u,isNegF:d,offsetF:m}=zf(n,a,i);n=c,l?s=s.add(hn(d,r[m])):o=o.add(hn(u,r[f]))}return jf(n),{p:o,f:s}}wNAFUnsafe(t,r,n,o=this.ZERO){let s=_i(t,this.bits);for(let i=0;i<s.windows&&n!==vr;i++){let{nextN:a,offset:c,isZero:f,isNeg:l}=zf(n,i,s);if(n=a,!f){let u=r[c];o=o.add(l?u.negate():u)}}return jf(n),o}getPrecomputes(t,r,n){let o=Li.get(r);return o||(o=this.precomputeWindow(r,t),t!==1&&(typeof n=="function"&&(o=n(o)),Li.set(r,o))),o}cached(t,r,n){let o=Ii(t);return this.wNAF(o,this.getPrecomputes(o,t,n),r)}unsafe(t,r,n,o){let s=Ii(t);return s===1?this._unsafeLadder(t,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),r,o)}createCache(t,r){Yf(r,this.bits),Zf.set(t,r),Li.delete(t)}hasCache(t){return Ii(t)!==1}};function Qf(e,t,r,n){let o=t,s=e.ZERO,i=e.ZERO;for(;r>vr||n>vr;)r&Qe&&(s=s.add(o)),n&Qe&&(i=i.add(o)),o=o.double(),r>>=Qe,n>>=Qe;return{p1:s,p2:i}}function Xf(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ai(t),t}else return Ar(e,{isLE:r})}function mo(e,t,r={},n){if(n===void 0&&(n=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let f=t[c];if(!(typeof f=="bigint"&&f>vr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Xf(t.p,r.Fp,n),s=Xf(t.n,r.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function _r(e,t){return function(n){let o=e(n);return{secretKey:o,publicKey:t(o)}}}var Ie=BigInt(0),gt=BigInt(1),Bi=BigInt(2),dp=BigInt(8);function pp(e,t,r,n){let o=e.sqr(r),s=e.sqr(n),i=e.add(e.mul(t.a,o),s),a=e.add(e.ONE,e.mul(t.d,e.mul(o,s)));return e.eql(i,a)}function Jf(e,t={}){let r=mo("edwards",e,t,t.FpFnLE),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i}=s;Zt(t,{},{uvRatio:"function"});let a=Bi<<BigInt(o.BYTES*8)-gt,c=h=>n.create(h),f=t.uvRatio||((h,b)=>{try{return{isValid:!0,value:n.sqrt(n.div(h,b))}}catch{return{isValid:!1,value:Ie}}});if(!pp(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function l(h,b,v=!1){let E=v?gt:Ie;return Le("coordinate "+h,b,E,a),b}function u(h){if(!(h instanceof p))throw new Error("EdwardsPoint expected")}let d=Sr((h,b)=>{let{X:v,Y:E,Z:D}=h,k=h.is0();b==null&&(b=k?dp:n.inv(D));let O=c(v*b),K=c(E*b),_=n.mul(D,b);if(k)return{x:Ie,y:gt};if(_!==gt)throw new Error("invZ was invalid");return{x:O,y:K}}),m=Sr(h=>{let{a:b,d:v}=s;if(h.is0())throw new Error("bad point: ZERO");let{X:E,Y:D,Z:k,T:O}=h,K=c(E*E),_=c(D*D),A=c(k*k),N=c(A*A),M=c(K*b),T=c(A*c(M+_)),x=c(N+c(v*c(K*_)));if(T!==x)throw new Error("bad point: equation left != right (1)");let g=c(E*D),y=c(k*O);if(g!==y)throw new Error("bad point: equation left != right (2)");return!0});class p{static BASE=new p(s.Gx,s.Gy,gt,c(s.Gx*s.Gy));static ZERO=new p(Ie,gt,gt,Ie);static Fp=n;static Fn=o;X;Y;Z;T;constructor(b,v,E,D){this.X=l("x",b),this.Y=l("y",v),this.Z=l("z",E,!0),this.T=l("t",D),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){if(b instanceof p)throw new Error("extended point not allowed");let{x:v,y:E}=b||{};return l("x",v),l("y",E),new p(v,E,gt,c(v*E))}static fromBytes(b,v=!1){let E=n.BYTES,{a:D,d:k}=s;b=Ye(F(b,E,"point")),ae(v,"zip215");let O=Ye(b),K=b[E-1];O[E-1]=K&-129;let _=Yt(O),A=v?a:n.ORDER;Le("point.y",_,Ie,A);let N=c(_*_),M=c(N-gt),T=c(k*N-D),{isValid:x,value:g}=f(M,T);if(!x)throw new Error("bad point: invalid y coordinate");let y=(g>)===gt,C=(K&128)!==0;if(!v&&g===Ie&&C)throw new Error("bad point: x=0 and x_0=1");return C!==y&&(g=c(-g)),p.fromAffine({x:g,y:_})}static fromHex(b,v=!1){return p.fromBytes(se(b),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,v=!0){return w.createCache(this,b),v||this.multiply(Bi),this}assertValidity(){m(this)}equals(b){u(b);let{X:v,Y:E,Z:D}=this,{X:k,Y:O,Z:K}=b,_=c(v*K),A=c(k*D),N=c(E*K),M=c(O*D);return _===A&&N===M}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:b}=s,{X:v,Y:E,Z:D}=this,k=c(v*v),O=c(E*E),K=c(Bi*c(D*D)),_=c(b*k),A=v+E,N=c(c(A*A)-k-O),M=_+O,T=M-K,x=_-O,g=c(N*T),y=c(M*x),C=c(N*x),I=c(T*M);return new p(g,y,I,C)}add(b){u(b);let{a:v,d:E}=s,{X:D,Y:k,Z:O,T:K}=this,{X:_,Y:A,Z:N,T:M}=b,T=c(D*_),x=c(k*A),g=c(K*E*M),y=c(O*N),C=c((D+k)*(_+A)-T-x),I=y-g,L=y+g,S=c(x-v*T),B=c(C*I),R=c(L*S),P=c(C*S),j=c(I*L);return new p(B,R,j,P)}subtract(b){return this.add(b.negate())}multiply(b){if(!o.isValidNot0(b))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:E}=w.cached(this,b,D=>Je(p,D));return Je(p,[v,E])[0]}multiplyUnsafe(b,v=p.ZERO){if(!o.isValid(b))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return b===Ie?p.ZERO:this.is0()||b===gt?this:w.unsafe(this,b,E=>Je(p,E),v)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return w.unsafe(this,s.n).is0()}toAffine(b){return d(this,b)}clearCofactor(){return i===gt?this:this.multiplyUnsafe(i)}toBytes(){let{x:b,y:v}=this.toAffine(),E=n.toBytes(v);return E[E.length-1]|=b>?128:0,E}toHex(){return oe(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let w=new Cr(p,o.BITS);return p.BASE.precompute(8),p}function tu(e,t,r={}){if(typeof t!="function")throw new Error('"hash" function param is required');Zt(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=r,{BASE:o,Fp:s,Fn:i}=e,a=r.randomBytes||Ae,c=r.adjustScalarBytes||(_=>_),f=r.domain||((_,A,N)=>{if(ae(N,"phflag"),A.length||N)throw new Error("Contexts/pre-hash are not supported");return _});function l(_){return i.create(Yt(_))}function u(_){let A=E.secretKey;F(_,E.secretKey,"secretKey");let N=F(t(_),2*A,"hashedSecretKey"),M=c(N.slice(0,A)),T=N.slice(A,2*A),x=l(M);return{head:M,prefix:T,scalar:x}}function d(_){let{head:A,prefix:N,scalar:M}=u(_),T=o.multiply(M),x=T.toBytes();return{head:A,prefix:N,scalar:M,point:T,pointBytes:x}}function m(_){return d(_).pointBytes}function p(_=Uint8Array.of(),...A){let N=Ot(...A);return l(t(f(N,F(_,void 0,"context"),!!n)))}function w(_,A,N={}){_=F(_,void 0,"message"),n&&(_=n(_));let{prefix:M,scalar:T,pointBytes:x}=d(A),g=p(N.context,M,_),y=o.multiply(g).toBytes(),C=p(N.context,y,x,_),I=i.create(g+C*T);if(!i.isValid(I))throw new Error("sign failed: invalid s");let L=Ot(y,i.toBytes(I));return F(L,E.signature,"result")}let h={zip215:!0};function b(_,A,N,M=h){let{context:T,zip215:x}=M,g=E.signature;_=F(_,g,"signature"),A=F(A,void 0,"message"),N=F(N,E.publicKey,"publicKey"),x!==void 0&&ae(x,"zip215"),n&&(A=n(A));let y=g/2,C=_.subarray(0,y),I=Yt(_.subarray(y,g)),L,S,B;try{L=e.fromBytes(N,x),S=e.fromBytes(C,x),B=o.multiplyUnsafe(I)}catch{return!1}if(!x&&L.isSmallOrder())return!1;let R=p(T,S.toBytes(),L.toBytes(),A);return S.add(L.multiplyUnsafe(R)).subtract(B).clearCofactor().is0()}let v=s.BYTES,E={secretKey:v,publicKey:v,signature:2*v,seed:v};function D(_=a(E.seed)){return F(_,E.seed,"seed")}function k(_){return ze(_)&&_.length===i.BYTES}function O(_,A){try{return!!e.fromBytes(_,A)}catch{return!1}}let K={getExtendedPublicKey:d,randomSecretKey:D,isValidSecretKey:k,isValidPublicKey:O,toMontgomery(_){let{y:A}=e.fromBytes(_),N=E.publicKey,M=N===32;if(!M&&N!==57)throw new Error("only defined for 25519 and 448");let T=M?s.div(gt+A,gt-A):s.div(A-gt,A+gt);return s.toBytes(T)},toMontgomerySecret(_){let A=E.secretKey;F(_,A);let N=t(_.subarray(0,A));return c(N).subarray(0,A)}};return Object.freeze({keygen:_r(D,m),getPublicKey:m,sign:w,verify:b,utils:K,Point:e,lengths:E})}var dn=BigInt(0),Lr=BigInt(1),go=BigInt(2);function mp(e){return Zt(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function eu(e){let t=mp(e),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=t,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||Ae,f=a?255:448,l=a?32:56,u=BigInt(a?9:5),d=BigInt(a?121665:39081),m=a?go**BigInt(254):go**BigInt(447),p=a?BigInt(8)*go**BigInt(251)-Lr:BigInt(4)*go**BigInt(445)-Lr,w=m+p+Lr,h=g=>at(g,r),b=v(u);function v(g){return fn(h(g),l)}function E(g){let y=Ye(F(g,l,"uCoordinate"));return a&&(y[31]&=127),h(Yt(y))}function D(g){return Yt(o(Ye(F(g,l,"scalar"))))}function k(g,y){let C=N(E(y),D(g));if(C===dn)throw new Error("invalid private or public key received");return v(C)}function O(g){return k(g,b)}let K=O,_=k;function A(g,y,C){let I=h(g*(y-C));return y=h(y-I),C=h(C+I),{x_2:y,x_3:C}}function N(g,y){Le("u",g,dn,r),Le("scalar",y,m,w);let C=y,I=g,L=Lr,S=dn,B=g,R=Lr,P=dn;for(let z=BigInt(f-1);z>=dn;z--){let V=C>>z&Lr;P^=V,{x_2:L,x_3:B}=A(P,L,B),{x_2:S,x_3:R}=A(P,S,R),P=V;let X=L+S,rt=h(X*X),lt=L-S,Z=h(lt*lt),ht=rt-Z,ur=B+R,qn=B-R,Xr=h(qn*X),Kc=h(ur*lt),Hc=Xr+Kc,Fc=Xr-Kc;B=h(Hc*Hc),R=h(I*h(Fc*Fc)),L=h(rt*Z),S=h(ht*(rt+h(d*ht)))}({x_2:L,x_3:B}=A(P,L,B)),{x_2:S,x_3:R}=A(P,S,R);let j=s(S);return h(L*j)}let M={secretKey:l,publicKey:l,seed:l},T=(g=c(l))=>(F(g,M.seed,"seed"),g),x={randomSecretKey:T};return Object.freeze({keygen:_r(T,K),getSharedSecret:_,getPublicKey:K,scalarMult:k,scalarMultBase:O,utils:x,GuBytes:b.slice(),lengths:M})}var gp=BigInt(1),ru=BigInt(2),yp=BigInt(3),bp=BigInt(5),xp=BigInt(8),yo=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),wp={p:yo,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:xp,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ou(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=yo,a=e*e%s*e%s,c=st(a,ru,s)*a%s,f=st(c,gp,s)*e%s,l=st(f,bp,s)*f%s,u=st(l,t,s)*l%s,d=st(u,r,s)*u%s,m=st(d,n,s)*d%s,p=st(m,o,s)*m%s,w=st(p,o,s)*m%s,h=st(w,t,s)*l%s;return{pow_p_5_8:st(h,ru,s)*e%s,b2:a}}function su(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var nu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ep(e,t){let r=yo,n=at(t*t*t,r),o=at(n*n*t,r),s=ou(e*o).pow_p_5_8,i=at(e*n*s,r),a=at(t*i*i,r),c=i,f=at(i*nu,r),l=a===e,u=a===at(-e,r),d=a===at(-e*nu,r);return l&&(i=c),(u||d)&&(i=f),Gf(i,r)&&(i=at(-i,r)),{isValid:l||u,value:i}}var Sp=Jf(wp,{uvRatio:Ep});function Ap(e){return tu(Sp,Rf,Object.assign({adjustScalarBytes:su},e))}var iu=Ap({});var pn=(()=>{let e=yo;return eu({P:e,type:"x25519",powPminus2:t=>{let{pow_p_5_8:r,b2:n}=ou(t);return at(st(r,yp,e)*n,e)},adjustScalarBytes:su})})();var mn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},bo=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var au={get(e=globalThis){let t=e.crypto;if(t?.subtle==null)throw new bo("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Kt=au;var xo=32;var Di,vp=(async()=>{try{return await Kt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Cp(e,t,r){if(e.buffer instanceof ArrayBuffer){let n=await Kt.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Kt.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function _p(e,t,r){return iu.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}async function cu(e,t,r){return Di==null&&(Di=await vp),Di?Cp(e,t,r):_p(e,t,r)}function wo(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}var Eo=class{type="Ed25519";raw;constructor(t){this.raw=Ti(t,xo)}toMultihash(){return Vt.digest(Se(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return ut.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:xt(this.raw,t.raw)}verify(t,r,n){n?.signal?.throwIfAborted();let o=cu(this.raw,r,t);return wo(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Ri(e){return e=Ti(e,xo),new Eo(e)}function Ti(e,t){if(e=Uint8Array.from(e??[]),e.length!==t)throw new Y(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var Ip=Math.pow(2,7),Bp=Math.pow(2,14),Dp=Math.pow(2,21),Pi=Math.pow(2,28),Oi=Math.pow(2,35),Ni=Math.pow(2,42),Ui=Math.pow(2,49),J=128,vt=127;function et(e){if(e<Ip)return 1;if(e<Bp)return 2;if(e<Dp)return 3;if(e<Pi)return 4;if(e<Oi)return 5;if(e<Ni)return 6;if(e<Ui)return 7;if(Number.MAX_SAFE_INTEGER!=null&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Be(e,t,r=0){switch(et(e)){case 8:t[r++]=e&255|J,e/=128;case 7:t[r++]=e&255|J,e/=128;case 6:t[r++]=e&255|J,e/=128;case 5:t[r++]=e&255|J,e/=128;case 4:t[r++]=e&255|J,e>>>=7;case 3:t[r++]=e&255|J,e>>>=7;case 2:t[r++]=e&255|J,e>>>=7;case 1:{t[r++]=e&255,e>>>=7;break}default:throw new Error("unreachable")}return t}function Tp(e,t,r=0){switch(et(e)){case 8:t.set(r++,e&255|J),e/=128;case 7:t.set(r++,e&255|J),e/=128;case 6:t.set(r++,e&255|J),e/=128;case 5:t.set(r++,e&255|J),e/=128;case 4:t.set(r++,e&255|J),e>>>=7;case 3:t.set(r++,e&255|J),e>>>=7;case 2:t.set(r++,e&255|J),e>>>=7;case 1:{t.set(r++,e&255),e>>>=7;break}default:throw new Error("unreachable")}return t}function gn(e,t){let r=e[t],n=0;if(n+=r&vt,r<J||(r=e[t+1],n+=(r&vt)<<7,r<J)||(r=e[t+2],n+=(r&vt)<<14,r<J)||(r=e[t+3],n+=(r&vt)<<21,r<J)||(r=e[t+4],n+=(r&vt)*Pi,r<J)||(r=e[t+5],n+=(r&vt)*Oi,r<J)||(r=e[t+6],n+=(r&vt)*Ni,r<J)||(r=e[t+7],n+=(r&vt)*Ui,r<J))return n;throw new RangeError("Could not decode varint")}function Rp(e,t){let r=e.get(t),n=0;if(n+=r&vt,r<J||(r=e.get(t+1),n+=(r&vt)<<7,r<J)||(r=e.get(t+2),n+=(r&vt)<<14,r<J)||(r=e.get(t+3),n+=(r&vt)<<21,r<J)||(r=e.get(t+4),n+=(r&vt)*Pi,r<J)||(r=e.get(t+5),n+=(r&vt)*Oi,r<J)||(r=e.get(t+6),n+=(r&vt)*Ni,r<J)||(r=e.get(t+7),n+=(r&vt)*Ui,r<J))return n;throw new RangeError("Could not decode varint")}function So(e,t,r=0){return t==null&&(t=it(et(e))),t instanceof Uint8Array?Be(e,t,r):Tp(e,t,r)}function ce(e,t=0){return e instanceof Uint8Array?gn(e,t):Rp(e,t)}var ki=new Float32Array([-0]),De=new Uint8Array(ki.buffer);function uu(e,t,r){ki[0]=e,t[r]=De[0],t[r+1]=De[1],t[r+2]=De[2],t[r+3]=De[3]}function lu(e,t){return De[0]=e[t],De[1]=e[t+1],De[2]=e[t+2],De[3]=e[t+3],ki[0]}var Mi=new Float64Array([-0]),Ct=new Uint8Array(Mi.buffer);function hu(e,t,r){Mi[0]=e,t[r]=Ct[0],t[r+1]=Ct[1],t[r+2]=Ct[2],t[r+3]=Ct[3],t[r+4]=Ct[4],t[r+5]=Ct[5],t[r+6]=Ct[6],t[r+7]=Ct[7]}function du(e,t){return Ct[0]=e[t],Ct[1]=e[t+1],Ct[2]=e[t+2],Ct[3]=e[t+3],Ct[4]=e[t+4],Ct[5]=e[t+5],Ct[6]=e[t+6],Ct[7]=e[t+7],Mi[0]}var Pp=BigInt(Number.MAX_SAFE_INTEGER),Op=BigInt(Number.MIN_SAFE_INTEGER),Ut=class e{lo;hi;constructor(t,r){this.lo=t|0,this.hi=r|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?t<16384?t<128?1:2:t<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return tr;if(t<Pp&&t>Op)return this.fromNumber(Number(t));let r=t<0n;r&&(t=-t);let n=t>>32n,o=t-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>pu&&(o=0n,++n>pu&&(n=0n))),new e(Number(o),Number(n))}static fromNumber(t){if(t===0)return tr;let r=t<0;r&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new e(n,o)}static from(t){return typeof t=="number"?e.fromNumber(t):typeof t=="bigint"?e.fromBigInt(t):typeof t=="string"?e.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new e(t.low>>>0,t.high>>>0):tr}},tr=new Ut(0,0);tr.toBigInt=function(){return 0n};tr.zzEncode=tr.zzDecode=function(){return this};tr.length=function(){return 1};var pu=4294967296n;function mu(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:(r&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function gu(e,t,r){if(r-t<1)return"";let o,s=[],i=0,a;for(;t<r;)a=e[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(e[t++]&63)<<6|e[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Ki(e,t,r){let n=r,o,s;for(let i=0;i<e.length;++i)o=e.charCodeAt(i),o<128?t[r++]=o:o<2048?(t[r++]=o>>6|192,t[r++]=o&63|128):(o&64512)===55296&&((s=e.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[r++]=o>>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=o&63|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=o&63|128);return r-n}function Wt(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function Ao(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}var Hi=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Wt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Wt(this,4);return Ao(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Wt(this,4);return Ao(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Wt(this,4);let t=lu(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Wt(this,4);let t=du(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),r=this.pos,n=this.pos+t;if(n>this.len)throw Wt(this,t);return this.pos+=t,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let t=this.bytes();return gu(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Wt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Wt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Ut(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw Wt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,t}if(this.len-this.pos>4){for(;r<5;++r)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;r<5;++r){if(this.pos>=this.len)throw Wt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Wt(this,8);let t=Ao(this.buf,this.pos+=4),r=Ao(this.buf,this.pos+=4);return new Ut(t,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=gn(this.buf,this.pos);return this.pos+=et(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function bn(e){return new Hi(e instanceof Uint8Array?e:e.subarray())}function Te(e,t,r){let n=bn(e);return t.decode(n,void 0,r)}function Fi(e){let t=e??8192,r=t>>>1,n,o=t;return function(i){if(i<1||i>r)return it(i);o+i>t&&(n=it(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var er=class{fn;len;next;val;constructor(t,r,n){this.fn=t,this.len=r,this.next=void 0,this.val=n}};function Vi(){}var Wi=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Np=Fi();function Up(e){return globalThis.Buffer!=null?it(e):Np(e)}var wn=class{len;head;tail;states;constructor(){this.len=0,this.head=new er(Vi,0,0),this.tail=this.head,this.states=null}_push(t,r,n){return this.tail=this.tail.next=new er(t,r,n),this.len+=r,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Gi((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(vo,10,Ut.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let r=Ut.fromBigInt(t);return this._push(vo,r.length(),r)}uint64Number(t){return this._push(Be,et(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let r=Ut.fromBigInt(t).zzEncode();return this._push(vo,r.length(),r)}sint64Number(t){let r=Ut.fromNumber(t).zzEncode();return this._push(vo,r.length(),r)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push($i,1,t?1:0)}fixed32(t){return this._push(xn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let r=Ut.fromBigInt(t);return this._push(xn,4,r.lo)._push(xn,4,r.hi)}fixed64Number(t){let r=Ut.fromNumber(t);return this._push(xn,4,r.lo)._push(xn,4,r.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(uu,4,t)}double(t){return this._push(hu,8,t)}bytes(t){let r=t.length>>>0;return r===0?this._push($i,1,0):this.uint32(r)._push(Mp,r,t)}string(t){let r=mu(t);return r!==0?this.uint32(r)._push(Ki,r,t):this._push($i,1,0)}fork(){return this.states=new Wi(this),this.head=this.tail=new er(Vi,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new er(Vi,0,0),this.len=0),this}ldelim(){let t=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=r,this.len+=n),this}finish(){let t=this.head.next,r=Up(this.len),n=0;for(;t!=null;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}};function $i(e,t,r){t[r]=e&255}function kp(e,t,r){for(;e>127;)t[r++]=e&127|128,e>>>=7;t[r]=e}var Gi=class extends er{next;constructor(t,r){super(kp,t,r),this.next=void 0}};function vo(e,t,r){for(;e.hi!==0;)t[r++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=e.lo&127|128,e.lo=e.lo>>>7;t[r++]=e.lo}function xn(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function Mp(e,t,r){t.set(e,r)}globalThis.Buffer!=null&&(wn.prototype.bytes=function(e){let t=e.length>>>0;return this.uint32(t),t>0&&this._push(Kp,t,e),this},wn.prototype.string=function(e){let t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Hp,t,e),this});function Kp(e,t,r){t.set(e,r)}function Hp(e,t,r){e.length<40?Ki(e,t,r):t.utf8Write!=null?t.utf8Write(e,r):t.set(G(e),r)}function qi(){return new wn}function Re(e,t){let r=qi();return t.encode(e,r,{lengthDelimited:!1}),r.finish()}function*Pe(e,t,r){let n=bn(e);yield*t.stream(n,void 0,"$",r)}var Co={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function _o(e,t,r,n,o){return{name:e,type:t,encode:r,decode:n,stream:o}}function rr(e){function t(s){if(e[s.toString()]==null)throw new Error("Invalid enum value");return e[s]}let r=function(i,a){let c=t(i);a.int32(c)},n=function(i){let a=i.int32();return t(a)},o=function*(i){let a=i.int32();yield t(a)};return _o("enum",Co.VARINT,r,n,o)}function Oe(e,t,r){return _o("message",Co.LENGTH_DELIMITED,e,t,r)}var ct;(function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(ct||(ct={}));var zi;(function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(zi||(zi={}));(function(e){e.codec=()=>rr(zi)})(ct||(ct={}));var Qt;(function(e){let t;e.codec=()=>(t==null&&(t=Oe((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ct.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=ct.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ct.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),t);function r(s){return Re(s,e.codec())}e.encode=r;function n(s,i){return Te(s,e.codec(),i)}e.decode=n;function o(s,i){return Pe(s,e.codec(),i)}e.stream=o})(Qt||(Qt={}));var ji;(function(e){let t;e.codec=()=>(t==null&&(t=Oe((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ct.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=ct.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ct.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),t);function r(s){return Re(s,e.codec())}e.encode=r;function n(s,i){return Te(s,e.codec(),i)}e.decode=n;function o(s,i){return Pe(s,e.codec(),i)}e.stream=o})(ji||(ji={}));function Fp(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Lo(e,t=""){if(typeof e!="number"){let r=t&&`"${t}" `;throw new TypeError(`${r}expected number, got ${typeof e}`)}if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw new RangeError(`${r}expected integer >= 0, got ${e}`)}}function Ne(e,t,r=""){let n=Fp(e),o=e?.length,s=t!==void 0;if(!n||s&&o!==t){let i=r&&`"${r}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return e}function En(e){if(typeof e!="function"||typeof e.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(Lo(e.outputLen),Lo(e.blockLen),e.outputLen<1)throw new Error('"outputLen" must be >= 1');if(e.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Ir(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Io(e,t){Ne(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function fe(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Bo(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Gt(e,t){return e<<32-t|e>>>t}function xu(e,t={}){let r=(o,s)=>e(s).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>e(o),Object.assign(r,t),Object.freeze(r)}var wu=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var An={};Bt(An,{MAX_RSA_KEY_SIZE:()=>Zi,generateRSAKeyPair:()=>_u,jwkToJWKKeyPair:()=>Lu,jwkToPkcs1:()=>qp,jwkToPkix:()=>ea,jwkToRSAPrivateKey:()=>sa,pkcs1MessageToJwk:()=>Ji,pkcs1MessageToRSAPrivateKey:()=>ra,pkcs1ToJwk:()=>Gp,pkcs1ToRSAPrivateKey:()=>Cu,pkixMessageToJwk:()=>ta,pkixMessageToRSAPublicKey:()=>oa,pkixToJwk:()=>zp,pkixToRSAPublicKey:()=>na});function Eu(e,t,r){return e&t^~e&r}function Su(e,t,r){return e&t^e&r^t&r}var Do=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,r,n,o){this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Bo(this.buffer)}update(t){Ir(this),Ne(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Bo(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Ir(this),Io(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,fe(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let u=i;u<o;u++)r[u]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Bo(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,l=this.get();if(f>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<f;u++)a.setUint32(4*u,l[u],s)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ue=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Vp=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]),Ue=new Uint32Array(64),Xi=class extends Do{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,r,n,o,s,i,a,c]}set(t,r,n,o,s,i,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,r){for(let u=0;u<16;u++,r+=4)Ue[u]=t.getUint32(r,!1);for(let u=16;u<64;u++){let d=Ue[u-15],m=Ue[u-2],p=Gt(d,7)^Gt(d,18)^d>>>3,w=Gt(m,17)^Gt(m,19)^m>>>10;Ue[u]=w+Ue[u-7]+p+Ue[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:f,H:l}=this;for(let u=0;u<64;u++){let d=Gt(a,6)^Gt(a,11)^Gt(a,25),m=l+d+Eu(a,c,f)+Vp[u]+Ue[u]|0,w=(Gt(n,2)^Gt(n,13)^Gt(n,22))+Su(n,o,s)|0;l=f,f=c,c=a,a=i+m|0,i=s,s=o,o=n,n=m+w|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,f,l)}roundClean(){fe(Ue)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),fe(this.buffer)}},Yi=class extends Xi{A=ue[0]|0;B=ue[1]|0;C=ue[2]|0;D=ue[3]|0;E=ue[4]|0;F=ue[5]|0;G=ue[6]|0;H=ue[7]|0;constructor(){super(32)}};var ke=xu(()=>new Yi,wu(1));var Br=class{type="RSA";jwk;_raw;_multihash;constructor(t,r){this.jwk=t,this._multihash=r}get raw(){return this._raw==null&&(this._raw=An.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return dt.createV1(114,this._multihash)}toString(){return ut.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:xt(this.raw,t.raw)}verify(t,r,n){return vu(this.jwk,r,t,n)}},Sn=class{type="RSA";jwk;_raw;publicKey;constructor(t,r){this.jwk=t,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=An.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:xt(this.raw,t.raw)}sign(t,r){return Au(this.jwk,t,r)}};var Zi=8192,Qi=18,$p=1062,Wp=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Gp(e){let t=ee(e);return Ji(t)}function Ji(e){return{n:$(e[1],"base64url"),e:$(e[2],"base64url"),d:$(e[3],"base64url"),p:$(e[4],"base64url"),q:$(e[5],"base64url"),dp:$(e[6],"base64url"),dq:$(e[7],"base64url"),qi:$(e[8],"base64url"),kty:"RSA"}}function qp(e){if(e.n==null||e.e==null||e.d==null||e.p==null||e.q==null||e.dp==null||e.dq==null||e.qi==null)throw new Y("JWK was missing components");return Ee([Pt(Uint8Array.from([0])),Pt(G(e.n,"base64url")),Pt(G(e.e,"base64url")),Pt(G(e.d,"base64url")),Pt(G(e.p,"base64url")),Pt(G(e.q,"base64url")),Pt(G(e.dp,"base64url")),Pt(G(e.dq,"base64url")),Pt(G(e.qi,"base64url"))]).subarray()}function zp(e){let t=ee(e,{offset:0});return ta(t)}function ta(e){let t=ee(e[1],{offset:0});return{kty:"RSA",n:$(t[0],"base64url"),e:$(t[1],"base64url")}}function ea(e){if(e.n==null||e.e==null)throw new Y("JWK was missing components");return Ee([Wp,co(Ee([Pt(G(e.n,"base64url")),Pt(G(e.e,"base64url"))]))]).subarray()}function Cu(e){let t=ee(e);return ra(t)}function ra(e){let t=Ji(e);return sa(t)}function na(e,t){if(e.byteLength>=$p)throw new lr("Key size is too large");let r=ee(e,{offset:0});return oa(r,e,t)}function oa(e,t,r){let n=ta(e);if(r==null){let o=ke(Qt.encode({Type:ct.RSA,Data:t}));r=Dt(Qi,o)}return new Br(n,r)}function sa(e){if(Bu(e)>Zi)throw new Y("Key size is too large");let t=Lu(e),r=ke(Qt.encode({Type:ct.RSA,Data:ea(t.publicKey)})),n=Dt(Qi,r);return new Sn(t.privateKey,new Br(t.publicKey,n))}async function _u(e){if(e>Zi)throw new Y("Key size is too large");let t=await Iu(e),r=ke(Qt.encode({Type:ct.RSA,Data:ea(t.publicKey)})),n=Dt(Qi,r);return new Sn(t.privateKey,new Br(t.publicKey,n))}function Lu(e){if(e==null)throw new Y("Missing key parameter");return{privateKey:e,publicKey:{kty:e.kty,n:e.n,e:e.e}}}async function Iu(e,t){let r=await Kt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);t?.signal?.throwIfAborted();let n=await jp(r,t);return{privateKey:n[0],publicKey:n[1]}}async function Au(e,t,r){let n=await Kt.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let o=await Kt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,t instanceof Uint8Array?t:t.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function vu(e,t,r,n){let o=await Kt.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Kt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),s}async function jp(e,t){if(e.privateKey==null||e.publicKey==null)throw new Y("Private and public key are required");let r=await Promise.all([Kt.get().subtle.exportKey("jwk",e.privateKey),Kt.get().subtle.exportKey("jwk",e.publicKey)]);return t?.signal?.throwIfAborted(),r}function Bu(e){if(e.kty!=="RSA")throw new Y("invalid key type");if(e.n==null)throw new Y("invalid key modulus");return G(e.n,"base64url").length*8}var To=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,r){if(fo(t),F(r,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?t.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),ne(o)}update(t){return wr(this),this.iHash.update(t),this}digestInto(t){wr(this),F(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ia=(e,t,r)=>new To(e,t).update(r).digest();ia.create=(e,t)=>new To(e,t);var Du=(e,t)=>(e+(e>=0?t:-t)/Tu)/t;function Xp(e,t,r){let[[n,o],[s,i]]=t,a=Du(i*e,r),c=Du(-o*e,r),f=e-a*n-c*s,l=-a*o-c*i,u=f<le,d=l<le;u&&(f=-f),d&&(l=-l);let m=un(Math.ceil(wi(r)/2))+Dr;if(f<le||f>=m||l<le||l>=m)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:u,k1:f,k2neg:d,k2:l}}function ca(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function aa(e,t){let r={};for(let n of Object.keys(t))r[n]=e[n]===void 0?t[n]:e[n];return ae(r.lowS,"lowS"),ae(r.prehash,"prehash"),r.format!==void 0&&ca(r.format),r}var fa=class extends Error{constructor(t=""){super(t)}},Me={Err:fa,_tlv:{encode:(e,t)=>{let{Err:r}=Me;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=cn(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?cn(o.length/2|128):"";return cn(e)+s+o+t},decode(e,t){let{Err:r}=Me,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let f=t.subarray(n,n+c);if(f.length!==c)throw new r("tlv.decode: length bytes not complete");if(f[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let l of f)i=i<<8|l;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=Me;if(e<le)throw new t("integer: negative integers are not allowed");let r=cn(e);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=Me;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Er(e)}},toSig(e){let{Err:t,_int:r,_tlv:n}=Me,o=F(e,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:f,l}=n.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(f)}},hexFromSig(e){let{_tlv:t,_int:r}=Me,n=t.encode(2,r.encode(e.r)),o=t.encode(2,r.encode(e.s)),s=n+o;return t.encode(48,s)}},le=BigInt(0),Dr=BigInt(1),Tu=BigInt(2),Ro=BigInt(3),Yp=BigInt(4);function Ru(e,t={}){let r=mo("weierstrass",e,t),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i,n:a}=s;Zt(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=t;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let f=Ou(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(T,x,g){let{x:y,y:C}=x.toAffine(),I=n.toBytes(y);if(ae(g,"isCompressed"),g){l();let L=!n.isOdd(C);return Ot(Pu(L),I)}else return Ot(Uint8Array.of(4),I,n.toBytes(C))}function d(T){F(T,void 0,"Point");let{publicKey:x,publicKeyUncompressed:g}=f,y=T.length,C=T[0],I=T.subarray(1);if(y===x&&(C===2||C===3)){let L=n.fromBytes(I);if(!n.isValid(L))throw new Error("bad point: is not on curve, wrong x");let S=w(L),B;try{B=n.sqrt(S)}catch(j){let z=j instanceof Error?": "+j.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}l();let R=n.isOdd(B);return(C&1)===1!==R&&(B=n.neg(B)),{x:L,y:B}}else if(y===g&&C===4){let L=n.BYTES,S=n.fromBytes(I.subarray(0,L)),B=n.fromBytes(I.subarray(L,L*2));if(!h(S,B))throw new Error("bad point: is not on curve");return{x:S,y:B}}else throw new Error(`bad point: got length ${y}, expected compressed=${x} or uncompressed=${g}`)}let m=t.toBytes||u,p=t.fromBytes||d;function w(T){let x=n.sqr(T),g=n.mul(x,T);return n.add(n.add(g,n.mul(T,s.a)),s.b)}function h(T,x){let g=n.sqr(x),y=w(T);return n.eql(g,y)}if(!h(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let b=n.mul(n.pow(s.a,Ro),Yp),v=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(b,v)))throw new Error("bad curve params: a or b");function E(T,x,g=!1){if(!n.isValid(x)||g&&n.is0(x))throw new Error(`bad point coordinate ${T}`);return x}function D(T){if(!(T instanceof A))throw new Error("Weierstrass Point expected")}function k(T){if(!c||!c.basises)throw new Error("no endo");return Xp(T,c.basises,o.ORDER)}let O=Sr((T,x)=>{let{X:g,Y:y,Z:C}=T;if(n.eql(C,n.ONE))return{x:g,y};let I=T.is0();x==null&&(x=I?n.ONE:n.inv(C));let L=n.mul(g,x),S=n.mul(y,x),B=n.mul(C,x);if(I)return{x:n.ZERO,y:n.ZERO};if(!n.eql(B,n.ONE))throw new Error("invZ was invalid");return{x:L,y:S}}),K=Sr(T=>{if(T.is0()){if(t.allowInfinityPoint&&!n.is0(T.Y))return;throw new Error("bad point: ZERO")}let{x,y:g}=T.toAffine();if(!n.isValid(x)||!n.isValid(g))throw new Error("bad point: x or y not field elements");if(!h(x,g))throw new Error("bad point: equation left != right");if(!T.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function _(T,x,g,y,C){return g=new A(n.mul(g.X,T),g.Y,g.Z),x=hn(y,x),g=hn(C,g),x.add(g)}class A{static BASE=new A(s.Gx,s.Gy,n.ONE);static ZERO=new A(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(x,g,y){this.X=E("x",x),this.Y=E("y",g,!0),this.Z=E("z",y),Object.freeze(this)}static CURVE(){return s}static fromAffine(x){let{x:g,y}=x||{};if(!x||!n.isValid(g)||!n.isValid(y))throw new Error("invalid affine point");if(x instanceof A)throw new Error("projective point not allowed");return n.is0(g)&&n.is0(y)?A.ZERO:new A(g,y,n.ONE)}static fromBytes(x){let g=A.fromAffine(p(F(x,void 0,"point")));return g.assertValidity(),g}static fromHex(x){return A.fromBytes(se(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,g=!0){return M.createCache(this,x),g||this.multiply(Ro),this}assertValidity(){K(this)}hasEvenY(){let{y:x}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(x)}equals(x){D(x);let{X:g,Y:y,Z:C}=this,{X:I,Y:L,Z:S}=x,B=n.eql(n.mul(g,S),n.mul(I,C)),R=n.eql(n.mul(y,S),n.mul(L,C));return B&&R}negate(){return new A(this.X,n.neg(this.Y),this.Z)}double(){let{a:x,b:g}=s,y=n.mul(g,Ro),{X:C,Y:I,Z:L}=this,S=n.ZERO,B=n.ZERO,R=n.ZERO,P=n.mul(C,C),j=n.mul(I,I),z=n.mul(L,L),V=n.mul(C,I);return V=n.add(V,V),R=n.mul(C,L),R=n.add(R,R),S=n.mul(x,R),B=n.mul(y,z),B=n.add(S,B),S=n.sub(j,B),B=n.add(j,B),B=n.mul(S,B),S=n.mul(V,S),R=n.mul(y,R),z=n.mul(x,z),V=n.sub(P,z),V=n.mul(x,V),V=n.add(V,R),R=n.add(P,P),P=n.add(R,P),P=n.add(P,z),P=n.mul(P,V),B=n.add(B,P),z=n.mul(I,L),z=n.add(z,z),P=n.mul(z,V),S=n.sub(S,P),R=n.mul(z,j),R=n.add(R,R),R=n.add(R,R),new A(S,B,R)}add(x){D(x);let{X:g,Y:y,Z:C}=this,{X:I,Y:L,Z:S}=x,B=n.ZERO,R=n.ZERO,P=n.ZERO,j=s.a,z=n.mul(s.b,Ro),V=n.mul(g,I),X=n.mul(y,L),rt=n.mul(C,S),lt=n.add(g,y),Z=n.add(I,L);lt=n.mul(lt,Z),Z=n.add(V,X),lt=n.sub(lt,Z),Z=n.add(g,C);let ht=n.add(I,S);return Z=n.mul(Z,ht),ht=n.add(V,rt),Z=n.sub(Z,ht),ht=n.add(y,C),B=n.add(L,S),ht=n.mul(ht,B),B=n.add(X,rt),ht=n.sub(ht,B),P=n.mul(j,Z),B=n.mul(z,rt),P=n.add(B,P),B=n.sub(X,P),P=n.add(X,P),R=n.mul(B,P),X=n.add(V,V),X=n.add(X,V),rt=n.mul(j,rt),Z=n.mul(z,Z),X=n.add(X,rt),rt=n.sub(V,rt),rt=n.mul(j,rt),Z=n.add(Z,rt),V=n.mul(X,Z),R=n.add(R,V),V=n.mul(ht,Z),B=n.mul(lt,B),B=n.sub(B,V),V=n.mul(lt,X),P=n.mul(ht,P),P=n.add(P,V),new A(B,R,P)}subtract(x){return this.add(x.negate())}is0(){return this.equals(A.ZERO)}multiply(x){let{endo:g}=t;if(!o.isValidNot0(x))throw new Error("invalid scalar: out of range");let y,C,I=L=>M.cached(this,L,S=>Je(A,S));if(g){let{k1neg:L,k1:S,k2neg:B,k2:R}=k(x),{p:P,f:j}=I(S),{p:z,f:V}=I(R);C=j.add(V),y=_(g.beta,P,z,L,B)}else{let{p:L,f:S}=I(x);y=L,C=S}return Je(A,[y,C])[0]}multiplyUnsafe(x){let{endo:g}=t,y=this;if(!o.isValid(x))throw new Error("invalid scalar: out of range");if(x===le||y.is0())return A.ZERO;if(x===Dr)return y;if(M.hasCache(this))return this.multiply(x);if(g){let{k1neg:C,k1:I,k2neg:L,k2:S}=k(x),{p1:B,p2:R}=Qf(A,y,I,S);return _(g.beta,B,R,C,L)}else return M.unsafe(y,x)}toAffine(x){return O(this,x)}isTorsionFree(){let{isTorsionFree:x}=t;return i===Dr?!0:x?x(A,this):M.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=t;return i===Dr?this:x?x(A,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(x=!0){return ae(x,"isCompressed"),this.assertValidity(),m(A,this,x)}toHex(x=!0){return oe(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=o.BITS,M=new Cr(A,t.endo?Math.ceil(N/2):N);return A.BASE.precompute(8),A}function Pu(e){return Uint8Array.of(e?2:3)}function Ou(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Zp(e,t={}){let{Fn:r}=e,n=t.randomBytes||Ae,o=Object.assign(Ou(e.Fp,r),{seed:vi(r.ORDER)});function s(m){try{let p=r.fromBytes(m);return r.isValidNot0(p)}catch{return!1}}function i(m,p){let{publicKey:w,publicKeyUncompressed:h}=o;try{let b=m.length;return p===!0&&b!==w||p===!1&&b!==h?!1:!!e.fromBytes(m)}catch{return!1}}function a(m=n(o.seed)){return Ci(F(m,o.seed,"seed"),r.ORDER)}function c(m,p=!0){return e.BASE.multiply(r.fromBytes(m)).toBytes(p)}function f(m){let{secretKey:p,publicKey:w,publicKeyUncompressed:h}=o;if(!ze(m)||"_lengths"in r&&r._lengths||p===w)return;let b=F(m,void 0,"key").length;return b===w||b===h}function l(m,p,w=!0){if(f(m)===!0)throw new Error("first arg must be private key");if(f(p)===!1)throw new Error("second arg must be public key");let h=r.fromBytes(m);return e.fromBytes(p).multiply(h).toBytes(w)}let u={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=_r(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:d,Point:e,utils:u,lengths:o})}function Nu(e,t,r={}){fo(t),Zt(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes||Ae,o=r.hmac||((g,y)=>ia(t,g,y)),{Fp:s,Fn:i}=e,{ORDER:a,BITS:c}=i,{keygen:f,getPublicKey:l,getSharedSecret:u,utils:d,lengths:m}=Zp(e,r),p={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},w=a*Tu<s.ORDER;function h(g){let y=a>>Dr;return g>y}function b(g,y){if(!i.isValidNot0(y))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return y}function v(){if(w)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function E(g,y){ca(y);let C=m.signature,I=y==="compact"?C:y==="recovered"?C+1:void 0;return F(g,I)}class D{r;s;recovery;constructor(y,C,I){if(this.r=b("r",y),this.s=b("s",C),I!=null){if(v(),![0,1,2,3].includes(I))throw new Error("invalid recovery id");this.recovery=I}Object.freeze(this)}static fromBytes(y,C=p.format){E(y,C);let I;if(C==="der"){let{r:R,s:P}=Me.toSig(F(y));return new D(R,P)}C==="recovered"&&(I=y[0],C="compact",y=y.subarray(1));let L=m.signature/2,S=y.subarray(0,L),B=y.subarray(L,L*2);return new D(i.fromBytes(S),i.fromBytes(B),I)}static fromHex(y,C){return this.fromBytes(se(y),C)}assertRecovery(){let{recovery:y}=this;if(y==null)throw new Error("invalid recovery id: must be present");return y}addRecoveryBit(y){return new D(this.r,this.s,y)}recoverPublicKey(y){let{r:C,s:I}=this,L=this.assertRecovery(),S=L===2||L===3?C+a:C;if(!s.isValid(S))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let B=s.toBytes(S),R=e.fromBytes(Ot(Pu((L&1)===0),B)),P=i.inv(S),j=O(F(y,void 0,"msgHash")),z=i.create(-j*P),V=i.create(I*P),X=e.BASE.multiplyUnsafe(z).add(R.multiplyUnsafe(V));if(X.is0())throw new Error("invalid recovery: point at infinify");return X.assertValidity(),X}hasHighS(){return h(this.s)}toBytes(y=p.format){if(ca(y),y==="der")return se(Me.hexFromSig(this));let{r:C,s:I}=this,L=i.toBytes(C),S=i.toBytes(I);return y==="recovered"?(v(),Ot(Uint8Array.of(this.assertRecovery()),L,S)):Ot(L,S)}toHex(y){return oe(this.toBytes(y))}}let k=r.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");let C=Er(y),I=y.length*8-c;return I>0?C>>BigInt(I):C},O=r.bits2int_modN||function(y){return i.create(k(y))},K=un(c);function _(g){return Le("num < 2^"+c,g,le,K),i.toBytes(g)}function A(g,y){return F(g,void 0,"message"),y?F(t(g),void 0,"prehashed message"):g}function N(g,y,C){let{lowS:I,prehash:L,extraEntropy:S}=aa(C,p);g=A(g,L);let B=O(g),R=i.fromBytes(y);if(!i.isValidNot0(R))throw new Error("invalid private key");let P=[_(R),_(B)];if(S!=null&&S!==!1){let X=S===!0?n(m.secretKey):S;P.push(F(X,void 0,"extraEntropy"))}let j=Ot(...P),z=B;function V(X){let rt=k(X);if(!i.isValidNot0(rt))return;let lt=i.inv(rt),Z=e.BASE.multiply(rt).toAffine(),ht=i.create(Z.x);if(ht===le)return;let ur=i.create(lt*i.create(z+ht*R));if(ur===le)return;let qn=(Z.x===ht?0:2)|Number(Z.y&Dr),Xr=ur;return I&&h(ur)&&(Xr=i.neg(ur),qn^=1),new D(ht,Xr,w?void 0:qn)}return{seed:j,k2sig:V}}function M(g,y,C={}){let{seed:I,k2sig:L}=N(g,y,C);return Nf(t.outputLen,i.BYTES,o)(I,L).toBytes(C.format)}function T(g,y,C,I={}){let{lowS:L,prehash:S,format:B}=aa(I,p);if(C=F(C,void 0,"publicKey"),y=A(y,S),!ze(g)){let R=g instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+R)}E(g,B);try{let R=D.fromBytes(g,B),P=e.fromBytes(C);if(L&&R.hasHighS())return!1;let{r:j,s:z}=R,V=O(y),X=i.inv(z),rt=i.create(V*X),lt=i.create(j*X),Z=e.BASE.multiplyUnsafe(rt).add(P.multiplyUnsafe(lt));return Z.is0()?!1:i.create(Z.x)===j}catch{return!1}}function x(g,y,C={}){let{prehash:I}=aa(C,p);return y=A(y,I),D.fromBytes(g,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:f,getPublicKey:l,getSharedSecret:u,utils:d,lengths:m,Point:e,sign:M,verify:T,recoverPublicKey:x,Signature:D,hash:t})}var la={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Qp={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Uu=BigInt(2);function Jp(e){let t=la.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=e*e*e%t,l=f*f*e%t,u=st(l,r,t)*l%t,d=st(u,r,t)*l%t,m=st(d,Uu,t)*f%t,p=st(m,o,t)*m%t,w=st(p,s,t)*p%t,h=st(w,a,t)*w%t,b=st(h,c,t)*h%t,v=st(b,a,t)*w%t,E=st(v,r,t)*l%t,D=st(E,i,t)*p%t,k=st(D,n,t)*f%t,O=st(k,Uu,t);if(!ua.eql(ua.sqr(O),e))throw new Error("Cannot find square root");return O}var ua=Ar(la.p,{sqrt:Jp}),t0=Ru(la,{Fp:ua,endo:Qp}),Tr=Nu(t0,Tf);function ku(e,t,r,n){let o=te.digest(r instanceof Uint8Array?r:r.subarray());if(wo(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Tr.verify(t,s,e,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new mn(String(s))});try{return n?.signal?.throwIfAborted(),Tr.verify(t,o.digest,e,{prehash:!1,format:"der"})}catch(s){throw new mn(String(s))}}var Po=class{type="secp256k1";raw;_key;constructor(t){this._key=Ku(t),this.raw=Mu(this._key)}toMultihash(){return Vt.digest(Se(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return ut.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:xt(this.raw,t.raw)}verify(t,r,n){return ku(this._key,r,t,n)}};function ha(e){return new Po(e)}function Mu(e){return Tr.Point.fromBytes(e).toBytes()}function Ku(e){try{return Tr.Point.fromBytes(e),e}catch(t){throw new lr(String(t))}}function vn(e,t){let{Type:r,Data:n}=Qt.decode(e),o=n??new Uint8Array;switch(r){case ct.RSA:return na(o,t);case ct.Ed25519:return Ri(o);case ct.secp256k1:return ha(o);case ct.ECDSA:return fi(o);default:throw new We}}function Hu(e){let{Type:t,Data:r}=Qt.decode(e.digest),n=r??new Uint8Array;switch(t){case ct.Ed25519:return Ri(n);case ct.secp256k1:return ha(n);case ct.ECDSA:return fi(n);default:throw new We}}function Se(e){return Qt.encode({Type:ct[e.type],Data:e.raw})}var Fu=Symbol.for("nodejs.util.inspect.custom"),e0=114,Cn=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ns]=!0;toString(){return this.string==null&&(this.string=ut.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return dt.createV1(e0,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return xt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return xt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Fu](){return`PeerId(${this.toString()})`}},_n=class extends Cn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Ln=class extends Cn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},In=class extends Cn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},r0=2336,Bn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Vt.digest(G(this.url))}[Fu](){return`PeerId(${this.url})`}[Ns]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return dt.createV1(r0,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=$(t)),t.toString()===this.toString())}};var n0=114,Vu=2336;function Rr(e,t){let r;if(e.charAt(0)==="1"||e.charAt(0)==="Q")r=br(ut.decode(`z${e}`));else{if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return o0(dt.parse(e));if(t==null)throw new Y('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=br(t.decode(e))}return $u(r)}function da(e){if(e.type==="Ed25519")return new Ln({multihash:e.toCID().multihash,publicKey:e});if(e.type==="secp256k1")return new In({multihash:e.toCID().multihash,publicKey:e});if(e.type==="RSA")return new _n({multihash:e.toCID().multihash,publicKey:e});throw new We}function $u(e){if(i0(e))return new _n({multihash:e});if(s0(e))try{let t=Hu(e);if(t.type==="Ed25519")return new Ln({multihash:e,publicKey:t});if(t.type==="secp256k1")return new In({multihash:e,publicKey:t})}catch{let r=$(e.digest);return new Bn(new URL(r))}throw new Jn("Supplied PeerID Multihash is invalid")}function o0(e){if(e?.multihash==null||e.version==null||e.version===1&&e.code!==n0&&e.code!==Vu)throw new Qn("Supplied PeerID CID is invalid");if(e.code===Vu){let t=$(e.multihash.digest);return new Bn(new URL(t))}return $u(e.multihash)}function s0(e){return e.code===Vt.code}function i0(e){return e.code===te.code}var Et=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},he=class extends Error{static name="ValidationError";name="ValidationError"},Oo=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},No=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Uo=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let r=this.index,n=t();return n===void 0&&(this.index=r),n}parseWith(t){let r=t();if(this.index===this.input.length)return r}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let r=this.readChar();if(r===t)return r})}readSeparator(t,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,r,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let d=Number.parseInt(u,t);if(!Number.isNaN(d))return d});if(l===void 0)break;if(s*=t,s+=l,s>f||(i+=1,r!==void 0&&i>r))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let r=0;r<t.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[r]=n}return t})}readIPv6Addr(){let t=r=>{for(let n=0;n<r.length/2;n++){let o=n*2;if(n<r.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return r[o]=i[0],r[o+1]=i[1],r[o+2]=i[2],r[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];r[o]=s>>8,r[o+1]=s&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,o]=t(r);if(n===16)return r;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var a0=45,c0=15,ko=new Uo;function Wu(e){if(!(e.length>c0))return ko.new(e).parseWith(()=>ko.readIPv4Addr())}function Gu(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>a0))return ko.new(e).parseWith(()=>ko.readIPv6Addr())}function Mo(e){return!!Wu(e)}function qu(e){return!!Gu(e)}function ma(e){return t=>$(t,e)}function ga(e){return t=>G(t,e)}function Pr(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function nr(e){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof e=="string"?parseInt(e):e),new Uint8Array(t)}function zu(e){let t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let r=G(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=nr(n);return Tt([r,o],r.length+o.length)}function ju(e){let t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let r=we.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=nr(n);return Tt([r,o],r.length+o.length)}function ya(e){let t=e.subarray(0,e.length-2),r=e.subarray(e.length-2),n=$(t,"base32"),o=Pr(r);return`${n}:${o}`}var ba=function(e){e=e.toString().trim();let t=new Uint8Array(4);return e.split(/\./g).forEach((r,n)=>{let o=parseInt(r,10);if(isNaN(o)||o<0||o>255)throw new Et("Invalid byte value in IP address");t[n]=o}),t},Xu=function(e){let t=0;e=e.toString().trim();let r=e.split(":",8),n;for(n=0;n<r.length;n++){let s=Mo(r[n]),i;s&&(i=ba(r[n]),r[n]=$(i.subarray(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,$(i.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 s=[n,1];for(n=9-r.length;n>0;n--)s.push("0");r.splice.apply(r,s)}let o=new Uint8Array(t+16);for(n=0;n<r.length;n++){r[n]===""&&(r[n]="0");let s=parseInt(r[n],16);if(isNaN(s)||s<0||s>65535)throw new Et("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},Yu=function(e){if(e.byteLength!==4)throw new Et("IPv4 address was incorrect length");let t=[];for(let r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},Zu=function(e){if(e.byteLength!==16)throw new Et("IPv6 address was incorrect length");let t=[];for(let n=0;n<e.byteLength;n+=2){let o=e[n],s=e[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}let r=t.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Et(`Invalid IPv6 address "${r}"`)}};function Qu(e){try{let t=new URL(`http://[${e}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new Et(`Invalid IPv6 address "${e}"`)}}var pa=Object.values(qe).map(e=>e.decoder),f0=(function(){let e=pa[0].or(pa[1]);return pa.slice(2).forEach(t=>e=e.or(t)),e})();function Ju(e){return f0.decode(e)}function tl(e){return t=>e.encoder.encode(t)}function u0(e){if(parseInt(e).toString()!==e)throw new he("Value must be an integer")}function l0(e){if(e<0)throw new he("Value must be a positive integer, or zero")}function h0(e){return t=>{if(t>e)throw new he(`Value must be smaller than or equal to ${e}`)}}function d0(...e){return t=>{for(let r of e)r(t)}}var Dn=d0(u0,l0,h0(65535));var yt=-1,xa=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let r;if(typeof t=="string"?r=this.protocolsByName.get(t):r=this.protocolsByCode.get(t),r==null)throw new No(`Protocol ${t} was unknown`);return r}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(r=>{this.protocolsByName.set(r,t)})}removeProtocol(t){let r=this.protocolsByCode.get(t);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},pe=new xa,L0=[{code:4,name:"ip4",size:32,valueToBytes:ba,bytesToValue:Yu,validate:e=>{if(!Mo(e))throw new he(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:nr,bytesToValue:Pr,validate:Dn},{code:273,name:"udp",size:16,valueToBytes:nr,bytesToValue:Pr,validate:Dn},{code:33,name:"dccp",size:16,valueToBytes:nr,bytesToValue:Pr,validate:Dn},{code:41,name:"ip6",size:128,valueToBytes:Xu,bytesToValue:Zu,stringToValue:Qu,validate:e=>{if(!qu(e))throw new he(`Invalid IPv6 address "${e}"`)}},{code:42,name:"ip6zone",size:yt},{code:43,name:"ipcidr",size:8,bytesToValue:ma("base10"),valueToBytes:ga("base10")},{code:53,name:"dns",size:yt},{code:54,name:"dns4",size:yt},{code:55,name:"dns6",size:yt},{code:56,name:"dnsaddr",size:yt},{code:132,name:"sctp",size:16,valueToBytes:nr,bytesToValue:Pr,validate:Dn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:yt,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:yt,bytesToValue:ma("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?ga("base58btc")(e):dt.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:ya,valueToBytes:zu},{code:445,name:"onion3",size:296,bytesToValue:ya,valueToBytes:ju},{code:446,name:"garlic64",size:yt},{code:447,name:"garlic32",size:yt},{code:448,name:"tls"},{code:449,name:"sni",size:yt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:yt,bytesToValue:tl(en),valueToBytes:Ju},{code:480,name:"http"},{code:481,name:"http-path",size:yt,stringToValue:e=>`/${decodeURIComponent(e)}`,valueToString:e=>encodeURIComponent(e.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:yt}];L0.forEach(e=>{pe.addProtocol(e)});function el(e){let t=[],r=0;for(;r<e.length;){let n=ce(e,r),o=pe.getProtocol(n),s=et(n),i=I0(o,e,r+s),a=0;i>0&&o.size===yt&&(a=et(i));let c=s+a+i,f={code:n,name:o.name,bytes:e.subarray(r,r+c)};if(i>0){let l=r+s+a,u=e.subarray(l,l+i);f.value=o.bytesToValue?.(u)??$(u)}t.push(f),r+=c}return t}function rl(e){let t=0,r=[];for(let n of e){if(n.bytes==null){let o=pe.getProtocol(n.code),s=et(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??G(n.value),a=i.byteLength,o.size===yt&&(c=et(a)));let f=new Uint8Array(s+c+a),l=0;Be(n.code,f,l),l+=s,i!=null&&(o.size===yt&&(Be(a,f,l),l+=c),f.set(i,l)),n.bytes=f}r.push(n.bytes),t+=n.bytes.byteLength}return Tt(r,t)}function nl(e){if(e.charAt(0)!=="/")throw new Et('String multiaddr must start with "/"');let t=[],r="protocol",n="",o="";for(let s=1;s<e.length;s++){let i=e.charAt(s);i!=="/"&&(r==="protocol"?o+=e.charAt(s):n+=e.charAt(s));let a=s===e.length-1;if(i==="/"||a){let c=pe.getProtocol(o);if(r==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",r="protocol";continue}else if(a)throw new Et(`Component ${o} was missing value`);r="value"}else if(r==="value"){let f={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Et(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}t.push(f),n="",o="",r="protocol"}}}if(o!==""&&n!=="")throw new Et("Incomplete multiaddr");return t}function ol(e){return`/${e.flatMap(t=>{if(t.value==null)return t.name;let r=pe.getProtocol(t.code);if(r==null)throw new Et(`Unknown protocol code ${t.code}`);return[t.name,r.valueToString?.(t.value)??t.value]}).join("/")}`}function I0(e,t,r){return e.size==null||e.size===0?0:e.size>0?e.size/8:ce(t,r)}var B0=Symbol.for("nodejs.util.inspect.custom"),Ua=Symbol.for("@multiformats/multiaddr");function D0(e){if(e==null&&(e="/"),sl(e))return e.getComponents();if(e instanceof Uint8Array)return el(e);if(typeof e=="string")return e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),e===""&&(e="/"),nl(e);if(Array.isArray(e))return e;throw new Et("Must be a string, Uint8Array, Component[], or another Multiaddr")}var $o=class e{[Ua]=!0;#t;#e;#r;constructor(t="/",r={}){this.#t=D0(t),r.validate!==!1&&T0(this)}get bytes(){return this.#r==null&&(this.#r=rl(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=ol(this.#t)),this.#e}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let r=new e(t);return new e([...this.#t,...r.getComponents()],{validate:!1})}decapsulate(t){let r=t.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new Oo(`Address ${this.toString()} does not contain subaddress: ${r}`);return new e(n.slice(0,o),{validate:!1})}decapsulateCode(t){let r;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){r=n;break}return new e(this.#t.slice(0,r),{validate:!1})}equals(t){return xt(this.bytes,t.bytes)}[B0](){return`Multiaddr(${this.toString()})`}};function T0(e){e.getComponents().forEach(t=>{let r=pe.getProtocol(t.code);t.value!=null&&r.validate?.(t.value)})}function sl(e){return!!e?.[Ua]}function kr(e){return new $o(e)}var nt=e=>({match:t=>{let r=t[0];return r==null||r.code!==e||r.value!=null?!1:t.slice(1)}}),H=(e,t)=>({match:r=>{let n=r[0];return n?.code!==e||n.value==null||t!=null&&n.value!==t?!1:r.slice(1)}}),il=e=>({match:t=>e.match(t)===!1?t:!1}),q=e=>({match:t=>{let r=e.match(t);return r===!1?t:r}}),_t=(...e)=>({match:t=>{let r;for(let n of e){let o=n.match(t);o!==!1&&(r==null||o.length<r.length)&&(r=o)}return r??!1}}),Q=(...e)=>({match:t=>{for(let r of e){let n=r.match(t);if(n===!1)return!1;t=n}return t}});function ot(...e){function t(o){if(o==null)return!1;let s=o.getComponents();for(let i of e){let a=i.match(s);if(a===!1)return!1;s=a}return s}function r(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:e,matches:r,exactMatch:n}}var R0=H(421),m2=ot(R0),Go=H(54),qo=H(55),zo=H(56),Ma=H(53),g2=ot(Go,q(H(421))),y2=ot(qo,q(H(421))),b2=ot(zo,q(H(421))),x2=ot(_t(Ma,zo,Go,qo),q(H(421))),al=Q(H(4),q(H(43))),cl=Q(q(H(42)),H(41),q(H(43))),Ka=_t(al,cl),Mr=_t(Ka,Ma,Go,qo,zo),w2=ot(_t(Ka,Q(_t(Ma,zo,Go,qo),q(H(421))))),E2=ot(al),S2=ot(cl),A2=ot(Ka),Ha=Q(Mr,H(6)),Tn=Q(Mr,H(273)),v2=ot(Q(Ha,q(H(421)))),C2=ot(Tn),Fa=Q(Tn,nt(460),q(H(421))),jo=Q(Tn,nt(461),q(H(421))),P0=_t(Fa,jo),_2=ot(Fa),L2=ot(jo),ka=_t(Mr,Ha,Tn,Fa,jo),fl=_t(Q(ka,nt(477),q(H(421)))),I2=ot(fl),ul=_t(Q(ka,nt(478),q(H(421))),Q(ka,nt(448),q(H(449)),nt(477),q(H(421)))),B2=ot(ul),ll=Q(Tn,nt(280),q(H(466)),q(H(466)),q(H(421))),hl=ot(ll),dl=Q(jo,nt(465),q(H(466)),q(H(466)),q(H(421))),D2=ot(dl),Wo=_t(fl,ul,Q(Ha,q(H(421))),Q(P0,q(H(421))),Q(Mr,q(H(421))),ll,dl,H(421)),pl=ot(Wo),O0=Q(q(Wo),nt(290),il(nt(281)),q(H(421))),T2=ot(O0),N0=_t(Q(Wo,nt(290),nt(281),q(H(421))),Q(Wo,nt(281),q(H(421))),Q(nt(281),q(H(421)))),ml=ot(N0),U0=Q(Mr,_t(Q(H(6,"80")),Q(H(6),nt(480)),nt(480)),q(H(481)),q(H(421))),R2=ot(U0),k0=Q(Mr,_t(Q(H(6,"443")),Q(H(6,"443"),nt(480)),Q(H(6),nt(443)),Q(H(6),nt(448),nt(480)),Q(nt(448),nt(480)),nt(448),nt(443)),q(H(481)),q(H(421))),P2=ot(k0),M0=_t(Q(H(777),q(H(421)))),O2=ot(M0),K0=_t(Q(H(400),q(H(421)))),N2=ot(K0);var Lt;(function(e){let t;(function(a){a.FIN="FIN",a.STOP_SENDING="STOP_SENDING",a.RESET="RESET",a.FIN_ACK="FIN_ACK"})(t=e.Flag||(e.Flag={}));let r;(function(a){a[a.FIN=0]="FIN",a[a.STOP_SENDING=1]="STOP_SENDING",a[a.RESET=2]="RESET",a[a.FIN_ACK=3]="FIN_ACK"})(r||(r={})),(function(a){a.codec=()=>rr(r)})(t=e.Flag||(e.Flag={}));let n;e.codec=()=>(n==null&&(n=Oe((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.flag!=null&&(c.uint32(8),e.Flag.codec().encode(a.flag,c)),a.message!=null&&(c.uint32(18),c.bytes(a.message)),f.lengthDelimited!==!1&&c.ldelim()},(a,c,f={})=>{let l={},u=c==null?a.len:a.pos+c;for(;a.pos<u;){let d=a.uint32();switch(d>>>3){case 1:{l.flag=e.Flag.codec().decode(a);break}case 2:{l.message=a.bytes();break}default:{a.skipType(d&7);break}}}return l},function*(a,c,f,l={}){let u=c==null?a.len:a.pos+c;for(;a.pos<u;){let d=a.uint32();switch(d>>>3){case 1:{yield{field:`${f}.flag`,value:e.Flag.codec().decode(a)};break}case 2:{yield{field:`${f}.message`,value:a.bytes()};break}default:{a.skipType(d&7);break}}}})),n);function o(a){return Re(a,e.codec())}e.encode=o;function s(a,c){return Te(a,e.codec(),c)}e.decode=s;function i(a,c){return Pe(a,e.codec(),c)}e.stream=i})(Lt||(Lt={}));var gl=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],Va=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),yl="libp2p+webrtc+v1/",bl=2*1024*1024,Kr=16*1024;function H0(e=Kr){let t=et(e-et(e)),r=1+et(Object.keys(Lt.Flag).length-1),n=1,o=e-t-r-n,s=et(o);return t+r+n+s}var xl=H0();var wl=1e4,$a="/webrtc",Rn="/webrtc-signaling/0.0.1";var Xo=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,r){if(En(t),Ne(r,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?t.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),fe(o)}update(t){return Ir(this),this.iHash.update(t),this}digestInto(t){Ir(this),Io(t,this),this.finished=!0;let r=t.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Wa=(()=>{let e=((t,r,n)=>new Xo(t,r).update(n).digest());return e.create=(t,r)=>new Xo(t,r),e})();function Ga(e){let t=e.getComponents(),r={},n=0;if(t[n]?.name==="ip6zone"&&(r.zone=`${t[n].value}`,n++),t[n].name==="ip4"||t[n].name==="ip6"||t[n].name==="dns"||t[n].name==="dns4"||t[n].name==="dns6"?(r.type=t[n].name,r.host=t[n].value,n++):t[n].name==="dnsaddr"&&(r.type=t[n].name,r.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(r.protocol=t[n].name==="tcp"?"tcp":"udp",r.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(r.type==="ip4"?r.cidr=parseInt(`${t[n].value}`):r.type==="ip6"&&(r.cidr=`${t[n].value}`),n++),r.type==null||r.host==null)throw new Y(`Multiaddr ${e} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(r.sni=t[n+1].value,n+=2),r}function Yo(){let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}var Zo=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Hr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Zo(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let r=this.head;this.head=r.next=new Zo(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var qa=class extends Error{type;code;constructor(t,r){super(t??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Fr(e={}){return F0(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}},e)}function F0(e,t){t=t??{};let r=t.onEnd,n=new Hr,o,s,i,a=Yo(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,b)=>{s=v=>{s=null,n.push(v);try{h(e(n))}catch(E){b(E)}return o}}):e(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Yo()})}},f=h=>s!=null?s(h):(n.push(h),o),l=h=>(n=new Hr,s!=null?s({error:h}):(n.push({error:h}),o)),u=h=>{if(i)return o;if(t?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:h})},d=h=>i?o:(i=!0,h!=null?l(h):f({done:!0})),m=()=>(n=new Hr,d(),{done:!0}),p=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:p,push:u,end:d,get readableLength(){return n.size},onEmpty:async h=>{let b=h?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let v,E;b!=null&&(v=new Promise((D,k)=>{E=()=>{k(new qa)},b.addEventListener("abort",E)}));try{await Promise.race([a.promise,v])}finally{E!=null&&b!=null&&b?.removeEventListener("abort",E)}}},r==null)return o;let w=o;return o={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(h){return w.throw(h),r!=null&&(r(h),r=void 0),{done:!0}},return(){return w.return(),r!=null&&(r(),r=void 0),{done:!0}},push:u,end(h){return w.end(h),r!=null&&(r(h),r=void 0),o},get readableLength(){return w.readableLength},onEmpty:h=>w.onEmpty(h)},o}var za=class e extends Error{name="TimeoutError";constructor(t,r){super(t,r),Error.captureStackTrace?.(this,e)}},El=e=>e.reason??new DOMException("This operation was aborted.","AbortError");function ja(e,t){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=t,a,c,l=new Promise((u,d)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){d(El(i));return}if(i&&(c=()=>{d(El(i))},i.addEventListener("abort",c,{once:!0})),e.then(u,d),r===Number.POSITIVE_INFINITY)return;let m=new za;a=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(p){d(p)}return}typeof e.cancel=="function"&&e.cancel(),o===!1?u():o instanceof Error?d(o):(m.message=o??`Promise timed out after ${r} milliseconds`,d(m))},r)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},l}var V0=e=>{let t=e.addEventListener||e.on||e.addListener,r=e.removeEventListener||e.off||e.removeListener;if(!t||!r)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}};function $0(e,t,r){let n,o=new Promise((s,i)=>{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 a=[t].flat(),c=[],{addListener:f,removeListener:l}=V0(e),u=async(...m)=>{let p=r.multiArgs?m:m[0];if(r.filter)try{if(!await r.filter(p))return}catch(w){n(),i(w);return}c.push(p),r.count===c.length&&(n(),s(c))},d=(...m)=>{n(),i(r.rejectionMultiArgs?m:m[0])};n=()=>{for(let m of a)l(m,u);for(let m of r.rejectionEvents)a.includes(m)||l(m,d)};for(let m of a)f(m,u);for(let m of r.rejectionEvents)a.includes(m)||f(m,d);r.signal&&r.signal.addEventListener("abort",()=>{d(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){let s=ja(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function St(e,t,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=$0(e,t,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var sr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},Qo=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},Jo=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function W0(e){return e.reason}async function me(e,t,r){if(t==null)return e;let n=r?.translateError??W0;if(t.aborted)return e.catch(()=>{}),Promise.reject(n(t));let o;try{return await Promise.race([e,new Promise((s,i)=>{o=()=>{i(n(t))},t.addEventListener("abort",o)})])}finally{o!=null&&t.removeEventListener("abort",o)}}var G0=Math.pow(2,20)*4,He=class extends be{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(t){super(),this.status="open",this.log=t.log,this.direction=t.direction??"outbound",this.inactivityTimeout=t.inactivityTimeout??12e4,this.maxReadBufferLength=t.maxReadBufferLength??G0,this.maxWriteBufferLength=t.maxWriteBufferLength,this.maxMessageSize=t.maxMessageSize,this.readBuffer=new W,this.writeBuffer=new W,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=o=>{this.onDrainPromise?.reject(o.error??new Jo)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(t){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),me(this.onDrainPromise.promise,t?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let t=Fr(),r=s=>{t.push(s.data)};this.addEventListener("message",r);let n=s=>{t.end(s.error)};this.addEventListener("close",n);let o=()=>{t.end()};this.addEventListener("remoteCloseWrite",o);try{yield*t}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(t){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new zt(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",t.byteLength),this.writeBuffer.append(t),this.processSendQueue()}abort(t){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",t),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(t)}catch(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new ro(t))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new zt("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 zt("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new zt(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.append(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new zt(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.prepend(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(t){if(t.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(t),this.dispatchReadBuffer()}}addEventListener(...t){super.addEventListener.apply(this,t),t[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 t=new hr;this.dispatchEvent(new no(t))}onTransportClosed(t){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"),t!=null?this.abort(t):(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 dr))}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 t=!0,r=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){t=!1;break}let s=this.writeBuffer.sublist(0,o),i=new W(s);this.writeBuffer.consume(s.byteLength);let a=this.sendData(s);if(t=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!t)break}return t||(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"),t}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 t=this.readBuffer.sublist();this.readBuffer.consume(t.byteLength),this.dispatchEvent(new eo(t))}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 Yr(`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 Yr(`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 ts=class extends He{remoteAddr;metricPrefix;metrics;constructor(t){super(t),this.metricPrefix=t.metricPrefix??"",this.metrics=t.metrics,this.remoteAddr=t.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(t){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 St(this,"idle",{...t,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 St(this,"drain",{...t,rejectionEvents:["close"]})),await this.sendClose(t),this.onTransportClosed())}};function Sl(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}var es=class extends be{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(t,r){super(),this.maConn=t,this.protocol=r.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=t.log.newScope(r.name),this.streamOptions=r.streamOptions,this.maxEarlyStreams=r.maxEarlyStreams??10,this.metrics=r.metrics;let n=i=>{try{this.onData(i.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let o=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",o);let s=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",s)}send(t){let r=this.maConn.send(t);return r===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),r}async close(t){this.status==="closed"||this.status==="closing"||(this.status="closing",await me(Promise.all([...this.streams].map(async r=>{await r.close(t)})),t?.signal),this.status="closed")}abort(t){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(r=>{r.abort(t)}),this.status="closed")}onTransportClosed(t){this.status="closing";try{[...this.streams].forEach(r=>{r.onTransportClosed(t)})}catch(r){this.abort(r)}this.status="closed"}async createStream(t){if(this.status!=="open")throw new Yn;let r=this.onCreateStream({...this.streamOptions,...t});return Sl(r)&&(r=await r),this.streams.push(r),this.cleanUpStream(r),r}onRemoteStream(t){if(this.streams.push(t),this.cleanUpStream(t),this.listenerCount("stream")===0){this.earlyStreams.push(t),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new Qo(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:t})}cleanUpStream(t){let r=n=>{let o=this.streams.findIndex(s=>s===t);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${t.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${t.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${t.direction}_stream_end`]:!0})};t.addEventListener("close",r),this.metrics?.increment({[`${t.direction}_stream`]:!0})}addEventListener(...t){super.addEventListener.apply(this,t),t[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(r=>{this.safeDispatchEvent("stream",{detail:r})}),this.earlyStreams=[]})}};var rs=class extends He{id;protocol;constructor(t){super(t),this.id=t.id,this.protocol=t.protocol??""}async close(t){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="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 St(this,"idle",{...t,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await St(this,"drain",{...t,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(t),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(t){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(t),this.readStatus="closed",this.log("closed readable end gracefully"))}};var q0=4194304,ns=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Pn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ya=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Za=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function z0(e){return typeof e?.closeRead=="function"}function j0(e){return typeof e?.close=="function"}function Xa(e){return z0(e)?e.remoteWriteStatus!=="writable"&&e.readBufferLength===0:j0(e)?e.status!=="open":!1}function X0(e){return e?.addEventListener!=null&&e?.removeEventListener!=null&&e?.send!=null&&e?.push!=null&&e?.log!=null}function Y0(e,t){let r=t?.maxBufferSize??q0,n=new W,o,s=!1;if(!X0(e))throw new Y("Argument should be a Stream or a Multiaddr");let i=l=>{if(n.append(l.data),n.byteLength>r){let u=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${u} > ${r}`))}o?.resolve()};e.addEventListener("message",i);let a=l=>{l.error!=null?o?.reject(l.error):o?.resolve()};e.addEventListener("close",a);let c=()=>{o?.resolve()};e.addEventListener("remoteCloseWrite",c);let f={readBuffer:n,async read(l){if(s===!0)throw new ns("Stream was unwrapped");if(Xa(e)){if(n.byteLength===0&&l?.bytes==null)return null;if(l?.bytes!=null&&n.byteLength<l.bytes)throw e.log.error("closed after reading %d/%d bytes",n.byteLength,l.bytes),new sr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${l.bytes} bytes`)}let u=l?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=u){o.resolve();break}if(await me(o.promise,l?.signal),Xa(e)){if(n.byteLength===0&&l?.bytes==null)return null;break}o=Promise.withResolvers()}let d=l?.bytes??n.byteLength;if(n.byteLength<d){if(Xa(e))throw e.log.error("closed while reading %d/%d bytes",n.byteLength,d),new sr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return f.read(l)}let m=n.sublist(0,d);return n.consume(d),m},async write(l,u){if(s===!0)throw new ns("Stream was unwrapped");e.send(l)||await St(e,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,e.removeEventListener("message",i),e.removeEventListener("close",a),e.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(e.log("stream unwrapped with %d unread bytes",n.byteLength),e.push(n))),e}};return f}function os(e,t={}){let r=Y0(e,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=et(t.maxDataLength));let n=t?.lengthDecoder??ce,o=t?.lengthEncoder??So;return{async read(i){let a=-1,c=new W;for(;;){let l=await r.read({...i,bytes:1});if(l==null)break;c.append(l);try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Pn("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Za(`Message length length too long - ${c.byteLength} > ${t.maxLengthLength}`);if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Ya(`Message length too long - ${a} > ${t.maxDataLength}`);let f=await r.read({...i,bytes:a});if(f==null)throw e.log.error("tried to read %d bytes but the stream closed",a),new sr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(f.byteLength!==a)throw e.log.error("read %d/%d bytes before the stream closed",f.byteLength,a),new sr(`Unexpected EOF - read ${f.byteLength}/${a} bytes before the stream closed`);return f},async write(i,a){await r.write(new W(o(i.byteLength),i),a)},async writeV(i,a){let c=new W(...i.flatMap(f=>[o(f.byteLength),f]));await r.write(c,a)},unwrap(){return r.unwrap()}}}function ss(e,t){let r=os(e,t),n={read:async(o,s)=>{let i=await r.read(s);return o.decode(i)},write:async(o,s,i)=>{await r.write(s.encode(o),i)},writeV:async(o,s,i)=>{await r.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}var Z0=1024*1024*4,Q0=1024*1024*4,is=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(t={}){this.buffer=new W,this.maxBufferSize=t.maxBufferSize??Z0,this.maxDataLength=t.maxDataLength??Q0,this.lengthDecoder=t.lengthDecoder??ce,this.encodingLength=t.encodingLength??et}*decode(t){if(this.buffer.append(t),this.buffer.byteLength>this.maxBufferSize)throw new Y(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let r;try{r=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(r<0||r>this.maxDataLength)throw new Pn("Invalid message length");let n=this.encodingLength(r),o=n+r;if(this.buffer.byteLength>=o){let s=this.buffer.sublist(n,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}};var as=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Vr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},cs=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},On=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function fs(e){return e[Symbol.asyncIterator]!=null}function Al(e,t){if(e.byteLength>t)throw new Vr("Message length too long")}var ls=e=>{let t=et(e),r=it(t);return So(e,r),ls.bytes=t,r};ls.bytes=0;function Nn(e,t){t=t??{};let r=t.lengthEncoder??ls,n=t?.maxDataLength??4194304;function*o(s){Al(s,n);let i=r(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return fs(e)?(async function*(){for await(let s of e)yield*o(s)})():(function*(){for(let s of e)yield*o(s)})()}Nn.single=(e,t)=>{t=t??{};let r=t.lengthEncoder??ls,n=t?.maxDataLength??4194304;return Al(e,n),new W(r(e.byteLength),e)};var ir;(function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(ir||(ir={}));var Qa=e=>{let t=ce(e);return Qa.bytes=et(t),t};Qa.bytes=0;function Un(e,t){let r=new W,n=ir.LENGTH,o=-1,s=t?.lengthDecoder??Qa,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===ir.LENGTH)try{if(o=s(r),o<0)throw new as("Invalid message length");if(o>a)throw new Vr("Message length too long");let f=s.bytes;r.consume(f),t?.onLength!=null&&t.onLength(o),n=ir.DATA}catch(f){if(f instanceof RangeError){if(r.byteLength>i)throw new cs("Message length length too long");break}throw f}if(n===ir.DATA){if(r.byteLength<o)break;let f=r.sublist(0,o);r.consume(o),t?.onData!=null&&t.onData(f),yield f,n=ir.LENGTH}}}return fs(e)?(async function*(){for await(let f of e)r.append(f),yield*c();if(r.byteLength>0)throw new On("Unexpected end of input")})():(function*(){for(let f of e)r.append(f),yield*c();if(r.byteLength>0)throw new On("Unexpected end of input")})()}Un.fromReader=(e,t)=>{let r=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await e.next(r);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}})();return Un(n,{...t??{},onLength:s=>{r=s}})};var vl=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},em=(function(){function e(t,r,n){this.name=t,this.version=r,this.os=n,this.type="browser"}return e})();var rm=(function(){function e(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return e})();var nm=(function(){function e(t,r,n,o){this.name=t,this.version=r,this.os=n,this.bot=o,this.type="bot-device"}return e})();var om=(function(){function e(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return e})();var sm=(function(){function e(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return e})();var im=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,am=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Cl=3,cm=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",im]],_l=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function Il(e){return e?Ll(e):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new sm:typeof navigator<"u"?Ll(navigator.userAgent):lm()}function fm(e){return e!==""&&cm.reduce(function(t,r){var n=r[0],o=r[1];if(t)return t;var s=o.exec(e);return!!s&&[n,s]},!1)}function Ll(e){var t=fm(e);if(!t)return null;var r=t[0],n=t[1];if(r==="searchbot")return new om;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<Cl&&(o=vl(vl([],o,!0),hm(Cl-o.length),!0)):o=[];var s=o.join("."),i=um(e),a=am.exec(e);return a&&a[1]?new nm(r,s,i,a[1]):new em(r,s,i)}function um(e){for(var t=0,r=_l.length;t<r;t++){var n=_l[t],o=n[0],s=n[1],i=s.exec(e);if(i)return o}return null}function lm(){var e=typeof process<"u"&&process.version;return e?new rm(process.version.slice(1)):null}function hm(e){for(var t=[],r=0;r<e;r++)t.push("0");return t}var Bl=Il(),hs=Bl!=null&&Bl.name==="firefox";async function Ja(e){return e=e??{},typeof e=="function"&&(e=await e()),e.iceServers=e.iceServers??gl.map(t=>({urls:[t]})),e}var Dl=(e=32)=>yl+[...Array(e)].map(()=>Va.at(Math.floor(Math.random()*Va.length))).join("");var tc=class extends rs{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(t){super({...t,maxMessageSize:(t.maxMessageSize??Kr)-xl}),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=Fr(),this.maxBufferedAmount=t.maxBufferedAmount??bl,this.finAckTimeout=t.finAckTimeout??wl,this.channel.onclose=()=>{this.log.trace("received datachannel close event"),this.onRemoteCloseWrite(),this.onTransportClosed()},this.channel.onerror=n=>{let o=n.error;this.log.trace("received datachannel error event - %e",o),this.abort(o)},this.channel.onmessage=async n=>{this.log("incoming message %d bytes",n.data.byteLength);let{data:o}=n;o===null||o.byteLength===0||this.incomingData.push(new Uint8Array(o,0,o.byteLength))},this.channel.bufferedAmountLowThreshold=0,this.channel.onbufferedamountlow=()=>{this.writableNeedsDrain&&this.safeDispatchEvent("drain")},Promise.resolve().then(async()=>{for await(let n of Un(this.incomingData))this.processIncomingProtobuf(n)}).catch(n=>{this.log.error("error processing incoming data channel messages - %e",n)});let r=()=>{this.channel.readyState==="open"&&(this.log.trace("stream closed, closing underlying datachannel"),this.channel.close())};this.addEventListener("close",r),this.channel.readyState!=="open"&&(this.log('channel ready state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),St(this.channel,"open",{rejectionEvents:["close","error"]}).then(()=>{this.log('channel ready state is now "%s", dispatching drain',this.channel.readyState),this.safeDispatchEvent("drain")}).catch(n=>{this.abort(n.error??n)}))}sendNewStream(){}_sendMessage(t){if(this.channel.readyState!=="open")throw new zt(`Invalid datachannel state - ${this.channel.readyState}`);if(this.log.trace('sending message, channel state "%s"',this.channel.readyState),hs){this.channel.send(t.subarray());return}for(let r of t)this.channel.send(r)}sendData(t){return this.channel.readyState!=="open"?{sentBytes:0,canSendMore:!1}:(this._sendMessage(Nn.single(Lt.encode({message:t.subarray()}))),{sentBytes:t.byteLength,canSendMore:this.channel.bufferedAmount<this.maxBufferedAmount})}sendReset(t){try{this.log.error("sending reset - %e",t),this._sendFlag(Lt.Flag.RESET),this.receivedFinAck?.reject(t)}catch(r){this.log.error("failed to send reset - %e",r)}}async sendCloseWrite(t){this._sendFlag(Lt.Flag.FIN),t?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let r=t?.signal??AbortSignal.timeout(this.finAckTimeout),n=[St(this.channel,"close",{signal:r}),St(this.channel,"error",{signal:r})];await Promise.any([me(this.receivedFinAck.promise,r),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(t){this._sendFlag(Lt.Flag.STOP_SENDING),t?.signal?.throwIfAborted()}processIncomingProtobuf(t){let r=Lt.decode(t);r.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new W(r.message)),r.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',r.flag,this.writeStatus,this.readStatus),r.flag===Lt.Flag.FIN&&(this._sendFlag(Lt.Flag.FIN_ACK),this.onRemoteCloseWrite()),r.flag===Lt.Flag.RESET&&(this.receivedFinAck?.reject(new hr("The stream was reset")),this.onRemoteReset()),r.flag===Lt.Flag.STOP_SENDING&&this.onRemoteCloseRead(),r.flag===Lt.Flag.FIN_ACK&&this.receivedFinAck?.resolve())}_sendFlag(t){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',t.toString(),this.channel.readyState),!1;this.log.trace("sending flag %s",t.toString());let r=Lt.encode({flag:t}),n=Nn.single(r);try{return this._sendMessage(n),!0}catch(o){this.log.error("could not send flag %s - %e",t.toString(),o)}return!1}sendPause(){}sendResume(){}};function kn(e){let{channel:t,direction:r,isHandshake:n}=e;return new tc({...e,id:`${t.id}`,log:e.log.newScope(`${n===!0?"handshake":r}:${t.id}`),protocol:""})}var Fe=class{protocol;peerConnection;metrics;dataChannelOptions;earlyDataChannels;constructor(t){this.onEarlyDataChannel=this.onEarlyDataChannel.bind(this),this.peerConnection=t.peerConnection,this.metrics=t.metrics,this.protocol=t.protocol??$a,this.dataChannelOptions=t.dataChannelOptions??{},this.peerConnection.addEventListener("datachannel",this.onEarlyDataChannel),this.earlyDataChannels=[]}onEarlyDataChannel(t){this.earlyDataChannels.push(t.channel)}createStreamMuxer(t){return this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel),new ec(t,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,earlyDataChannels:this.earlyDataChannels})}},ec=class extends es{peerConnection;dataChannelOptions;constructor(t,r){super(t,{...r,name:"muxer"}),this.peerConnection=r.peerConnection,this.protocol=r.protocol??$a,this.dataChannelOptions=r.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{this.onDataChannel(n)},queueMicrotask(()=>{if(this.status!=="open"){r.earlyDataChannels.forEach(n=>{n.close()});return}r.earlyDataChannels.forEach(n=>{this.onDataChannel(n)})})}onDataChannel(t){if(this.log("incoming datachannel with channel id %d, protocol %s and status %s",t.id,t.protocol,t.readyState),t.label==="init"){this.log.trace("closing init channel %d",t.id),t.close();return}let r=kn({...this.streamOptions,...this.dataChannelOptions,channel:t,direction:"inbound",log:this.log});this.onRemoteStream(r)}async onCreateStream(t){let r=this.peerConnection.createDataChannel("",{});return this.log("open channel %d for protocol %s",r.id,t?.protocol),kn({...t,...this.dataChannelOptions,channel:r,direction:"outbound",log:this.log})}onData(){}};var rc=class extends ts{peerConnection;constructor(t){super(t),this.peerConnection=t.peerConnection;let r=t.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change %s initial state %s",this.peerConnection.connectionState,r),(this.peerConnection.connectionState==="disconnected"||this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.onTransportClosed(),this.peerConnection.close())}}sendData(t){return{sentBytes:t.byteLength,canSendMore:!0}}async sendClose(t){this.peerConnection.close(),t?.signal?.throwIfAborted()}sendReset(){this.peerConnection.close()}sendPause(){}sendResume(){}},Mn=e=>new rc(e);var ds=globalThis.RTCPeerConnection,ps=globalThis.RTCSessionDescription,Tl=globalThis.RTCIceCandidate;var kt=class extends Event{type;detail;constructor(t,r){super(t),this.type=t,this.detail=r}};var Ve=class extends Error{constructor(t){super(`WebRTC transport error: ${t}`),this.name="WebRTCTransportError"}},Ht=class extends Ve{constructor(t="SDP handshake failed"){super(t),this.name="SDPHandshakeFailedError"}};var ms=class extends Ve{constructor(t,r){super(`Invalid fingerprint "${t}" within ${r}`),this.name="WebRTC/InvalidFingerprintError"}};var gs=class extends Ve{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},ys=class extends Ve{constructor(t){super(`unsupported hash algorithm code: ${t} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var Nt;(function(e){let t;(function(a){a.SDP_OFFER="SDP_OFFER",a.SDP_ANSWER="SDP_ANSWER",a.ICE_CANDIDATE="ICE_CANDIDATE"})(t=e.Type||(e.Type={}));let r;(function(a){a[a.SDP_OFFER=0]="SDP_OFFER",a[a.SDP_ANSWER=1]="SDP_ANSWER",a[a.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(r||(r={})),(function(a){a.codec=()=>rr(r)})(t=e.Type||(e.Type={}));let n;e.codec=()=>(n==null&&(n=Oe((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),e.Type.codec().encode(a.type,c)),a.data!=null&&(c.uint32(18),c.string(a.data)),f.lengthDelimited!==!1&&c.ldelim()},(a,c,f={})=>{let l={},u=c==null?a.len:a.pos+c;for(;a.pos<u;){let d=a.uint32();switch(d>>>3){case 1:{l.type=e.Type.codec().decode(a);break}case 2:{l.data=a.string();break}default:{a.skipType(d&7);break}}}return l},function*(a,c,f,l={}){let u=c==null?a.len:a.pos+c;for(;a.pos<u;){let d=a.uint32();switch(d>>>3){case 1:{yield{field:`${f}.type`,value:e.Type.codec().decode(a)};break}case 2:{yield{field:`${f}.data`,value:a.string()};break}default:{a.skipType(d&7);break}}}})),n);function o(a){return Re(a,e.codec())}e.encode=o;function s(a,c){return Te(a,e.codec(),c)}e.decode=s;function i(a,c){return Pe(a,e.codec(),c)}e.stream=i})(Nt||(Nt={}));var bs=async(e,t,r)=>{try{let n=Promise.withResolvers();for(dm(e,n);;){let o=await Promise.race([n.promise,t.read({signal:r.signal})]);if(o==null){r.signal?.throwIfAborted();break}if(o.type!==Nt.Type.ICE_CANDIDATE)throw new to("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){r.onProgress?.(new kt("webrtc:end-of-ice-candidates")),r.log.trace("end-of-candidates received");continue}let i=new Tl(s);r.log.trace("%s received new ICE candidate %o",r.direction,s);try{r.onProgress?.(new kt("webrtc:add-ice-candidate",i.candidate)),await e.addIceCandidate(i)}catch(a){r.log.error("%s bad candidate received %o - %e",r.direction,s,a)}}}catch(n){if(r.log.error("%s error parsing ICE candidate - %e",r.direction,n),r.signal?.aborted===!0&&e.connectionState!=="connected")throw n}};function dm(e,t){if(e.connectionState==="connected"){t.resolve();return}e.onconnectionstatechange=r=>{switch(e.connectionState){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new Xn(`RTCPeerConnection connection state became "${e.connectionState}"`));break;default:break}}}function xs(e){let t;for(let r of e.getComponents())r.name==="p2p"&&(t=Rr(r.value??""));if(t==null)throw new Zn("Remote peerId must be present in multiaddr");return t}async function Rl({rtcConfiguration:e,dataChannel:t,signal:r,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:f}){let{circuitAddress:l,targetPeer:u}=Pl(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing circuit address: %a",l);let d=s.getConnections(u),m;d.length===0?(f?.(new kt("webrtc:dial-relay")),m=await i.dial(l,{signal:r,onProgress:f})):(f?.(new kt("webrtc:reuse-relay-connection")),m=d[0]),f?.(new kt("webrtc:open-signaling-stream"));let p=await m.newStream(Rn,{signal:r,runOnLimitedConnection:!0}),w=ss(p).pb(Nt),h=new ds(e);h.addEventListener("connectionstatechange",()=>{h.connectionState==="closed"&&h.close()});let b=new Fe({peerConnection:h,dataChannelOptions:t});try{let v=h.createDataChannel("init");h.onicecandidate=({candidate:O})=>{if(h.connectionState==="connected"){a.trace("ignore new ice candidate as peer connection is already connected");return}if(O==null||O?.candidate===""){a.trace("initiator detected end of ICE candidates");return}let K=JSON.stringify(O?.toJSON()??null);a.trace("initiator sending ICE candidate %o",O),w.write({type:Nt.Type.ICE_CANDIDATE,data:K},{signal:r}).catch(_=>{a.error("error sending ICE candidate - %e",_)})},h.onicecandidateerror=O=>{a.error("initiator ICE candidate error",O)};let E=await h.createOffer().catch(O=>{throw a.error("could not execute createOffer - %e",O),new Ht("Failed to set createOffer")});a.trace("initiator send SDP offer %s",E.sdp),f?.(new kt("webrtc:send-sdp-offer")),await w.write({type:Nt.Type.SDP_OFFER,data:E.sdp},{signal:r}),await h.setLocalDescription(E).catch(O=>{throw a.error("could not execute setLocalDescription - %e",O),new Ht("Failed to set localDescription")}),f?.(new kt("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let D=await w.read({signal:r});if(D.type!==Nt.Type.SDP_ANSWER)throw new Ht("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",D.data);let k=new ps({type:"answer",sdp:D.data});return await h.setRemoteDescription(k).catch(O=>{throw a.error("could not execute setRemoteDescription - %e",O),new Ht("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),f?.(new kt("webrtc:read-ice-candidates")),await bs(h,w,{direction:"initiator",signal:r,log:a,onProgress:f}),a.trace("initiator connected"),v.readyState!=="open"&&(a.trace("wait for init channel to open"),await St(v,"open",{signal:r})),a.trace("closing init channel"),v.close(),a.trace("waiting for init channel to close"),await St(v,"close",{signal:r}),f?.(new kt("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await p.close({signal:r}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:h,muxerFactory:b}}catch(v){throw a.error("outgoing signaling error - %e",v),h.close(),p.abort(v),v}finally{h.onicecandidate=null,h.onicecandidateerror=null}}var Ol=ot(pl.matchers[0],nt(290)),ws=class e extends be{transportManager;shutdownController;events;constructor(t,r){super(),this.transportManager=t.transportManager,this.events=t.events,this.shutdownController=r.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(t){t.detail.getAddrs().filter(n=>Ol.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(t=>!(t instanceof e)).map(t=>t.getAddrs().filter(r=>Ol.exactMatch(r)).map(r=>r.encapsulate("/webrtc"))).flat()}updateAnnounceAddrs(){}async close(){this.events.removeEventListener("transport:listening",this.onTransportListening),this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function Nl(e,t,{peerConnection:r,signal:n,log:o}){o.trace("new inbound signaling stream");let s=ss(e).pb(Nt);try{r.onicecandidate=({candidate:u})=>{if(r.connectionState==="connected"){o.trace("ignore new ice candidate as peer connection is already connected");return}if(u==null||u?.candidate===""){o.trace("recipient detected end of ICE candidates");return}let d=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",d),s.write({type:Nt.Type.ICE_CANDIDATE,data:d},{signal:n}).catch(m=>{o.error("error sending ICE candidate - %e",m)})},o.trace("recipient read SDP offer");let c=await s.read({signal:n});if(c.type!==Nt.Type.SDP_OFFER)throw new Ht(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let f=new ps({type:"offer",sdp:c.data});await r.setRemoteDescription(f).catch(u=>{throw o.error("could not execute setRemoteDescription - %e",u),new Ht("Failed to set remoteDescription")});let l=await r.createAnswer().catch(u=>{throw o.error("could not execute createAnswer - %e",u),new Ht("Failed to create answer")});o.trace("recipient send SDP answer %s",l.sdp),await s.write({type:Nt.Type.SDP_ANSWER,data:l.sdp},{signal:n}),await r.setLocalDescription(l).catch(u=>{throw o.error("could not execute setLocalDescription - %e",u),new Ht("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await bs(r,s,{direction:"recipient",signal:n,log:o})}catch(c){if(r.connectionState!=="connected")throw o.error("error while handling signaling stream from peer %a - %e",t.remoteAddr,c),r.close(),c;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",t.remoteAddr,c)}let i=xs(t.remoteAddr),a=kr(`/webrtc/p2p/${i}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:i}}var Es=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,r={}){this.components=t,this.init=r,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[oo]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[pr]=["@libp2p/transport"];[$c]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(Rn,(t,r)=>{let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(t,r,n).catch(o=>{this.log.error("failed to handle incoming connect from %p - %e",r.remotePeer,o)}).finally(()=>{n.clear()})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(Rn),this._started=!1}createListener(t){return new ws(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(ml.exactMatch)}dialFilter(t){return this.listenFilter(t)}async dial(t,r){this.log.trace("dialing address: %a",t);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await Rl({rtcConfiguration:await Ja(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:t,dataChannelOptions:this.init.dataChannel,signal:r.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:r.onProgress}),i=Mn({peerConnection:o,remoteAddr:n,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")}),a=await r.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,remotePeer:xs(t),muxerFactory:s,onProgress:r.onProgress,signal:r.signal});return this._closeOnShutdown(o,i),a}async _onProtocol(t,r,n){let o=new ds(await Ja(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{o.connectionState==="closed"&&o.close()});let s=new Fe({peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i,remotePeer:a}=await Nl(t,r,{peerConnection:o,signal:n,log:this.log});await t.close({signal:n});let c=Mn({peerConnection:o,remoteAddr:i,metrics:this.metrics?.listenerEvents,direction:"inbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")});await this.components.upgrader.upgradeInbound(c,{skipEncryption:!0,skipProtection:!0,remotePeer:a,muxerFactory:s,signal:n}),this._closeOnShutdown(o,c)}catch(i){throw this.log.error("incoming signaling error - %e",i),o.close(),t.abort(i),i}}_closeOnShutdown(t,r){let n=()=>{r.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection - %e",o)})};this.shutdownController.signal.addEventListener("abort",n),t.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function Pl(e){let t=e.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(t==null)throw new Y("Destination peer id was missing");return{circuitAddress:kr(e.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:Rr(t)}}var $r=!!globalThis.process?.env?.DUMP_SESSION_KEYS,nc=16;function pm(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Ss(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function As(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function bt(e,t,r=""){let n=pm(e),o=e?.length,s=t!==void 0;if(!n||s&&o!==t){let i=r&&`"${r}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function oc(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ul(e,t){bt(e,void 0,"output");let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function ge(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function ye(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function mm(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var gm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function kl(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function Ml(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}var sc=(e,t)=>{function r(n,...o){if(bt(n,void 0,"key"),!gm)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){let l=o[0];bt(l,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let s=e.tagLength;s&&o[1]!==void 0&&bt(o[1],void 0,"AAD");let i=t(n,...o),a=(l,u)=>{if(u!==void 0){if(l!==2)throw new Error("cipher output not supported");bt(u,void 0,"output")}},c=!1;return{encrypt(l,u){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,bt(l),a(i.encrypt.length,u),i.encrypt(l,u)},decrypt(l,u){if(bt(l),s&&l.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,u),i.decrypt(l,u)}}}return Object.assign(r,e),r};function ic(e,t,r=!0){if(t===void 0)return new Uint8Array(e);if(t.length!==e)throw new Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(r&&!ym(t))throw new Error("invalid output, must be aligned");return t}function Kl(e,t,r){Ss(r);let n=new Uint8Array(16),o=mm(n);return o.setBigUint64(0,BigInt(t),r),o.setBigUint64(8,BigInt(e),r),n}function ym(e){return e.byteOffset%4===0}function Wr(e){return Uint8Array.from(e)}var Fl=e=>Uint8Array.from(e.split(""),t=>t.charCodeAt(0)),bm=Fl("expand 16-byte k"),xm=Fl("expand 32-byte k"),wm=ge(bm),Em=ge(xm);function U(e,t){return e<<t|e>>>32-t}function ac(e){return e.byteOffset%4===0}var vs=64,Sm=16,Vl=2**32-1,Hl=Uint32Array.of();function Am(e,t,r,n,o,s,i,a){let c=o.length,f=new Uint8Array(vs),l=ge(f),u=ac(o)&&ac(s),d=u?ge(o):Hl,m=u?ge(s):Hl;for(let p=0;p<c;i++){if(e(t,r,n,l,i,a),i>=Vl)throw new Error("arx: counter overflow");let w=Math.min(vs,c-p);if(u&&w===vs){let h=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let b=0,v;b<Sm;b++)v=h+b,m[v]=d[v]^l[b];p+=vs;continue}for(let h=0,b;h<w;h++)b=p+h,s[b]=o[b]^f[h];p+=w}}function cc(e,t){let{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=kl({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return As(o),As(i),Ss(s),Ss(r),(a,c,f,l,u=0)=>{bt(a,void 0,"key"),bt(c,void 0,"nonce"),bt(f,void 0,"data");let d=f.length;if(l===void 0&&(l=new Uint8Array(d)),bt(l,void 0,"output"),As(u),u<0||u>=Vl)throw new Error("arx: counter overflow");if(l.length<d)throw new Error(`arx: output (${l.length}) is shorter than data (${d})`);let m=[],p=a.length,w,h;if(p===32)m.push(w=Wr(a)),h=Em;else if(p===16&&r)w=new Uint8Array(32),w.set(a),w.set(a,16),h=wm,m.push(w);else throw bt(a,32,"arx key"),new Error("invalid key size");ac(c)||m.push(c=Wr(c));let b=ge(w);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,b,ge(c.subarray(0,16)),b),c=c.subarray(16)}let v=16-o;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let D=new Uint8Array(12);D.set(c,s?0:12-c.length),c=D,m.push(c)}let E=ge(c);return Am(e,h,b,E,f,l,u,i),ye(...m),l}}function At(e,t){return e[t++]&255|(e[t++]&255)<<8}var fc=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;constructor(t){t=Wr(bt(t,32,"key"));let r=At(t,0),n=At(t,2),o=At(t,4),s=At(t,6),i=At(t,8),a=At(t,10),c=At(t,12),f=At(t,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|f<<8)&8191,this.r[9]=f>>>5&127;for(let l=0;l<8;l++)this.pad[l]=At(t,16+2*l)}process(t,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],f=i[2],l=i[3],u=i[4],d=i[5],m=i[6],p=i[7],w=i[8],h=i[9],b=At(t,r+0),v=At(t,r+2),E=At(t,r+4),D=At(t,r+6),k=At(t,r+8),O=At(t,r+10),K=At(t,r+12),_=At(t,r+14),A=s[0]+(b&8191),N=s[1]+((b>>>13|v<<3)&8191),M=s[2]+((v>>>10|E<<6)&8191),T=s[3]+((E>>>7|D<<9)&8191),x=s[4]+((D>>>4|k<<12)&8191),g=s[5]+(k>>>1&8191),y=s[6]+((k>>>14|O<<2)&8191),C=s[7]+((O>>>11|K<<5)&8191),I=s[8]+((K>>>8|_<<8)&8191),L=s[9]+(_>>>5|o),S=0,B=S+A*a+N*(5*h)+M*(5*w)+T*(5*p)+x*(5*m);S=B>>>13,B&=8191,B+=g*(5*d)+y*(5*u)+C*(5*l)+I*(5*f)+L*(5*c),S+=B>>>13,B&=8191;let R=S+A*c+N*a+M*(5*h)+T*(5*w)+x*(5*p);S=R>>>13,R&=8191,R+=g*(5*m)+y*(5*d)+C*(5*u)+I*(5*l)+L*(5*f),S+=R>>>13,R&=8191;let P=S+A*f+N*c+M*a+T*(5*h)+x*(5*w);S=P>>>13,P&=8191,P+=g*(5*p)+y*(5*m)+C*(5*d)+I*(5*u)+L*(5*l),S+=P>>>13,P&=8191;let j=S+A*l+N*f+M*c+T*a+x*(5*h);S=j>>>13,j&=8191,j+=g*(5*w)+y*(5*p)+C*(5*m)+I*(5*d)+L*(5*u),S+=j>>>13,j&=8191;let z=S+A*u+N*l+M*f+T*c+x*a;S=z>>>13,z&=8191,z+=g*(5*h)+y*(5*w)+C*(5*p)+I*(5*m)+L*(5*d),S+=z>>>13,z&=8191;let V=S+A*d+N*u+M*l+T*f+x*c;S=V>>>13,V&=8191,V+=g*a+y*(5*h)+C*(5*w)+I*(5*p)+L*(5*m),S+=V>>>13,V&=8191;let X=S+A*m+N*d+M*u+T*l+x*f;S=X>>>13,X&=8191,X+=g*c+y*a+C*(5*h)+I*(5*w)+L*(5*p),S+=X>>>13,X&=8191;let rt=S+A*p+N*m+M*d+T*u+x*l;S=rt>>>13,rt&=8191,rt+=g*f+y*c+C*a+I*(5*h)+L*(5*w),S+=rt>>>13,rt&=8191;let lt=S+A*w+N*p+M*m+T*d+x*u;S=lt>>>13,lt&=8191,lt+=g*l+y*f+C*c+I*a+L*(5*h),S+=lt>>>13,lt&=8191;let Z=S+A*h+N*w+M*p+T*m+x*d;S=Z>>>13,Z&=8191,Z+=g*u+y*l+C*f+I*c+L*a,S+=Z>>>13,Z&=8191,S=(S<<2)+S|0,S=S+B|0,B=S&8191,S=S>>>13,R+=S,s[0]=B,s[1]=R,s[2]=P,s[3]=j,s[4]=z,s[5]=V,s[6]=X,s[7]=rt,s[8]=lt,s[9]=Z}finalize(){let{h:t,pad:r}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+r[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+r[a]|0)+(i>>>16)|0,t[a]=i&65535;ye(n)}update(t){oc(this),bt(t),t=Wr(t);let{buffer:r,blockLen:n}=this,o=t.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(t,s);continue}r.set(t.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){ye(this.h,this.r,this.buffer,this.pad)}digestInto(t){oc(this),Ul(t,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:o}=this;if(o){for(r[o++]=1;o<16;o++)r[o]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)t[s++]=n[i]>>>0,t[s++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}};function vm(e){let t=(n,o)=>e(o).update(n).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}var $l=vm(e=>new fc(e));function ql(e,t,r,n,o,s=20){let i=e[0],a=e[1],c=e[2],f=e[3],l=t[0],u=t[1],d=t[2],m=t[3],p=t[4],w=t[5],h=t[6],b=t[7],v=o,E=r[0],D=r[1],k=r[2],O=i,K=a,_=c,A=f,N=l,M=u,T=d,x=m,g=p,y=w,C=h,I=b,L=v,S=E,B=D,R=k;for(let j=0;j<s;j+=2)O=O+N|0,L=U(L^O,16),g=g+L|0,N=U(N^g,12),O=O+N|0,L=U(L^O,8),g=g+L|0,N=U(N^g,7),K=K+M|0,S=U(S^K,16),y=y+S|0,M=U(M^y,12),K=K+M|0,S=U(S^K,8),y=y+S|0,M=U(M^y,7),_=_+T|0,B=U(B^_,16),C=C+B|0,T=U(T^C,12),_=_+T|0,B=U(B^_,8),C=C+B|0,T=U(T^C,7),A=A+x|0,R=U(R^A,16),I=I+R|0,x=U(x^I,12),A=A+x|0,R=U(R^A,8),I=I+R|0,x=U(x^I,7),O=O+M|0,R=U(R^O,16),C=C+R|0,M=U(M^C,12),O=O+M|0,R=U(R^O,8),C=C+R|0,M=U(M^C,7),K=K+T|0,L=U(L^K,16),I=I+L|0,T=U(T^I,12),K=K+T|0,L=U(L^K,8),I=I+L|0,T=U(T^I,7),_=_+x|0,S=U(S^_,16),g=g+S|0,x=U(x^g,12),_=_+x|0,S=U(S^_,8),g=g+S|0,x=U(x^g,7),A=A+N|0,B=U(B^A,16),y=y+B|0,N=U(N^y,12),A=A+N|0,B=U(B^A,8),y=y+B|0,N=U(N^y,7);let P=0;n[P++]=i+O|0,n[P++]=a+K|0,n[P++]=c+_|0,n[P++]=f+A|0,n[P++]=l+N|0,n[P++]=u+M|0,n[P++]=d+T|0,n[P++]=m+x|0,n[P++]=p+g|0,n[P++]=w+y|0,n[P++]=h+C|0,n[P++]=b+I|0,n[P++]=v+L|0,n[P++]=E+S|0,n[P++]=D+B|0,n[P++]=k+R|0}function Cm(e,t,r,n){let o=e[0],s=e[1],i=e[2],a=e[3],c=t[0],f=t[1],l=t[2],u=t[3],d=t[4],m=t[5],p=t[6],w=t[7],h=r[0],b=r[1],v=r[2],E=r[3];for(let k=0;k<20;k+=2)o=o+c|0,h=U(h^o,16),d=d+h|0,c=U(c^d,12),o=o+c|0,h=U(h^o,8),d=d+h|0,c=U(c^d,7),s=s+f|0,b=U(b^s,16),m=m+b|0,f=U(f^m,12),s=s+f|0,b=U(b^s,8),m=m+b|0,f=U(f^m,7),i=i+l|0,v=U(v^i,16),p=p+v|0,l=U(l^p,12),i=i+l|0,v=U(v^i,8),p=p+v|0,l=U(l^p,7),a=a+u|0,E=U(E^a,16),w=w+E|0,u=U(u^w,12),a=a+u|0,E=U(E^a,8),w=w+E|0,u=U(u^w,7),o=o+f|0,E=U(E^o,16),p=p+E|0,f=U(f^p,12),o=o+f|0,E=U(E^o,8),p=p+E|0,f=U(f^p,7),s=s+l|0,h=U(h^s,16),w=w+h|0,l=U(l^w,12),s=s+l|0,h=U(h^s,8),w=w+h|0,l=U(l^w,7),i=i+u|0,b=U(b^i,16),d=d+b|0,u=U(u^d,12),i=i+u|0,b=U(b^i,8),d=d+b|0,u=U(u^d,7),a=a+c|0,v=U(v^a,16),m=m+v|0,c=U(c^m,12),a=a+c|0,v=U(v^a,8),m=m+v|0,c=U(c^m,7);let D=0;n[D++]=o,n[D++]=s,n[D++]=i,n[D++]=a,n[D++]=h,n[D++]=b,n[D++]=v,n[D++]=E}var _m=cc(ql,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Lm=cc(ql,{counterRight:!1,counterLength:8,extendNonceFn:Cm,allowShortKeys:!1});var Im=new Uint8Array(16),Wl=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(Im.subarray(r))},Bm=new Uint8Array(32);function Gl(e,t,r,n,o){o!==void 0&&bt(o,void 0,"AAD");let s=e(t,r,Bm),i=Kl(n.length,o?o.length:0,!0),a=$l.create(s);o&&Wl(a,o),Wl(a,n),a.update(i);let c=a.digest();return ye(s,i),c}var zl=e=>(t,r,n)=>({encrypt(s,i){let a=s.length;i=ic(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);e(t,r,c,c,1);let f=Gl(e,t,r,c,n);return i.set(f,a),ye(f),i},decrypt(s,i){i=ic(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),f=Gl(e,t,r,a,n);if(!Ml(c,f))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),e(t,r,i,i,1),ye(f),i}}),uc=sc({blockSize:64,nonceLength:12,tagLength:16},zl(_m)),kS=sc({blockSize:64,nonceLength:24,tagLength:16},zl(Lm));function Xl(e,t,r){return En(e),r===void 0&&(r=new Uint8Array(e.outputLen)),Wa(e,r,t)}var lc=Uint8Array.of(0),jl=Uint8Array.of();function Yl(e,t,r,n=32){En(e),Lo(n,"length"),Ne(t,void 0,"prk");let o=e.outputLen;if(t.length<o)throw new Error('"prk" must be at least HashLen octets');if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);r===void 0?r=jl:Ne(r,void 0,"info");let i=new Uint8Array(s*o),a=Wa.create(e,t),c=a._cloneInto(),f=new Uint8Array(a.outputLen);for(let l=0;l<s;l++)lc[0]=l+1,c.update(l===0?jl:f).update(r).update(lc).digestInto(f),i.set(f,o*l),a._cloneInto(c);return a.destroy(),c.destroy(),fe(f,lc),i.slice(0,n)}var hc={hashSHA256(e){return ke(e.subarray())},getHKDF(e,t){let r=Xl(ke,t,e),o=Yl(ke,r,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let e=pn.utils.randomSecretKey();return{publicKey:pn.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed(e){return{publicKey:pn.getPublicKey(e),privateKey:e}},generateX25519SharedKey(e,t){return pn.getSharedSecret(e.subarray(),t.subarray())},chaCha20Poly1305Encrypt(e,t,r,n){return uc(n,t,r).encrypt(e.subarray())},chaCha20Poly1305Decrypt(e,t,r,n,o){return uc(n,t,r).decrypt(e.subarray(),o)}};var Zl=hc;function Ql(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}var Gr=e=>{let t=it(2);return t[0]=e>>8,t[1]=e,t};Gr.bytes=2;var qr=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};qr.bytes=2;function Jl(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function dc(e,t){!t.enabled||!$r||(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${$(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${$(e.privateKey,"hex")}`)):t("Missing local static keys."))}function pc(e,t){!t.enabled||!$r||(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${$(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${$(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function th(e,t){!t.enabled||!$r||t(e?`REMOTE_STATIC_PUBLIC_KEY ${$(e.subarray(),"hex")}`:"Missing remote static public key.")}function mc(e,t){!t.enabled||!$r||t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${$(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function gc(e,t,r){!r.enabled||!$r||(r(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&$(e.k,"hex")}`),r(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&$(t.k,"hex")}`))}var zr=class e extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=e.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var Dm=0,Tm=4294967295,Rm="Cipherstate has reached maximum n, a new handshake must be performed",Cs=class{n;bytes;view;constructor(t=Dm){this.n=t,this.bytes=pt(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>Tm)throw new Error(Rm)}};var ar=pt(0),jr=class{k;n;crypto;constructor(t,r=void 0,n=0){this.crypto=t,this.k=r,this.n=new Cs(n)}hasKey(){return!!this.k}encryptWithAd(t,r){if(!this.hasKey())return r;this.n.assertValue();let n=this.crypto.encrypt(r,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,r,n){if(!this.hasKey())return r;this.n.assertValue();let o=this.crypto.decrypt(r,this.n.getBytes(),t,this.k,n);return this.n.increment(),o}},yc=class{cs;ck;h;crypto;constructor(t,r){this.crypto=t;let n=G(r,"utf-8");this.h=Pm(t,n),this.ck=this.h,this.cs=new jr(t)}mixKey(t){let[r,n]=this.crypto.hkdf(this.ck,t);this.ck=r,this.cs=new jr(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new W(this.h,t))}encryptAndHash(t){let r=this.cs.encryptWithAd(this.h,t);return this.mixHash(r),r}decryptAndHash(t){let r=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),r}split(){let[t,r]=this.crypto.hkdf(this.ck,ar);return[new jr(this.crypto,t),new jr(this.crypto,r)]}},bc=class{ss;s;e;rs;re;initiator;crypto;constructor(t){let{crypto:r,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:f}=t;this.crypto=r,this.ss=new yc(r,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=f}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let t=this.crypto.generateKeypair();return this.ss.mixHash(t.publicKey),this.e=t,t.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(t,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<r+32)throw new Error("message is not long enough");this.re=t.sublist(r,r+32),this.ss.mixHash(this.re)}readS(t,r=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(t.byteLength<r+n)throw new Error("message is not long enough");let o=t.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Kn=class extends bc{writeMessageA(t){return new W(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let r=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new W(r,n,this.ss.encryptAndHash(t))}writeMessageC(t){let r=this.writeS();return this.writeSE(),new W(r,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(r){throw new zr(`handshake stage 0 validation fail: ${r.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();let r=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+r))}catch(r){throw new zr(`handshake stage 1 validation fail: ${r.message}`)}}readMessageC(t){try{let r=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(r))}catch(r){throw new zr(`handshake stage 2 validation fail: ${r.message}`)}}};function Pm(e,t){if(t.length<=32){let r=pt(32);return r.set(t),r}else return e.hash(t)}var xc=new Float32Array([-0]),$e=new Uint8Array(xc.buffer);function eh(e,t,r){xc[0]=e,t[r]=$e[0],t[r+1]=$e[1],t[r+2]=$e[2],t[r+3]=$e[3]}function rh(e,t){return $e[0]=e[t],$e[1]=e[t+1],$e[2]=e[t+2],$e[3]=e[t+3],xc[0]}var wc=new Float64Array([-0]),It=new Uint8Array(wc.buffer);function nh(e,t,r){wc[0]=e,t[r]=It[0],t[r+1]=It[1],t[r+2]=It[2],t[r+3]=It[3],t[r+4]=It[4],t[r+5]=It[5],t[r+6]=It[6],t[r+7]=It[7]}function oh(e,t){return It[0]=e[t],It[1]=e[t+1],It[2]=e[t+2],It[3]=e[t+3],It[4]=e[t+4],It[5]=e[t+5],It[6]=e[t+6],It[7]=e[t+7],wc[0]}var Om=BigInt(Number.MAX_SAFE_INTEGER),Nm=BigInt(Number.MIN_SAFE_INTEGER),Mt=class e{lo;hi;constructor(t,r){this.lo=t|0,this.hi=r|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?t<16384?t<128?1:2:t<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return cr;if(t<Om&&t>Nm)return this.fromNumber(Number(t));let r=t<0n;r&&(t=-t);let n=t>>32n,o=t-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>sh&&(o=0n,++n>sh&&(n=0n))),new e(Number(o),Number(n))}static fromNumber(t){if(t===0)return cr;let r=t<0;r&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new e(n,o)}static from(t){return typeof t=="number"?e.fromNumber(t):typeof t=="bigint"?e.fromBigInt(t):typeof t=="string"?e.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new e(t.low>>>0,t.high>>>0):cr}},cr=new Mt(0,0);cr.toBigInt=function(){return 0n};cr.zzEncode=cr.zzDecode=function(){return this};cr.length=function(){return 1};var sh=4294967296n;function ih(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:(r&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function ah(e,t,r){if(r-t<1)return"";let o,s=[],i=0,a;for(;t<r;)a=e[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(e[t++]&63)<<6|e[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Ec(e,t,r){let n=r,o,s;for(let i=0;i<e.length;++i)o=e.charCodeAt(i),o<128?t[r++]=o:o<2048?(t[r++]=o>>6|192,t[r++]=o&63|128):(o&64512)===55296&&((s=e.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[r++]=o>>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=o&63|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=o&63|128);return r-n}function qt(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function _s(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}var Sc=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,qt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw qt(this,4);return _s(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw qt(this,4);return _s(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw qt(this,4);let t=rh(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw qt(this,4);let t=oh(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),r=this.pos,n=this.pos+t;if(n>this.len)throw qt(this,t);return this.pos+=t,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let t=this.bytes();return ah(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw qt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw qt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Mt(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw qt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,t}if(this.len-this.pos>4){for(;r<5;++r)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;r<5;++r){if(this.pos>=this.len)throw qt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw qt(this,8);let t=_s(this.buf,this.pos+=4),r=_s(this.buf,this.pos+=4);return new Mt(t,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=gn(this.buf,this.pos);return this.pos+=et(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Ac(e){return new Sc(e instanceof Uint8Array?e:e.subarray())}function Ls(e,t,r){let n=Ac(e);return t.decode(n,void 0,r)}function vc(e){let t=e??8192,r=t>>>1,n,o=t;return function(i){if(i<1||i>r)return it(i);o+i>t&&(n=it(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var fr=class{fn;len;next;val;constructor(t,r,n){this.fn=t,this.len=r,this.next=void 0,this.val=n}};function Cc(){}var Lc=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Um=vc();function km(e){return globalThis.Buffer!=null?it(e):Um(e)}var Fn=class{len;head;tail;states;constructor(){this.len=0,this.head=new fr(Cc,0,0),this.tail=this.head,this.states=null}_push(t,r,n){return this.tail=this.tail.next=new fr(t,r,n),this.len+=r,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Ic((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Is,10,Mt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let r=Mt.fromBigInt(t);return this._push(Is,r.length(),r)}uint64Number(t){return this._push(Be,et(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let r=Mt.fromBigInt(t).zzEncode();return this._push(Is,r.length(),r)}sint64Number(t){let r=Mt.fromNumber(t).zzEncode();return this._push(Is,r.length(),r)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(_c,1,t?1:0)}fixed32(t){return this._push(Hn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let r=Mt.fromBigInt(t);return this._push(Hn,4,r.lo)._push(Hn,4,r.hi)}fixed64Number(t){let r=Mt.fromNumber(t);return this._push(Hn,4,r.lo)._push(Hn,4,r.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(eh,4,t)}double(t){return this._push(nh,8,t)}bytes(t){let r=t.length>>>0;return r===0?this._push(_c,1,0):this.uint32(r)._push(Km,r,t)}string(t){let r=ih(t);return r!==0?this.uint32(r)._push(Ec,r,t):this._push(_c,1,0)}fork(){return this.states=new Lc(this),this.head=this.tail=new fr(Cc,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new fr(Cc,0,0),this.len=0),this}ldelim(){let t=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=r,this.len+=n),this}finish(){let t=this.head.next,r=km(this.len),n=0;for(;t!=null;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}};function _c(e,t,r){t[r]=e&255}function Mm(e,t,r){for(;e>127;)t[r++]=e&127|128,e>>>=7;t[r]=e}var Ic=class extends fr{next;constructor(t,r){super(Mm,t,r),this.next=void 0}};function Is(e,t,r){for(;e.hi!==0;)t[r++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=e.lo&127|128,e.lo=e.lo>>>7;t[r++]=e.lo}function Hn(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function Km(e,t,r){t.set(e,r)}globalThis.Buffer!=null&&(Fn.prototype.bytes=function(e){let t=e.length>>>0;return this.uint32(t),t>0&&this._push(Hm,t,e),this},Fn.prototype.string=function(e){let t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Fm,t,e),this});function Hm(e,t,r){t.set(e,r)}function Fm(e,t,r){e.length<40?Ec(e,t,r):t.utf8Write!=null?t.utf8Write(e,r):t.set(G(e),r)}function Bc(){return new Fn}function Bs(e,t){let r=Bc();return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var Vn;(function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(Vn||(Vn={}));function Dc(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function Ds(e,t){return Dc("message",Vn.LENGTH_DELIMITED,e,t)}var $n=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var Ts;(function(e){let t;e.codec=()=>(t==null&&(t=Ds((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.webtransportCerthashes!=null)for(let s of r.webtransportCerthashes)n.uint32(10),n.bytes(s);if(r.streamMuxers!=null)for(let s of r.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new $n('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(r.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new $n('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(r.string());break}default:{r.skipType(a&7);break}}}return s})),t),e.encode=r=>Bs(r,e.codec()),e.decode=(r,n)=>Ls(r,e.codec(),n)})(Ts||(Ts={}));var Wn;(function(e){let t;e.codec=()=>(t==null&&(t=Ds((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.identityKey!=null&&r.identityKey.byteLength>0&&(n.uint32(10),n.bytes(r.identityKey)),r.identitySig!=null&&r.identitySig.byteLength>0&&(n.uint32(18),n.bytes(r.identitySig)),r.extensions!=null&&(n.uint32(34),Ts.codec().encode(r.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={identityKey:pt(0),identitySig:pt(0)},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{s.identityKey=r.bytes();break}case 2:{s.identitySig=r.bytes();break}case 4:{s.extensions=Ts.codec().decode(r,r.uint32(),{limits:o.limits?.extensions});break}default:{r.skipType(a&7);break}}}return s})),t),e.encode=r=>Bs(r,e.codec()),e.decode=(r,n)=>Ls(r,e.codec(),n)})(Wn||(Wn={}));async function Rc(e,t,r){let n=await e.sign(uh(t));return Wn.encode({identityKey:Se(e.publicKey),identitySig:n,extensions:r})}async function Pc(e,t,r){try{let n=Wn.decode(e),o=vn(n.identityKey);if(r?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${r}`);if(!t)throw new Error("Remote static does not exist");let s=uh(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new zn(n.message)}}function uh(e){let t=G("noise-libp2p-static-key:");return e instanceof Uint8Array?Tt([t,e],t.length+e.length):(e.prepend(t),e)}var Tc=class extends He{stream;handshake;metrics;decoder;constructor(t,r,n){super({log:t.log,inactivityTimeout:t.inactivityTimeout,maxReadBufferLength:t.maxReadBufferLength,direction:t.direction}),this.stream=t,this.handshake=r,this.metrics=n,this.decoder=new is({lengthDecoder:qr,maxBufferSize:16*1024*1024,encodingLength:()=>2});let o=c=>{try{for(let f of this.decoder.decode(c.data))this.onData(this.decrypt(f))}catch(f){this.abort(f)}};this.stream.addEventListener("message",o);let s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(t){let r=new W;for(let n=0;n<t.byteLength;n+=65519){let o=n+65519;o>t.byteLength&&(o=t.byteLength);let s;t instanceof Uint8Array?s=this.handshake.encrypt(t.subarray(n,o)):s=this.handshake.encrypt(t.sublist(n,o)),this.metrics?.encryptedPackets.increment(),r.append(Gr(s.byteLength)),r.append(s)}return r}decrypt(t){let r=new W;for(let n=0;n<t.byteLength;n+=65535){let o=n+65535;if(o>t.byteLength&&(o=t.byteLength),o-nc<n)throw new Error("Invalid chunk");let s;t instanceof Uint8Array?s=t.subarray(n,o):s=t.sublist(n,o);let i=t.subarray(n,o-nc);try{let a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),r.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return r}close(t){return this.stream.close(t)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(t){this.stream.abort(t)}sendData(t){return{sentBytes:t.byteLength,canSendMore:this.stream.send(this.encrypt(t))}}};function Oc(e,t,r){return new Tc(e,t,r)}async function lh(e,t){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=e,l=await Rc(s,a.publicKey,f),u=new Kn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});dc(u.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(u.writeMessageA(ar),t),r.trace("Stage 0 - Initiator finished sending first message."),pc(u.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");let d=u.readMessageB(await n.read(t));r.trace("Stage 1 - Initiator received the message."),mc(u.re,r),th(u.rs,r),r.trace("Initiator going to check remote's signature...");let m=await Pc(d,u.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(u.writeMessageC(l),t),r.trace("Stage 2 - Initiator sent message with signed payload.");let[p,w]=u.ss.split();return gc(p,w,r),{payload:m,encrypt:h=>p.encryptWithAd(ar,h),decrypt:(h,b)=>w.decryptWithAd(ar,h,b)}}async function hh(e,t){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=e,l=await Rc(s,a.publicKey,f),u=new Kn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});dc(u.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),u.readMessageA(await n.read(t)),r.trace("Stage 0 - Responder received first message."),mc(u.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(u.writeMessageB(l),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),pc(u.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");let d=u.readMessageC(await n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");let m=await Pc(d,u.rs,c),[p,w]=u.ss.split();return gc(p,w,r),{payload:m,encrypt:h=>w.encryptWithAd(ar,h),decrypt:(h,b)=>p.decryptWithAd(ar,h,b)}}var Rs=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(t,r={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=r,{metrics:a}=t;this.components=t,this.log=t.logger.forComponent("libp2p:noise");let c=s??Zl;this.crypto=Ql(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?Jl(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??pt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[pr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,r){let n=t.log?.newScope("noise")??this.log,o=os(t,{lengthEncoder:Gr,lengthDecoder:qr,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=vn(s.payload.identityKey);return{connection:Oc(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:da(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(t){if(t==null||t.length===0)return;let r=this.components.upgrader.getStreamMuxers();if(r!=null)for(let n of t){let o=r.get(n);if(o!=null)return o}if(t.length)throw new jn("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(t,r){let n=t.log?.newScope("noise")??this.log,o=os(t,{lengthEncoder:Gr,lengthDecoder:qr,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=vn(s.payload.identityKey);return{connection:Oc(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:da(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(t,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await lh({connection:t,privateKey:r,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(t,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await hh({connection:t,privateKey:r,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function dh(e={}){return t=>new Rs(t,e)}var Nc=Object.values(qe).map(e=>e.decoder).reduce((e,t)=>e.or(t)),Vm=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function ph(e){return e?.match(Vm)?.groups?.fingerprint}function Uc(e){let r=e.getComponents().find(n=>n.code===466)?.value;if(r===void 0||r==="")throw new Y(`Couldn't find a certhash component of multiaddr: ${e.toString()}`);return r}function $m(e){return Ft.decode(Nc.decode(e))}function Wm(e){let t=$m(Uc(e)),r=Gm(t.code),n=t.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new ms(n,e.toString());return`${r} ${o.join(":").toUpperCase()}`}function mh(e){let t=e.split(":").map(o=>parseInt(o,16)),r=Uint8Array.from(t),n=Dt(te.code,r);return kr(`/certhash/${en.encode(n.bytes)}`)}function Gm(e){switch(e){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new ys(e)}}function gh(e,t){let{host:r,port:n,type:o}=Ga(e);if(o!=="ip4"&&o!=="ip6")throw new Y(`Multiaddr ${e} was not an IPv4 or IPv6 address`);let s=Wm(e);return{type:"answer",sdp:`v=0
|
|
3
3
|
o=- 0 0 IN IP${o==="ip4"?4:6} ${r}
|
|
4
4
|
s=-
|
|
5
5
|
t=0 0
|
|
@@ -13,10 +13,10 @@ a=ice-pwd:${t}
|
|
|
13
13
|
a=fingerprint:${s}
|
|
14
14
|
a=setup:passive
|
|
15
15
|
a=sctp-port:5000
|
|
16
|
-
a=max-message-size:${
|
|
16
|
+
a=max-message-size:${Kr}
|
|
17
17
|
a=candidate:1467250027 1 UDP 1467250027 ${r} ${n} typ host
|
|
18
18
|
a=end-of-candidates
|
|
19
|
-
`}}function
|
|
19
|
+
`}}function yh(e,t){let{host:r,port:n,type:o}=Ga(e);if(o!=="ip4"&&o!=="ip6")throw new Y(`Multiaddr ${e} was not an IPv4 or IPv6 address`);return{type:"offer",sdp:`v=0
|
|
20
20
|
o=- 0 0 IN IP${o==="ip4"?4:6} ${r}
|
|
21
21
|
s=-
|
|
22
22
|
c=IN IP${o==="ip4"?4:6} ${r}
|
|
@@ -29,15 +29,15 @@ a=ice-ufrag:${t}
|
|
|
29
29
|
a=ice-pwd:${t}
|
|
30
30
|
a=fingerprint:sha-256 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00
|
|
31
31
|
a=sctp-port:5000
|
|
32
|
-
a=max-message-size:${
|
|
32
|
+
a=max-message-size:${Kr}
|
|
33
33
|
a=candidate:1467250027 1 UDP 1467250027 ${r} ${n} typ host
|
|
34
34
|
a=end-of-candidates
|
|
35
|
-
`}}function
|
|
35
|
+
`}}function kc(e,t){if(e.sdp===void 0)throw new Y("Can't munge a missing SDP");let r=e.sdp.includes(`\r
|
|
36
36
|
`)?`\r
|
|
37
37
|
`:`
|
|
38
38
|
`;try{e.sdp=e.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
|
|
39
39
|
a=ice-ufrag:`+t+r).replace(/\na=ice-pwd:[^\n]*\n/,`
|
|
40
|
-
a=ice-pwd:`+t+r)}catch{}return e}var
|
|
40
|
+
a=ice-pwd:`+t+r)}catch{}return e}var Mc=G("libp2p-webrtc-noise:");function xh(e,t,r){let n=e.trim().toLowerCase().replaceAll(":",""),o=G(n,"hex"),s=Dt(te.code,o),i=Nc.decode(Uc(t)),a=Mc.byteLength+s.bytes.byteLength+i.byteLength;return r==="server"?Tt([Mc,i,s.bytes],a):Tt([Mc,s.bytes,i],a)}var qm=hs?"iceconnectionstatechange":"connectionstatechange";function zm(e,t){return e.role==="server"}async function wh(e,t,r,n){let o=e.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let u=await e.createOffer();n.log.trace("client created local offer %s",u.sdp);let d=kc(u,r);n.log.trace("client setting local offer %s",d.sdp),await e.setLocalDescription(d);let m=gh(n.remoteAddr,r);n.log.trace("client setting server description %s",m.sdp),await e.setRemoteDescription(m)}else{let u=yh(n.remoteAddr,r);n.log.trace("server setting client %s %s",u.type,u.sdp),await e.setRemoteDescription(u),n.log.trace("server creating local answer");let d=await e.createAnswer();n.log.trace("server created local answer");let m=kc(d,r);n.log.trace("server setting local description %s",d.sdp),await e.setLocalDescription(m)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await St(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),zm(n,e)){let u=e.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(mh(u))}let s=ph(e.localDescription?.sdp);if(s==null)throw new Ve("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=xh(s,n.remoteAddr,n.role),a=dh({prologueBytes:i})(n),c=kn({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),f=Mn({peerConnection:e,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(e.addEventListener(qm,()=>{switch(e.connectionState){case"failed":case"disconnected":case"closed":f.close().catch(u=>{n.log.error("error closing connection - %e",u),f.abort(u)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let u=await a.secureInbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});return n.log.trace("%s upgrade outbound",n.role),await n.upgrader.upgradeOutbound(f,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:t,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let l=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});f.remoteAddr=f.remoteAddr.encapsulate(`/p2p/${l.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(f,{skipProtection:!0,skipEncryption:!0,remotePeer:l.remotePeer,muxerFactory:t,signal:n.signal})}catch(s){throw o.close(),e.close(),s}}async function Eh(e,t,r={}){let n=r.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof r.rtcConfiguration=="function"?await r.rtcConfiguration():r.rtcConfiguration,s=new RTCPeerConnection({...o??{},certificates:[n]}),i=new Fe({peerConnection:s,metrics:r.events,dataChannelOptions:r.dataChannel});return{peerConnection:s,muxerFactory:i}}var Ps=class{log;metrics;components;init;constructor(t,r={}){this.log=t.logger.forComponent("libp2p:webrtc-direct"),this.components=t,this.init=r,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[oo]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[pr]=["@libp2p/transport"];async dial(t,r){this.log("dial %a",t),r.signal.throwIfAborted();let n,o=t.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=Rr(o));let s=Dl(),{peerConnection:i,muxerFactory:a}=await Eh("client",s,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await wh(i,a,s,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:r.signal,remoteAddr:t,dataChannel:this.init.dataChannel,upgrader:r.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw i.close(),c}}createListener(t){throw new gs("WebRTCDirectTransport.createListener")}listenFilter(t){return[]}dialFilter(t){return t.filter(hl.exactMatch)}};function jm(e){return t=>new Ps(t,e)}function Xm(e){return t=>new Es(t,e)}return _h(Ym);})();
|
|
41
41
|
/*! Bundled license information:
|
|
42
42
|
|
|
43
43
|
@noble/hashes/utils.js:
|