@libp2p/webrtc 6.0.11 → 6.0.12
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 +4 -4
- package/dist/index.min.js.map +3 -3
- package/package.json +3 -3
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 Sl=Object.getOwnPropertyDescriptor;var vl=Object.getOwnPropertyNames;var Al=Object.prototype.hasOwnProperty;var Ie=(t,e)=>{for(var r in e)ss(t,r,{get:e[r],enumerable:!0})},Cl=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of vl(e))!Al.call(t,o)&&o!==r&&ss(t,o,{get:()=>e[o],enumerable:!(n=Sl(e,o))||n.enumerable});return t};var _l=t=>Cl(ss({},"__esModule",{value:!0}),t);var km={};Ie(km,{webRTC:()=>Km,webRTCDirect:()=>Mm});var Tn=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},Rn=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},Y=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},er=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Pn=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},On=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},tr=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var je=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Hr=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var Nn=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Un=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Mn=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Kn=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Rt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var kn=class extends Event{data;constructor(e,r){super("message",r),this.data=e}},rr=class extends Event{error;local;constructor(e,r,n){super("close",n),this.error=r,this.local=e}},Hn=class extends rr{constructor(e,r){super(!0,e,r)}},Fn=class extends rr{constructor(e,r){super(!1,e,r)}};var is=Symbol.for("@libp2p/peer-id");var Vn=Symbol.for("@libp2p/transport");var ec;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(ec||(ec={}));var mt=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){super.addEventListener(e,r,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:r,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,r,n){super.removeEventListener(e.toString(),r??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==r),this.#e.set(e,o))}dispatchEvent(e){let r=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),r}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}};var nr=Symbol.for("@libp2p/service-capabilities"),tc=Symbol.for("@libp2p/service-dependencies");var ls={};Ie(ls,{base58btc:()=>ce,base58flickr:()=>Pl});var y0=new Uint8Array(0);function rc(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function et(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function nc(t){return new TextEncoder().encode(t)}function oc(t){return new TextDecoder().decode(t)}function Ll(t,e){if(t.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<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var E=0,h=0,b=0,A=d.length;b!==A&&d[b]===0;)b++,E++;for(var x=(A-b)*l+1>>>0,D=new Uint8Array(x);b!==A;){for(var M=d[b],O=0,k=x-1;(M!==0||O<h)&&k!==-1;k--,O++)M+=256*D[k]>>>0,D[k]=M%a>>>0,M=M/a>>>0;if(M!==0)throw new Error("Non-zero carry");h=O,b++}for(var _=x-h;_!==x&&D[_]===0;)_++;for(var v=c.repeat(E);_<x;++_)v+=t.charAt(D[_]);return v}function y(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var E=0;if(d[E]!==" "){for(var h=0,b=0;d[E]===c;)h++,E++;for(var A=(d.length-E)*u+1>>>0,x=new Uint8Array(A);d[E];){var D=r[d.charCodeAt(E)];if(D===255)return;for(var M=0,O=A-1;(D!==0||M<b)&&O!==-1;O--,M++)D+=a*x[O]>>>0,x[O]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");b=M,E++}if(d[E]!==" "){for(var k=A-b;k!==A&&x[k]===0;)k++;for(var _=new Uint8Array(h+(A-k)),v=h;k!==A;)_[v++]=x[k++];return _}}}function p(d){var E=y(d);if(E)return E;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:y,decode:p}}var Il=Ll,Bl=Il,ic=Bl;var as=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},cs=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,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(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ac(this,e)}},us=class{decoders;constructor(e){this.decoders=e}or(e){return ac(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ac(t,e){return new us({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var fs=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new as(e,r,n),this.decoder=new cs(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function or({name:t,prefix:e,encode:r,decode:n}){return new fs(t,e,r,n)}function gt({name:t,prefix:e,alphabet:r}){let{encode:n,decode:o}=ic(r,t);return or({prefix:e,name:t,encode:n,decode:s=>et(o(s))})}function Dl(t,e,r,n){let o=t.length;for(;t[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 l=e[t[u]];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 Tl(t,e,r){let n=e[e.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function Rl(t){let e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function ae({name:t,prefix:e,bitsPerChar:r,alphabet:n}){let o=Rl(n);return or({prefix:e,name:t,encode(s){return Tl(s,n,r)},decode(s){return Dl(s,o,r,t)}})}var ce=gt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Pl=gt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var hs={};Ie(hs,{base32:()=>yt,base32hex:()=>Ml,base32hexpad:()=>kl,base32hexpadupper:()=>Hl,base32hexupper:()=>Kl,base32pad:()=>Nl,base32padupper:()=>Ul,base32upper:()=>Ol,base32z:()=>Fl});var yt=ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ol=ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Nl=ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ul=ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ml=ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Kl=ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),kl=ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Hl=ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Fl=ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ds={};Ie(ds,{base36:()=>Fr,base36upper:()=>Vl});var Fr=gt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Vl=gt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var He={};Ie(He,{Digest:()=>Pt,create:()=>Be,decode:()=>ar,equals:()=>ms,hasCode:()=>ah});var $l=fc,cc=128,ql=127,Wl=~ql,Gl=Math.pow(2,31);function fc(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Gl;)e[r++]=t&255|cc,t/=128;for(;t&Wl;)e[r++]=t&255|cc,t>>>=7;return e[r]=t|0,fc.bytes=r-n+1,e}var zl=ps,jl=128,uc=127;function ps(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw ps.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&uc)<<o:(i&uc)*Math.pow(2,o),o+=7}while(i>=jl);return ps.bytes=s-n,r}var Xl=Math.pow(2,7),Yl=Math.pow(2,14),Zl=Math.pow(2,21),Ql=Math.pow(2,28),Jl=Math.pow(2,35),eh=Math.pow(2,42),th=Math.pow(2,49),rh=Math.pow(2,56),nh=Math.pow(2,63),oh=function(t){return t<Xl?1:t<Yl?2:t<Zl?3:t<Ql?4:t<Jl?5:t<eh?6:t<th?7:t<rh?8:t<nh?9:10},sh={encode:$l,decode:zl,encodingLength:oh},ih=sh,Vr=ih;function $r(t,e=0){return[Vr.decode(t,e),Vr.decode.bytes]}function sr(t,e,r=0){return Vr.encode(t,e,r),e}function ir(t){return Vr.encodingLength(t)}function Be(t,e){let r=e.byteLength,n=ir(t),o=n+ir(r),s=new Uint8Array(o+r);return sr(t,s,0),sr(r,s,n),s.set(e,o),new Pt(t,r,e,s)}function ar(t){let e=et(t),[r,n]=$r(e),[o,s]=$r(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Pt(r,o,i,e)}function ms(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&rc(t.bytes,r.bytes)}}var Pt=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}};function ah(t,e){return t.code===e}function lc(t,e){let{bytes:r,version:n}=t;switch(n){case 0:return uh(r,gs(t),e??ce.encoder);default:return fh(r,gs(t),e??yt.encoder)}}var hc=new WeakMap;function gs(t){let e=hc.get(t);if(e==null){let r=new Map;return hc.set(t,r),r}return e}var he=class t{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,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:e,multihash:r}=this;if(e!==qr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==lh)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.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:e,digest:r}=this.multihash,n=Be(e,r);return t.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(e){return t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&ms(e.multihash,n.multihash)}toString(e){return lc(this,e)}toJSON(){return{"/":lc(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new t(n,o,s,i??dc(n,o,s.bytes))}else if(r[hh]===!0){let{version:n,multihash:o,code:s}=r,i=ar(o);return t.create(n,s,i)}else return null}static create(e,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(e){case 0:{if(r!==qr)throw new Error(`Version 0 CID must use dag-pb (code: ${qr}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=dc(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,qr,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,o=et(e.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 Pt(r.multihashCode,r.digestSize,s,o);return[r.version===0?t.createV0(i):t.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[f,y]=$r(e.subarray(r));return r+=y,f},o=n(),s=qr;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,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,r){let[n,o]=ch(e,r),s=t.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return gs(s).set(n,e),s}};function ch(t,e){switch(t[0]){case"Q":{let r=e??ce;return[ce.prefix,r.decode(`${ce.prefix}${t}`)]}case ce.prefix:{let r=e??ce;return[ce.prefix,r.decode(t)]}case yt.prefix:{let r=e??yt;return[yt.prefix,r.decode(t)]}case Fr.prefix:{let r=e??Fr;return[Fr.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function uh(t,e,r){let{prefix:n}=r;if(n!==ce.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return o}function fh(t,e,r){let{prefix:n}=r,o=e.get(n);if(o==null){let s=r.encode(t);return e.set(n,s),s}else return o}var qr=112,lh=18;function dc(t,e,r){let n=ir(t),o=n+ir(e),s=new Uint8Array(o+r.byteLength);return sr(t,s,0),sr(e,s,n),s.set(r,o),s}var hh=Symbol.for("@ipld/js-cid/CID");var ys={};Ie(ys,{identity:()=>Fe});var pc=0,dh="identity",mc=et;function ph(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return Be(pc,mc(t))}var Fe={code:pc,name:dh,encode:mc,digest:ph};function we(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function de(t=0){return new Uint8Array(t)}function pe(t=0){return new Uint8Array(t)}function De(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=pe(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}var yc=Symbol.for("@achingbrain/uint8arraylist");function gc(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(let n of t){let o=r+n.byteLength;if(e<o)return{buf:n,index:e-r};r=o}throw new RangeError("index is out of bounds")}function qn(t){return!!t?.[yc]}var q=class t{bufs;length;[yc]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let r=0;for(let n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(qn(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(...e){this.prependAll(e)}prependAll(e){let r=0;for(let n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(qn(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(e){let r=gc(this.bufs,e);return r.buf[r.index]}set(e,r){let n=gc(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(qn(e))for(let n=0;n<e.length;n++)this.set(r+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,r){let{bufs:n,length:o}=this._subList(e,r);return De(n,o)}subarray(e,r){let{bufs:n,length:o}=this._subList(e,r);return n.length===1?n[0]:De(n,o)}sublist(e,r){let{bufs:n,length:o}=this._subList(e,r),s=new t;return s.length=o,s.bufs=[...n],s}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:this.bufs,length:this.length};let n=[],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,e>=c)continue;let u=e>=a&&e<c,l=r>a&&r<=c;if(u&&l){if(e===a&&r===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(r-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-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-e}}indexOf(e,r=0){if(!qn(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.length===0)return r>this.length?this.length:r;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=r;f<=c;f+=l){l=0;for(let y=u;y>=0;y--){let p=this.get(f+y);if(n[y]!==p){l=Math.max(1,y-a[p]);break}}if(l===0)return f}return-1}getInt8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){let n=pe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){let o=de(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,e)}getInt32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){let o=de(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,e)}getBigInt64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){let o=de(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,e)}getUint8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){let n=pe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){let o=de(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,e)}getUint32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){let o=de(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,e)}getBigUint64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){let o=de(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,e)}getFloat32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){let o=de(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,e)}getFloat64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){let o=de(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof t)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!we(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){let n=new t;return n.bufs=e,r==null&&(r=e.reduce((o,s)=>o+s.byteLength,0)),n.length=r,n}};var bs={};Ie(bs,{base10:()=>gh});var gh=gt({prefix:"9",name:"base10",alphabet:"0123456789"});var ws={};Ie(ws,{base16:()=>yh,base16upper:()=>bh});var yh=ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),bh=ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var xs={};Ie(xs,{base2:()=>wh});var wh=ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Es={};Ie(Es,{base256emoji:()=>Ah});var bc=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}"),xh=bc.reduce((t,e,r)=>(t[r]=e,t),[]),Eh=bc.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function Sh(t){return t.reduce((e,r)=>(e+=xh[r],e),"")}function vh(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=Eh[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var Ah=or({prefix:"\u{1F680}",name:"base256emoji",encode:Sh,decode:vh});var Ss={};Ie(Ss,{base64:()=>Ch,base64pad:()=>_h,base64url:()=>Wr,base64urlpad:()=>Lh});var Ch=ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),_h=ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Wr=ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Lh=ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var vs={};Ie(vs,{base8:()=>Ih});var Ih=ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var As={};Ie(As,{identity:()=>Bh});var Bh=or({prefix:"\0",name:"identity",encode:t=>oc(t),decode:t=>nc(t)});var J0=new TextEncoder,eg=new TextDecoder;var Ls={};Ie(Ls,{sha256:()=>tt,sha512:()=>Ph});var Rh=20;function _s({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new Cs(t,e,r,n,o)}var Cs=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??Rh,this.maxDigestLength=s}digest(e,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(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?wc(n,this.code,r?.truncate):n.then(o=>wc(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function wc(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return Be(e,t)}function Ec(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var tt=_s({name:"sha2-256",code:18,encode:Ec("SHA-256")}),Ph=_s({name:"sha2-512",code:19,encode:Ec("SHA-512")});var Ot={...As,...xs,...vs,...bs,...ws,...hs,...ds,...ls,...Ss,...Es},hg={...Ls,...ys};function vc(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var Sc=vc("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Is=vc("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=pe(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Oh={utf8:Sc,"utf-8":Sc,hex:Ot.base16,latin1:Is,ascii:Is,binary:Is,...Ot},Wn=Oh;function j(t,e="utf8"){let r=Wn[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function $(t,e="utf8"){let r=Wn[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}var Nh=parseInt("11111",2),Bs=parseInt("10000000",2),Uh=parseInt("01111111",2),Ac={0:Gr,1:Gr,2:Mh,3:Hh,4:Fh,5:kh,6:Kh,16:Gr,22:Gr,48:Gr};function rt(t,e={offset:0}){let r=t[e.offset]&Nh;if(e.offset++,Ac[r]!=null)return Ac[r](t,e);throw new Error("No decoder for tag "+r)}function zr(t,e){let r=0;if((t[e.offset]&Bs)===Bs){let n=t[e.offset]&Uh,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=t[e.offset].toString(16).padStart(2,"0");r=parseInt(o,16)}else r=t[e.offset],e.offset++;return r}function Gr(t,e){zr(t,e);let r=[];for(;!(e.offset>=t.byteLength);){let n=rt(t,e);if(n===null)break;r.push(n)}return r}function Mh(t,e){let r=zr(t,e),n=e.offset,o=e.offset+r,s=[];for(let i=n;i<o;i++)i===n&&t[i]===0||s.push(t[i]);return e.offset+=r,Uint8Array.from(s)}function Kh(t,e){let r=zr(t,e),n=e.offset+r,o=t[e.offset];e.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(;e.offset<n;){let u=t[e.offset];if(e.offset++,c.push(u&127),u<128){c.reverse();let l=0;for(let f=0;f<c.length;f++)l+=c[f]<<f*7;a+=`.${l}`,c=[]}}return a}function kh(t,e){return e.offset++,null}function Hh(t,e){let r=zr(t,e),n=t[e.offset];e.offset++;let o=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Fh(t,e){let r=zr(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function Vh(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);let r=new q;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function Ds(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);let e=Vh(t.byteLength);return new q(Uint8Array.from([e.byteLength|Bs]),e)}function Re(t){let e=new q,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new q(Uint8Array.from([2]),Ds(e),e)}function Gn(t){let e=Uint8Array.from([0]),r=new q(e,t);return new q(Uint8Array.from([3]),Ds(r),r)}function bt(t,e=48){let r=new q;for(let n of t)r.append(n);return new q(Uint8Array.from([e]),Ds(r),r)}async function Cc(t,e,r,n){let o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,r.subarray());return n?.signal?.throwIfAborted(),s}var $h=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),qh=Uint8Array.from([6,5,43,129,4,0,34]),Wh=Uint8Array.from([6,5,43,129,4,0,35]),Gh={ext:!0,kty:"EC",crv:"P-256"},zh={ext:!0,kty:"EC",crv:"P-384"},jh={ext:!0,kty:"EC",crv:"P-521"},Ts=32,Rs=48,Ps=66;function Os(t){let e=rt(t);return _c(e)}function _c(t){let e=t[1][1][0],r=1,n,o;if(e.byteLength===Ts*2+1)return n=$(e.subarray(r,r+Ts),"base64url"),o=$(e.subarray(r+Ts),"base64url"),new cr({...Gh,key_ops:["verify"],x:n,y:o});if(e.byteLength===Rs*2+1)return n=$(e.subarray(r,r+Rs),"base64url"),o=$(e.subarray(r+Rs),"base64url"),new cr({...zh,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ps*2+1)return n=$(e.subarray(r,r+Ps),"base64url"),o=$(e.subarray(r+Ps),"base64url"),new cr({...jh,key_ops:["verify"],x:n,y:o});throw new Y(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Lc(t){return bt([Re(Uint8Array.from([1])),bt([Xh(t.crv)],160),bt([Gn(new q(Uint8Array.from([4]),j(t.x??"","base64url"),j(t.y??"","base64url")))],161)]).subarray()}function Xh(t){if(t==="P-256")return $h;if(t==="P-384")return qh;if(t==="P-521")return Wh;throw new Y(`Invalid curve ${t}`)}var cr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Lc(this.jwk)),this._raw}toMultihash(){return Fe.digest(wt(this))}toCID(){return he.createV1(114,this.toMultihash())}toString(){return ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}async verify(e,r,n){return Cc(this.jwk,r,e,n)}};function Nt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Me(t,e=""){if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${t}`)}}function F(t,e,r=""){let n=Nt(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){let i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function Ut(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Me(t.outputLen),Me(t.blockLen)}function ur(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Bc(t,e){F(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Ve(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function zn(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function $e(t,e){return t<<32-e|t>>>e}var Dc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Yh=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ot(t){if(F(t),Dc)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Yh[t[r]];return e}var nt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ic(t){if(t>=nt._0&&t<=nt._9)return t-nt._0;if(t>=nt.A&&t<=nt.F)return t-(nt.A-10);if(t>=nt.a&&t<=nt.f)return t-(nt.a-10)}function st(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Dc)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=Ic(t.charCodeAt(s)),a=Ic(t.charCodeAt(s+1));if(i===void 0||a===void 0){let c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Pe(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];F(o),e+=o.length}let r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){let s=t[n];r.set(s,o),o+=s.length}return r}function Ns(t,e={}){let r=(o,s)=>t(s).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function xt(t=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}var Us=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Tc(t,e,r){return t&e^~t&r}function Rc(t,e,r){return t&e^t&r^e&r}var jr=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,o){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=zn(this.buffer)}update(e){ur(this),F(e);let{view:r,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=zn(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ur(this),Bc(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,Ve(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)r[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=zn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},it=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var xe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var jn=BigInt(4294967295),Pc=BigInt(32);function Zh(t,e=!1){return e?{h:Number(t&jn),l:Number(t>>Pc&jn)}:{h:Number(t>>Pc&jn)|0,l:Number(t&jn)|0}}function Oc(t,e=!1){let r=t.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=Zh(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Ms=(t,e,r)=>t>>>r,Ks=(t,e,r)=>t<<32-r|e>>>r,Mt=(t,e,r)=>t>>>r|e<<32-r,Kt=(t,e,r)=>t<<32-r|e>>>r,Xr=(t,e,r)=>t<<64-r|e>>>r-32,Yr=(t,e,r)=>t>>>r-32|e<<64-r;function Xe(t,e,r,n){let o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}var Nc=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Uc=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Mc=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Kc=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0,kc=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0),Hc=(t,e,r,n,o,s)=>e+r+n+o+s+(t/2**32|0)|0;var Jh=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]),Et=new Uint32Array(64),ks=class extends jr{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|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(e,r){for(let f=0;f<16;f++,r+=4)Et[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let y=Et[f-15],p=Et[f-2],d=$e(y,7)^$e(y,18)^y>>>3,E=$e(p,17)^$e(p,19)^p>>>10;Et[f]=E+Et[f-7]+d+Et[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let y=$e(a,6)^$e(a,11)^$e(a,25),p=l+y+Tc(a,c,u)+Jh[f]+Et[f]|0,E=($e(n,2)^$e(n,13)^$e(n,22))+Rc(n,o,s)|0;l=u,u=c,c=a,a=i+p|0,i=s,s=o,o=n,n=p+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,l=l+this.H|0,this.set(n,o,s,i,a,c,u,l)}roundClean(){Ve(Et)}destroy(){this.set(0,0,0,0,0,0,0,0),Ve(this.buffer)}},Hs=class extends ks{A=it[0]|0;B=it[1]|0;C=it[2]|0;D=it[3]|0;E=it[4]|0;F=it[5]|0;G=it[6]|0;H=it[7]|0;constructor(){super(32)}};var Fc=Oc(["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(t=>BigInt(t))),ed=Fc[0],td=Fc[1],St=new Uint32Array(80),vt=new Uint32Array(80),Fs=class extends jr{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:y,Gh:p,Gl:d,Hh:E,Hl:h}=this;return[e,r,n,o,s,i,a,c,u,l,f,y,p,d,E,h]}set(e,r,n,o,s,i,a,c,u,l,f,y,p,d,E,h){this.Ah=e|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=l|0,this.Fh=f|0,this.Fl=y|0,this.Gh=p|0,this.Gl=d|0,this.Hh=E|0,this.Hl=h|0}process(e,r){for(let x=0;x<16;x++,r+=4)St[x]=e.getUint32(r),vt[x]=e.getUint32(r+=4);for(let x=16;x<80;x++){let D=St[x-15]|0,M=vt[x-15]|0,O=Mt(D,M,1)^Mt(D,M,8)^Ms(D,M,7),k=Kt(D,M,1)^Kt(D,M,8)^Ks(D,M,7),_=St[x-2]|0,v=vt[x-2]|0,N=Mt(_,v,19)^Xr(_,v,61)^Ms(_,v,6),K=Kt(_,v,19)^Yr(_,v,61)^Ks(_,v,6),T=Mc(k,K,vt[x-7],vt[x-16]),w=Kc(T,O,N,St[x-7],St[x-16]);St[x]=w|0,vt[x]=T|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:y,Fh:p,Fl:d,Gh:E,Gl:h,Hh:b,Hl:A}=this;for(let x=0;x<80;x++){let D=Mt(f,y,14)^Mt(f,y,18)^Xr(f,y,41),M=Kt(f,y,14)^Kt(f,y,18)^Yr(f,y,41),O=f&p^~f&E,k=y&d^~y&h,_=kc(A,M,k,td[x],vt[x]),v=Hc(_,b,D,O,ed[x],St[x]),N=_|0,K=Mt(n,o,28)^Xr(n,o,34)^Xr(n,o,39),T=Kt(n,o,28)^Yr(n,o,34)^Yr(n,o,39),w=n&s^n&a^s&a,m=o&i^o&c^i&c;b=E|0,A=h|0,E=p|0,h=d|0,p=f|0,d=y|0,{h:f,l:y}=Xe(u|0,l|0,v|0,N|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let g=Nc(N,T,m);n=Uc(g,v,K,w),o=g|0}({h:n,l:o}=Xe(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Xe(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Xe(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Xe(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:y}=Xe(this.Eh|0,this.El|0,f|0,y|0),{h:p,l:d}=Xe(this.Fh|0,this.Fl|0,p|0,d|0),{h:E,l:h}=Xe(this.Gh|0,this.Gl|0,E|0,h|0),{h:b,l:A}=Xe(this.Hh|0,this.Hl|0,b|0,A|0),this.set(n,o,s,i,a,c,u,l,f,y,p,d,E,h,b,A)}roundClean(){Ve(St,vt)}destroy(){Ve(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Vs=class extends Fs{Ah=xe[0]|0;Al=xe[1]|0;Bh=xe[2]|0;Bl=xe[3]|0;Ch=xe[4]|0;Cl=xe[5]|0;Dh=xe[6]|0;Dl=xe[7]|0;Eh=xe[8]|0;El=xe[9]|0;Fh=xe[10]|0;Fl=xe[11]|0;Gh=xe[12]|0;Gl=xe[13]|0;Hh=xe[14]|0;Hl=xe[15]|0;constructor(){super(64)}};var Ye=Ns(()=>new Hs,Us(1));var Vc=Ns(()=>new Vs,Us(3));var qs=BigInt(0),$s=BigInt(1);function at(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function $c(t){if(typeof t=="bigint"){if(!Xn(t))throw new Error("positive bigint expected, got "+t)}else Me(t);return t}function Zr(t){let e=$c(t).toString(16);return e.length&1?"0"+e:e}function qc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?qs:BigInt("0x"+t)}function fr(t){return qc(ot(t))}function Ze(t){return qc(ot(kt(F(t)).reverse()))}function Yn(t,e){Me(e),t=$c(t);let r=st(t.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function Qr(t,e){return Yn(t,e).reverse()}function kt(t){return Uint8Array.from(t)}var Xn=t=>typeof t=="bigint"&&qs<=t;function rd(t,e,r){return Xn(t)&&Xn(e)&&Xn(r)&&e<=t&&t<r}function At(t,e,r,n){if(!rd(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Ws(t){let e;for(e=0;t>qs;t>>=$s,e+=1);return e}var Jr=t=>($s<<BigInt(t))-$s;function Wc(t,e,r){if(Me(t,"hashLen"),Me(e,"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(t),u=n(t),l=0,f=()=>{c.fill(1),u.fill(0),l=0},y=(...h)=>r(u,Pe(c,...h)),p=(h=o)=>{u=y(s,h),c=y(),h.length!==0&&(u=y(i,h),c=y())},d=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let h=0,b=[];for(;h<e;){c=y();let A=c.slice();b.push(A),h+=c.length}return Pe(...b)};return(h,b)=>{f(),p(h);let A;for(;!(A=b(d()));)p();return f(),A}}function Qe(t,e={},r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(s,i,a){let c=t[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(e,!1),o(r,!0)}function lr(t){let e=new WeakMap;return(r,...n)=>{let o=e.get(r);if(o!==void 0)return o;let s=t(r,...n);return e.set(r,s),s}}var Te=BigInt(0),me=BigInt(1),Ht=BigInt(2),jc=BigInt(3),Xc=BigInt(4),Yc=BigInt(5),nd=BigInt(7),Zc=BigInt(8),od=BigInt(9),Qc=BigInt(16);function ie(t,e){let r=t%e;return r>=Te?r:e+r}function oe(t,e,r){let n=t;for(;e-- >Te;)n*=n,n%=r;return n}function Gc(t,e){if(t===Te)throw new Error("invert: expected non-zero number");if(e<=Te)throw new Error("invert: expected positive modulus, got "+e);let r=ie(t,e),n=e,o=Te,s=me,i=me,a=Te;for(;r!==Te;){let u=n/r,l=n%r,f=o-i*u,y=s-a*u;n=r,r=l,o=i,s=a,i=f,a=y}if(n!==me)throw new Error("invert: does not exist");return ie(o,e)}function zs(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function Jc(t,e){let r=(t.ORDER+me)/Xc,n=t.pow(e,r);return zs(t,n,e),n}function sd(t,e){let r=(t.ORDER-Yc)/Zc,n=t.mul(e,Ht),o=t.pow(n,r),s=t.mul(e,o),i=t.mul(t.mul(s,Ht),o),a=t.mul(s,t.sub(i,t.ONE));return zs(t,a,e),a}function id(t){let e=hr(t),r=eu(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+nd)/Qc;return(a,c)=>{let u=a.pow(c,i),l=a.mul(u,n),f=a.mul(u,o),y=a.mul(u,s),p=a.eql(a.sqr(l),c),d=a.eql(a.sqr(f),c);u=a.cmov(u,l,p),l=a.cmov(y,f,d);let E=a.eql(a.sqr(l),c),h=a.cmov(u,l,E);return zs(a,h,c),h}}function eu(t){if(t<jc)throw new Error("sqrt is not defined for small field");let e=t-me,r=0;for(;e%Ht===Te;)e/=Ht,r++;let n=Ht,o=hr(t);for(;zc(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Jc;let s=o.pow(n,e),i=(e+me)/Ht;return function(c,u){if(c.is0(u))return u;if(zc(c,u)!==1)throw new Error("Cannot find square root");let l=r,f=c.mul(c.ONE,s),y=c.pow(u,e),p=c.pow(u,i);for(;!c.eql(y,c.ONE);){if(c.is0(y))return c.ZERO;let d=1,E=c.sqr(y);for(;!c.eql(E,c.ONE);)if(d++,E=c.sqr(E),d===l)throw new Error("Cannot find square root");let h=me<<BigInt(l-d-1),b=c.pow(f,h);l=d,f=c.sqr(b),y=c.mul(y,f),p=c.mul(p,b)}return p}}function ad(t){return t%Xc===jc?Jc:t%Zc===Yc?sd:t%Qc===od?id(t):eu(t)}var tu=(t,e)=>(ie(t,e)&me)===me,cd=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function js(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=cd.reduce((n,o)=>(n[o]="function",n),e);return Qe(t,r),t}function ud(t,e,r){if(r<Te)throw new Error("invalid exponent, negatives unsupported");if(r===Te)return t.ONE;if(r===me)return e;let n=t.ONE,o=e;for(;r>Te;)r&me&&(n=t.mul(n,o)),o=t.sqr(o),r>>=me;return n}function en(t,e,r=!1){let n=new Array(e.length).fill(r?t.ZERO:void 0),o=e.reduce((i,a,c)=>t.is0(a)?i:(n[c]=i,t.mul(i,a)),t.ONE),s=t.inv(o);return e.reduceRight((i,a,c)=>t.is0(a)?i:(n[c]=t.mul(i,n[c]),t.mul(i,a)),s),n}function zc(t,e){let r=(t.ORDER-me)/Ht,n=t.pow(e,r),o=t.eql(n,t.ONE),s=t.eql(n,t.ZERO),i=t.eql(n,t.neg(t.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function fd(t,e){e!==void 0&&Me(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var Gs=class{ORDER;BITS;BYTES;isLE;ZERO=Te;ONE=me;_lengths;_sqrt;_mod;constructor(e,r={}){if(e<=Te)throw new Error("invalid field: expected ORDER > 0, got "+e);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}=fd(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ie(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Te<=e&&e<this.ORDER}is0(e){return e===Te}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&me)===me}neg(e){return ie(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return ie(e*e,this.ORDER)}add(e,r){return ie(e+r,this.ORDER)}sub(e,r){return ie(e-r,this.ORDER)}mul(e,r){return ie(e*r,this.ORDER)}pow(e,r){return ud(this,e,r)}div(e,r){return ie(e*Gc(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return Gc(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=ad(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Qr(e,this.BYTES):Yn(e,this.BYTES)}fromBytes(e,r=!1){F(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(o);u.set(e,s?0:u.length-e.length),e=u}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?Ze(e):fr(e);if(a&&(c=ie(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return en(this,e)}cmov(e,r,n){return n?r:e}};function hr(t,e={}){return new Gs(t,e)}function ru(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function Xs(t){let e=ru(t);return e+Math.ceil(e/2)}function Ys(t,e,r=!1){F(t);let n=t.length,o=ru(e),s=Xs(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?Ze(t):fr(t),a=ie(i,e-me)+me;return r?Qr(a,o):Yn(a,o)}var dr=BigInt(0),Ft=BigInt(1);function tn(t,e){let r=e.negate();return t?r:e}function Vt(t,e){let r=en(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function iu(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Zs(t,e){iu(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),o=2**t,s=Jr(t),i=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function nu(t,e,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(t&o),c=t>>i;a>n&&(a-=s,c+=Ft);let u=e*n,l=u+Math.abs(a)-1,f=a===0,y=a<0,p=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:y,isNegF:p,offsetF:u}}var Qs=new WeakMap,au=new WeakMap;function Js(t){return au.get(t)||1}function ou(t){if(t!==dr)throw new Error("invalid wNAF")}var pr=class{BASE;ZERO;Fn;bits;constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let o=e;for(;r>dr;)r&Ft&&(n=n.add(o)),o=o.double(),r>>=Ft;return n}precomputeWindow(e,r){let{windows:n,windowSize:o}=Zs(r,this.bits),s=[],i=e,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(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Zs(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:y,offsetF:p}=nu(n,a,i);n=c,l?s=s.add(tn(y,r[p])):o=o.add(tn(f,r[u]))}return ou(n),{p:o,f:s}}wNAFUnsafe(e,r,n,o=this.ZERO){let s=Zs(e,this.bits);for(let i=0;i<s.windows&&n!==dr;i++){let{nextN:a,offset:c,isZero:u,isNeg:l}=nu(n,i,s);if(n=a,!u){let f=r[c];o=o.add(l?f.negate():f)}}return ou(n),o}getPrecomputes(e,r,n){let o=Qs.get(r);return o||(o=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(o=n(o)),Qs.set(r,o))),o}cached(e,r,n){let o=Js(e);return this.wNAF(o,this.getPrecomputes(o,e,n),r)}unsafe(e,r,n,o){let s=Js(e);return s===1?this._unsafeLadder(e,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),r,o)}createCache(e,r){iu(r,this.bits),au.set(e,r),Qs.delete(e)}hasCache(e){return Js(e)!==1}};function cu(t,e,r,n){let o=e,s=t.ZERO,i=t.ZERO;for(;r>dr||n>dr;)r&Ft&&(s=s.add(o)),n&Ft&&(i=i.add(o)),o=o.double(),r>>=Ft,n>>=Ft;return{p1:s,p2:i}}function su(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return js(e),e}else return hr(t,{isLE:r})}function Zn(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let u=e[c];if(!(typeof u=="bigint"&&u>dr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=su(e.p,r.Fp,n),s=su(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function mr(t,e){return function(n){let o=t(n);return{secretKey:o,publicKey:e(o)}}}var Ct=BigInt(0),ge=BigInt(1),ei=BigInt(2),ld=BigInt(8);function hd(t,e,r,n){let o=t.sqr(r),s=t.sqr(n),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function uu(t,e={}){let r=Zn("edwards",t,e,e.FpFnLE),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i}=s;Qe(e,{},{uvRatio:"function"});let a=ei<<BigInt(o.BYTES*8)-ge,c=h=>n.create(h),u=e.uvRatio||((h,b)=>{try{return{isValid:!0,value:n.sqrt(n.div(h,b))}}catch{return{isValid:!1,value:Ct}}});if(!hd(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function l(h,b,A=!1){let x=A?ge:Ct;return At("coordinate "+h,b,x,a),b}function f(h){if(!(h instanceof d))throw new Error("EdwardsPoint expected")}let y=lr((h,b)=>{let{X:A,Y:x,Z:D}=h,M=h.is0();b==null&&(b=M?ld:n.inv(D));let O=c(A*b),k=c(x*b),_=n.mul(D,b);if(M)return{x:Ct,y:ge};if(_!==ge)throw new Error("invZ was invalid");return{x:O,y:k}}),p=lr(h=>{let{a:b,d:A}=s;if(h.is0())throw new Error("bad point: ZERO");let{X:x,Y:D,Z:M,T:O}=h,k=c(x*x),_=c(D*D),v=c(M*M),N=c(v*v),K=c(k*b),T=c(v*c(K+_)),w=c(N+c(A*c(k*_)));if(T!==w)throw new Error("bad point: equation left != right (1)");let m=c(x*D),g=c(M*O);if(m!==g)throw new Error("bad point: equation left != right (2)");return!0});class d{static BASE=new d(s.Gx,s.Gy,ge,c(s.Gx*s.Gy));static ZERO=new d(Ct,ge,ge,Ct);static Fp=n;static Fn=o;X;Y;Z;T;constructor(b,A,x,D){this.X=l("x",b),this.Y=l("y",A),this.Z=l("z",x,!0),this.T=l("t",D),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){if(b instanceof d)throw new Error("extended point not allowed");let{x:A,y:x}=b||{};return l("x",A),l("y",x),new d(A,x,ge,c(A*x))}static fromBytes(b,A=!1){let x=n.BYTES,{a:D,d:M}=s;b=kt(F(b,x,"point")),at(A,"zip215");let O=kt(b),k=b[x-1];O[x-1]=k&-129;let _=Ze(O),v=A?a:n.ORDER;At("point.y",_,Ct,v);let N=c(_*_),K=c(N-ge),T=c(M*N-D),{isValid:w,value:m}=u(K,T);if(!w)throw new Error("bad point: invalid y coordinate");let g=(m&ge)===ge,C=(k&128)!==0;if(!A&&m===Ct&&C)throw new Error("bad point: x=0 and x_0=1");return C!==g&&(m=c(-m)),d.fromAffine({x:m,y:_})}static fromHex(b,A=!1){return d.fromBytes(st(b),A)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,A=!0){return E.createCache(this,b),A||this.multiply(ei),this}assertValidity(){p(this)}equals(b){f(b);let{X:A,Y:x,Z:D}=this,{X:M,Y:O,Z:k}=b,_=c(A*k),v=c(M*D),N=c(x*k),K=c(O*D);return _===v&&N===K}is0(){return this.equals(d.ZERO)}negate(){return new d(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:b}=s,{X:A,Y:x,Z:D}=this,M=c(A*A),O=c(x*x),k=c(ei*c(D*D)),_=c(b*M),v=A+x,N=c(c(v*v)-M-O),K=_+O,T=K-k,w=_-O,m=c(N*T),g=c(K*w),C=c(N*w),I=c(T*K);return new d(m,g,I,C)}add(b){f(b);let{a:A,d:x}=s,{X:D,Y:M,Z:O,T:k}=this,{X:_,Y:v,Z:N,T:K}=b,T=c(D*_),w=c(M*v),m=c(k*x*K),g=c(O*N),C=c((D+M)*(_+v)-T-w),I=g-m,L=g+m,S=c(w-A*T),B=c(C*I),R=c(L*S),P=c(C*S),z=c(I*L);return new d(B,R,z,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:A,f:x}=E.cached(this,b,D=>Vt(d,D));return Vt(d,[A,x])[0]}multiplyUnsafe(b,A=d.ZERO){if(!o.isValid(b))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return b===Ct?d.ZERO:this.is0()||b===ge?this:E.unsafe(this,b,x=>Vt(d,x),A)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return E.unsafe(this,s.n).is0()}toAffine(b){return y(this,b)}clearCofactor(){return i===ge?this:this.multiplyUnsafe(i)}toBytes(){let{x:b,y:A}=this.toAffine(),x=n.toBytes(A);return x[x.length-1]|=b&ge?128:0,x}toHex(){return ot(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let E=new pr(d,o.BITS);return d.BASE.precompute(8),d}function fu(t,e,r={}){if(typeof e!="function")throw new Error('"hash" function param is required');Qe(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=r,{BASE:o,Fp:s,Fn:i}=t,a=r.randomBytes||xt,c=r.adjustScalarBytes||(_=>_),u=r.domain||((_,v,N)=>{if(at(N,"phflag"),v.length||N)throw new Error("Contexts/pre-hash are not supported");return _});function l(_){return i.create(Ze(_))}function f(_){let v=x.secretKey;F(_,x.secretKey,"secretKey");let N=F(e(_),2*v,"hashedSecretKey"),K=c(N.slice(0,v)),T=N.slice(v,2*v),w=l(K);return{head:K,prefix:T,scalar:w}}function y(_){let{head:v,prefix:N,scalar:K}=f(_),T=o.multiply(K),w=T.toBytes();return{head:v,prefix:N,scalar:K,point:T,pointBytes:w}}function p(_){return y(_).pointBytes}function d(_=Uint8Array.of(),...v){let N=Pe(...v);return l(e(u(N,F(_,void 0,"context"),!!n)))}function E(_,v,N={}){_=F(_,void 0,"message"),n&&(_=n(_));let{prefix:K,scalar:T,pointBytes:w}=y(v),m=d(N.context,K,_),g=o.multiply(m).toBytes(),C=d(N.context,g,w,_),I=i.create(m+C*T);if(!i.isValid(I))throw new Error("sign failed: invalid s");let L=Pe(g,i.toBytes(I));return F(L,x.signature,"result")}let h={zip215:!0};function b(_,v,N,K=h){let{context:T,zip215:w}=K,m=x.signature;_=F(_,m,"signature"),v=F(v,void 0,"message"),N=F(N,x.publicKey,"publicKey"),w!==void 0&&at(w,"zip215"),n&&(v=n(v));let g=m/2,C=_.subarray(0,g),I=Ze(_.subarray(g,m)),L,S,B;try{L=t.fromBytes(N,w),S=t.fromBytes(C,w),B=o.multiplyUnsafe(I)}catch{return!1}if(!w&&L.isSmallOrder())return!1;let R=d(T,S.toBytes(),L.toBytes(),v);return S.add(L.multiplyUnsafe(R)).subtract(B).clearCofactor().is0()}let A=s.BYTES,x={secretKey:A,publicKey:A,signature:2*A,seed:A};function D(_=a(x.seed)){return F(_,x.seed,"seed")}function M(_){return Nt(_)&&_.length===i.BYTES}function O(_,v){try{return!!t.fromBytes(_,v)}catch{return!1}}let k={getExtendedPublicKey:y,randomSecretKey:D,isValidSecretKey:M,isValidPublicKey:O,toMontgomery(_){let{y:v}=t.fromBytes(_),N=x.publicKey,K=N===32;if(!K&&N!==57)throw new Error("only defined for 25519 and 448");let T=K?s.div(ge+v,ge-v):s.div(v-ge,v+ge);return s.toBytes(T)},toMontgomerySecret(_){let v=x.secretKey;F(_,v);let N=e(_.subarray(0,v));return c(N).subarray(0,v)}};return Object.freeze({keygen:mr(D,p),getPublicKey:p,sign:E,verify:b,utils:k,Point:t,lengths:x})}var rn=BigInt(0),gr=BigInt(1),Qn=BigInt(2);function dd(t){return Qe(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function lu(t){let e=dd(t),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||xt,u=a?255:448,l=a?32:56,f=BigInt(a?9:5),y=BigInt(a?121665:39081),p=a?Qn**BigInt(254):Qn**BigInt(447),d=a?BigInt(8)*Qn**BigInt(251)-gr:BigInt(4)*Qn**BigInt(445)-gr,E=p+d+gr,h=m=>ie(m,r),b=A(f);function A(m){return Qr(h(m),l)}function x(m){let g=kt(F(m,l,"uCoordinate"));return a&&(g[31]&=127),h(Ze(g))}function D(m){return Ze(o(kt(F(m,l,"scalar"))))}function M(m,g){let C=N(x(g),D(m));if(C===rn)throw new Error("invalid private or public key received");return A(C)}function O(m){return M(m,b)}let k=O,_=M;function v(m,g,C){let I=h(m*(g-C));return g=h(g-I),C=h(C+I),{x_2:g,x_3:C}}function N(m,g){At("u",m,rn,r),At("scalar",g,p,E);let C=g,I=m,L=gr,S=rn,B=m,R=gr,P=rn;for(let W=BigInt(u-1);W>=rn;W--){let V=C>>W&gr;P^=V,{x_2:L,x_3:B}=v(P,L,B),{x_2:S,x_3:R}=v(P,S,R),P=V;let X=L+S,te=h(X*X),ue=L-S,Z=h(ue*ue),le=te-Z,Jt=B+R,Dn=B-R,kr=h(Dn*X),Za=h(Jt*ue),Qa=kr+Za,Ja=kr-Za;B=h(Qa*Qa),R=h(I*h(Ja*Ja)),L=h(te*Z),S=h(le*(te+h(y*le)))}({x_2:L,x_3:B}=v(P,L,B)),{x_2:S,x_3:R}=v(P,S,R);let z=s(S);return h(L*z)}let K={secretKey:l,publicKey:l,seed:l},T=(m=c(l))=>(F(m,K.seed,"seed"),m),w={randomSecretKey:T};return Object.freeze({keygen:mr(T,k),getSharedSecret:_,getPublicKey:k,scalarMult:M,scalarMultBase:O,utils:w,GuBytes:b.slice(),lengths:K})}var pd=BigInt(1),hu=BigInt(2),md=BigInt(3),gd=BigInt(5),yd=BigInt(8),Jn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),bd={p:Jn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:yd,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function pu(t){let e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=Jn,a=t*t%s*t%s,c=oe(a,hu,s)*a%s,u=oe(c,pd,s)*t%s,l=oe(u,gd,s)*u%s,f=oe(l,e,s)*l%s,y=oe(f,r,s)*f%s,p=oe(y,n,s)*y%s,d=oe(p,o,s)*p%s,E=oe(d,o,s)*p%s,h=oe(E,e,s)*l%s;return{pow_p_5_8:oe(h,hu,s)*t%s,b2:a}}function mu(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var du=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function wd(t,e){let r=Jn,n=ie(e*e*e,r),o=ie(n*n*e,r),s=pu(t*o).pow_p_5_8,i=ie(t*n*s,r),a=ie(e*i*i,r),c=i,u=ie(i*du,r),l=a===t,f=a===ie(-t,r),y=a===ie(-t*du,r);return l&&(i=c),(f||y)&&(i=u),tu(i,r)&&(i=ie(-i,r)),{isValid:l||f,value:i}}var xd=uu(bd,{uvRatio:wd});function Ed(t){return fu(xd,Vc,Object.assign({adjustScalarBytes:mu},t))}var gu=Ed({});var nn=(()=>{let t=Jn;return lu({P:t,type:"x25519",powPminus2:e=>{let{pow_p_5_8:r,b2:n}=pu(e);return ie(oe(r,md,t)*n,t)},adjustScalarBytes:mu})})();var on=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},eo=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var yu={get(t=globalThis){let e=t.crypto;if(e?.subtle==null)throw new eo("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 e}};var Ke=yu;var to=32;var ti,Sd=(async()=>{try{return await Ke.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function vd(t,e,r){if(t.buffer instanceof ArrayBuffer){let n=await Ke.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await Ke.get().subtle.verify({name:"Ed25519"},n,e,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Ad(t,e,r){return gu.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}async function bu(t,e,r){return ti==null&&(ti=await Sd),ti?vd(t,e,r):Ad(t,e,r)}function ro(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var no=class{type="Ed25519";raw;constructor(e){this.raw=ri(e,to)}toMultihash(){return Fe.digest(wt(this))}toCID(){return he.createV1(114,this.toMultihash())}toString(){return ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();let o=bu(this.raw,r,e);return ro(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function ni(t){return t=ri(t,to),new no(t)}function ri(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new Y(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}var _d=Math.pow(2,7),Ld=Math.pow(2,14),Id=Math.pow(2,21),oi=Math.pow(2,28),si=Math.pow(2,35),ii=Math.pow(2,42),ai=Math.pow(2,49),J=128,Ae=127;function se(t){if(t<_d)return 1;if(t<Ld)return 2;if(t<Id)return 3;if(t<oi)return 4;if(t<si)return 5;if(t<ii)return 6;if(t<ai)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function yr(t,e,r=0){switch(se(t)){case 8:e[r++]=t&255|J,t/=128;case 7:e[r++]=t&255|J,t/=128;case 6:e[r++]=t&255|J,t/=128;case 5:e[r++]=t&255|J,t/=128;case 4:e[r++]=t&255|J,t>>>=7;case 3:e[r++]=t&255|J,t>>>=7;case 2:e[r++]=t&255|J,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Bd(t,e,r=0){switch(se(t)){case 8:e.set(r++,t&255|J),t/=128;case 7:e.set(r++,t&255|J),t/=128;case 6:e.set(r++,t&255|J),t/=128;case 5:e.set(r++,t&255|J),t/=128;case 4:e.set(r++,t&255|J),t>>>=7;case 3:e.set(r++,t&255|J),t>>>=7;case 2:e.set(r++,t&255|J),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function ci(t,e){let r=t[e],n=0;if(n+=r&Ae,r<J||(r=t[e+1],n+=(r&Ae)<<7,r<J)||(r=t[e+2],n+=(r&Ae)<<14,r<J)||(r=t[e+3],n+=(r&Ae)<<21,r<J)||(r=t[e+4],n+=(r&Ae)*oi,r<J)||(r=t[e+5],n+=(r&Ae)*si,r<J)||(r=t[e+6],n+=(r&Ae)*ii,r<J)||(r=t[e+7],n+=(r&Ae)*ai,r<J))return n;throw new RangeError("Could not decode varint")}function Dd(t,e){let r=t.get(e),n=0;if(n+=r&Ae,r<J||(r=t.get(e+1),n+=(r&Ae)<<7,r<J)||(r=t.get(e+2),n+=(r&Ae)<<14,r<J)||(r=t.get(e+3),n+=(r&Ae)<<21,r<J)||(r=t.get(e+4),n+=(r&Ae)*oi,r<J)||(r=t.get(e+5),n+=(r&Ae)*si,r<J)||(r=t.get(e+6),n+=(r&Ae)*ii,r<J)||(r=t.get(e+7),n+=(r&Ae)*ai,r<J))return n;throw new RangeError("Could not decode varint")}function oo(t,e,r=0){return e==null&&(e=pe(se(t))),e instanceof Uint8Array?yr(t,e,r):Bd(t,e,r)}function ct(t,e=0){return t instanceof Uint8Array?ci(t,e):Dd(t,e)}var ui=new Float32Array([-0]),_t=new Uint8Array(ui.buffer);function xu(t,e,r){ui[0]=t,e[r]=_t[0],e[r+1]=_t[1],e[r+2]=_t[2],e[r+3]=_t[3]}function Eu(t,e){return _t[0]=t[e],_t[1]=t[e+1],_t[2]=t[e+2],_t[3]=t[e+3],ui[0]}var fi=new Float64Array([-0]),Ce=new Uint8Array(fi.buffer);function Su(t,e,r){fi[0]=t,e[r]=Ce[0],e[r+1]=Ce[1],e[r+2]=Ce[2],e[r+3]=Ce[3],e[r+4]=Ce[4],e[r+5]=Ce[5],e[r+6]=Ce[6],e[r+7]=Ce[7]}function vu(t,e){return Ce[0]=t[e],Ce[1]=t[e+1],Ce[2]=t[e+2],Ce[3]=t[e+3],Ce[4]=t[e+4],Ce[5]=t[e+5],Ce[6]=t[e+6],Ce[7]=t[e+7],fi[0]}var Td=BigInt(Number.MAX_SAFE_INTEGER),Rd=BigInt(Number.MIN_SAFE_INTEGER),Ne=class t{lo;hi;constructor(e,r){this.lo=e|0,this.hi=r|0}toNumber(e=!1){if(!e&&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(e=!1){if(e)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(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return $t;if(e<Td&&e>Rd)return this.fromNumber(Number(e));let r=e<0n;r&&(e=-e);let n=e>>32n,o=e-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>Au&&(o=0n,++n>Au&&(n=0n))),new t(Number(o),Number(n))}static fromNumber(e){if(e===0)return $t;let r=e<0;r&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new t(n,o)}static from(e){return typeof e=="number"?t.fromNumber(e):typeof e=="bigint"?t.fromBigInt(e):typeof e=="string"?t.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new t(e.low>>>0,e.high>>>0):$t}},$t=new Ne(0,0);$t.toBigInt=function(){return 0n};$t.zzEncode=$t.zzDecode=function(){return this};$t.length=function(){return 1};var Au=4294967296n;function Cu(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:(r&64512)===55296&&(t.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function _u(t,e,r){if(r-e<1)return"";let o,s=[],i=0,a;for(;e<r;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&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 li(t,e,r){let n=r,o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[r++]=o:o<2048?(e[r++]=o>>6|192,e[r++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[r++]=o>>18|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128,e[r++]=o&63|128):(e[r++]=o>>12|224,e[r++]=o>>6&63|128,e[r++]=o&63|128);return r-n}function qe(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function so(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}var hi=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,qe(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw qe(this,4);return so(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw qe(this,4);return so(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw qe(this,4);let e=Eu(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw qe(this,4);let e=vu(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw qe(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let e=this.bytes();return _u(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw qe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw qe(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Ne(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw qe(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,e}if(this.len-this.pos>4){for(;r<5;++r)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;r<5;++r){if(this.pos>=this.len)throw qe(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw qe(this,8);let e=so(this.buf,this.pos+=4),r=so(this.buf,this.pos+=4);return new Ne(e,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=ci(this.buf,this.pos);return this.pos+=se(e),e}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 di(t){return new hi(t instanceof Uint8Array?t:t.subarray())}function We(t,e,r){let n=di(t);return e.decode(n,void 0,r)}function pi(t){let e=t??8192,r=e>>>1,n,o=e;return function(i){if(i<1||i>r)return pe(i);o+i>e&&(n=pe(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var qt=class{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}};function mi(){}var yi=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Pd=pi();function Od(t){return globalThis.Buffer!=null?pe(t):Pd(t)}var cn=class{len;head;tail;states;constructor(){this.len=0,this.head=new qt(mi,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new qt(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new bi((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(io,10,Ne.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let r=Ne.fromBigInt(e);return this._push(io,r.length(),r)}uint64Number(e){return this._push(yr,se(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let r=Ne.fromBigInt(e).zzEncode();return this._push(io,r.length(),r)}sint64Number(e){let r=Ne.fromNumber(e).zzEncode();return this._push(io,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(gi,1,e?1:0)}fixed32(e){return this._push(an,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let r=Ne.fromBigInt(e);return this._push(an,4,r.lo)._push(an,4,r.hi)}fixed64Number(e){let r=Ne.fromNumber(e);return this._push(an,4,r.lo)._push(an,4,r.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(xu,4,e)}double(e){return this._push(Su,8,e)}bytes(e){let r=e.length>>>0;return r===0?this._push(gi,1,0):this.uint32(r)._push(Ud,r,e)}string(e){let r=Cu(e);return r!==0?this.uint32(r)._push(li,r,e):this._push(gi,1,0)}fork(){return this.states=new yi(this),this.head=this.tail=new qt(mi,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 qt(mi,0,0),this.len=0),this}ldelim(){let e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=r,this.len+=n),this}finish(){let e=this.head.next,r=Od(this.len),n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}};function gi(t,e,r){e[r]=t&255}function Nd(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}var bi=class extends qt{next;constructor(e,r){super(Nd,e,r),this.next=void 0}};function io(t,e,r){for(;t.hi!==0;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}function an(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function Ud(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(cn.prototype.bytes=function(t){let e=t.length>>>0;return this.uint32(e),e>0&&this._push(Md,e,t),this},cn.prototype.string=function(t){let e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(Kd,e,t),this});function Md(t,e,r){e.set(t,r)}function Kd(t,e,r){t.length<40?li(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(j(t),r)}function wi(){return new cn}function Ge(t,e){let r=wi();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var br;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(br||(br={}));function ao(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function Wt(t){function e(o){if(t[o.toString()]==null)throw new Error("Invalid enum value");return t[o]}let r=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return ao("enum",br.VARINT,r,n)}function ze(t,e){return ao("message",br.LENGTH_DELIMITED,t,e)}var un=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var fe;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(fe||(fe={}));var xi;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(xi||(xi={}));(function(t){t.codec=()=>Wt(xi)})(fe||(fe={}));var Je;(function(t){let e;t.codec=()=>(e==null&&(e=ze((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),fe.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{s.Type=fe.codec().decode(r);break}case 2:{s.Data=r.bytes();break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ge(r,t.codec()),t.decode=(r,n)=>We(r,t.codec(),n)})(Je||(Je={}));var Ei;(function(t){let e;t.codec=()=>(e==null&&(e=ze((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),fe.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{s.Type=fe.codec().decode(r);break}case 2:{s.Data=r.bytes();break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ge(r,t.codec()),t.decode=(r,n)=>We(r,t.codec(),n)})(Ei||(Ei={}));var ln={};Ie(ln,{MAX_RSA_KEY_SIZE:()=>Si,generateRSAKeyPair:()=>Ru,jwkToJWKKeyPair:()=>Pu,jwkToPkcs1:()=>Vd,jwkToPkix:()=>_i,jwkToRSAPrivateKey:()=>Di,pkcs1MessageToJwk:()=>Ai,pkcs1MessageToRSAPrivateKey:()=>Li,pkcs1ToJwk:()=>Fd,pkcs1ToRSAPrivateKey:()=>Tu,pkixMessageToJwk:()=>Ci,pkixMessageToRSAPublicKey:()=>Bi,pkixToJwk:()=>$d,pkixToRSAPublicKey:()=>Ii});var wr=class{type="RSA";jwk;_raw;_multihash;constructor(e,r){this.jwk=e,this._multihash=r}get raw(){return this._raw==null&&(this._raw=ln.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return he.createV1(114,this._multihash)}toString(){return ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}verify(e,r,n){return Du(this.jwk,r,e,n)}},fn=class{type="RSA";jwk;_raw;publicKey;constructor(e,r){this.jwk=e,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=ln.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}sign(e,r){return Bu(this.jwk,e,r)}};var Si=8192,vi=18,kd=1062,Hd=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Fd(t){let e=rt(t);return Ai(e)}function Ai(t){return{n:$(t[1],"base64url"),e:$(t[2],"base64url"),d:$(t[3],"base64url"),p:$(t[4],"base64url"),q:$(t[5],"base64url"),dp:$(t[6],"base64url"),dq:$(t[7],"base64url"),qi:$(t[8],"base64url"),kty:"RSA"}}function Vd(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new Y("JWK was missing components");return bt([Re(Uint8Array.from([0])),Re(j(t.n,"base64url")),Re(j(t.e,"base64url")),Re(j(t.d,"base64url")),Re(j(t.p,"base64url")),Re(j(t.q,"base64url")),Re(j(t.dp,"base64url")),Re(j(t.dq,"base64url")),Re(j(t.qi,"base64url"))]).subarray()}function $d(t){let e=rt(t,{offset:0});return Ci(e)}function Ci(t){let e=rt(t[1],{offset:0});return{kty:"RSA",n:$(e[0],"base64url"),e:$(e[1],"base64url")}}function _i(t){if(t.n==null||t.e==null)throw new Y("JWK was missing components");return bt([Hd,Gn(bt([Re(j(t.n,"base64url")),Re(j(t.e,"base64url"))]))]).subarray()}function Tu(t){let e=rt(t);return Li(e)}function Li(t){let e=Ai(t);return Di(e)}function Ii(t,e){if(t.byteLength>=kd)throw new er("Key size is too large");let r=rt(t,{offset:0});return Bi(r,t,e)}function Bi(t,e,r){let n=Ci(t);if(r==null){let o=Ye(Je.encode({Type:fe.RSA,Data:e}));r=Be(vi,o)}return new wr(n,r)}function Di(t){if(Nu(t)>Si)throw new Y("Key size is too large");let e=Pu(t),r=Ye(Je.encode({Type:fe.RSA,Data:_i(e.publicKey)})),n=Be(vi,r);return new fn(e.privateKey,new wr(e.publicKey,n))}async function Ru(t){if(t>Si)throw new Y("Key size is too large");let e=await Ou(t),r=Ye(Je.encode({Type:fe.RSA,Data:_i(e.publicKey)})),n=Be(vi,r);return new fn(e.privateKey,new wr(e.publicKey,n))}function Pu(t){if(t==null)throw new Y("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function Ou(t,e){let r=await Ke.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await qd(r,e);return{privateKey:n[0],publicKey:n[1]}}async function Bu(t,e,r){let n=await Ke.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let o=await Ke.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Du(t,e,r,n){let o=await Ke.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ke.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),s}async function qd(t,e){if(t.privateKey==null||t.publicKey==null)throw new Y("Private and public key are required");let r=await Promise.all([Ke.get().subtle.exportKey("jwk",t.privateKey),Ke.get().subtle.exportKey("jwk",t.publicKey)]);return e?.signal?.throwIfAborted(),r}function Nu(t){if(t.kty!=="RSA")throw new Y("invalid key type");if(t.n==null)throw new Y("invalid key modulus");return j(t.n,"base64url").length*8}var co=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,r){if(Ut(e),F(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Ve(o)}update(e){return ur(this),this.iHash.update(e),this}digestInto(e){ur(this),F(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},xr=(t,e,r)=>new co(t,e).update(r).digest();xr.create=(t,e)=>new co(t,e);var Uu=(t,e)=>(t+(t>=0?e:-e)/Mu)/e;function Wd(t,e,r){let[[n,o],[s,i]]=e,a=Uu(i*t,r),c=Uu(-o*t,r),u=t-a*n-c*s,l=-a*o-c*i,f=u<ut,y=l<ut;f&&(u=-u),y&&(l=-l);let p=Jr(Math.ceil(Ws(r)/2))+Er;if(u<ut||u>=p||l<ut||l>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:y,k2:l}}function Ri(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Ti(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return at(r.lowS,"lowS"),at(r.prehash,"prehash"),r.format!==void 0&&Ri(r.format),r}var Pi=class extends Error{constructor(e=""){super(e)}},Lt={Err:Pi,_tlv:{encode:(t,e)=>{let{Err:r}=Lt;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,o=Zr(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?Zr(o.length/2|128):"";return Zr(t)+s+o+e},decode(t,e){let{Err:r}=Lt,n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let o=e[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=e.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 l of u)i=i<<8|l;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(t){let{Err:e}=Lt;if(t<ut)throw new e("integer: negative integers are not allowed");let r=Zr(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=Lt;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return fr(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=Lt,o=F(t,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(t){let{_tlv:e,_int:r}=Lt,n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),s=n+o;return e.encode(48,s)}},ut=BigInt(0),Er=BigInt(1),Mu=BigInt(2),uo=BigInt(3),Gd=BigInt(4);function Ku(t,e={}){let r=Zn("weierstrass",t,e),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i,n:a}=s;Qe(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;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=Hu(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(T,w,m){let{x:g,y:C}=w.toAffine(),I=n.toBytes(g);if(at(m,"isCompressed"),m){l();let L=!n.isOdd(C);return Pe(ku(L),I)}else return Pe(Uint8Array.of(4),I,n.toBytes(C))}function y(T){F(T,void 0,"Point");let{publicKey:w,publicKeyUncompressed:m}=u,g=T.length,C=T[0],I=T.subarray(1);if(g===w&&(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=E(L),B;try{B=n.sqrt(S)}catch(z){let W=z instanceof Error?": "+z.message:"";throw new Error("bad point: is not on curve, sqrt error"+W)}l();let R=n.isOdd(B);return(C&1)===1!==R&&(B=n.neg(B)),{x:L,y:B}}else if(g===m&&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 ${g}, expected compressed=${w} or uncompressed=${m}`)}let p=e.toBytes||f,d=e.fromBytes||y;function E(T){let w=n.sqr(T),m=n.mul(w,T);return n.add(n.add(m,n.mul(T,s.a)),s.b)}function h(T,w){let m=n.sqr(w),g=E(T);return n.eql(m,g)}if(!h(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let b=n.mul(n.pow(s.a,uo),Gd),A=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(b,A)))throw new Error("bad curve params: a or b");function x(T,w,m=!1){if(!n.isValid(w)||m&&n.is0(w))throw new Error(`bad point coordinate ${T}`);return w}function D(T){if(!(T instanceof v))throw new Error("Weierstrass Point expected")}function M(T){if(!c||!c.basises)throw new Error("no endo");return Wd(T,c.basises,o.ORDER)}let O=lr((T,w)=>{let{X:m,Y:g,Z:C}=T;if(n.eql(C,n.ONE))return{x:m,y:g};let I=T.is0();w==null&&(w=I?n.ONE:n.inv(C));let L=n.mul(m,w),S=n.mul(g,w),B=n.mul(C,w);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=lr(T=>{if(T.is0()){if(e.allowInfinityPoint&&!n.is0(T.Y))return;throw new Error("bad point: ZERO")}let{x:w,y:m}=T.toAffine();if(!n.isValid(w)||!n.isValid(m))throw new Error("bad point: x or y not field elements");if(!h(w,m))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,m,g,C){return m=new v(n.mul(m.X,T),m.Y,m.Z),w=tn(g,w),m=tn(C,m),w.add(m)}class v{static BASE=new v(s.Gx,s.Gy,n.ONE);static ZERO=new v(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(w,m,g){this.X=x("x",w),this.Y=x("y",m,!0),this.Z=x("z",g),Object.freeze(this)}static CURVE(){return s}static fromAffine(w){let{x:m,y:g}=w||{};if(!w||!n.isValid(m)||!n.isValid(g))throw new Error("invalid affine point");if(w instanceof v)throw new Error("projective point not allowed");return n.is0(m)&&n.is0(g)?v.ZERO:new v(m,g,n.ONE)}static fromBytes(w){let m=v.fromAffine(d(F(w,void 0,"point")));return m.assertValidity(),m}static fromHex(w){return v.fromBytes(st(w))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,m=!0){return K.createCache(this,w),m||this.multiply(uo),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:m,Y:g,Z:C}=this,{X:I,Y:L,Z:S}=w,B=n.eql(n.mul(m,S),n.mul(I,C)),R=n.eql(n.mul(g,S),n.mul(L,C));return B&&R}negate(){return new v(this.X,n.neg(this.Y),this.Z)}double(){let{a:w,b:m}=s,g=n.mul(m,uo),{X:C,Y:I,Z:L}=this,S=n.ZERO,B=n.ZERO,R=n.ZERO,P=n.mul(C,C),z=n.mul(I,I),W=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(w,R),B=n.mul(g,W),B=n.add(S,B),S=n.sub(z,B),B=n.add(z,B),B=n.mul(S,B),S=n.mul(V,S),R=n.mul(g,R),W=n.mul(w,W),V=n.sub(P,W),V=n.mul(w,V),V=n.add(V,R),R=n.add(P,P),P=n.add(R,P),P=n.add(P,W),P=n.mul(P,V),B=n.add(B,P),W=n.mul(I,L),W=n.add(W,W),P=n.mul(W,V),S=n.sub(S,P),R=n.mul(W,z),R=n.add(R,R),R=n.add(R,R),new v(S,B,R)}add(w){D(w);let{X:m,Y:g,Z:C}=this,{X:I,Y:L,Z:S}=w,B=n.ZERO,R=n.ZERO,P=n.ZERO,z=s.a,W=n.mul(s.b,uo),V=n.mul(m,I),X=n.mul(g,L),te=n.mul(C,S),ue=n.add(m,g),Z=n.add(I,L);ue=n.mul(ue,Z),Z=n.add(V,X),ue=n.sub(ue,Z),Z=n.add(m,C);let le=n.add(I,S);return Z=n.mul(Z,le),le=n.add(V,te),Z=n.sub(Z,le),le=n.add(g,C),B=n.add(L,S),le=n.mul(le,B),B=n.add(X,te),le=n.sub(le,B),P=n.mul(z,Z),B=n.mul(W,te),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),te=n.mul(z,te),Z=n.mul(W,Z),X=n.add(X,te),te=n.sub(V,te),te=n.mul(z,te),Z=n.add(Z,te),V=n.mul(X,Z),R=n.add(R,V),V=n.mul(le,Z),B=n.mul(ue,B),B=n.sub(B,V),V=n.mul(ue,X),P=n.mul(le,P),P=n.add(P,V),new v(B,R,P)}subtract(w){return this.add(w.negate())}is0(){return this.equals(v.ZERO)}multiply(w){let{endo:m}=e;if(!o.isValidNot0(w))throw new Error("invalid scalar: out of range");let g,C,I=L=>K.cached(this,L,S=>Vt(v,S));if(m){let{k1neg:L,k1:S,k2neg:B,k2:R}=M(w),{p:P,f:z}=I(S),{p:W,f:V}=I(R);C=z.add(V),g=_(m.beta,P,W,L,B)}else{let{p:L,f:S}=I(w);g=L,C=S}return Vt(v,[g,C])[0]}multiplyUnsafe(w){let{endo:m}=e,g=this;if(!o.isValid(w))throw new Error("invalid scalar: out of range");if(w===ut||g.is0())return v.ZERO;if(w===Er)return g;if(K.hasCache(this))return this.multiply(w);if(m){let{k1neg:C,k1:I,k2neg:L,k2:S}=M(w),{p1:B,p2:R}=cu(v,g,I,S);return _(m.beta,B,R,C,L)}else return K.unsafe(g,w)}toAffine(w){return O(this,w)}isTorsionFree(){let{isTorsionFree:w}=e;return i===Er?!0:w?w(v,this):K.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:w}=e;return i===Er?this:w?w(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(w=!0){return at(w,"isCompressed"),this.assertValidity(),p(v,this,w)}toHex(w=!0){return ot(this.toBytes(w))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=o.BITS,K=new pr(v,e.endo?Math.ceil(N/2):N);return v.BASE.precompute(8),v}function ku(t){return Uint8Array.of(t?2:3)}function Hu(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function zd(t,e={}){let{Fn:r}=t,n=e.randomBytes||xt,o=Object.assign(Hu(t.Fp,r),{seed:Xs(r.ORDER)});function s(p){try{let d=r.fromBytes(p);return r.isValidNot0(d)}catch{return!1}}function i(p,d){let{publicKey:E,publicKeyUncompressed:h}=o;try{let b=p.length;return d===!0&&b!==E||d===!1&&b!==h?!1:!!t.fromBytes(p)}catch{return!1}}function a(p=n(o.seed)){return Ys(F(p,o.seed,"seed"),r.ORDER)}function c(p,d=!0){return t.BASE.multiply(r.fromBytes(p)).toBytes(d)}function u(p){let{secretKey:d,publicKey:E,publicKeyUncompressed:h}=o;if(!Nt(p)||"_lengths"in r&&r._lengths||d===E)return;let b=F(p,void 0,"key").length;return b===E||b===h}function l(p,d,E=!0){if(u(p)===!0)throw new Error("first arg must be private key");if(u(d)===!1)throw new Error("second arg must be public key");let h=r.fromBytes(p);return t.fromBytes(d).multiply(h).toBytes(E)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},y=mr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:y,Point:t,utils:f,lengths:o})}function Fu(t,e,r={}){Ut(e),Qe(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes||xt,o=r.hmac||((m,g)=>xr(e,m,g)),{Fp:s,Fn:i}=t,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:l,getSharedSecret:f,utils:y,lengths:p}=zd(t,r),d={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},E=a*Mu<s.ORDER;function h(m){let g=a>>Er;return m>g}function b(m,g){if(!i.isValidNot0(g))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return g}function A(){if(E)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function x(m,g){Ri(g);let C=p.signature,I=g==="compact"?C:g==="recovered"?C+1:void 0;return F(m,I)}class D{r;s;recovery;constructor(g,C,I){if(this.r=b("r",g),this.s=b("s",C),I!=null){if(A(),![0,1,2,3].includes(I))throw new Error("invalid recovery id");this.recovery=I}Object.freeze(this)}static fromBytes(g,C=d.format){x(g,C);let I;if(C==="der"){let{r:R,s:P}=Lt.toSig(F(g));return new D(R,P)}C==="recovered"&&(I=g[0],C="compact",g=g.subarray(1));let L=p.signature/2,S=g.subarray(0,L),B=g.subarray(L,L*2);return new D(i.fromBytes(S),i.fromBytes(B),I)}static fromHex(g,C){return this.fromBytes(st(g),C)}assertRecovery(){let{recovery:g}=this;if(g==null)throw new Error("invalid recovery id: must be present");return g}addRecoveryBit(g){return new D(this.r,this.s,g)}recoverPublicKey(g){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=t.fromBytes(Pe(ku((L&1)===0),B)),P=i.inv(S),z=O(F(g,void 0,"msgHash")),W=i.create(-z*P),V=i.create(I*P),X=t.BASE.multiplyUnsafe(W).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(g=d.format){if(Ri(g),g==="der")return st(Lt.hexFromSig(this));let{r:C,s:I}=this,L=i.toBytes(C),S=i.toBytes(I);return g==="recovered"?(A(),Pe(Uint8Array.of(this.assertRecovery()),L,S)):Pe(L,S)}toHex(g){return ot(this.toBytes(g))}}let M=r.bits2int||function(g){if(g.length>8192)throw new Error("input is too large");let C=fr(g),I=g.length*8-c;return I>0?C>>BigInt(I):C},O=r.bits2int_modN||function(g){return i.create(M(g))},k=Jr(c);function _(m){return At("num < 2^"+c,m,ut,k),i.toBytes(m)}function v(m,g){return F(m,void 0,"message"),g?F(e(m),void 0,"prehashed message"):m}function N(m,g,C){let{lowS:I,prehash:L,extraEntropy:S}=Ti(C,d);m=v(m,L);let B=O(m),R=i.fromBytes(g);if(!i.isValidNot0(R))throw new Error("invalid private key");let P=[_(R),_(B)];if(S!=null&&S!==!1){let X=S===!0?n(p.secretKey):S;P.push(F(X,void 0,"extraEntropy"))}let z=Pe(...P),W=B;function V(X){let te=M(X);if(!i.isValidNot0(te))return;let ue=i.inv(te),Z=t.BASE.multiply(te).toAffine(),le=i.create(Z.x);if(le===ut)return;let Jt=i.create(ue*i.create(W+le*R));if(Jt===ut)return;let Dn=(Z.x===le?0:2)|Number(Z.y&Er),kr=Jt;return I&&h(Jt)&&(kr=i.neg(Jt),Dn^=1),new D(le,kr,E?void 0:Dn)}return{seed:z,k2sig:V}}function K(m,g,C={}){let{seed:I,k2sig:L}=N(m,g,C);return Wc(e.outputLen,i.BYTES,o)(I,L).toBytes(C.format)}function T(m,g,C,I={}){let{lowS:L,prehash:S,format:B}=Ti(I,d);if(C=F(C,void 0,"publicKey"),g=v(g,S),!Nt(m)){let R=m instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+R)}x(m,B);try{let R=D.fromBytes(m,B),P=t.fromBytes(C);if(L&&R.hasHighS())return!1;let{r:z,s:W}=R,V=O(g),X=i.inv(W),te=i.create(V*X),ue=i.create(z*X),Z=t.BASE.multiplyUnsafe(te).add(P.multiplyUnsafe(ue));return Z.is0()?!1:i.create(Z.x)===z}catch{return!1}}function w(m,g,C={}){let{prehash:I}=Ti(C,d);return g=v(g,I),D.fromBytes(m,"recovered").recoverPublicKey(g).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:f,utils:y,lengths:p,Point:t,sign:K,verify:T,recoverPublicKey:w,Signature:D,hash:e})}var Ni={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},jd={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Vu=BigInt(2);function Xd(t){let e=Ni.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,f=oe(l,r,e)*l%e,y=oe(f,r,e)*l%e,p=oe(y,Vu,e)*u%e,d=oe(p,o,e)*p%e,E=oe(d,s,e)*d%e,h=oe(E,a,e)*E%e,b=oe(h,c,e)*h%e,A=oe(b,a,e)*E%e,x=oe(A,r,e)*l%e,D=oe(x,i,e)*d%e,M=oe(D,n,e)*u%e,O=oe(M,Vu,e);if(!Oi.eql(Oi.sqr(O),t))throw new Error("Cannot find square root");return O}var Oi=hr(Ni.p,{sqrt:Xd}),Yd=Ku(Ni,{Fp:Oi,endo:jd}),Sr=Fu(Yd,Ye);function $u(t,e,r,n){let o=tt.digest(r instanceof Uint8Array?r:r.subarray());if(ro(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Sr.verify(e,s,t,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new on(String(s))});try{return n?.signal?.throwIfAborted(),Sr.verify(e,o.digest,t,{prehash:!1,format:"der"})}catch(s){throw new on(String(s))}}var fo=class{type="secp256k1";raw;_key;constructor(e){this._key=Wu(e),this.raw=qu(this._key)}toMultihash(){return Fe.digest(wt(this))}toCID(){return he.createV1(114,this.toMultihash())}toString(){return ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}verify(e,r,n){return $u(this._key,r,e,n)}};function Ui(t){return new fo(t)}function qu(t){return Sr.Point.fromBytes(t).toBytes()}function Wu(t){try{return Sr.Point.fromBytes(t),t}catch(e){throw new er(String(e))}}function hn(t,e){let{Type:r,Data:n}=Je.decode(t),o=n??new Uint8Array;switch(r){case fe.RSA:return Ii(o,e);case fe.Ed25519:return ni(o);case fe.secp256k1:return Ui(o);case fe.ECDSA:return Os(o);default:throw new Rt}}function Gu(t){let{Type:e,Data:r}=Je.decode(t.digest),n=r??new Uint8Array;switch(e){case fe.Ed25519:return ni(n);case fe.secp256k1:return Ui(n);case fe.ECDSA:return Os(n);default:throw new Rt}}function wt(t){return Je.encode({Type:fe[t.type],Data:t.raw})}var zu=Symbol.for("nodejs.util.inspect.custom"),Zd=114,dn=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[is]=!0;toString(){return this.string==null&&(this.string=ce.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return he.createV1(Zd,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return we(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return we(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[zu](){return`PeerId(${this.toString()})`}},pn=class extends dn{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},mn=class extends dn{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},gn=class extends dn{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Qd=2336,yn=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Fe.digest(j(this.url))}[zu](){return`PeerId(${this.url})`}[is]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return he.createV1(Qd,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=$(e)),e.toString()===this.toString())}};var Jd=114,ju=2336;function vr(t,e){let r;if(t.charAt(0)==="1"||t.charAt(0)==="Q")r=ar(ce.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return ep(he.parse(t));if(e==null)throw new Y('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=ar(e.decode(t))}return Xu(r)}function Mi(t){if(t.type==="Ed25519")return new mn({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new gn({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new pn({multihash:t.toCID().multihash,publicKey:t});throw new Rt}function Xu(t){if(rp(t))return new pn({multihash:t});if(tp(t))try{let e=Gu(t);if(e.type==="Ed25519")return new mn({multihash:t,publicKey:e});if(e.type==="secp256k1")return new gn({multihash:t,publicKey:e})}catch{let r=$(t.digest);return new yn(new URL(r))}throw new Mn("Supplied PeerID Multihash is invalid")}function ep(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==Jd&&t.code!==ju)throw new Un("Supplied PeerID CID is invalid");if(t.code===ju){let e=$(t.multihash.digest);return new yn(new URL(e))}return Xu(t.multihash)}function tp(t){return t.code===Fe.code}function rp(t){return t.code===tt.code}var Ee=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ft=class extends Error{static name="ValidationError";name="ValidationError"},lo=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},ho=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var po=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let r=this.index,n=e();return n===void 0&&(this.index=r),n}parseWith(e){let r=e();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(e){return this.readAtomically(()=>{let r=this.readChar();if(r===e)return r})}readSeparator(e,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,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 l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let y=Number.parseInt(f,e);if(!Number.isNaN(y))return y});if(l===void 0)break;if(s*=e,s+=l,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 e=new Uint8Array(4);for(let r=0;r<e.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[r]=n}return e})}readIPv6Addr(){let e=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]=e(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]=e(s.subarray(0,i));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var np=45,op=15,mo=new po;function Yu(t){if(!(t.length>op))return mo.new(t).parseWith(()=>mo.readIPv4Addr())}function Zu(t){if(t.includes("%")&&(t=t.split("%")[0]),!(t.length>np))return mo.new(t).parseWith(()=>mo.readIPv6Addr())}function go(t){return!!Yu(t)}function Qu(t){return!!Zu(t)}function ki(t){return e=>$(e,t)}function Hi(t){return e=>j(e,t)}function Ar(t){return new DataView(t.buffer).getUint16(t.byteOffset).toString()}function Gt(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof t=="string"?parseInt(t):t),new Uint8Array(e)}function Ju(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let r=j(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Gt(n);return De([r,o],r.length+o.length)}function ef(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let r=yt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Gt(n);return De([r,o],r.length+o.length)}function Fi(t){let e=t.subarray(0,t.length-2),r=t.subarray(t.length-2),n=$(e,"base32"),o=Ar(r);return`${n}:${o}`}var Vi=function(t){t=t.toString().trim();let e=new Uint8Array(4);return t.split(/\./g).forEach((r,n)=>{let o=parseInt(r,10);if(isNaN(o)||o<0||o>255)throw new Ee("Invalid byte value in IP address");e[n]=o}),e},tf=function(t){let e=0;t=t.toString().trim();let r=t.split(":",8),n;for(n=0;n<r.length;n++){let s=go(r[n]),i;s&&(i=Vi(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(e+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 Ee("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},rf=function(t){if(t.byteLength!==4)throw new Ee("IPv4 address was incorrect length");let e=[];for(let r=0;r<t.byteLength;r++)e.push(t[r]);return e.join(".")},nf=function(t){if(t.byteLength!==16)throw new Ee("IPv6 address was incorrect length");let e=[];for(let n=0;n<t.byteLength;n+=2){let o=t[n],s=t[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let r=e.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Ee(`Invalid IPv6 address "${r}"`)}};function of(t){try{let e=new URL(`http://[${t}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ee(`Invalid IPv6 address "${t}"`)}}var Ki=Object.values(Ot).map(t=>t.decoder),sp=(function(){let t=Ki[0].or(Ki[1]);return Ki.slice(2).forEach(e=>t=t.or(e)),t})();function sf(t){return sp.decode(t)}function af(t){return e=>t.encoder.encode(e)}function ip(t){if(parseInt(t).toString()!==t)throw new ft("Value must be an integer")}function ap(t){if(t<0)throw new ft("Value must be a positive integer, or zero")}function cp(t){return e=>{if(e>t)throw new ft(`Value must be smaller than or equal to ${t}`)}}function up(...t){return e=>{for(let r of t)r(e)}}var bn=up(ip,ap,cp(65535));var ye=-1,$i=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let r;if(typeof e=="string"?r=this.protocolsByName.get(e):r=this.protocolsByCode.get(e),r==null)throw new ho(`Protocol ${e} was unknown`);return r}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(r=>{this.protocolsByName.set(r,e)})}removeProtocol(e){let r=this.protocolsByCode.get(e);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},lt=new $i,Ap=[{code:4,name:"ip4",size:32,valueToBytes:Vi,bytesToValue:rf,validate:t=>{if(!go(t))throw new ft(`Invalid IPv4 address "${t}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Gt,bytesToValue:Ar,validate:bn},{code:273,name:"udp",size:16,valueToBytes:Gt,bytesToValue:Ar,validate:bn},{code:33,name:"dccp",size:16,valueToBytes:Gt,bytesToValue:Ar,validate:bn},{code:41,name:"ip6",size:128,valueToBytes:tf,bytesToValue:nf,stringToValue:of,validate:t=>{if(!Qu(t))throw new ft(`Invalid IPv6 address "${t}"`)}},{code:42,name:"ip6zone",size:ye},{code:43,name:"ipcidr",size:8,bytesToValue:ki("base10"),valueToBytes:Hi("base10")},{code:53,name:"dns",size:ye},{code:54,name:"dns4",size:ye},{code:55,name:"dns6",size:ye},{code:56,name:"dnsaddr",size:ye},{code:132,name:"sctp",size:16,valueToBytes:Gt,bytesToValue:Ar,validate:bn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ye,stringToValue:t=>decodeURIComponent(t),valueToString:t=>encodeURIComponent(t)},{code:421,name:"p2p",aliases:["ipfs"],size:ye,bytesToValue:ki("base58btc"),valueToBytes:t=>t.startsWith("Q")||t.startsWith("1")?Hi("base58btc")(t):he.parse(t).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Fi,valueToBytes:Ju},{code:445,name:"onion3",size:296,bytesToValue:Fi,valueToBytes:ef},{code:446,name:"garlic64",size:ye},{code:447,name:"garlic32",size:ye},{code:448,name:"tls"},{code:449,name:"sni",size:ye},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ye,bytesToValue:af(Wr),valueToBytes:sf},{code:480,name:"http"},{code:481,name:"http-path",size:ye,stringToValue:t=>`/${decodeURIComponent(t)}`,valueToString:t=>encodeURIComponent(t.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:ye}];Ap.forEach(t=>{lt.addProtocol(t)});function cf(t){let e=[],r=0;for(;r<t.length;){let n=ct(t,r),o=lt.getProtocol(n),s=se(n),i=Cp(o,t,r+s),a=0;i>0&&o.size===ye&&(a=se(i));let c=s+a+i,u={code:n,name:o.name,bytes:t.subarray(r,r+c)};if(i>0){let l=r+s+a,f=t.subarray(l,l+i);u.value=o.bytesToValue?.(f)??$(f)}e.push(u),r+=c}return e}function uf(t){let e=0,r=[];for(let n of t){if(n.bytes==null){let o=lt.getProtocol(n.code),s=se(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??j(n.value),a=i.byteLength,o.size===ye&&(c=se(a)));let u=new Uint8Array(s+c+a),l=0;yr(n.code,u,l),l+=s,i!=null&&(o.size===ye&&(yr(a,u,l),l+=c),u.set(i,l)),n.bytes=u}r.push(n.bytes),e+=n.bytes.byteLength}return De(r,e)}function ff(t){if(t.charAt(0)!=="/")throw new Ee('String multiaddr must start with "/"');let e=[],r="protocol",n="",o="";for(let s=1;s<t.length;s++){let i=t.charAt(s);i!=="/"&&(r==="protocol"?o+=t.charAt(s):n+=t.charAt(s));let a=s===t.length-1;if(i==="/"||a){let c=lt.getProtocol(o);if(r==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",r="protocol";continue}else if(a)throw new Ee(`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 Ee(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",o="",r="protocol"}}}if(o!==""&&n!=="")throw new Ee("Incomplete multiaddr");return e}function lf(t){return`/${t.flatMap(e=>{if(e.value==null)return e.name;let r=lt.getProtocol(e.code);if(r==null)throw new Ee(`Unknown protocol code ${e.code}`);return[e.name,r.valueToString?.(e.value)??e.value]}).join("/")}`}function Cp(t,e,r){return t.size==null||t.size===0?0:t.size>0?t.size/8:ct(e,r)}var _p=Symbol.for("nodejs.util.inspect.custom"),ia=Symbol.for("@multiformats/multiaddr");function Lp(t){if(t==null&&(t="/"),hf(t))return t.getComponents();if(t instanceof Uint8Array)return cf(t);if(typeof t=="string")return t=t.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),t===""&&(t="/"),ff(t);if(Array.isArray(t))return t;throw new Ee("Must be a string, Uint8Array, Component[], or another Multiaddr")}var xo=class t{[ia]=!0;#e;#t;#r;constructor(e="/",r={}){this.#e=Lp(e),r.validate!==!1&&Ip(this)}get bytes(){return this.#r==null&&(this.#r=uf(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=lf(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let r=new t(e);return new t([...this.#e,...r.getComponents()],{validate:!1})}decapsulate(e){let r=e.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new lo(`Address ${this.toString()} does not contain subaddress: ${r}`);return new t(n.slice(0,o),{validate:!1})}decapsulateCode(e){let r;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){r=n;break}return new t(this.#e.slice(0,r),{validate:!1})}equals(e){return we(this.bytes,e.bytes)}[_p](){return`Multiaddr(${this.toString()})`}};function Ip(t){t.getComponents().forEach(e=>{let r=lt.getProtocol(e.code);e.value!=null&&r.validate?.(e.value)})}function hf(t){return!!t?.[ia]}function Ir(t){return new xo(t)}var re=t=>({match:e=>{let r=e[0];return r==null||r.code!==t||r.value!=null?!1:e.slice(1)}}),H=(t,e)=>({match:r=>{let n=r[0];return n?.code!==t||n.value==null||e!=null&&n.value!==e?!1:r.slice(1)}}),df=t=>({match:e=>t.match(e)===!1?e:!1}),G=t=>({match:e=>{let r=t.match(e);return r===!1?e:r}}),_e=(...t)=>({match:e=>{let r;for(let n of t){let o=n.match(e);o!==!1&&(r==null||o.length<r.length)&&(r=o)}return r??!1}}),ee=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e}});function ne(...t){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of t){let a=i.match(s);if(a===!1)return!1;s=a}return s}function r(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:t,matches:r,exactMatch:n}}var Bp=H(421),Gx=ne(Bp),So=H(54),vo=H(55),Ao=H(56),ca=H(53),zx=ne(So,G(H(421))),jx=ne(vo,G(H(421))),Xx=ne(Ao,G(H(421))),Yx=ne(_e(ca,Ao,So,vo),G(H(421))),pf=ee(H(4),G(H(43))),mf=ee(G(H(42)),H(41),G(H(43))),ua=_e(pf,mf),Xt=_e(ua,ca,So,vo,Ao),Zx=ne(_e(ua,ee(_e(ca,Ao,So,vo),G(H(421))))),Qx=ne(pf),Jx=ne(mf),e1=ne(ua),fa=ee(Xt,H(6)),wn=ee(Xt,H(273)),t1=ne(ee(fa,G(H(421)))),r1=ne(wn),la=ee(wn,re(460),G(H(421))),Co=ee(wn,re(461),G(H(421))),Dp=_e(la,Co),n1=ne(la),o1=ne(Co),aa=_e(Xt,fa,wn,la,Co),gf=_e(ee(aa,re(477),G(H(421)))),s1=ne(gf),yf=_e(ee(aa,re(478),G(H(421))),ee(aa,re(448),G(H(449)),re(477),G(H(421)))),i1=ne(yf),bf=ee(wn,re(280),G(H(466)),G(H(466)),G(H(421))),wf=ne(bf),xf=ee(Co,re(465),G(H(466)),G(H(466)),G(H(421))),a1=ne(xf),Eo=_e(gf,yf,ee(fa,G(H(421))),ee(Dp,G(H(421))),ee(Xt,G(H(421))),bf,xf,H(421)),Ef=ne(Eo),Tp=ee(G(Eo),re(290),df(re(281)),G(H(421))),c1=ne(Tp),Rp=_e(ee(Eo,re(290),re(281),G(H(421))),ee(Eo,re(281),G(H(421))),ee(re(281),G(H(421)))),Sf=ne(Rp),Pp=_e(ee(Xt,H(6),re(480),G(H(421))),ee(Xt,re(480),G(H(421)))),u1=ne(Pp),Op=ee(Xt,_e(ee(H(6,"443"),re(480)),ee(H(6),re(443)),ee(H(6),re(448),re(480)),ee(re(448),re(480)),re(448),re(443)),G(H(421))),f1=ne(Op),Np=_e(ee(H(777),G(H(421)))),l1=ne(Np),Up=_e(ee(H(400),G(H(421)))),h1=ne(Up);var Le;(function(t){let e;(function(o){o.FIN="FIN",o.STOP_SENDING="STOP_SENDING",o.RESET="RESET",o.FIN_ACK="FIN_ACK"})(e=t.Flag||(t.Flag={}));let r;(function(o){o[o.FIN=0]="FIN",o[o.STOP_SENDING=1]="STOP_SENDING",o[o.RESET=2]="RESET",o[o.FIN_ACK=3]="FIN_ACK"})(r||(r={})),(function(o){o.codec=()=>Wt(r)})(e=t.Flag||(t.Flag={}));let n;t.codec=()=>(n==null&&(n=ze((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.flag!=null&&(s.uint32(8),t.Flag.codec().encode(o.flag,s)),o.message!=null&&(s.uint32(18),s.bytes(o.message)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{a.flag=t.Flag.codec().decode(o);break}case 2:{a.message=o.bytes();break}default:{o.skipType(u&7);break}}}return a})),n),t.encode=o=>Ge(o,t.codec()),t.decode=(o,s)=>We(o,t.codec(),s)})(Le||(Le={}));var vf=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],ha=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Af="libp2p+webrtc+v1/",Cf=2*1024*1024,Br=16*1024;function Mp(t=Br){let e=se(t-se(t)),r=1+se(Object.keys(Le.Flag).length-1),n=1,o=t-e-r-n,s=se(o);return e+r+n+s}var _f=Mp();var Lf=1e4,da="/webrtc",xn="/webrtc-signaling/0.0.1";function pa(t){let e=t.getComponents(),r={},n=0;if(e[n]?.name==="ip6zone"&&(r.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(r.type=e[n].name,r.host=e[n].value,n++):e[n].name==="dnsaddr"&&(r.type=e[n].name,r.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(r.protocol=e[n].name==="tcp"?"tcp":"udp",r.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(r.type==="ip4"?r.cidr=parseInt(`${e[n].value}`):r.type==="ip6"&&(r.cidr=`${e[n].value}`),n++),r.type==null||r.host==null)throw new Y(`Multiaddr ${t} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(r.sni=e[n+1].value,n+=2),r}function _o(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var Lo=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Dr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Lo(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new Lo(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var ma=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Tr(t={}){return Kp(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function Kp(t,e){e=e??{};let r=e.onEnd,n=new Dr,o,s,i,a=_o(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,b)=>{s=A=>{s=null,n.push(A);try{h(t(n))}catch(x){b(x)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=_o()})}},u=h=>s!=null?s(h):(n.push(h),o),l=h=>(n=new Dr,s!=null?s({error:h}):(n.push({error:h}),o)),f=h=>{if(i)return o;if(e?.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})},y=h=>i?o:(i=!0,h!=null?l(h):u({done:!0})),p=()=>(n=new Dr,y(),{done:!0}),d=h=>(y(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:d,push:f,end:y,get readableLength(){return n.size},onEmpty:async h=>{let b=h?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let A,x;b!=null&&(A=new Promise((D,M)=>{x=()=>{M(new ma)},b.addEventListener("abort",x)}));try{await Promise.race([a.promise,A])}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:f,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 ga=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},ya=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},If=t=>globalThis.DOMException===void 0?new ya(t):new DOMException(t),Bf=t=>{let e=t.reason===void 0?If("This operation was aborted."):t.reason;return e instanceof Error?e:If(e)};function ba(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,a,u=new Promise((l,f)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(e.signal){let{signal:p}=e;p.aborted&&f(Bf(p)),a=()=>{f(Bf(p))},p.addEventListener("abort",a,{once:!0})}if(r===Number.POSITIVE_INFINITY){t.then(l,f);return}let y=new ga;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(p){f(p)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?l():o instanceof Error?f(o):(y.message=o??`Promise timed out after ${r} milliseconds`,f(y))},r),(async()=>{try{l(await t)}catch(p){f(p)}})()}).finally(()=>{u.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return u.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},u}var kp=t=>{let e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function Hp(t,e,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=[e].flat(),c=[],{addListener:u,removeListener:l}=kp(t),f=async(...p)=>{let d=r.multiArgs?p:p[0];if(r.filter)try{if(!await r.filter(d))return}catch(E){n(),i(E);return}c.push(d),r.count===c.length&&(n(),s(c))},y=(...p)=>{n(),i(r.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)l(p,f);for(let p of r.rejectionEvents)a.includes(p)||l(p,y)};for(let p of a)u(p,f);for(let p of r.rejectionEvents)a.includes(p)||u(p,y);r.signal&&r.signal.addEventListener("abort",()=>{y(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){let s=ba(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Se(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Hp(t,e,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var Yt=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},Io=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},Bo=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Fp(t){return t.reason}async function ht(t,e,r){if(e==null)return t;let n=r?.translateError??Fp;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([t,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Vp=Math.pow(2,20)*4,Bt=class extends mt{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??Vp,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new q,this.writeBuffer=new q,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 Bo)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),ht(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Tr(),r=s=>{e.push(s.data)};this.addEventListener("message",r);let n=s=>{e.end(s.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new je(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new Hn(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new je("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 je("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new je(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new je(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new tr;this.dispatchEvent(new Fn(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new rr))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,r=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let s=this.writeBuffer.sublist(0,o),i=new q(s);this.writeBuffer.consume(s.byteLength);let a=this.sendData(s);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,r,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new kn(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Hr(`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 Hr(`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 Do=class extends Bt{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",r=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),r.error!=null?r.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):r.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Se(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Se(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function Df(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var To=class extends mt{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,r){super(),this.maConn=e,this.protocol=r.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.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(e){let r=this.maConn.send(e);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(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await ht(Promise.all([...this.streams].map(async r=>{await r.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(r=>{r.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(r=>{r.onTransportClosed(e)})}catch(r){this.abort(r)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new On;let r=this.onCreateStream({...this.streamOptions,...e});return Df(r)&&(r=await r),this.streams.push(r),this.cleanUpStream(r),r}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new Io(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let r=n=>{let o=this.streams.findIndex(s=>s===e);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",r),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(r=>{this.safeDispatchEvent("stream",{detail:r})}),this.earlyStreams=[]})}};var Ro=class extends Bt{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){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 Se(this,"idle",{...e,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 Se(this,"drain",{...e,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(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};var $p=4194304,Po=class extends Error{static name="UnwrappedError";name="UnwrappedError"},En=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},xa=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ea=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function qp(t){return typeof t?.closeRead=="function"}function Wp(t){return typeof t?.close=="function"}function wa(t){return qp(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:Wp(t)?t.status!=="open":!1}function Gp(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function zp(t,e){let r=e?.maxBufferSize??$p,n=new q,o,s=!1;if(!Gp(t))throw new Y("Argument should be a Stream or a Multiaddr");let i=l=>{if(n.append(l.data),n.byteLength>r){let f=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${f} > ${r}`))}o?.resolve()};t.addEventListener("message",i);let a=l=>{l.error!=null?o?.reject(l.error):o?.resolve()};t.addEventListener("close",a);let c=()=>{o?.resolve()};t.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(l){if(s===!0)throw new Po("Stream was unwrapped");if(wa(t)){if(l?.bytes==null)return null;if(n.byteLength<l.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,l.bytes),new Yt(`Unexpected EOF - stream closed after reading ${n.byteLength}/${l.bytes} bytes`)}let f=l?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=f){o.resolve();break}if(await ht(o.promise,l?.signal),wa(t)){if(n.byteLength===0&&l?.bytes==null)return null;break}o=Promise.withResolvers()}let y=l?.bytes??n.byteLength;if(n.byteLength<y){if(wa(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,y),new Yt(`Unexpected EOF - stream closed while reading ${n.byteLength}/${y} bytes`);return u.read(l)}let p=n.sublist(0,y);return n.consume(y),p},async write(l,f){if(s===!0)throw new Po("Stream was unwrapped");t.send(l)||await Se(t,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",i),t.removeEventListener("close",a),t.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.push(n))),t}};return u}function Oo(t,e={}){let r=zp(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=se(e.maxDataLength));let n=e?.lengthDecoder??ct,o=e?.lengthEncoder??oo;return{async read(i){let a=-1,c=new q;for(;;){let l=await r.read({...i,bytes:1});if(l==null)break;c.append(l);try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new En("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Ea(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new xa(`Message length too long - ${a} > ${e.maxDataLength}`);let u=await r.read({...i,bytes:a});if(u==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new Yt(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(u.byteLength!==a)throw t.log.error("read %d/%d bytes before the stream closed",u.byteLength,a),new Yt(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await r.write(new q(o(i.byteLength),i),a)},async writeV(i,a){let c=new q(...i.flatMap(u=>[o(u.byteLength),u]));await r.write(c,a)},unwrap(){return r.unwrap()}}}function No(t,e){let r=Oo(t,e),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 jp=1024*1024*4,Xp=1024*1024*4,Uo=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new q,this.maxBufferSize=e.maxBufferSize??jp,this.maxDataLength=e.maxDataLength??Xp,this.lengthDecoder=e.lengthDecoder??ct,this.encodingLength=e.encodingLength??se}*decode(e){if(this.buffer.append(e),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 En("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 Mo=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Rr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ko=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Sn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ko(t){return t[Symbol.asyncIterator]!=null}function Tf(t,e){if(t.byteLength>e)throw new Rr("Message length too long")}var Fo=t=>{let e=se(t),r=pe(e);return oo(t,r),Fo.bytes=e,r};Fo.bytes=0;function vn(t,e){e=e??{};let r=e.lengthEncoder??Fo,n=e?.maxDataLength??4194304;function*o(s){Tf(s,n);let i=r(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return ko(t)?(async function*(){for await(let s of t)yield*o(s)})():(function*(){for(let s of t)yield*o(s)})()}vn.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??Fo,n=e?.maxDataLength??4194304;return Tf(t,n),new q(r(t.byteLength),t)};var Zt;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(Zt||(Zt={}));var Sa=t=>{let e=ct(t);return Sa.bytes=se(e),e};Sa.bytes=0;function An(t,e){let r=new q,n=Zt.LENGTH,o=-1,s=e?.lengthDecoder??Sa,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===Zt.LENGTH)try{if(o=s(r),o<0)throw new Mo("Invalid message length");if(o>a)throw new Rr("Message length too long");let u=s.bytes;r.consume(u),e?.onLength!=null&&e.onLength(o),n=Zt.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>i)throw new Ko("Message length length too long");break}throw u}if(n===Zt.DATA){if(r.byteLength<o)break;let u=r.sublist(0,o);r.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Zt.LENGTH}}}return ko(t)?(async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw new Sn("Unexpected end of input")})():(function*(){for(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw new Sn("Unexpected end of input")})()}An.fromReader=(t,e)=>{let r=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await t.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 An(n,{...e??{},onLength:s=>{r=s}})};var Rf=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,s;n<o;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))},Qp=(function(){function t(e,r,n){this.name=e,this.version=r,this.os=n,this.type="browser"}return t})();var Jp=(function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t})();var em=(function(){function t(e,r,n,o){this.name=e,this.version=r,this.os=n,this.bot=o,this.type="bot-device"}return t})();var tm=(function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t})();var rm=(function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t})();var nm=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,om=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Pf=3,sm=[["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",nm]],Of=[["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 Uf(t){return t?Nf(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new rm:typeof navigator<"u"?Nf(navigator.userAgent):cm()}function im(t){return t!==""&&sm.reduce(function(e,r){var n=r[0],o=r[1];if(e)return e;var s=o.exec(t);return!!s&&[n,s]},!1)}function Nf(t){var e=im(t);if(!e)return null;var r=e[0],n=e[1];if(r==="searchbot")return new tm;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<Pf&&(o=Rf(Rf([],o,!0),um(Pf-o.length),!0)):o=[];var s=o.join("."),i=am(t),a=om.exec(t);return a&&a[1]?new em(r,s,i,a[1]):new Qp(r,s,i)}function am(t){for(var e=0,r=Of.length;e<r;e++){var n=Of[e],o=n[0],s=n[1],i=s.exec(t);if(i)return o}return null}function cm(){var t=typeof process<"u"&&process.version;return t?new Jp(process.version.slice(1)):null}function um(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var Mf=Uf(),Vo=Mf!=null&&Mf.name==="firefox";async function va(t){return t=t??{},typeof t=="function"&&(t=await t()),t.iceServers=t.iceServers??vf.map(e=>({urls:[e]})),t}var Kf=(t=32)=>Af+[...Array(t)].map(()=>ha.at(Math.floor(Math.random()*ha.length))).join("");var Aa=class extends Ro{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(e){super({...e,maxMessageSize:(e.maxMessageSize??Br)-_f}),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=Tr(),this.maxBufferedAmount=e.maxBufferedAmount??Cf,this.finAckTimeout=e.finAckTimeout??Lf,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 An(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),Se(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(e){if(this.channel.readyState!=="open")throw new je(`Invalid datachannel state - ${this.channel.readyState}`);if(this.log.trace('sending message, channel state "%s"',this.channel.readyState),Vo){this.channel.send(e.subarray());return}for(let r of e)this.channel.send(r)}sendData(e){return this.channel.readyState!=="open"?{sentBytes:0,canSendMore:!1}:(this._sendMessage(vn.single(Le.encode({message:e.subarray()}))),{sentBytes:e.byteLength,canSendMore:this.channel.bufferedAmount<this.maxBufferedAmount})}sendReset(e){try{this.log.error("sending reset - %e",e),this._sendFlag(Le.Flag.RESET),this.receivedFinAck?.reject(e)}catch(r){this.log.error("failed to send reset - %e",r)}}async sendCloseWrite(e){this._sendFlag(Le.Flag.FIN),e?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let r=e?.signal??AbortSignal.timeout(this.finAckTimeout),n=[Se(this.channel,"close",{signal:r}),Se(this.channel,"error",{signal:r})];await Promise.any([ht(this.receivedFinAck.promise,r),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(e){this._sendFlag(Le.Flag.STOP_SENDING),e?.signal?.throwIfAborted()}processIncomingProtobuf(e){let r=Le.decode(e);r.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new q(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===Le.Flag.FIN&&(this._sendFlag(Le.Flag.FIN_ACK),this.onRemoteCloseWrite()),r.flag===Le.Flag.RESET&&(this.receivedFinAck?.reject(new tr("The stream was reset")),this.onRemoteReset()),r.flag===Le.Flag.STOP_SENDING&&this.onRemoteCloseRead(),r.flag===Le.Flag.FIN_ACK&&this.receivedFinAck?.resolve())}_sendFlag(e){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',e.toString(),this.channel.readyState),!1;this.log.trace("sending flag %s",e.toString());let r=Le.encode({flag:e}),n=vn.single(r);try{return this._sendMessage(n),!0}catch(o){this.log.error("could not send flag %s - %e",e.toString(),o)}return!1}sendPause(){}sendResume(){}};function Cn(t){let{channel:e,direction:r,isHandshake:n}=t;return new Aa({...t,id:`${e.id}`,log:t.log.newScope(`${n===!0?"handshake":r}:${e.id}`),protocol:""})}var Dt=class{protocol;peerConnection;metrics;dataChannelOptions;earlyDataChannels;constructor(e){this.onEarlyDataChannel=this.onEarlyDataChannel.bind(this),this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??da,this.dataChannelOptions=e.dataChannelOptions??{},this.peerConnection.addEventListener("datachannel",this.onEarlyDataChannel),this.earlyDataChannels=[]}onEarlyDataChannel(e){this.earlyDataChannels.push(e.channel)}createStreamMuxer(e){return this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel),new Ca(e,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,earlyDataChannels:this.earlyDataChannels})}},Ca=class extends To{peerConnection;dataChannelOptions;constructor(e,r){super(e,{...r,name:"muxer"}),this.peerConnection=r.peerConnection,this.protocol=r.protocol??da,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(e){if(this.log("incoming datachannel with channel id %d, protocol %s and status %s",e.id,e.protocol,e.readyState),e.label==="init"){this.log.trace("closing init channel %d",e.id),e.close();return}let r=Cn({...this.streamOptions,...this.dataChannelOptions,channel:e,direction:"inbound",log:this.log});this.onRemoteStream(r)}async onCreateStream(e){let r=this.peerConnection.createDataChannel("",{});return this.log("open channel %d for protocol %s",r.id,e?.protocol),Cn({...e,...this.dataChannelOptions,channel:r,direction:"outbound",log:this.log})}onData(){}};var _a=class extends Do{peerConnection;constructor(e){super(e),this.peerConnection=e.peerConnection;let r=e.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(e){return{sentBytes:e.byteLength,canSendMore:!0}}async sendClose(e){this.peerConnection.close(),e?.signal?.throwIfAborted()}sendReset(){this.peerConnection.close()}sendPause(){}sendResume(){}},_n=t=>new _a(t);var $o=globalThis.RTCPeerConnection,qo=globalThis.RTCSessionDescription,kf=globalThis.RTCIceCandidate;var Ue=class extends Event{type;detail;constructor(e,r){super(e),this.type=e,this.detail=r}};var Tt=class extends Error{constructor(e){super(`WebRTC transport error: ${e}`),this.name="WebRTCTransportError"}},ke=class extends Tt{constructor(e="SDP handshake failed"){super(e),this.name="SDPHandshakeFailedError"}};var Wo=class extends Tt{constructor(e,r){super(`Invalid fingerprint "${e}" within ${r}`),this.name="WebRTC/InvalidFingerprintError"}};var Go=class extends Tt{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},zo=class extends Tt{constructor(e){super(`unsupported hash algorithm code: ${e} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var Oe;(function(t){let e;(function(o){o.SDP_OFFER="SDP_OFFER",o.SDP_ANSWER="SDP_ANSWER",o.ICE_CANDIDATE="ICE_CANDIDATE"})(e=t.Type||(t.Type={}));let r;(function(o){o[o.SDP_OFFER=0]="SDP_OFFER",o[o.SDP_ANSWER=1]="SDP_ANSWER",o[o.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(r||(r={})),(function(o){o.codec=()=>Wt(r)})(e=t.Type||(t.Type={}));let n;t.codec=()=>(n==null&&(n=ze((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),t.Type.codec().encode(o.type,s)),o.data!=null&&(s.uint32(18),s.string(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{a.type=t.Type.codec().decode(o);break}case 2:{a.data=o.string();break}default:{o.skipType(u&7);break}}}return a})),n),t.encode=o=>Ge(o,t.codec()),t.decode=(o,s)=>We(o,t.codec(),s)})(Oe||(Oe={}));var jo=async(t,e,r)=>{try{let n=Promise.withResolvers();for(fm(t,n);;){let o=await Promise.race([n.promise,e.read({signal:r.signal})]);if(o==null){r.signal?.throwIfAborted();break}if(o.type!==Oe.Type.ICE_CANDIDATE)throw new Kn("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){r.onProgress?.(new Ue("webrtc:end-of-ice-candidates")),r.log.trace("end-of-candidates received");continue}let i=new kf(s);r.log.trace("%s received new ICE candidate %o",r.direction,s);try{r.onProgress?.(new Ue("webrtc:add-ice-candidate",i.candidate)),await t.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&&t.connectionState!=="connected")throw n}};function fm(t,e){if(t.connectionState==="connected"){e.resolve();return}t.onconnectionstatechange=r=>{switch(t.connectionState){case"connected":e.resolve();break;case"failed":case"disconnected":case"closed":e.reject(new Pn(`RTCPeerConnection connection state became "${t.connectionState}"`));break;default:break}}}function Xo(t){let e;for(let r of t.getComponents())r.name==="p2p"&&(e=vr(r.value??""));if(e==null)throw new Nn("Remote peerId must be present in multiaddr");return e}async function Hf({rtcConfiguration:t,dataChannel:e,signal:r,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:u}){let{circuitAddress:l,targetPeer:f}=Ff(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing circuit address: %a",l);let y=s.getConnections(f),p;y.length===0?(u?.(new Ue("webrtc:dial-relay")),p=await i.dial(l,{signal:r,onProgress:u})):(u?.(new Ue("webrtc:reuse-relay-connection")),p=y[0]),u?.(new Ue("webrtc:open-signaling-stream"));let d=await p.newStream(xn,{signal:r,runOnLimitedConnection:!0}),E=No(d).pb(Oe),h=new $o(t);h.addEventListener("connectionstatechange",()=>{switch(h.connectionState){case"closed":h.close();break;default:break}});let b=new Dt({peerConnection:h,dataChannelOptions:e});try{let A=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:Oe.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 ke("Failed to set createOffer")});a.trace("initiator send SDP offer %s",x.sdp),u?.(new Ue("webrtc:send-sdp-offer")),await E.write({type:Oe.Type.SDP_OFFER,data:x.sdp},{signal:r}),await h.setLocalDescription(x).catch(O=>{throw a.error("could not execute setLocalDescription - %e",O),new ke("Failed to set localDescription")}),u?.(new Ue("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let D=await E.read({signal:r});if(D.type!==Oe.Type.SDP_ANSWER)throw new ke("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",D.data);let M=new qo({type:"answer",sdp:D.data});return await h.setRemoteDescription(M).catch(O=>{throw a.error("could not execute setRemoteDescription - %e",O),new ke("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),u?.(new Ue("webrtc:read-ice-candidates")),await jo(h,E,{direction:"initiator",signal:r,log:a,onProgress:u}),a.trace("initiator connected"),A.readyState!=="open"&&(a.trace("wait for init channel to open"),await Se(A,"open",{signal:r})),a.trace("closing init channel"),A.close(),a.trace("waiting for init channel to close"),await Se(A,"close",{signal:r}),u?.(new Ue("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await d.close({signal:r}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:h,muxerFactory:b}}catch(A){throw a.error("outgoing signaling error - %e",A),h.close(),d.abort(A),A}finally{h.onicecandidate=null,h.onicecandidateerror=null}}var Vf=ne(Ef.matchers[0],re(290)),Yo=class t extends mt{transportManager;shutdownController;events;constructor(e,r){super(),this.transportManager=e.transportManager,this.events=e.events,this.shutdownController=r.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(e){e.detail.getAddrs().filter(n=>Vf.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(e=>!(e instanceof t)).map(e=>e.getAddrs().filter(r=>Vf.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 $f(t,e,{peerConnection:r,signal:n,log:o}){o.trace("new inbound signaling stream");let s=No(t).pb(Oe);try{r.onicecandidate=({candidate:f})=>{if(r.connectionState==="connected"){o.trace("ignore new ice candidate as peer connection is already connected");return}if(f==null||f?.candidate===""){o.trace("recipient detected end of ICE candidates");return}let y=JSON.stringify(f?.toJSON()??null);o.trace("recipient sending ICE candidate %s",y),s.write({type:Oe.Type.ICE_CANDIDATE,data:y},{signal:n}).catch(p=>{o.error("error sending ICE candidate - %e",p)})},o.trace("recipient read SDP offer");let c=await s.read({signal:n});if(c.type!==Oe.Type.SDP_OFFER)throw new ke(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let u=new qo({type:"offer",sdp:c.data});await r.setRemoteDescription(u).catch(f=>{throw o.error("could not execute setRemoteDescription - %e",f),new ke("Failed to set remoteDescription")});let l=await r.createAnswer().catch(f=>{throw o.error("could not execute createAnswer - %e",f),new ke("Failed to create answer")});o.trace("recipient send SDP answer %s",l.sdp),await s.write({type:Oe.Type.SDP_ANSWER,data:l.sdp},{signal:n}),await r.setLocalDescription(l).catch(f=>{throw o.error("could not execute setLocalDescription - %e",f),new ke("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await jo(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",e.remoteAddr,c),r.close(),c;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",e.remoteAddr,c)}let i=Xo(e.remoteAddr),a=Ir(`/webrtc/p2p/${i}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:i}}var Zo=class{components;init;log;_started=!1;metrics;shutdownController;constructor(e,r={}){this.components=e,this.init=r,this.log=e.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[Vn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[nr]=["@libp2p/transport"];[tc]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(xn,(e,r)=>{let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(e,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(xn),this._started=!1}createListener(e){return new Yo(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(Sf.exactMatch)}dialFilter(e){return this.listenFilter(e)}async dial(e,r){this.log.trace("dialing address: %a",e);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await Hf({rtcConfiguration:await va(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:e,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=_n({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:Xo(e),muxerFactory:s,onProgress:r.onProgress,signal:r.signal});return this._closeOnShutdown(o,i),a}async _onProtocol(e,r,n){let o=new $o(await va(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{switch(o.connectionState){case"closed":o.close();break;default:break}});let s=new Dt({peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i,remotePeer:a}=await $f(e,r,{peerConnection:o,signal:n,log:this.log});await e.close({signal:n});let c=_n({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(),e.abort(i),i}}_closeOnShutdown(e,r){let n=()=>{r.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection - %e",o)})};this.shutdownController.signal.addEventListener("abort",n),e.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function Ff(t){let e=t.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(e==null)throw new Y("Destination peer id was missing");return{circuitAddress:Ir(t.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:vr(e)}}var Pr=!!globalThis.process?.env?.DUMP_SESSION_KEYS,La=16;function lm(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Qo(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function Jo(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function be(t,e,r=""){let n=lm(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){let i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function Ia(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function qf(t,e){be(t,void 0,"output");let r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function dt(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function pt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function hm(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var dm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Wf(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Gf(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}var Ba=(t,e)=>{function r(n,...o){if(be(n,void 0,"key"),!dm)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){let l=o[0];be(l,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let s=t.tagLength;s&&o[1]!==void 0&&be(o[1],void 0,"AAD");let i=e(n,...o),a=(l,f)=>{if(f!==void 0){if(l!==2)throw new Error("cipher output not supported");be(f,void 0,"output")}},c=!1;return{encrypt(l,f){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,be(l),a(i.encrypt.length,f),i.encrypt(l,f)},decrypt(l,f){if(be(l),s&&l.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,f),i.decrypt(l,f)}}}return Object.assign(r,t),r};function Da(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(r&&!pm(e))throw new Error("invalid output, must be aligned");return e}function zf(t,e,r){Qo(r);let n=new Uint8Array(16),o=hm(n);return o.setBigUint64(0,BigInt(e),r),o.setBigUint64(8,BigInt(t),r),n}function pm(t){return t.byteOffset%4===0}function Or(t){return Uint8Array.from(t)}var Xf=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),mm=Xf("expand 16-byte k"),gm=Xf("expand 32-byte k"),ym=dt(mm),bm=dt(gm);function U(t,e){return t<<e|t>>>32-e}function Ta(t){return t.byteOffset%4===0}var es=64,wm=16,Yf=2**32-1,jf=Uint32Array.of();function xm(t,e,r,n,o,s,i,a){let c=o.length,u=new Uint8Array(es),l=dt(u),f=Ta(o)&&Ta(s),y=f?dt(o):jf,p=f?dt(s):jf;for(let d=0;d<c;i++){if(t(e,r,n,l,i,a),i>=Yf)throw new Error("arx: counter overflow");let E=Math.min(es,c-d);if(f&&E===es){let h=d/4;if(d%4!==0)throw new Error("arx: invalid block position");for(let b=0,A;b<wm;b++)A=h+b,p[A]=y[A]^l[b];d+=es;continue}for(let h=0,b;h<E;h++)b=d+h,s[b]=o[b]^u[h];d+=E}}function Ra(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Wf({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Jo(o),Jo(i),Qo(s),Qo(r),(a,c,u,l,f=0)=>{be(a,void 0,"key"),be(c,void 0,"nonce"),be(u,void 0,"data");let y=u.length;if(l===void 0&&(l=new Uint8Array(y)),be(l,void 0,"output"),Jo(f),f<0||f>=Yf)throw new Error("arx: counter overflow");if(l.length<y)throw new Error(`arx: output (${l.length}) is shorter than data (${y})`);let p=[],d=a.length,E,h;if(d===32)p.push(E=Or(a)),h=bm;else if(d===16&&r)E=new Uint8Array(32),E.set(a),E.set(a,16),h=ym,p.push(E);else throw be(a,32,"arx key"),new Error("invalid key size");Ta(c)||p.push(c=Or(c));let b=dt(E);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,b,dt(c.subarray(0,16)),b),c=c.subarray(16)}let A=16-o;if(A!==c.length)throw new Error(`arx: nonce must be ${A} or 16 bytes`);if(A!==12){let D=new Uint8Array(12);D.set(c,s?0:12-c.length),c=D,p.push(c)}let x=dt(c);return xm(t,h,b,x,u,l,f,i),pt(...p),l}}function ve(t,e){return t[e++]&255|(t[e++]&255)<<8}var Pa=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(e){e=Or(be(e,32,"key"));let r=ve(e,0),n=ve(e,2),o=ve(e,4),s=ve(e,6),i=ve(e,8),a=ve(e,10),c=ve(e,12),u=ve(e,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 l=0;l<8;l++)this.pad[l]=ve(e,16+2*l)}process(e,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],u=i[2],l=i[3],f=i[4],y=i[5],p=i[6],d=i[7],E=i[8],h=i[9],b=ve(e,r+0),A=ve(e,r+2),x=ve(e,r+4),D=ve(e,r+6),M=ve(e,r+8),O=ve(e,r+10),k=ve(e,r+12),_=ve(e,r+14),v=s[0]+(b&8191),N=s[1]+((b>>>13|A<<3)&8191),K=s[2]+((A>>>10|x<<6)&8191),T=s[3]+((x>>>7|D<<9)&8191),w=s[4]+((D>>>4|M<<12)&8191),m=s[5]+(M>>>1&8191),g=s[6]+((M>>>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+v*a+N*(5*h)+K*(5*E)+T*(5*d)+w*(5*p);S=B>>>13,B&=8191,B+=m*(5*y)+g*(5*f)+C*(5*l)+I*(5*u)+L*(5*c),S+=B>>>13,B&=8191;let R=S+v*c+N*a+K*(5*h)+T*(5*E)+w*(5*d);S=R>>>13,R&=8191,R+=m*(5*p)+g*(5*y)+C*(5*f)+I*(5*l)+L*(5*u),S+=R>>>13,R&=8191;let P=S+v*u+N*c+K*a+T*(5*h)+w*(5*E);S=P>>>13,P&=8191,P+=m*(5*d)+g*(5*p)+C*(5*y)+I*(5*f)+L*(5*l),S+=P>>>13,P&=8191;let z=S+v*l+N*u+K*c+T*a+w*(5*h);S=z>>>13,z&=8191,z+=m*(5*E)+g*(5*d)+C*(5*p)+I*(5*y)+L*(5*f),S+=z>>>13,z&=8191;let W=S+v*f+N*l+K*u+T*c+w*a;S=W>>>13,W&=8191,W+=m*(5*h)+g*(5*E)+C*(5*d)+I*(5*p)+L*(5*y),S+=W>>>13,W&=8191;let V=S+v*y+N*f+K*l+T*u+w*c;S=V>>>13,V&=8191,V+=m*a+g*(5*h)+C*(5*E)+I*(5*d)+L*(5*p),S+=V>>>13,V&=8191;let X=S+v*p+N*y+K*f+T*l+w*u;S=X>>>13,X&=8191,X+=m*c+g*a+C*(5*h)+I*(5*E)+L*(5*d),S+=X>>>13,X&=8191;let te=S+v*d+N*p+K*y+T*f+w*l;S=te>>>13,te&=8191,te+=m*u+g*c+C*a+I*(5*h)+L*(5*E),S+=te>>>13,te&=8191;let ue=S+v*E+N*d+K*p+T*y+w*f;S=ue>>>13,ue&=8191,ue+=m*l+g*u+C*c+I*a+L*(5*h),S+=ue>>>13,ue&=8191;let Z=S+v*h+N*E+K*d+T*p+w*y;S=Z>>>13,Z&=8191,Z+=m*f+g*l+C*u+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]=z,s[4]=W,s[5]=V,s[6]=X,s[7]=te,s[8]=ue,s[9]=Z}finalize(){let{h:e,pad:r}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[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++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+r[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+r[a]|0)+(i>>>16)|0,e[a]=i&65535;pt(n)}update(e){Ia(this),be(e),e=Or(e);let{buffer:r,blockLen:n}=this,o=e.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(e,s);continue}r.set(e.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(){pt(this.h,this.r,this.buffer,this.pad)}digestInto(e){Ia(this),qf(e,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++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8;return e}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}};function Em(t){let e=(n,o)=>t(o).update(n).digest(),r=t(new Uint8Array(32));return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}var Zf=Em(t=>new Pa(t));function el(t,e,r,n,o,s=20){let i=t[0],a=t[1],c=t[2],u=t[3],l=e[0],f=e[1],y=e[2],p=e[3],d=e[4],E=e[5],h=e[6],b=e[7],A=o,x=r[0],D=r[1],M=r[2],O=i,k=a,_=c,v=u,N=l,K=f,T=y,w=p,m=d,g=E,C=h,I=b,L=A,S=x,B=D,R=M;for(let z=0;z<s;z+=2)O=O+N|0,L=U(L^O,16),m=m+L|0,N=U(N^m,12),O=O+N|0,L=U(L^O,8),m=m+L|0,N=U(N^m,7),k=k+K|0,S=U(S^k,16),g=g+S|0,K=U(K^g,12),k=k+K|0,S=U(S^k,8),g=g+S|0,K=U(K^g,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),v=v+w|0,R=U(R^v,16),I=I+R|0,w=U(w^I,12),v=v+w|0,R=U(R^v,8),I=I+R|0,w=U(w^I,7),O=O+K|0,R=U(R^O,16),C=C+R|0,K=U(K^C,12),O=O+K|0,R=U(R^O,8),C=C+R|0,K=U(K^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),_=_+w|0,S=U(S^_,16),m=m+S|0,w=U(w^m,12),_=_+w|0,S=U(S^_,8),m=m+S|0,w=U(w^m,7),v=v+N|0,B=U(B^v,16),g=g+B|0,N=U(N^g,12),v=v+N|0,B=U(B^v,8),g=g+B|0,N=U(N^g,7);let P=0;n[P++]=i+O|0,n[P++]=a+k|0,n[P++]=c+_|0,n[P++]=u+v|0,n[P++]=l+N|0,n[P++]=f+K|0,n[P++]=y+T|0,n[P++]=p+w|0,n[P++]=d+m|0,n[P++]=E+g|0,n[P++]=h+C|0,n[P++]=b+I|0,n[P++]=A+L|0,n[P++]=x+S|0,n[P++]=D+B|0,n[P++]=M+R|0}function Sm(t,e,r,n){let o=t[0],s=t[1],i=t[2],a=t[3],c=e[0],u=e[1],l=e[2],f=e[3],y=e[4],p=e[5],d=e[6],E=e[7],h=r[0],b=r[1],A=r[2],x=r[3];for(let M=0;M<20;M+=2)o=o+c|0,h=U(h^o,16),y=y+h|0,c=U(c^y,12),o=o+c|0,h=U(h^o,8),y=y+h|0,c=U(c^y,7),s=s+u|0,b=U(b^s,16),p=p+b|0,u=U(u^p,12),s=s+u|0,b=U(b^s,8),p=p+b|0,u=U(u^p,7),i=i+l|0,A=U(A^i,16),d=d+A|0,l=U(l^d,12),i=i+l|0,A=U(A^i,8),d=d+A|0,l=U(l^d,7),a=a+f|0,x=U(x^a,16),E=E+x|0,f=U(f^E,12),a=a+f|0,x=U(x^a,8),E=E+x|0,f=U(f^E,7),o=o+u|0,x=U(x^o,16),d=d+x|0,u=U(u^d,12),o=o+u|0,x=U(x^o,8),d=d+x|0,u=U(u^d,7),s=s+l|0,h=U(h^s,16),E=E+h|0,l=U(l^E,12),s=s+l|0,h=U(h^s,8),E=E+h|0,l=U(l^E,7),i=i+f|0,b=U(b^i,16),y=y+b|0,f=U(f^y,12),i=i+f|0,b=U(b^i,8),y=y+b|0,f=U(f^y,7),a=a+c|0,A=U(A^a,16),p=p+A|0,c=U(c^p,12),a=a+c|0,A=U(A^a,8),p=p+A|0,c=U(c^p,7);let D=0;n[D++]=o,n[D++]=s,n[D++]=i,n[D++]=a,n[D++]=h,n[D++]=b,n[D++]=A,n[D++]=x}var vm=Ra(el,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Am=Ra(el,{counterRight:!1,counterLength:8,extendNonceFn:Sm,allowShortKeys:!1});var Cm=new Uint8Array(16),Qf=(t,e)=>{t.update(e);let r=e.length%16;r&&t.update(Cm.subarray(r))},_m=new Uint8Array(32);function Jf(t,e,r,n,o){o!==void 0&&be(o,void 0,"AAD");let s=t(e,r,_m),i=zf(n.length,o?o.length:0,!0),a=Zf.create(s);o&&Qf(a,o),Qf(a,n),a.update(i);let c=a.digest();return pt(s,i),c}var tl=t=>(e,r,n)=>({encrypt(s,i){let a=s.length;i=Da(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);t(e,r,c,c,1);let u=Jf(t,e,r,c,n);return i.set(u,a),pt(u),i},decrypt(s,i){i=Da(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),u=Jf(t,e,r,a,n);if(!Gf(c,u))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,r,i,i,1),pt(u),i}}),Oa=Ba({blockSize:64,nonceLength:12,tagLength:16},tl(vm)),hS=Ba({blockSize:64,nonceLength:24,tagLength:16},tl(Am));function nl(t,e,r){return Ut(t),r===void 0&&(r=new Uint8Array(t.outputLen)),xr(t,r,e)}var Na=Uint8Array.of(0),rl=Uint8Array.of();function ol(t,e,r,n=32){Ut(t),Me(n,"length");let o=t.outputLen;if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);r===void 0?r=rl:F(r,void 0,"info");let i=new Uint8Array(s*o),a=xr.create(t,e),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let l=0;l<s;l++)Na[0]=l+1,c.update(l===0?rl:u).update(r).update(Na).digestInto(u),i.set(u,o*l),a._cloneInto(c);return a.destroy(),c.destroy(),Ve(u,Na),i.slice(0,n)}var Ua={hashSHA256(t){return Ye(t.subarray())},getHKDF(t,e){let r=nl(Ye,e,t),o=ol(Ye,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 t=nn.utils.randomSecretKey();return{publicKey:nn.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:nn.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return nn.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,r,n){return Oa(n,e,r).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,r,n,o){return Oa(n,e,r).decrypt(t.subarray(),o)}};var sl=Ua;function il(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,r)=>t.generateX25519SharedKey(e.privateKey,r).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}var Nr=t=>{let e=pe(2);return e[0]=t>>8,e[1]=t,e};Nr.bytes=2;var Ur=t=>{if(t.length<2)throw RangeError("Could not decode int16BE");if(t instanceof Uint8Array){let e=0;return e+=t[0]<<8,e+=t[1],e}return t.getUint16(0)};Ur.bytes=2;function al(t){return{xxHandshakeSuccesses:t.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:t.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:t.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:t.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:t.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Ma(t,e){!e.enabled||!Pr||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${$(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${$(t.privateKey,"hex")}`)):e("Missing local static keys."))}function Ka(t,e){!e.enabled||!Pr||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${$(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${$(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function cl(t,e){!e.enabled||!Pr||e(t?`REMOTE_STATIC_PUBLIC_KEY ${$(t.subarray(),"hex")}`:"Missing remote static public key.")}function ka(t,e){!e.enabled||!Pr||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${$(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Ha(t,e,r){!r.enabled||!Pr||(r(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&$(t.k,"hex")}`),r(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&$(e.k,"hex")}`))}var Mr=class t extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=t.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var Lm=0,Im=4294967295,Bm="Cipherstate has reached maximum n, a new handshake must be performed",ts=class{n;bytes;view;constructor(e=Lm){this.n=e,this.bytes=de(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>Im)throw new Error(Bm)}};var Qt=de(0),Kr=class{k;n;crypto;constructor(e,r=void 0,n=0){this.crypto=e,this.k=r,this.n=new ts(n)}hasKey(){return!!this.k}encryptWithAd(e,r){if(!this.hasKey())return r;this.n.assertValue();let n=this.crypto.encrypt(r,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,r,n){if(!this.hasKey())return r;this.n.assertValue();let o=this.crypto.decrypt(r,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},Fa=class{cs;ck;h;crypto;constructor(e,r){this.crypto=e;let n=j(r,"utf-8");this.h=Dm(e,n),this.ck=this.h,this.cs=new Kr(e)}mixKey(e){let[r,n]=this.crypto.hkdf(this.ck,e);this.ck=r,this.cs=new Kr(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new q(this.h,e))}encryptAndHash(e){let r=this.cs.encryptWithAd(this.h,e);return this.mixHash(r),r}decryptAndHash(e){let r=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),r}split(){let[e,r]=this.crypto.hkdf(this.ck,Qt);return[new Kr(this.crypto,e),new Kr(this.crypto,r)]}},Va=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:r,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:u}=e;this.crypto=r,this.ss=new Fa(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 e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.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(e,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<r+32)throw new Error("message is not long enough");this.re=e.sublist(r,r+32),this.ss.mixHash(this.re)}readS(e,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(e.byteLength<r+n)throw new Error("message is not long enough");let o=e.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Ln=class extends Va{writeMessageA(e){return new q(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let r=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new q(r,n,this.ss.encryptAndHash(e))}writeMessageC(e){let r=this.writeS();return this.writeSE(),new q(r,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(r){throw new Mr(`handshake stage 0 validation fail: ${r.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let r=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+r))}catch(r){throw new Mr(`handshake stage 1 validation fail: ${r.message}`)}}readMessageC(e){try{let r=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(r))}catch(r){throw new Mr(`handshake stage 2 validation fail: ${r.message}`)}}};function Dm(t,e){if(e.length<=32){let r=de(32);return r.set(e),r}else return t.hash(e)}var rs;(function(t){let e;t.codec=()=>(e==null&&(e=ze((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 un('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 un('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(r.string());break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ge(r,t.codec()),t.decode=(r,n)=>We(r,t.codec(),n)})(rs||(rs={}));var In;(function(t){let e;t.codec=()=>(e==null&&(e=ze((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),rs.codec().encode(r.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={identityKey:de(0),identitySig:de(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=rs.codec().decode(r,r.uint32(),{limits:o.limits?.extensions});break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ge(r,t.codec()),t.decode=(r,n)=>We(r,t.codec(),n)})(In||(In={}));async function qa(t,e,r){let n=await t.sign(fl(e));return In.encode({identityKey:wt(t.publicKey),identitySig:n,extensions:r})}async function Wa(t,e,r){try{let n=In.decode(t),o=hn(n.identityKey);if(r?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${r}`);if(!e)throw new Error("Remote static does not exist");let s=fl(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Tn(n.message)}}function fl(t){let e=j("noise-libp2p-static-key:");return t instanceof Uint8Array?De([e,t],e.length+t.length):(t.prepend(e),t)}var $a=class extends Bt{stream;handshake;metrics;decoder;constructor(e,r,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=r,this.metrics=n,this.decoder=new Uo({lengthDecoder:Ur,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(e){let r=new q;for(let n=0;n<e.byteLength;n+=65519){let o=n+65519;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),r.append(Nr(s.byteLength)),r.append(s)}return r}decrypt(e){let r=new q;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-La<n)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(n,o):s=e.sublist(n,o);let i=e.subarray(n,o-La);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(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function Ga(t,e,r){return new $a(t,e,r)}async function ll(t,e){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:u}=t,l=await qa(s,a.publicKey,u),f=new Ln({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Ma(f.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(f.writeMessageA(Qt),e),r.trace("Stage 0 - Initiator finished sending first message."),Ka(f.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");let y=f.readMessageB(await n.read(e));r.trace("Stage 1 - Initiator received the message."),ka(f.re,r),cl(f.rs,r),r.trace("Initiator going to check remote's signature...");let p=await Wa(y,f.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(f.writeMessageC(l),e),r.trace("Stage 2 - Initiator sent message with signed payload.");let[d,E]=f.ss.split();return Ha(d,E,r),{payload:p,encrypt:h=>d.encryptWithAd(Qt,h),decrypt:(h,b)=>E.decryptWithAd(Qt,h,b)}}async function hl(t,e){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:u}=t,l=await qa(s,a.publicKey,u),f=new Ln({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Ma(f.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),f.readMessageA(await n.read(e)),r.trace("Stage 0 - Responder received first message."),ka(f.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(f.writeMessageB(l),e),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Ka(f.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");let y=f.readMessageC(await n.read(e));r.trace("Stage 2 - Responder received the message, finished handshake.");let p=await Wa(y,f.rs,c),[d,E]=f.ss.split();return Ha(d,E,r),{payload:p,encrypt:h=>E.encryptWithAd(Qt,h),decrypt:(h,b)=>d.decryptWithAd(Qt,h,b)}}var ns=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,r={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=r,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=s??sl;this.crypto=il(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?al(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??de(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[nr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,r){let n=e.log?.newScope("noise")??this.log,o=Oo(e,{lengthEncoder:Nr,lengthDecoder:Ur,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=hn(s.payload.identityKey);return{connection:Ga(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Mi(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let r=this.components.upgrader.getStreamMuxers();if(r!=null)for(let n of e){let o=r.get(n);if(o!=null)return o}if(e.length)throw new Rn("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,r){let n=e.log?.newScope("noise")??this.log,o=Oo(e,{lengthEncoder:Nr,lengthDecoder:Ur,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=hn(s.payload.identityKey);return{connection:Ga(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Mi(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await ll({connection:e,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(e,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await hl({connection:e,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 dl(t={}){return e=>new ns(e,t)}var za=Object.values(Ot).map(t=>t.decoder).reduce((t,e)=>t.or(e)),Tm=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function pl(t){return t?.match(Tm)?.groups?.fingerprint}function ja(t){let r=t.getComponents().find(n=>n.code===466)?.value;if(r===void 0||r==="")throw new Y(`Couldn't find a certhash component of multiaddr: ${t.toString()}`);return r}function Rm(t){return He.decode(za.decode(t))}function Pm(t){let e=Rm(ja(t)),r=Om(e.code),n=e.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new Wo(n,t.toString());return`${r} ${o.join(":").toUpperCase()}`}function ml(t){let e=t.split(":").map(o=>parseInt(o,16)),r=Uint8Array.from(e),n=Be(tt.code,r);return Ir(`/certhash/${Wr.encode(n.bytes)}`)}function Om(t){switch(t){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new zo(t)}}function gl(t,e){let{host:r,port:n,type:o}=pa(t);if(o!=="ip4"&&o!=="ip6")throw new Y(`Multiaddr ${t} was not an IPv4 or IPv6 address`);let s=Pm(t);return{type:"answer",sdp:`v=0
|
|
2
|
+
"use strict";var Libp2PWebrtc=(()=>{var ss=Object.defineProperty;var xl=Object.getOwnPropertyDescriptor;var El=Object.getOwnPropertyNames;var Sl=Object.prototype.hasOwnProperty;var Ie=(t,e)=>{for(var r in e)ss(t,r,{get:e[r],enumerable:!0})},vl=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of El(e))!Sl.call(t,o)&&o!==r&&ss(t,o,{get:()=>e[o],enumerable:!(n=xl(e,o))||n.enumerable});return t};var Al=t=>vl(ss({},"__esModule",{value:!0}),t);var Mm={};Ie(Mm,{webRTC:()=>Um,webRTCDirect:()=>Nm});var Tn=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},Rn=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},Y=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},er=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Pn=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},On=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},tr=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var je=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Hr=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var Nn=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Un=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Mn=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Kn=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Rt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var kn=class extends Event{data;constructor(e,r){super("message",r),this.data=e}},rr=class extends Event{error;local;constructor(e,r,n){super("close",n),this.error=r,this.local=e}},Hn=class extends rr{constructor(e,r){super(!0,e,r)}},Fn=class extends rr{constructor(e,r){super(!1,e,r)}};var is=Symbol.for("@libp2p/peer-id");var Vn=Symbol.for("@libp2p/transport");var Ja;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Ja||(Ja={}));var mt=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){super.addEventListener(e,r,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:r,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,r,n){super.removeEventListener(e.toString(),r??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==r),this.#e.set(e,o))}dispatchEvent(e){let r=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),r}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}};var nr=Symbol.for("@libp2p/service-capabilities"),ec=Symbol.for("@libp2p/service-dependencies");var ls={};Ie(ls,{base58btc:()=>ce,base58flickr:()=>Tl});var m0=new Uint8Array(0);function tc(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function et(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function rc(t){return new TextEncoder().encode(t)}function nc(t){return new TextDecoder().decode(t)}function Cl(t,e){if(t.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<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var E=0,h=0,b=0,A=d.length;b!==A&&d[b]===0;)b++,E++;for(var x=(A-b)*l+1>>>0,D=new Uint8Array(x);b!==A;){for(var M=d[b],O=0,k=x-1;(M!==0||O<h)&&k!==-1;k--,O++)M+=256*D[k]>>>0,D[k]=M%a>>>0,M=M/a>>>0;if(M!==0)throw new Error("Non-zero carry");h=O,b++}for(var _=x-h;_!==x&&D[_]===0;)_++;for(var v=c.repeat(E);_<x;++_)v+=t.charAt(D[_]);return v}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var E=0;if(d[E]!==" "){for(var h=0,b=0;d[E]===c;)h++,E++;for(var A=(d.length-E)*u+1>>>0,x=new Uint8Array(A);d[E];){var D=r[d.charCodeAt(E)];if(D===255)return;for(var M=0,O=A-1;(D!==0||M<b)&&O!==-1;O--,M++)D+=a*x[O]>>>0,x[O]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");b=M,E++}if(d[E]!==" "){for(var k=A-b;k!==A&&x[k]===0;)k++;for(var _=new Uint8Array(h+(A-k)),v=h;k!==A;)_[v++]=x[k++];return _}}}function m(d){var E=p(d);if(E)return E;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:p,decode:m}}var _l=Cl,Ll=_l,sc=Ll;var as=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},cs=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,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(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ic(this,e)}},us=class{decoders;constructor(e){this.decoders=e}or(e){return ic(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ic(t,e){return new us({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var fs=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new as(e,r,n),this.decoder=new cs(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function or({name:t,prefix:e,encode:r,decode:n}){return new fs(t,e,r,n)}function gt({name:t,prefix:e,alphabet:r}){let{encode:n,decode:o}=sc(r,t);return or({prefix:e,name:t,encode:n,decode:s=>et(o(s))})}function Il(t,e,r,n){let o=t.length;for(;t[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 l=e[t[u]];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 Bl(t,e,r){let n=e[e.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function Dl(t){let e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function ae({name:t,prefix:e,bitsPerChar:r,alphabet:n}){let o=Dl(n);return or({prefix:e,name:t,encode(s){return Bl(s,n,r)},decode(s){return Il(s,o,r,t)}})}var ce=gt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Tl=gt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var hs={};Ie(hs,{base32:()=>yt,base32hex:()=>Nl,base32hexpad:()=>Ml,base32hexpadupper:()=>Kl,base32hexupper:()=>Ul,base32pad:()=>Pl,base32padupper:()=>Ol,base32upper:()=>Rl,base32z:()=>kl});var yt=ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Rl=ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Pl=ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ol=ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Nl=ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ul=ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ml=ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Kl=ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),kl=ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ds={};Ie(ds,{base36:()=>Fr,base36upper:()=>Hl});var Fr=gt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Hl=gt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var He={};Ie(He,{Digest:()=>Pt,create:()=>Be,decode:()=>ar,equals:()=>ms,hasCode:()=>sh});var Fl=uc,ac=128,Vl=127,$l=~Vl,ql=Math.pow(2,31);function uc(t,e,r){e=e||[],r=r||0;for(var n=r;t>=ql;)e[r++]=t&255|ac,t/=128;for(;t&$l;)e[r++]=t&255|ac,t>>>=7;return e[r]=t|0,uc.bytes=r-n+1,e}var Wl=ps,Gl=128,cc=127;function ps(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw ps.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&cc)<<o:(i&cc)*Math.pow(2,o),o+=7}while(i>=Gl);return ps.bytes=s-n,r}var zl=Math.pow(2,7),jl=Math.pow(2,14),Xl=Math.pow(2,21),Yl=Math.pow(2,28),Zl=Math.pow(2,35),Ql=Math.pow(2,42),Jl=Math.pow(2,49),eh=Math.pow(2,56),th=Math.pow(2,63),rh=function(t){return t<zl?1:t<jl?2:t<Xl?3:t<Yl?4:t<Zl?5:t<Ql?6:t<Jl?7:t<eh?8:t<th?9:10},nh={encode:Fl,decode:Wl,encodingLength:rh},oh=nh,Vr=oh;function $r(t,e=0){return[Vr.decode(t,e),Vr.decode.bytes]}function sr(t,e,r=0){return Vr.encode(t,e,r),e}function ir(t){return Vr.encodingLength(t)}function Be(t,e){let r=e.byteLength,n=ir(t),o=n+ir(r),s=new Uint8Array(o+r);return sr(t,s,0),sr(r,s,n),s.set(e,o),new Pt(t,r,e,s)}function ar(t){let e=et(t),[r,n]=$r(e),[o,s]=$r(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Pt(r,o,i,e)}function ms(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&tc(t.bytes,r.bytes)}}var Pt=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}};function sh(t,e){return t.code===e}function fc(t,e){let{bytes:r,version:n}=t;switch(n){case 0:return ah(r,gs(t),e??ce.encoder);default:return ch(r,gs(t),e??yt.encoder)}}var lc=new WeakMap;function gs(t){let e=lc.get(t);if(e==null){let r=new Map;return lc.set(t,r),r}return e}var he=class t{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,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:e,multihash:r}=this;if(e!==qr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==uh)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.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:e,digest:r}=this.multihash,n=Be(e,r);return t.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(e){return t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&ms(e.multihash,n.multihash)}toString(e){return fc(this,e)}toJSON(){return{"/":fc(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new t(n,o,s,i??hc(n,o,s.bytes))}else if(r[fh]===!0){let{version:n,multihash:o,code:s}=r,i=ar(o);return t.create(n,s,i)}else return null}static create(e,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(e){case 0:{if(r!==qr)throw new Error(`Version 0 CID must use dag-pb (code: ${qr}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=hc(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,qr,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,o=et(e.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 Pt(r.multihashCode,r.digestSize,s,o);return[r.version===0?t.createV0(i):t.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[f,p]=$r(e.subarray(r));return r+=p,f},o=n(),s=qr;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,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,r){let[n,o]=ih(e,r),s=t.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return gs(s).set(n,e),s}};function ih(t,e){switch(t[0]){case"Q":{let r=e??ce;return[ce.prefix,r.decode(`${ce.prefix}${t}`)]}case ce.prefix:{let r=e??ce;return[ce.prefix,r.decode(t)]}case yt.prefix:{let r=e??yt;return[yt.prefix,r.decode(t)]}case Fr.prefix:{let r=e??Fr;return[Fr.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function ah(t,e,r){let{prefix:n}=r;if(n!==ce.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return o}function ch(t,e,r){let{prefix:n}=r,o=e.get(n);if(o==null){let s=r.encode(t);return e.set(n,s),s}else return o}var qr=112,uh=18;function hc(t,e,r){let n=ir(t),o=n+ir(e),s=new Uint8Array(o+r.byteLength);return sr(t,s,0),sr(e,s,n),s.set(r,o),s}var fh=Symbol.for("@ipld/js-cid/CID");var ys={};Ie(ys,{identity:()=>Fe});var dc=0,lh="identity",pc=et;function hh(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return Be(dc,pc(t))}var Fe={code:dc,name:lh,encode:pc,digest:hh};function we(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function de(t=0){return new Uint8Array(t)}function pe(t=0){return new Uint8Array(t)}function De(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=pe(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}var gc=Symbol.for("@achingbrain/uint8arraylist");function mc(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(let n of t){let o=r+n.byteLength;if(e<o)return{buf:n,index:e-r};r=o}throw new RangeError("index is out of bounds")}function qn(t){return!!t?.[gc]}var q=class t{bufs;length;[gc]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let r=0;for(let n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(qn(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(...e){this.prependAll(e)}prependAll(e){let r=0;for(let n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(qn(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(e){let r=mc(this.bufs,e);return r.buf[r.index]}set(e,r){let n=mc(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(qn(e))for(let n=0;n<e.length;n++)this.set(r+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,r){let{bufs:n,length:o}=this._subList(e,r);return De(n,o)}subarray(e,r){let{bufs:n,length:o}=this._subList(e,r);return n.length===1?n[0]:De(n,o)}sublist(e,r){let{bufs:n,length:o}=this._subList(e,r),s=new t;return s.length=o,s.bufs=[...n],s}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:this.bufs,length:this.length};let n=[],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,e>=c)continue;let u=e>=a&&e<c,l=r>a&&r<=c;if(u&&l){if(e===a&&r===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(r-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-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-e}}indexOf(e,r=0){if(!qn(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.length===0)return r>this.length?this.length:r;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=r;f<=c;f+=l){l=0;for(let p=u;p>=0;p--){let m=this.get(f+p);if(n[p]!==m){l=Math.max(1,p-a[m]);break}}if(l===0)return f}return-1}getInt8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){let n=pe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){let o=de(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,e)}getInt32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){let o=de(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,e)}getBigInt64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){let o=de(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,e)}getUint8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){let n=pe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){let o=de(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,e)}getUint32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){let o=de(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,e)}getBigUint64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){let o=de(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,e)}getFloat32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){let o=de(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,e)}getFloat64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){let o=de(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof t)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!we(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){let n=new t;return n.bufs=e,r==null&&(r=e.reduce((o,s)=>o+s.byteLength,0)),n.length=r,n}};var bs={};Ie(bs,{base10:()=>ph});var ph=gt({prefix:"9",name:"base10",alphabet:"0123456789"});var ws={};Ie(ws,{base16:()=>mh,base16upper:()=>gh});var mh=ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),gh=ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var xs={};Ie(xs,{base2:()=>yh});var yh=ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Es={};Ie(Es,{base256emoji:()=>Sh});var yc=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}"),bh=yc.reduce((t,e,r)=>(t[r]=e,t),[]),wh=yc.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function xh(t){return t.reduce((e,r)=>(e+=bh[r],e),"")}function Eh(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=wh[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var Sh=or({prefix:"\u{1F680}",name:"base256emoji",encode:xh,decode:Eh});var Ss={};Ie(Ss,{base64:()=>vh,base64pad:()=>Ah,base64url:()=>Wr,base64urlpad:()=>Ch});var vh=ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ah=ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Wr=ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ch=ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var vs={};Ie(vs,{base8:()=>_h});var _h=ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var As={};Ie(As,{identity:()=>Lh});var Lh=or({prefix:"\0",name:"identity",encode:t=>nc(t),decode:t=>rc(t)});var Z0=new TextEncoder,Q0=new TextDecoder;var Ls={};Ie(Ls,{sha256:()=>tt,sha512:()=>Th});var Dh=20;function _s({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new Cs(t,e,r,n,o)}var Cs=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??Dh,this.maxDigestLength=s}digest(e,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(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?bc(n,this.code,r?.truncate):n.then(o=>bc(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function bc(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return Be(e,t)}function xc(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var tt=_s({name:"sha2-256",code:18,encode:xc("SHA-256")}),Th=_s({name:"sha2-512",code:19,encode:xc("SHA-512")});var Ot={...As,...xs,...vs,...bs,...ws,...hs,...ds,...ls,...Ss,...Es},fg={...Ls,...ys};function Sc(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var Ec=Sc("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Is=Sc("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=pe(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Rh={utf8:Ec,"utf-8":Ec,hex:Ot.base16,latin1:Is,ascii:Is,binary:Is,...Ot},Wn=Rh;function j(t,e="utf8"){let r=Wn[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function $(t,e="utf8"){let r=Wn[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}var Ph=parseInt("11111",2),Bs=parseInt("10000000",2),Oh=parseInt("01111111",2),vc={0:Gr,1:Gr,2:Nh,3:Kh,4:kh,5:Mh,6:Uh,16:Gr,22:Gr,48:Gr};function rt(t,e={offset:0}){let r=t[e.offset]&Ph;if(e.offset++,vc[r]!=null)return vc[r](t,e);throw new Error("No decoder for tag "+r)}function zr(t,e){let r=0;if((t[e.offset]&Bs)===Bs){let n=t[e.offset]&Oh,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=t[e.offset].toString(16).padStart(2,"0");r=parseInt(o,16)}else r=t[e.offset],e.offset++;return r}function Gr(t,e){zr(t,e);let r=[];for(;!(e.offset>=t.byteLength);){let n=rt(t,e);if(n===null)break;r.push(n)}return r}function Nh(t,e){let r=zr(t,e),n=e.offset,o=e.offset+r,s=[];for(let i=n;i<o;i++)i===n&&t[i]===0||s.push(t[i]);return e.offset+=r,Uint8Array.from(s)}function Uh(t,e){let r=zr(t,e),n=e.offset+r,o=t[e.offset];e.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(;e.offset<n;){let u=t[e.offset];if(e.offset++,c.push(u&127),u<128){c.reverse();let l=0;for(let f=0;f<c.length;f++)l+=c[f]<<f*7;a+=`.${l}`,c=[]}}return a}function Mh(t,e){return e.offset++,null}function Kh(t,e){let r=zr(t,e),n=t[e.offset];e.offset++;let o=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function kh(t,e){let r=zr(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function Hh(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);let r=new q;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function Ds(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);let e=Hh(t.byteLength);return new q(Uint8Array.from([e.byteLength|Bs]),e)}function Re(t){let e=new q,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new q(Uint8Array.from([2]),Ds(e),e)}function Gn(t){let e=Uint8Array.from([0]),r=new q(e,t);return new q(Uint8Array.from([3]),Ds(r),r)}function bt(t,e=48){let r=new q;for(let n of t)r.append(n);return new q(Uint8Array.from([e]),Ds(r),r)}async function Ac(t,e,r,n){let o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,r.subarray());return n?.signal?.throwIfAborted(),s}var Fh=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Vh=Uint8Array.from([6,5,43,129,4,0,34]),$h=Uint8Array.from([6,5,43,129,4,0,35]),qh={ext:!0,kty:"EC",crv:"P-256"},Wh={ext:!0,kty:"EC",crv:"P-384"},Gh={ext:!0,kty:"EC",crv:"P-521"},Ts=32,Rs=48,Ps=66;function Os(t){let e=rt(t);return Cc(e)}function Cc(t){let e=t[1][1][0],r=1,n,o;if(e.byteLength===Ts*2+1)return n=$(e.subarray(r,r+Ts),"base64url"),o=$(e.subarray(r+Ts),"base64url"),new cr({...qh,key_ops:["verify"],x:n,y:o});if(e.byteLength===Rs*2+1)return n=$(e.subarray(r,r+Rs),"base64url"),o=$(e.subarray(r+Rs),"base64url"),new cr({...Wh,key_ops:["verify"],x:n,y:o});if(e.byteLength===Ps*2+1)return n=$(e.subarray(r,r+Ps),"base64url"),o=$(e.subarray(r+Ps),"base64url"),new cr({...Gh,key_ops:["verify"],x:n,y:o});throw new Y(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function _c(t){return bt([Re(Uint8Array.from([1])),bt([zh(t.crv)],160),bt([Gn(new q(Uint8Array.from([4]),j(t.x??"","base64url"),j(t.y??"","base64url")))],161)]).subarray()}function zh(t){if(t==="P-256")return Fh;if(t==="P-384")return Vh;if(t==="P-521")return $h;throw new Y(`Invalid curve ${t}`)}var cr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=_c(this.jwk)),this._raw}toMultihash(){return Fe.digest(wt(this))}toCID(){return he.createV1(114,this.toMultihash())}toString(){return ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}async verify(e,r,n){return Ac(this.jwk,r,e,n)}};function Nt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Me(t,e=""){if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${t}`)}}function F(t,e,r=""){let n=Nt(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){let i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function Ut(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Me(t.outputLen),Me(t.blockLen)}function ur(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Ic(t,e){F(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Ve(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function zn(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function $e(t,e){return t<<32-e|t>>>e}var Bc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",jh=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ot(t){if(F(t),Bc)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=jh[t[r]];return e}var nt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Lc(t){if(t>=nt._0&&t<=nt._9)return t-nt._0;if(t>=nt.A&&t<=nt.F)return t-(nt.A-10);if(t>=nt.a&&t<=nt.f)return t-(nt.a-10)}function st(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Bc)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=Lc(t.charCodeAt(s)),a=Lc(t.charCodeAt(s+1));if(i===void 0||a===void 0){let c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Pe(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];F(o),e+=o.length}let r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){let s=t[n];r.set(s,o),o+=s.length}return r}function Ns(t,e={}){let r=(o,s)=>t(s).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function xt(t=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}var Us=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Dc(t,e,r){return t&e^~t&r}function Tc(t,e,r){return t&e^t&r^e&r}var jr=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,o){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=zn(this.buffer)}update(e){ur(this),F(e);let{view:r,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=zn(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ur(this),Ic(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,Ve(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)r[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=zn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},it=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var xe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var jn=BigInt(4294967295),Rc=BigInt(32);function Xh(t,e=!1){return e?{h:Number(t&jn),l:Number(t>>Rc&jn)}:{h:Number(t>>Rc&jn)|0,l:Number(t&jn)|0}}function Pc(t,e=!1){let r=t.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=Xh(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Ms=(t,e,r)=>t>>>r,Ks=(t,e,r)=>t<<32-r|e>>>r,Mt=(t,e,r)=>t>>>r|e<<32-r,Kt=(t,e,r)=>t<<32-r|e>>>r,Xr=(t,e,r)=>t<<64-r|e>>>r-32,Yr=(t,e,r)=>t>>>r-32|e<<64-r;function Xe(t,e,r,n){let o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}var Oc=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Nc=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Uc=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Mc=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0,Kc=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0),kc=(t,e,r,n,o,s)=>e+r+n+o+s+(t/2**32|0)|0;var Zh=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]),Et=new Uint32Array(64),ks=class extends jr{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|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(e,r){for(let f=0;f<16;f++,r+=4)Et[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let p=Et[f-15],m=Et[f-2],d=$e(p,7)^$e(p,18)^p>>>3,E=$e(m,17)^$e(m,19)^m>>>10;Et[f]=E+Et[f-7]+d+Et[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let p=$e(a,6)^$e(a,11)^$e(a,25),m=l+p+Dc(a,c,u)+Zh[f]+Et[f]|0,E=($e(n,2)^$e(n,13)^$e(n,22))+Tc(n,o,s)|0;l=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,l=l+this.H|0,this.set(n,o,s,i,a,c,u,l)}roundClean(){Ve(Et)}destroy(){this.set(0,0,0,0,0,0,0,0),Ve(this.buffer)}},Hs=class extends ks{A=it[0]|0;B=it[1]|0;C=it[2]|0;D=it[3]|0;E=it[4]|0;F=it[5]|0;G=it[6]|0;H=it[7]|0;constructor(){super(32)}};var Hc=Pc(["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(t=>BigInt(t))),Qh=Hc[0],Jh=Hc[1],St=new Uint32Array(80),vt=new Uint32Array(80),Fs=class extends jr{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:p,Gh:m,Gl:d,Hh:E,Hl:h}=this;return[e,r,n,o,s,i,a,c,u,l,f,p,m,d,E,h]}set(e,r,n,o,s,i,a,c,u,l,f,p,m,d,E,h){this.Ah=e|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=l|0,this.Fh=f|0,this.Fl=p|0,this.Gh=m|0,this.Gl=d|0,this.Hh=E|0,this.Hl=h|0}process(e,r){for(let x=0;x<16;x++,r+=4)St[x]=e.getUint32(r),vt[x]=e.getUint32(r+=4);for(let x=16;x<80;x++){let D=St[x-15]|0,M=vt[x-15]|0,O=Mt(D,M,1)^Mt(D,M,8)^Ms(D,M,7),k=Kt(D,M,1)^Kt(D,M,8)^Ks(D,M,7),_=St[x-2]|0,v=vt[x-2]|0,N=Mt(_,v,19)^Xr(_,v,61)^Ms(_,v,6),K=Kt(_,v,19)^Yr(_,v,61)^Ks(_,v,6),T=Uc(k,K,vt[x-7],vt[x-16]),w=Mc(T,O,N,St[x-7],St[x-16]);St[x]=w|0,vt[x]=T|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:p,Fh:m,Fl:d,Gh:E,Gl:h,Hh:b,Hl:A}=this;for(let x=0;x<80;x++){let D=Mt(f,p,14)^Mt(f,p,18)^Xr(f,p,41),M=Kt(f,p,14)^Kt(f,p,18)^Yr(f,p,41),O=f&m^~f&E,k=p&d^~p&h,_=Kc(A,M,k,Jh[x],vt[x]),v=kc(_,b,D,O,Qh[x],St[x]),N=_|0,K=Mt(n,o,28)^Xr(n,o,34)^Xr(n,o,39),T=Kt(n,o,28)^Yr(n,o,34)^Yr(n,o,39),w=n&s^n&a^s&a,g=o&i^o&c^i&c;b=E|0,A=h|0,E=m|0,h=d|0,m=f|0,d=p|0,{h:f,l:p}=Xe(u|0,l|0,v|0,N|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let y=Oc(N,T,g);n=Nc(y,v,K,w),o=y|0}({h:n,l:o}=Xe(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Xe(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Xe(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Xe(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:p}=Xe(this.Eh|0,this.El|0,f|0,p|0),{h:m,l:d}=Xe(this.Fh|0,this.Fl|0,m|0,d|0),{h:E,l:h}=Xe(this.Gh|0,this.Gl|0,E|0,h|0),{h:b,l:A}=Xe(this.Hh|0,this.Hl|0,b|0,A|0),this.set(n,o,s,i,a,c,u,l,f,p,m,d,E,h,b,A)}roundClean(){Ve(St,vt)}destroy(){Ve(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Vs=class extends Fs{Ah=xe[0]|0;Al=xe[1]|0;Bh=xe[2]|0;Bl=xe[3]|0;Ch=xe[4]|0;Cl=xe[5]|0;Dh=xe[6]|0;Dl=xe[7]|0;Eh=xe[8]|0;El=xe[9]|0;Fh=xe[10]|0;Fl=xe[11]|0;Gh=xe[12]|0;Gl=xe[13]|0;Hh=xe[14]|0;Hl=xe[15]|0;constructor(){super(64)}};var Ye=Ns(()=>new Hs,Us(1));var Fc=Ns(()=>new Vs,Us(3));var qs=BigInt(0),$s=BigInt(1);function at(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function Vc(t){if(typeof t=="bigint"){if(!Xn(t))throw new Error("positive bigint expected, got "+t)}else Me(t);return t}function Zr(t){let e=Vc(t).toString(16);return e.length&1?"0"+e:e}function $c(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?qs:BigInt("0x"+t)}function fr(t){return $c(ot(t))}function Ze(t){return $c(ot(kt(F(t)).reverse()))}function Yn(t,e){Me(e),t=Vc(t);let r=st(t.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function Qr(t,e){return Yn(t,e).reverse()}function kt(t){return Uint8Array.from(t)}var Xn=t=>typeof t=="bigint"&&qs<=t;function ed(t,e,r){return Xn(t)&&Xn(e)&&Xn(r)&&e<=t&&t<r}function At(t,e,r,n){if(!ed(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Ws(t){let e;for(e=0;t>qs;t>>=$s,e+=1);return e}var Jr=t=>($s<<BigInt(t))-$s;function qc(t,e,r){if(Me(t,"hashLen"),Me(e,"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(t),u=n(t),l=0,f=()=>{c.fill(1),u.fill(0),l=0},p=(...h)=>r(u,Pe(c,...h)),m=(h=o)=>{u=p(s,h),c=p(),h.length!==0&&(u=p(i,h),c=p())},d=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let h=0,b=[];for(;h<e;){c=p();let A=c.slice();b.push(A),h+=c.length}return Pe(...b)};return(h,b)=>{f(),m(h);let A;for(;!(A=b(d()));)m();return f(),A}}function Qe(t,e={},r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(s,i,a){let c=t[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(e,!1),o(r,!0)}function lr(t){let e=new WeakMap;return(r,...n)=>{let o=e.get(r);if(o!==void 0)return o;let s=t(r,...n);return e.set(r,s),s}}var Te=BigInt(0),me=BigInt(1),Ht=BigInt(2),zc=BigInt(3),jc=BigInt(4),Xc=BigInt(5),td=BigInt(7),Yc=BigInt(8),rd=BigInt(9),Zc=BigInt(16);function ie(t,e){let r=t%e;return r>=Te?r:e+r}function oe(t,e,r){let n=t;for(;e-- >Te;)n*=n,n%=r;return n}function Wc(t,e){if(t===Te)throw new Error("invert: expected non-zero number");if(e<=Te)throw new Error("invert: expected positive modulus, got "+e);let r=ie(t,e),n=e,o=Te,s=me,i=me,a=Te;for(;r!==Te;){let u=n/r,l=n%r,f=o-i*u,p=s-a*u;n=r,r=l,o=i,s=a,i=f,a=p}if(n!==me)throw new Error("invert: does not exist");return ie(o,e)}function zs(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function Qc(t,e){let r=(t.ORDER+me)/jc,n=t.pow(e,r);return zs(t,n,e),n}function nd(t,e){let r=(t.ORDER-Xc)/Yc,n=t.mul(e,Ht),o=t.pow(n,r),s=t.mul(e,o),i=t.mul(t.mul(s,Ht),o),a=t.mul(s,t.sub(i,t.ONE));return zs(t,a,e),a}function od(t){let e=hr(t),r=Jc(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+td)/Zc;return(a,c)=>{let u=a.pow(c,i),l=a.mul(u,n),f=a.mul(u,o),p=a.mul(u,s),m=a.eql(a.sqr(l),c),d=a.eql(a.sqr(f),c);u=a.cmov(u,l,m),l=a.cmov(p,f,d);let E=a.eql(a.sqr(l),c),h=a.cmov(u,l,E);return zs(a,h,c),h}}function Jc(t){if(t<zc)throw new Error("sqrt is not defined for small field");let e=t-me,r=0;for(;e%Ht===Te;)e/=Ht,r++;let n=Ht,o=hr(t);for(;Gc(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Qc;let s=o.pow(n,e),i=(e+me)/Ht;return function(c,u){if(c.is0(u))return u;if(Gc(c,u)!==1)throw new Error("Cannot find square root");let l=r,f=c.mul(c.ONE,s),p=c.pow(u,e),m=c.pow(u,i);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let d=1,E=c.sqr(p);for(;!c.eql(E,c.ONE);)if(d++,E=c.sqr(E),d===l)throw new Error("Cannot find square root");let h=me<<BigInt(l-d-1),b=c.pow(f,h);l=d,f=c.sqr(b),p=c.mul(p,f),m=c.mul(m,b)}return m}}function sd(t){return t%jc===zc?Qc:t%Yc===Xc?nd:t%Zc===rd?od(t):Jc(t)}var eu=(t,e)=>(ie(t,e)&me)===me,id=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function js(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=id.reduce((n,o)=>(n[o]="function",n),e);return Qe(t,r),t}function ad(t,e,r){if(r<Te)throw new Error("invalid exponent, negatives unsupported");if(r===Te)return t.ONE;if(r===me)return e;let n=t.ONE,o=e;for(;r>Te;)r&me&&(n=t.mul(n,o)),o=t.sqr(o),r>>=me;return n}function en(t,e,r=!1){let n=new Array(e.length).fill(r?t.ZERO:void 0),o=e.reduce((i,a,c)=>t.is0(a)?i:(n[c]=i,t.mul(i,a)),t.ONE),s=t.inv(o);return e.reduceRight((i,a,c)=>t.is0(a)?i:(n[c]=t.mul(i,n[c]),t.mul(i,a)),s),n}function Gc(t,e){let r=(t.ORDER-me)/Ht,n=t.pow(e,r),o=t.eql(n,t.ONE),s=t.eql(n,t.ZERO),i=t.eql(n,t.neg(t.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function cd(t,e){e!==void 0&&Me(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var Gs=class{ORDER;BITS;BYTES;isLE;ZERO=Te;ONE=me;_lengths;_sqrt;_mod;constructor(e,r={}){if(e<=Te)throw new Error("invalid field: expected ORDER > 0, got "+e);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}=cd(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ie(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Te<=e&&e<this.ORDER}is0(e){return e===Te}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&me)===me}neg(e){return ie(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return ie(e*e,this.ORDER)}add(e,r){return ie(e+r,this.ORDER)}sub(e,r){return ie(e-r,this.ORDER)}mul(e,r){return ie(e*r,this.ORDER)}pow(e,r){return ad(this,e,r)}div(e,r){return ie(e*Wc(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return Wc(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=sd(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Qr(e,this.BYTES):Yn(e,this.BYTES)}fromBytes(e,r=!1){F(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(o);u.set(e,s?0:u.length-e.length),e=u}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?Ze(e):fr(e);if(a&&(c=ie(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return en(this,e)}cmov(e,r,n){return n?r:e}};function hr(t,e={}){return new Gs(t,e)}function tu(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function Xs(t){let e=tu(t);return e+Math.ceil(e/2)}function Ys(t,e,r=!1){F(t);let n=t.length,o=tu(e),s=Xs(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?Ze(t):fr(t),a=ie(i,e-me)+me;return r?Qr(a,o):Yn(a,o)}var dr=BigInt(0),Ft=BigInt(1);function tn(t,e){let r=e.negate();return t?r:e}function Vt(t,e){let r=en(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function su(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Zs(t,e){su(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),o=2**t,s=Jr(t),i=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function ru(t,e,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(t&o),c=t>>i;a>n&&(a-=s,c+=Ft);let u=e*n,l=u+Math.abs(a)-1,f=a===0,p=a<0,m=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:p,isNegF:m,offsetF:u}}var Qs=new WeakMap,iu=new WeakMap;function Js(t){return iu.get(t)||1}function nu(t){if(t!==dr)throw new Error("invalid wNAF")}var pr=class{BASE;ZERO;Fn;bits;constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let o=e;for(;r>dr;)r&Ft&&(n=n.add(o)),o=o.double(),r>>=Ft;return n}precomputeWindow(e,r){let{windows:n,windowSize:o}=Zs(r,this.bits),s=[],i=e,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(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Zs(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:p,offsetF:m}=ru(n,a,i);n=c,l?s=s.add(tn(p,r[m])):o=o.add(tn(f,r[u]))}return nu(n),{p:o,f:s}}wNAFUnsafe(e,r,n,o=this.ZERO){let s=Zs(e,this.bits);for(let i=0;i<s.windows&&n!==dr;i++){let{nextN:a,offset:c,isZero:u,isNeg:l}=ru(n,i,s);if(n=a,!u){let f=r[c];o=o.add(l?f.negate():f)}}return nu(n),o}getPrecomputes(e,r,n){let o=Qs.get(r);return o||(o=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(o=n(o)),Qs.set(r,o))),o}cached(e,r,n){let o=Js(e);return this.wNAF(o,this.getPrecomputes(o,e,n),r)}unsafe(e,r,n,o){let s=Js(e);return s===1?this._unsafeLadder(e,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),r,o)}createCache(e,r){su(r,this.bits),iu.set(e,r),Qs.delete(e)}hasCache(e){return Js(e)!==1}};function au(t,e,r,n){let o=e,s=t.ZERO,i=t.ZERO;for(;r>dr||n>dr;)r&Ft&&(s=s.add(o)),n&Ft&&(i=i.add(o)),o=o.double(),r>>=Ft,n>>=Ft;return{p1:s,p2:i}}function ou(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return js(e),e}else return hr(t,{isLE:r})}function Zn(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let u=e[c];if(!(typeof u=="bigint"&&u>dr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=ou(e.p,r.Fp,n),s=ou(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function mr(t,e){return function(n){let o=t(n);return{secretKey:o,publicKey:e(o)}}}var Ct=BigInt(0),ge=BigInt(1),ei=BigInt(2),ud=BigInt(8);function fd(t,e,r,n){let o=t.sqr(r),s=t.sqr(n),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function cu(t,e={}){let r=Zn("edwards",t,e,e.FpFnLE),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i}=s;Qe(e,{},{uvRatio:"function"});let a=ei<<BigInt(o.BYTES*8)-ge,c=h=>n.create(h),u=e.uvRatio||((h,b)=>{try{return{isValid:!0,value:n.sqrt(n.div(h,b))}}catch{return{isValid:!1,value:Ct}}});if(!fd(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function l(h,b,A=!1){let x=A?ge:Ct;return At("coordinate "+h,b,x,a),b}function f(h){if(!(h instanceof d))throw new Error("EdwardsPoint expected")}let p=lr((h,b)=>{let{X:A,Y:x,Z:D}=h,M=h.is0();b==null&&(b=M?ud:n.inv(D));let O=c(A*b),k=c(x*b),_=n.mul(D,b);if(M)return{x:Ct,y:ge};if(_!==ge)throw new Error("invZ was invalid");return{x:O,y:k}}),m=lr(h=>{let{a:b,d:A}=s;if(h.is0())throw new Error("bad point: ZERO");let{X:x,Y:D,Z:M,T:O}=h,k=c(x*x),_=c(D*D),v=c(M*M),N=c(v*v),K=c(k*b),T=c(v*c(K+_)),w=c(N+c(A*c(k*_)));if(T!==w)throw new Error("bad point: equation left != right (1)");let g=c(x*D),y=c(M*O);if(g!==y)throw new Error("bad point: equation left != right (2)");return!0});class d{static BASE=new d(s.Gx,s.Gy,ge,c(s.Gx*s.Gy));static ZERO=new d(Ct,ge,ge,Ct);static Fp=n;static Fn=o;X;Y;Z;T;constructor(b,A,x,D){this.X=l("x",b),this.Y=l("y",A),this.Z=l("z",x,!0),this.T=l("t",D),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){if(b instanceof d)throw new Error("extended point not allowed");let{x:A,y:x}=b||{};return l("x",A),l("y",x),new d(A,x,ge,c(A*x))}static fromBytes(b,A=!1){let x=n.BYTES,{a:D,d:M}=s;b=kt(F(b,x,"point")),at(A,"zip215");let O=kt(b),k=b[x-1];O[x-1]=k&-129;let _=Ze(O),v=A?a:n.ORDER;At("point.y",_,Ct,v);let N=c(_*_),K=c(N-ge),T=c(M*N-D),{isValid:w,value:g}=u(K,T);if(!w)throw new Error("bad point: invalid y coordinate");let y=(g&ge)===ge,C=(k&128)!==0;if(!A&&g===Ct&&C)throw new Error("bad point: x=0 and x_0=1");return C!==y&&(g=c(-g)),d.fromAffine({x:g,y:_})}static fromHex(b,A=!1){return d.fromBytes(st(b),A)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,A=!0){return E.createCache(this,b),A||this.multiply(ei),this}assertValidity(){m(this)}equals(b){f(b);let{X:A,Y:x,Z:D}=this,{X:M,Y:O,Z:k}=b,_=c(A*k),v=c(M*D),N=c(x*k),K=c(O*D);return _===v&&N===K}is0(){return this.equals(d.ZERO)}negate(){return new d(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:b}=s,{X:A,Y:x,Z:D}=this,M=c(A*A),O=c(x*x),k=c(ei*c(D*D)),_=c(b*M),v=A+x,N=c(c(v*v)-M-O),K=_+O,T=K-k,w=_-O,g=c(N*T),y=c(K*w),C=c(N*w),I=c(T*K);return new d(g,y,I,C)}add(b){f(b);let{a:A,d:x}=s,{X:D,Y:M,Z:O,T:k}=this,{X:_,Y:v,Z:N,T:K}=b,T=c(D*_),w=c(M*v),g=c(k*x*K),y=c(O*N),C=c((D+M)*(_+v)-T-w),I=y-g,L=y+g,S=c(w-A*T),B=c(C*I),R=c(L*S),P=c(C*S),z=c(I*L);return new d(B,R,z,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:A,f:x}=E.cached(this,b,D=>Vt(d,D));return Vt(d,[A,x])[0]}multiplyUnsafe(b,A=d.ZERO){if(!o.isValid(b))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return b===Ct?d.ZERO:this.is0()||b===ge?this:E.unsafe(this,b,x=>Vt(d,x),A)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return E.unsafe(this,s.n).is0()}toAffine(b){return p(this,b)}clearCofactor(){return i===ge?this:this.multiplyUnsafe(i)}toBytes(){let{x:b,y:A}=this.toAffine(),x=n.toBytes(A);return x[x.length-1]|=b&ge?128:0,x}toHex(){return ot(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let E=new pr(d,o.BITS);return d.BASE.precompute(8),d}function uu(t,e,r={}){if(typeof e!="function")throw new Error('"hash" function param is required');Qe(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=r,{BASE:o,Fp:s,Fn:i}=t,a=r.randomBytes||xt,c=r.adjustScalarBytes||(_=>_),u=r.domain||((_,v,N)=>{if(at(N,"phflag"),v.length||N)throw new Error("Contexts/pre-hash are not supported");return _});function l(_){return i.create(Ze(_))}function f(_){let v=x.secretKey;F(_,x.secretKey,"secretKey");let N=F(e(_),2*v,"hashedSecretKey"),K=c(N.slice(0,v)),T=N.slice(v,2*v),w=l(K);return{head:K,prefix:T,scalar:w}}function p(_){let{head:v,prefix:N,scalar:K}=f(_),T=o.multiply(K),w=T.toBytes();return{head:v,prefix:N,scalar:K,point:T,pointBytes:w}}function m(_){return p(_).pointBytes}function d(_=Uint8Array.of(),...v){let N=Pe(...v);return l(e(u(N,F(_,void 0,"context"),!!n)))}function E(_,v,N={}){_=F(_,void 0,"message"),n&&(_=n(_));let{prefix:K,scalar:T,pointBytes:w}=p(v),g=d(N.context,K,_),y=o.multiply(g).toBytes(),C=d(N.context,y,w,_),I=i.create(g+C*T);if(!i.isValid(I))throw new Error("sign failed: invalid s");let L=Pe(y,i.toBytes(I));return F(L,x.signature,"result")}let h={zip215:!0};function b(_,v,N,K=h){let{context:T,zip215:w}=K,g=x.signature;_=F(_,g,"signature"),v=F(v,void 0,"message"),N=F(N,x.publicKey,"publicKey"),w!==void 0&&at(w,"zip215"),n&&(v=n(v));let y=g/2,C=_.subarray(0,y),I=Ze(_.subarray(y,g)),L,S,B;try{L=t.fromBytes(N,w),S=t.fromBytes(C,w),B=o.multiplyUnsafe(I)}catch{return!1}if(!w&&L.isSmallOrder())return!1;let R=d(T,S.toBytes(),L.toBytes(),v);return S.add(L.multiplyUnsafe(R)).subtract(B).clearCofactor().is0()}let A=s.BYTES,x={secretKey:A,publicKey:A,signature:2*A,seed:A};function D(_=a(x.seed)){return F(_,x.seed,"seed")}function M(_){return Nt(_)&&_.length===i.BYTES}function O(_,v){try{return!!t.fromBytes(_,v)}catch{return!1}}let k={getExtendedPublicKey:p,randomSecretKey:D,isValidSecretKey:M,isValidPublicKey:O,toMontgomery(_){let{y:v}=t.fromBytes(_),N=x.publicKey,K=N===32;if(!K&&N!==57)throw new Error("only defined for 25519 and 448");let T=K?s.div(ge+v,ge-v):s.div(v-ge,v+ge);return s.toBytes(T)},toMontgomerySecret(_){let v=x.secretKey;F(_,v);let N=e(_.subarray(0,v));return c(N).subarray(0,v)}};return Object.freeze({keygen:mr(D,m),getPublicKey:m,sign:E,verify:b,utils:k,Point:t,lengths:x})}var rn=BigInt(0),gr=BigInt(1),Qn=BigInt(2);function ld(t){return Qe(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function fu(t){let e=ld(t),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||xt,u=a?255:448,l=a?32:56,f=BigInt(a?9:5),p=BigInt(a?121665:39081),m=a?Qn**BigInt(254):Qn**BigInt(447),d=a?BigInt(8)*Qn**BigInt(251)-gr:BigInt(4)*Qn**BigInt(445)-gr,E=m+d+gr,h=g=>ie(g,r),b=A(f);function A(g){return Qr(h(g),l)}function x(g){let y=kt(F(g,l,"uCoordinate"));return a&&(y[31]&=127),h(Ze(y))}function D(g){return Ze(o(kt(F(g,l,"scalar"))))}function M(g,y){let C=N(x(y),D(g));if(C===rn)throw new Error("invalid private or public key received");return A(C)}function O(g){return M(g,b)}let k=O,_=M;function v(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){At("u",g,rn,r),At("scalar",y,m,E);let C=y,I=g,L=gr,S=rn,B=g,R=gr,P=rn;for(let W=BigInt(u-1);W>=rn;W--){let V=C>>W&gr;P^=V,{x_2:L,x_3:B}=v(P,L,B),{x_2:S,x_3:R}=v(P,S,R),P=V;let X=L+S,te=h(X*X),ue=L-S,Z=h(ue*ue),le=te-Z,Jt=B+R,Dn=B-R,kr=h(Dn*X),Ya=h(Jt*ue),Za=kr+Ya,Qa=kr-Ya;B=h(Za*Za),R=h(I*h(Qa*Qa)),L=h(te*Z),S=h(le*(te+h(p*le)))}({x_2:L,x_3:B}=v(P,L,B)),{x_2:S,x_3:R}=v(P,S,R);let z=s(S);return h(L*z)}let K={secretKey:l,publicKey:l,seed:l},T=(g=c(l))=>(F(g,K.seed,"seed"),g),w={randomSecretKey:T};return Object.freeze({keygen:mr(T,k),getSharedSecret:_,getPublicKey:k,scalarMult:M,scalarMultBase:O,utils:w,GuBytes:b.slice(),lengths:K})}var hd=BigInt(1),lu=BigInt(2),dd=BigInt(3),pd=BigInt(5),md=BigInt(8),Jn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),gd={p:Jn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:md,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function du(t){let e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=Jn,a=t*t%s*t%s,c=oe(a,lu,s)*a%s,u=oe(c,hd,s)*t%s,l=oe(u,pd,s)*u%s,f=oe(l,e,s)*l%s,p=oe(f,r,s)*f%s,m=oe(p,n,s)*p%s,d=oe(m,o,s)*m%s,E=oe(d,o,s)*m%s,h=oe(E,e,s)*l%s;return{pow_p_5_8:oe(h,lu,s)*t%s,b2:a}}function pu(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var hu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function yd(t,e){let r=Jn,n=ie(e*e*e,r),o=ie(n*n*e,r),s=du(t*o).pow_p_5_8,i=ie(t*n*s,r),a=ie(e*i*i,r),c=i,u=ie(i*hu,r),l=a===t,f=a===ie(-t,r),p=a===ie(-t*hu,r);return l&&(i=c),(f||p)&&(i=u),eu(i,r)&&(i=ie(-i,r)),{isValid:l||f,value:i}}var bd=cu(gd,{uvRatio:yd});function wd(t){return uu(bd,Fc,Object.assign({adjustScalarBytes:pu},t))}var mu=wd({});var nn=(()=>{let t=Jn;return fu({P:t,type:"x25519",powPminus2:e=>{let{pow_p_5_8:r,b2:n}=du(e);return ie(oe(r,dd,t)*n,t)},adjustScalarBytes:pu})})();var on=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},eo=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var gu={get(t=globalThis){let e=t.crypto;if(e?.subtle==null)throw new eo("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 e}};var Ke=gu;var to=32;var ti,xd=(async()=>{try{return await Ke.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Ed(t,e,r){if(t.buffer instanceof ArrayBuffer){let n=await Ke.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await Ke.get().subtle.verify({name:"Ed25519"},n,e,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Sd(t,e,r){return mu.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}async function yu(t,e,r){return ti==null&&(ti=await xd),ti?Ed(t,e,r):Sd(t,e,r)}function ro(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var no=class{type="Ed25519";raw;constructor(e){this.raw=ri(e,to)}toMultihash(){return Fe.digest(wt(this))}toCID(){return he.createV1(114,this.toMultihash())}toString(){return ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();let o=yu(this.raw,r,e);return ro(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function ni(t){return t=ri(t,to),new no(t)}function ri(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new Y(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}var Ad=Math.pow(2,7),Cd=Math.pow(2,14),_d=Math.pow(2,21),oi=Math.pow(2,28),si=Math.pow(2,35),ii=Math.pow(2,42),ai=Math.pow(2,49),J=128,Ae=127;function se(t){if(t<Ad)return 1;if(t<Cd)return 2;if(t<_d)return 3;if(t<oi)return 4;if(t<si)return 5;if(t<ii)return 6;if(t<ai)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function yr(t,e,r=0){switch(se(t)){case 8:e[r++]=t&255|J,t/=128;case 7:e[r++]=t&255|J,t/=128;case 6:e[r++]=t&255|J,t/=128;case 5:e[r++]=t&255|J,t/=128;case 4:e[r++]=t&255|J,t>>>=7;case 3:e[r++]=t&255|J,t>>>=7;case 2:e[r++]=t&255|J,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Ld(t,e,r=0){switch(se(t)){case 8:e.set(r++,t&255|J),t/=128;case 7:e.set(r++,t&255|J),t/=128;case 6:e.set(r++,t&255|J),t/=128;case 5:e.set(r++,t&255|J),t/=128;case 4:e.set(r++,t&255|J),t>>>=7;case 3:e.set(r++,t&255|J),t>>>=7;case 2:e.set(r++,t&255|J),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function ci(t,e){let r=t[e],n=0;if(n+=r&Ae,r<J||(r=t[e+1],n+=(r&Ae)<<7,r<J)||(r=t[e+2],n+=(r&Ae)<<14,r<J)||(r=t[e+3],n+=(r&Ae)<<21,r<J)||(r=t[e+4],n+=(r&Ae)*oi,r<J)||(r=t[e+5],n+=(r&Ae)*si,r<J)||(r=t[e+6],n+=(r&Ae)*ii,r<J)||(r=t[e+7],n+=(r&Ae)*ai,r<J))return n;throw new RangeError("Could not decode varint")}function Id(t,e){let r=t.get(e),n=0;if(n+=r&Ae,r<J||(r=t.get(e+1),n+=(r&Ae)<<7,r<J)||(r=t.get(e+2),n+=(r&Ae)<<14,r<J)||(r=t.get(e+3),n+=(r&Ae)<<21,r<J)||(r=t.get(e+4),n+=(r&Ae)*oi,r<J)||(r=t.get(e+5),n+=(r&Ae)*si,r<J)||(r=t.get(e+6),n+=(r&Ae)*ii,r<J)||(r=t.get(e+7),n+=(r&Ae)*ai,r<J))return n;throw new RangeError("Could not decode varint")}function oo(t,e,r=0){return e==null&&(e=pe(se(t))),e instanceof Uint8Array?yr(t,e,r):Ld(t,e,r)}function ct(t,e=0){return t instanceof Uint8Array?ci(t,e):Id(t,e)}var ui=new Float32Array([-0]),_t=new Uint8Array(ui.buffer);function wu(t,e,r){ui[0]=t,e[r]=_t[0],e[r+1]=_t[1],e[r+2]=_t[2],e[r+3]=_t[3]}function xu(t,e){return _t[0]=t[e],_t[1]=t[e+1],_t[2]=t[e+2],_t[3]=t[e+3],ui[0]}var fi=new Float64Array([-0]),Ce=new Uint8Array(fi.buffer);function Eu(t,e,r){fi[0]=t,e[r]=Ce[0],e[r+1]=Ce[1],e[r+2]=Ce[2],e[r+3]=Ce[3],e[r+4]=Ce[4],e[r+5]=Ce[5],e[r+6]=Ce[6],e[r+7]=Ce[7]}function Su(t,e){return Ce[0]=t[e],Ce[1]=t[e+1],Ce[2]=t[e+2],Ce[3]=t[e+3],Ce[4]=t[e+4],Ce[5]=t[e+5],Ce[6]=t[e+6],Ce[7]=t[e+7],fi[0]}var Bd=BigInt(Number.MAX_SAFE_INTEGER),Dd=BigInt(Number.MIN_SAFE_INTEGER),Ne=class t{lo;hi;constructor(e,r){this.lo=e|0,this.hi=r|0}toNumber(e=!1){if(!e&&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(e=!1){if(e)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(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return $t;if(e<Bd&&e>Dd)return this.fromNumber(Number(e));let r=e<0n;r&&(e=-e);let n=e>>32n,o=e-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>vu&&(o=0n,++n>vu&&(n=0n))),new t(Number(o),Number(n))}static fromNumber(e){if(e===0)return $t;let r=e<0;r&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new t(n,o)}static from(e){return typeof e=="number"?t.fromNumber(e):typeof e=="bigint"?t.fromBigInt(e):typeof e=="string"?t.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new t(e.low>>>0,e.high>>>0):$t}},$t=new Ne(0,0);$t.toBigInt=function(){return 0n};$t.zzEncode=$t.zzDecode=function(){return this};$t.length=function(){return 1};var vu=4294967296n;function Au(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:(r&64512)===55296&&(t.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Cu(t,e,r){if(r-e<1)return"";let o,s=[],i=0,a;for(;e<r;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&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 li(t,e,r){let n=r,o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[r++]=o:o<2048?(e[r++]=o>>6|192,e[r++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[r++]=o>>18|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128,e[r++]=o&63|128):(e[r++]=o>>12|224,e[r++]=o>>6&63|128,e[r++]=o&63|128);return r-n}function qe(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function so(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}var hi=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,qe(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw qe(this,4);return so(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw qe(this,4);return so(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw qe(this,4);let e=xu(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw qe(this,4);let e=Su(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw qe(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let e=this.bytes();return Cu(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw qe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw qe(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Ne(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw qe(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,e}if(this.len-this.pos>4){for(;r<5;++r)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;r<5;++r){if(this.pos>=this.len)throw qe(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw qe(this,8);let e=so(this.buf,this.pos+=4),r=so(this.buf,this.pos+=4);return new Ne(e,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=ci(this.buf,this.pos);return this.pos+=se(e),e}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 di(t){return new hi(t instanceof Uint8Array?t:t.subarray())}function We(t,e,r){let n=di(t);return e.decode(n,void 0,r)}function pi(t){let e=t??8192,r=e>>>1,n,o=e;return function(i){if(i<1||i>r)return pe(i);o+i>e&&(n=pe(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var qt=class{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}};function mi(){}var yi=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Td=pi();function Rd(t){return globalThis.Buffer!=null?pe(t):Td(t)}var cn=class{len;head;tail;states;constructor(){this.len=0,this.head=new qt(mi,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new qt(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new bi((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(io,10,Ne.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let r=Ne.fromBigInt(e);return this._push(io,r.length(),r)}uint64Number(e){return this._push(yr,se(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let r=Ne.fromBigInt(e).zzEncode();return this._push(io,r.length(),r)}sint64Number(e){let r=Ne.fromNumber(e).zzEncode();return this._push(io,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(gi,1,e?1:0)}fixed32(e){return this._push(an,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let r=Ne.fromBigInt(e);return this._push(an,4,r.lo)._push(an,4,r.hi)}fixed64Number(e){let r=Ne.fromNumber(e);return this._push(an,4,r.lo)._push(an,4,r.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(wu,4,e)}double(e){return this._push(Eu,8,e)}bytes(e){let r=e.length>>>0;return r===0?this._push(gi,1,0):this.uint32(r)._push(Od,r,e)}string(e){let r=Au(e);return r!==0?this.uint32(r)._push(li,r,e):this._push(gi,1,0)}fork(){return this.states=new yi(this),this.head=this.tail=new qt(mi,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 qt(mi,0,0),this.len=0),this}ldelim(){let e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=r,this.len+=n),this}finish(){let e=this.head.next,r=Rd(this.len),n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}};function gi(t,e,r){e[r]=t&255}function Pd(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}var bi=class extends qt{next;constructor(e,r){super(Pd,e,r),this.next=void 0}};function io(t,e,r){for(;t.hi!==0;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}function an(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function Od(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(cn.prototype.bytes=function(t){let e=t.length>>>0;return this.uint32(e),e>0&&this._push(Nd,e,t),this},cn.prototype.string=function(t){let e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(Ud,e,t),this});function Nd(t,e,r){e.set(t,r)}function Ud(t,e,r){t.length<40?li(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(j(t),r)}function wi(){return new cn}function Ge(t,e){let r=wi();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var br;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(br||(br={}));function ao(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function Wt(t){function e(o){if(t[o.toString()]==null)throw new Error("Invalid enum value");return t[o]}let r=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return ao("enum",br.VARINT,r,n)}function ze(t,e){return ao("message",br.LENGTH_DELIMITED,t,e)}var un=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var fe;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(fe||(fe={}));var xi;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(xi||(xi={}));(function(t){t.codec=()=>Wt(xi)})(fe||(fe={}));var Je;(function(t){let e;t.codec=()=>(e==null&&(e=ze((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),fe.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{s.Type=fe.codec().decode(r);break}case 2:{s.Data=r.bytes();break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ge(r,t.codec()),t.decode=(r,n)=>We(r,t.codec(),n)})(Je||(Je={}));var Ei;(function(t){let e;t.codec=()=>(e==null&&(e=ze((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),fe.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{s.Type=fe.codec().decode(r);break}case 2:{s.Data=r.bytes();break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ge(r,t.codec()),t.decode=(r,n)=>We(r,t.codec(),n)})(Ei||(Ei={}));var ln={};Ie(ln,{MAX_RSA_KEY_SIZE:()=>Si,generateRSAKeyPair:()=>Tu,jwkToJWKKeyPair:()=>Ru,jwkToPkcs1:()=>Hd,jwkToPkix:()=>_i,jwkToRSAPrivateKey:()=>Di,pkcs1MessageToJwk:()=>Ai,pkcs1MessageToRSAPrivateKey:()=>Li,pkcs1ToJwk:()=>kd,pkcs1ToRSAPrivateKey:()=>Du,pkixMessageToJwk:()=>Ci,pkixMessageToRSAPublicKey:()=>Bi,pkixToJwk:()=>Fd,pkixToRSAPublicKey:()=>Ii});var wr=class{type="RSA";jwk;_raw;_multihash;constructor(e,r){this.jwk=e,this._multihash=r}get raw(){return this._raw==null&&(this._raw=ln.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return he.createV1(114,this._multihash)}toString(){return ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}verify(e,r,n){return Bu(this.jwk,r,e,n)}},fn=class{type="RSA";jwk;_raw;publicKey;constructor(e,r){this.jwk=e,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=ln.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}sign(e,r){return Iu(this.jwk,e,r)}};var Si=8192,vi=18,Md=1062,Kd=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function kd(t){let e=rt(t);return Ai(e)}function Ai(t){return{n:$(t[1],"base64url"),e:$(t[2],"base64url"),d:$(t[3],"base64url"),p:$(t[4],"base64url"),q:$(t[5],"base64url"),dp:$(t[6],"base64url"),dq:$(t[7],"base64url"),qi:$(t[8],"base64url"),kty:"RSA"}}function Hd(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new Y("JWK was missing components");return bt([Re(Uint8Array.from([0])),Re(j(t.n,"base64url")),Re(j(t.e,"base64url")),Re(j(t.d,"base64url")),Re(j(t.p,"base64url")),Re(j(t.q,"base64url")),Re(j(t.dp,"base64url")),Re(j(t.dq,"base64url")),Re(j(t.qi,"base64url"))]).subarray()}function Fd(t){let e=rt(t,{offset:0});return Ci(e)}function Ci(t){let e=rt(t[1],{offset:0});return{kty:"RSA",n:$(e[0],"base64url"),e:$(e[1],"base64url")}}function _i(t){if(t.n==null||t.e==null)throw new Y("JWK was missing components");return bt([Kd,Gn(bt([Re(j(t.n,"base64url")),Re(j(t.e,"base64url"))]))]).subarray()}function Du(t){let e=rt(t);return Li(e)}function Li(t){let e=Ai(t);return Di(e)}function Ii(t,e){if(t.byteLength>=Md)throw new er("Key size is too large");let r=rt(t,{offset:0});return Bi(r,t,e)}function Bi(t,e,r){let n=Ci(t);if(r==null){let o=Ye(Je.encode({Type:fe.RSA,Data:e}));r=Be(vi,o)}return new wr(n,r)}function Di(t){if(Ou(t)>Si)throw new Y("Key size is too large");let e=Ru(t),r=Ye(Je.encode({Type:fe.RSA,Data:_i(e.publicKey)})),n=Be(vi,r);return new fn(e.privateKey,new wr(e.publicKey,n))}async function Tu(t){if(t>Si)throw new Y("Key size is too large");let e=await Pu(t),r=Ye(Je.encode({Type:fe.RSA,Data:_i(e.publicKey)})),n=Be(vi,r);return new fn(e.privateKey,new wr(e.publicKey,n))}function Ru(t){if(t==null)throw new Y("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function Pu(t,e){let r=await Ke.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await Vd(r,e);return{privateKey:n[0],publicKey:n[1]}}async function Iu(t,e,r){let n=await Ke.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let o=await Ke.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Bu(t,e,r,n){let o=await Ke.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ke.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),s}async function Vd(t,e){if(t.privateKey==null||t.publicKey==null)throw new Y("Private and public key are required");let r=await Promise.all([Ke.get().subtle.exportKey("jwk",t.privateKey),Ke.get().subtle.exportKey("jwk",t.publicKey)]);return e?.signal?.throwIfAborted(),r}function Ou(t){if(t.kty!=="RSA")throw new Y("invalid key type");if(t.n==null)throw new Y("invalid key modulus");return j(t.n,"base64url").length*8}var co=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,r){if(Ut(e),F(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Ve(o)}update(e){return ur(this),this.iHash.update(e),this}digestInto(e){ur(this),F(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},xr=(t,e,r)=>new co(t,e).update(r).digest();xr.create=(t,e)=>new co(t,e);var Nu=(t,e)=>(t+(t>=0?e:-e)/Uu)/e;function $d(t,e,r){let[[n,o],[s,i]]=e,a=Nu(i*t,r),c=Nu(-o*t,r),u=t-a*n-c*s,l=-a*o-c*i,f=u<ut,p=l<ut;f&&(u=-u),p&&(l=-l);let m=Jr(Math.ceil(Ws(r)/2))+Er;if(u<ut||u>=m||l<ut||l>=m)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:p,k2:l}}function Ri(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Ti(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return at(r.lowS,"lowS"),at(r.prehash,"prehash"),r.format!==void 0&&Ri(r.format),r}var Pi=class extends Error{constructor(e=""){super(e)}},Lt={Err:Pi,_tlv:{encode:(t,e)=>{let{Err:r}=Lt;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,o=Zr(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?Zr(o.length/2|128):"";return Zr(t)+s+o+e},decode(t,e){let{Err:r}=Lt,n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let o=e[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=e.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 l of u)i=i<<8|l;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(t){let{Err:e}=Lt;if(t<ut)throw new e("integer: negative integers are not allowed");let r=Zr(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=Lt;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return fr(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=Lt,o=F(t,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(t){let{_tlv:e,_int:r}=Lt,n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),s=n+o;return e.encode(48,s)}},ut=BigInt(0),Er=BigInt(1),Uu=BigInt(2),uo=BigInt(3),qd=BigInt(4);function Mu(t,e={}){let r=Zn("weierstrass",t,e),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i,n:a}=s;Qe(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;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=ku(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(T,w,g){let{x:y,y:C}=w.toAffine(),I=n.toBytes(y);if(at(g,"isCompressed"),g){l();let L=!n.isOdd(C);return Pe(Ku(L),I)}else return Pe(Uint8Array.of(4),I,n.toBytes(C))}function p(T){F(T,void 0,"Point");let{publicKey:w,publicKeyUncompressed:g}=u,y=T.length,C=T[0],I=T.subarray(1);if(y===w&&(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=E(L),B;try{B=n.sqrt(S)}catch(z){let W=z instanceof Error?": "+z.message:"";throw new Error("bad point: is not on curve, sqrt error"+W)}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=${w} or uncompressed=${g}`)}let m=e.toBytes||f,d=e.fromBytes||p;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,uo),qd),A=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(b,A)))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 v))throw new Error("Weierstrass Point expected")}function M(T){if(!c||!c.basises)throw new Error("no endo");return $d(T,c.basises,o.ORDER)}let O=lr((T,w)=>{let{X:g,Y:y,Z:C}=T;if(n.eql(C,n.ONE))return{x:g,y};let I=T.is0();w==null&&(w=I?n.ONE:n.inv(C));let L=n.mul(g,w),S=n.mul(y,w),B=n.mul(C,w);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=lr(T=>{if(T.is0()){if(e.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 v(n.mul(g.X,T),g.Y,g.Z),w=tn(y,w),g=tn(C,g),w.add(g)}class v{static BASE=new v(s.Gx,s.Gy,n.ONE);static ZERO=new v(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 v)throw new Error("projective point not allowed");return n.is0(g)&&n.is0(y)?v.ZERO:new v(g,y,n.ONE)}static fromBytes(w){let g=v.fromAffine(d(F(w,void 0,"point")));return g.assertValidity(),g}static fromHex(w){return v.fromBytes(st(w))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,g=!0){return K.createCache(this,w),g||this.multiply(uo),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:I,Y:L,Z:S}=w,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 v(this.X,n.neg(this.Y),this.Z)}double(){let{a:w,b:g}=s,y=n.mul(g,uo),{X:C,Y:I,Z:L}=this,S=n.ZERO,B=n.ZERO,R=n.ZERO,P=n.mul(C,C),z=n.mul(I,I),W=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(w,R),B=n.mul(y,W),B=n.add(S,B),S=n.sub(z,B),B=n.add(z,B),B=n.mul(S,B),S=n.mul(V,S),R=n.mul(y,R),W=n.mul(w,W),V=n.sub(P,W),V=n.mul(w,V),V=n.add(V,R),R=n.add(P,P),P=n.add(R,P),P=n.add(P,W),P=n.mul(P,V),B=n.add(B,P),W=n.mul(I,L),W=n.add(W,W),P=n.mul(W,V),S=n.sub(S,P),R=n.mul(W,z),R=n.add(R,R),R=n.add(R,R),new v(S,B,R)}add(w){D(w);let{X:g,Y:y,Z:C}=this,{X:I,Y:L,Z:S}=w,B=n.ZERO,R=n.ZERO,P=n.ZERO,z=s.a,W=n.mul(s.b,uo),V=n.mul(g,I),X=n.mul(y,L),te=n.mul(C,S),ue=n.add(g,y),Z=n.add(I,L);ue=n.mul(ue,Z),Z=n.add(V,X),ue=n.sub(ue,Z),Z=n.add(g,C);let le=n.add(I,S);return Z=n.mul(Z,le),le=n.add(V,te),Z=n.sub(Z,le),le=n.add(y,C),B=n.add(L,S),le=n.mul(le,B),B=n.add(X,te),le=n.sub(le,B),P=n.mul(z,Z),B=n.mul(W,te),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),te=n.mul(z,te),Z=n.mul(W,Z),X=n.add(X,te),te=n.sub(V,te),te=n.mul(z,te),Z=n.add(Z,te),V=n.mul(X,Z),R=n.add(R,V),V=n.mul(le,Z),B=n.mul(ue,B),B=n.sub(B,V),V=n.mul(ue,X),P=n.mul(le,P),P=n.add(P,V),new v(B,R,P)}subtract(w){return this.add(w.negate())}is0(){return this.equals(v.ZERO)}multiply(w){let{endo:g}=e;if(!o.isValidNot0(w))throw new Error("invalid scalar: out of range");let y,C,I=L=>K.cached(this,L,S=>Vt(v,S));if(g){let{k1neg:L,k1:S,k2neg:B,k2:R}=M(w),{p:P,f:z}=I(S),{p:W,f:V}=I(R);C=z.add(V),y=_(g.beta,P,W,L,B)}else{let{p:L,f:S}=I(w);y=L,C=S}return Vt(v,[y,C])[0]}multiplyUnsafe(w){let{endo:g}=e,y=this;if(!o.isValid(w))throw new Error("invalid scalar: out of range");if(w===ut||y.is0())return v.ZERO;if(w===Er)return y;if(K.hasCache(this))return this.multiply(w);if(g){let{k1neg:C,k1:I,k2neg:L,k2:S}=M(w),{p1:B,p2:R}=au(v,y,I,S);return _(g.beta,B,R,C,L)}else return K.unsafe(y,w)}toAffine(w){return O(this,w)}isTorsionFree(){let{isTorsionFree:w}=e;return i===Er?!0:w?w(v,this):K.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:w}=e;return i===Er?this:w?w(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(w=!0){return at(w,"isCompressed"),this.assertValidity(),m(v,this,w)}toHex(w=!0){return ot(this.toBytes(w))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=o.BITS,K=new pr(v,e.endo?Math.ceil(N/2):N);return v.BASE.precompute(8),v}function Ku(t){return Uint8Array.of(t?2:3)}function ku(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Wd(t,e={}){let{Fn:r}=t,n=e.randomBytes||xt,o=Object.assign(ku(t.Fp,r),{seed:Xs(r.ORDER)});function s(m){try{let d=r.fromBytes(m);return r.isValidNot0(d)}catch{return!1}}function i(m,d){let{publicKey:E,publicKeyUncompressed:h}=o;try{let b=m.length;return d===!0&&b!==E||d===!1&&b!==h?!1:!!t.fromBytes(m)}catch{return!1}}function a(m=n(o.seed)){return Ys(F(m,o.seed,"seed"),r.ORDER)}function c(m,d=!0){return t.BASE.multiply(r.fromBytes(m)).toBytes(d)}function u(m){let{secretKey:d,publicKey:E,publicKeyUncompressed:h}=o;if(!Nt(m)||"_lengths"in r&&r._lengths||d===E)return;let b=F(m,void 0,"key").length;return b===E||b===h}function l(m,d,E=!0){if(u(m)===!0)throw new Error("first arg must be private key");if(u(d)===!1)throw new Error("second arg must be public key");let h=r.fromBytes(m);return t.fromBytes(d).multiply(h).toBytes(E)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},p=mr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:p,Point:t,utils:f,lengths:o})}function Hu(t,e,r={}){Ut(e),Qe(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes||xt,o=r.hmac||((g,y)=>xr(e,g,y)),{Fp:s,Fn:i}=t,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:l,getSharedSecret:f,utils:p,lengths:m}=Wd(t,r),d={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},E=a*Uu<s.ORDER;function h(g){let y=a>>Er;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 A(){if(E)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function x(g,y){Ri(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(A(),![0,1,2,3].includes(I))throw new Error("invalid recovery id");this.recovery=I}Object.freeze(this)}static fromBytes(y,C=d.format){x(y,C);let I;if(C==="der"){let{r:R,s:P}=Lt.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(st(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=t.fromBytes(Pe(Ku((L&1)===0),B)),P=i.inv(S),z=O(F(y,void 0,"msgHash")),W=i.create(-z*P),V=i.create(I*P),X=t.BASE.multiplyUnsafe(W).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=d.format){if(Ri(y),y==="der")return st(Lt.hexFromSig(this));let{r:C,s:I}=this,L=i.toBytes(C),S=i.toBytes(I);return y==="recovered"?(A(),Pe(Uint8Array.of(this.assertRecovery()),L,S)):Pe(L,S)}toHex(y){return ot(this.toBytes(y))}}let M=r.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");let C=fr(y),I=y.length*8-c;return I>0?C>>BigInt(I):C},O=r.bits2int_modN||function(y){return i.create(M(y))},k=Jr(c);function _(g){return At("num < 2^"+c,g,ut,k),i.toBytes(g)}function v(g,y){return F(g,void 0,"message"),y?F(e(g),void 0,"prehashed message"):g}function N(g,y,C){let{lowS:I,prehash:L,extraEntropy:S}=Ti(C,d);g=v(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 z=Pe(...P),W=B;function V(X){let te=M(X);if(!i.isValidNot0(te))return;let ue=i.inv(te),Z=t.BASE.multiply(te).toAffine(),le=i.create(Z.x);if(le===ut)return;let Jt=i.create(ue*i.create(W+le*R));if(Jt===ut)return;let Dn=(Z.x===le?0:2)|Number(Z.y&Er),kr=Jt;return I&&h(Jt)&&(kr=i.neg(Jt),Dn^=1),new D(le,kr,E?void 0:Dn)}return{seed:z,k2sig:V}}function K(g,y,C={}){let{seed:I,k2sig:L}=N(g,y,C);return qc(e.outputLen,i.BYTES,o)(I,L).toBytes(C.format)}function T(g,y,C,I={}){let{lowS:L,prehash:S,format:B}=Ti(I,d);if(C=F(C,void 0,"publicKey"),y=v(y,S),!Nt(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=t.fromBytes(C);if(L&&R.hasHighS())return!1;let{r:z,s:W}=R,V=O(y),X=i.inv(W),te=i.create(V*X),ue=i.create(z*X),Z=t.BASE.multiplyUnsafe(te).add(P.multiplyUnsafe(ue));return Z.is0()?!1:i.create(Z.x)===z}catch{return!1}}function w(g,y,C={}){let{prehash:I}=Ti(C,d);return y=v(y,I),D.fromBytes(g,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:f,utils:p,lengths:m,Point:t,sign:K,verify:T,recoverPublicKey:w,Signature:D,hash:e})}var Ni={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Gd={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Fu=BigInt(2);function zd(t){let e=Ni.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,f=oe(l,r,e)*l%e,p=oe(f,r,e)*l%e,m=oe(p,Fu,e)*u%e,d=oe(m,o,e)*m%e,E=oe(d,s,e)*d%e,h=oe(E,a,e)*E%e,b=oe(h,c,e)*h%e,A=oe(b,a,e)*E%e,x=oe(A,r,e)*l%e,D=oe(x,i,e)*d%e,M=oe(D,n,e)*u%e,O=oe(M,Fu,e);if(!Oi.eql(Oi.sqr(O),t))throw new Error("Cannot find square root");return O}var Oi=hr(Ni.p,{sqrt:zd}),jd=Mu(Ni,{Fp:Oi,endo:Gd}),Sr=Hu(jd,Ye);function Vu(t,e,r,n){let o=tt.digest(r instanceof Uint8Array?r:r.subarray());if(ro(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Sr.verify(e,s,t,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new on(String(s))});try{return n?.signal?.throwIfAborted(),Sr.verify(e,o.digest,t,{prehash:!1,format:"der"})}catch(s){throw new on(String(s))}}var fo=class{type="secp256k1";raw;_key;constructor(e){this._key=qu(e),this.raw=$u(this._key)}toMultihash(){return Fe.digest(wt(this))}toCID(){return he.createV1(114,this.toMultihash())}toString(){return ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}verify(e,r,n){return Vu(this._key,r,e,n)}};function Ui(t){return new fo(t)}function $u(t){return Sr.Point.fromBytes(t).toBytes()}function qu(t){try{return Sr.Point.fromBytes(t),t}catch(e){throw new er(String(e))}}function hn(t,e){let{Type:r,Data:n}=Je.decode(t),o=n??new Uint8Array;switch(r){case fe.RSA:return Ii(o,e);case fe.Ed25519:return ni(o);case fe.secp256k1:return Ui(o);case fe.ECDSA:return Os(o);default:throw new Rt}}function Wu(t){let{Type:e,Data:r}=Je.decode(t.digest),n=r??new Uint8Array;switch(e){case fe.Ed25519:return ni(n);case fe.secp256k1:return Ui(n);case fe.ECDSA:return Os(n);default:throw new Rt}}function wt(t){return Je.encode({Type:fe[t.type],Data:t.raw})}var Gu=Symbol.for("nodejs.util.inspect.custom"),Xd=114,dn=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[is]=!0;toString(){return this.string==null&&(this.string=ce.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return he.createV1(Xd,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return we(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return we(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Gu](){return`PeerId(${this.toString()})`}},pn=class extends dn{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},mn=class extends dn{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},gn=class extends dn{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Yd=2336,yn=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Fe.digest(j(this.url))}[Gu](){return`PeerId(${this.url})`}[is]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return he.createV1(Yd,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=$(e)),e.toString()===this.toString())}};var Zd=114,zu=2336;function vr(t,e){let r;if(t.charAt(0)==="1"||t.charAt(0)==="Q")r=ar(ce.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return Qd(he.parse(t));if(e==null)throw new Y('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=ar(e.decode(t))}return ju(r)}function Mi(t){if(t.type==="Ed25519")return new mn({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new gn({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new pn({multihash:t.toCID().multihash,publicKey:t});throw new Rt}function ju(t){if(ep(t))return new pn({multihash:t});if(Jd(t))try{let e=Wu(t);if(e.type==="Ed25519")return new mn({multihash:t,publicKey:e});if(e.type==="secp256k1")return new gn({multihash:t,publicKey:e})}catch{let r=$(t.digest);return new yn(new URL(r))}throw new Mn("Supplied PeerID Multihash is invalid")}function Qd(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==Zd&&t.code!==zu)throw new Un("Supplied PeerID CID is invalid");if(t.code===zu){let e=$(t.multihash.digest);return new yn(new URL(e))}return ju(t.multihash)}function Jd(t){return t.code===Fe.code}function ep(t){return t.code===tt.code}var Ee=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ft=class extends Error{static name="ValidationError";name="ValidationError"},lo=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},ho=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var po=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let r=this.index,n=e();return n===void 0&&(this.index=r),n}parseWith(e){let r=e();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(e){return this.readAtomically(()=>{let r=this.readChar();if(r===e)return r})}readSeparator(e,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,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 l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let p=Number.parseInt(f,e);if(!Number.isNaN(p))return p});if(l===void 0)break;if(s*=e,s+=l,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 e=new Uint8Array(4);for(let r=0;r<e.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[r]=n}return e})}readIPv6Addr(){let e=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]=e(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]=e(s.subarray(0,i));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var tp=45,rp=15,mo=new po;function Xu(t){if(!(t.length>rp))return mo.new(t).parseWith(()=>mo.readIPv4Addr())}function Yu(t){if(t.includes("%")&&(t=t.split("%")[0]),!(t.length>tp))return mo.new(t).parseWith(()=>mo.readIPv6Addr())}function go(t){return!!Xu(t)}function Zu(t){return!!Yu(t)}function ki(t){return e=>$(e,t)}function Hi(t){return e=>j(e,t)}function Ar(t){return new DataView(t.buffer).getUint16(t.byteOffset).toString()}function Gt(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof t=="string"?parseInt(t):t),new Uint8Array(e)}function Qu(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let r=j(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Gt(n);return De([r,o],r.length+o.length)}function Ju(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let r=yt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Gt(n);return De([r,o],r.length+o.length)}function Fi(t){let e=t.subarray(0,t.length-2),r=t.subarray(t.length-2),n=$(e,"base32"),o=Ar(r);return`${n}:${o}`}var Vi=function(t){t=t.toString().trim();let e=new Uint8Array(4);return t.split(/\./g).forEach((r,n)=>{let o=parseInt(r,10);if(isNaN(o)||o<0||o>255)throw new Ee("Invalid byte value in IP address");e[n]=o}),e},ef=function(t){let e=0;t=t.toString().trim();let r=t.split(":",8),n;for(n=0;n<r.length;n++){let s=go(r[n]),i;s&&(i=Vi(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(e+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 Ee("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},tf=function(t){if(t.byteLength!==4)throw new Ee("IPv4 address was incorrect length");let e=[];for(let r=0;r<t.byteLength;r++)e.push(t[r]);return e.join(".")},rf=function(t){if(t.byteLength!==16)throw new Ee("IPv6 address was incorrect length");let e=[];for(let n=0;n<t.byteLength;n+=2){let o=t[n],s=t[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let r=e.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Ee(`Invalid IPv6 address "${r}"`)}};function nf(t){try{let e=new URL(`http://[${t}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ee(`Invalid IPv6 address "${t}"`)}}var Ki=Object.values(Ot).map(t=>t.decoder),np=(function(){let t=Ki[0].or(Ki[1]);return Ki.slice(2).forEach(e=>t=t.or(e)),t})();function of(t){return np.decode(t)}function sf(t){return e=>t.encoder.encode(e)}function op(t){if(parseInt(t).toString()!==t)throw new ft("Value must be an integer")}function sp(t){if(t<0)throw new ft("Value must be a positive integer, or zero")}function ip(t){return e=>{if(e>t)throw new ft(`Value must be smaller than or equal to ${t}`)}}function ap(...t){return e=>{for(let r of t)r(e)}}var bn=ap(op,sp,ip(65535));var ye=-1,$i=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let r;if(typeof e=="string"?r=this.protocolsByName.get(e):r=this.protocolsByCode.get(e),r==null)throw new ho(`Protocol ${e} was unknown`);return r}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(r=>{this.protocolsByName.set(r,e)})}removeProtocol(e){let r=this.protocolsByCode.get(e);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},lt=new $i,Sp=[{code:4,name:"ip4",size:32,valueToBytes:Vi,bytesToValue:tf,validate:t=>{if(!go(t))throw new ft(`Invalid IPv4 address "${t}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Gt,bytesToValue:Ar,validate:bn},{code:273,name:"udp",size:16,valueToBytes:Gt,bytesToValue:Ar,validate:bn},{code:33,name:"dccp",size:16,valueToBytes:Gt,bytesToValue:Ar,validate:bn},{code:41,name:"ip6",size:128,valueToBytes:ef,bytesToValue:rf,stringToValue:nf,validate:t=>{if(!Zu(t))throw new ft(`Invalid IPv6 address "${t}"`)}},{code:42,name:"ip6zone",size:ye},{code:43,name:"ipcidr",size:8,bytesToValue:ki("base10"),valueToBytes:Hi("base10")},{code:53,name:"dns",size:ye},{code:54,name:"dns4",size:ye},{code:55,name:"dns6",size:ye},{code:56,name:"dnsaddr",size:ye},{code:132,name:"sctp",size:16,valueToBytes:Gt,bytesToValue:Ar,validate:bn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ye,stringToValue:t=>decodeURIComponent(t),valueToString:t=>encodeURIComponent(t)},{code:421,name:"p2p",aliases:["ipfs"],size:ye,bytesToValue:ki("base58btc"),valueToBytes:t=>t.startsWith("Q")||t.startsWith("1")?Hi("base58btc")(t):he.parse(t).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Fi,valueToBytes:Qu},{code:445,name:"onion3",size:296,bytesToValue:Fi,valueToBytes:Ju},{code:446,name:"garlic64",size:ye},{code:447,name:"garlic32",size:ye},{code:448,name:"tls"},{code:449,name:"sni",size:ye},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ye,bytesToValue:sf(Wr),valueToBytes:of},{code:480,name:"http"},{code:481,name:"http-path",size:ye,stringToValue:t=>`/${decodeURIComponent(t)}`,valueToString:t=>encodeURIComponent(t.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:ye}];Sp.forEach(t=>{lt.addProtocol(t)});function af(t){let e=[],r=0;for(;r<t.length;){let n=ct(t,r),o=lt.getProtocol(n),s=se(n),i=vp(o,t,r+s),a=0;i>0&&o.size===ye&&(a=se(i));let c=s+a+i,u={code:n,name:o.name,bytes:t.subarray(r,r+c)};if(i>0){let l=r+s+a,f=t.subarray(l,l+i);u.value=o.bytesToValue?.(f)??$(f)}e.push(u),r+=c}return e}function cf(t){let e=0,r=[];for(let n of t){if(n.bytes==null){let o=lt.getProtocol(n.code),s=se(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??j(n.value),a=i.byteLength,o.size===ye&&(c=se(a)));let u=new Uint8Array(s+c+a),l=0;yr(n.code,u,l),l+=s,i!=null&&(o.size===ye&&(yr(a,u,l),l+=c),u.set(i,l)),n.bytes=u}r.push(n.bytes),e+=n.bytes.byteLength}return De(r,e)}function uf(t){if(t.charAt(0)!=="/")throw new Ee('String multiaddr must start with "/"');let e=[],r="protocol",n="",o="";for(let s=1;s<t.length;s++){let i=t.charAt(s);i!=="/"&&(r==="protocol"?o+=t.charAt(s):n+=t.charAt(s));let a=s===t.length-1;if(i==="/"||a){let c=lt.getProtocol(o);if(r==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",r="protocol";continue}else if(a)throw new Ee(`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 Ee(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",o="",r="protocol"}}}if(o!==""&&n!=="")throw new Ee("Incomplete multiaddr");return e}function ff(t){return`/${t.flatMap(e=>{if(e.value==null)return e.name;let r=lt.getProtocol(e.code);if(r==null)throw new Ee(`Unknown protocol code ${e.code}`);return[e.name,r.valueToString?.(e.value)??e.value]}).join("/")}`}function vp(t,e,r){return t.size==null||t.size===0?0:t.size>0?t.size/8:ct(e,r)}var Ap=Symbol.for("nodejs.util.inspect.custom"),ia=Symbol.for("@multiformats/multiaddr");function Cp(t){if(t==null&&(t="/"),lf(t))return t.getComponents();if(t instanceof Uint8Array)return af(t);if(typeof t=="string")return t=t.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),t===""&&(t="/"),uf(t);if(Array.isArray(t))return t;throw new Ee("Must be a string, Uint8Array, Component[], or another Multiaddr")}var xo=class t{[ia]=!0;#e;#t;#r;constructor(e="/",r={}){this.#e=Cp(e),r.validate!==!1&&_p(this)}get bytes(){return this.#r==null&&(this.#r=cf(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=ff(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let r=new t(e);return new t([...this.#e,...r.getComponents()],{validate:!1})}decapsulate(e){let r=e.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new lo(`Address ${this.toString()} does not contain subaddress: ${r}`);return new t(n.slice(0,o),{validate:!1})}decapsulateCode(e){let r;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){r=n;break}return new t(this.#e.slice(0,r),{validate:!1})}equals(e){return we(this.bytes,e.bytes)}[Ap](){return`Multiaddr(${this.toString()})`}};function _p(t){t.getComponents().forEach(e=>{let r=lt.getProtocol(e.code);e.value!=null&&r.validate?.(e.value)})}function lf(t){return!!t?.[ia]}function Ir(t){return new xo(t)}var re=t=>({match:e=>{let r=e[0];return r==null||r.code!==t||r.value!=null?!1:e.slice(1)}}),H=(t,e)=>({match:r=>{let n=r[0];return n?.code!==t||n.value==null||e!=null&&n.value!==e?!1:r.slice(1)}}),hf=t=>({match:e=>t.match(e)===!1?e:!1}),G=t=>({match:e=>{let r=t.match(e);return r===!1?e:r}}),_e=(...t)=>({match:e=>{let r;for(let n of t){let o=n.match(e);o!==!1&&(r==null||o.length<r.length)&&(r=o)}return r??!1}}),ee=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e}});function ne(...t){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of t){let a=i.match(s);if(a===!1)return!1;s=a}return s}function r(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:t,matches:r,exactMatch:n}}var Lp=H(421),qx=ne(Lp),So=H(54),vo=H(55),Ao=H(56),ca=H(53),Wx=ne(So,G(H(421))),Gx=ne(vo,G(H(421))),zx=ne(Ao,G(H(421))),jx=ne(_e(ca,Ao,So,vo),G(H(421))),df=ee(H(4),G(H(43))),pf=ee(G(H(42)),H(41),G(H(43))),ua=_e(df,pf),Xt=_e(ua,ca,So,vo,Ao),Xx=ne(_e(ua,ee(_e(ca,Ao,So,vo),G(H(421))))),Yx=ne(df),Zx=ne(pf),Qx=ne(ua),fa=ee(Xt,H(6)),wn=ee(Xt,H(273)),Jx=ne(ee(fa,G(H(421)))),e1=ne(wn),la=ee(wn,re(460),G(H(421))),Co=ee(wn,re(461),G(H(421))),Ip=_e(la,Co),t1=ne(la),r1=ne(Co),aa=_e(Xt,fa,wn,la,Co),mf=_e(ee(aa,re(477),G(H(421)))),n1=ne(mf),gf=_e(ee(aa,re(478),G(H(421))),ee(aa,re(448),G(H(449)),re(477),G(H(421)))),o1=ne(gf),yf=ee(wn,re(280),G(H(466)),G(H(466)),G(H(421))),bf=ne(yf),wf=ee(Co,re(465),G(H(466)),G(H(466)),G(H(421))),s1=ne(wf),Eo=_e(mf,gf,ee(fa,G(H(421))),ee(Ip,G(H(421))),ee(Xt,G(H(421))),yf,wf,H(421)),xf=ne(Eo),Bp=ee(G(Eo),re(290),hf(re(281)),G(H(421))),i1=ne(Bp),Dp=_e(ee(Eo,re(290),re(281),G(H(421))),ee(Eo,re(281),G(H(421))),ee(re(281),G(H(421)))),Ef=ne(Dp),Tp=_e(ee(Xt,H(6),re(480),G(H(421))),ee(Xt,re(480),G(H(421)))),a1=ne(Tp),Rp=ee(Xt,_e(ee(H(6,"443"),re(480)),ee(H(6),re(443)),ee(H(6),re(448),re(480)),ee(re(448),re(480)),re(448),re(443)),G(H(421))),c1=ne(Rp),Pp=_e(ee(H(777),G(H(421)))),u1=ne(Pp),Op=_e(ee(H(400),G(H(421)))),f1=ne(Op);var Le;(function(t){let e;(function(o){o.FIN="FIN",o.STOP_SENDING="STOP_SENDING",o.RESET="RESET",o.FIN_ACK="FIN_ACK"})(e=t.Flag||(t.Flag={}));let r;(function(o){o[o.FIN=0]="FIN",o[o.STOP_SENDING=1]="STOP_SENDING",o[o.RESET=2]="RESET",o[o.FIN_ACK=3]="FIN_ACK"})(r||(r={})),(function(o){o.codec=()=>Wt(r)})(e=t.Flag||(t.Flag={}));let n;t.codec=()=>(n==null&&(n=ze((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.flag!=null&&(s.uint32(8),t.Flag.codec().encode(o.flag,s)),o.message!=null&&(s.uint32(18),s.bytes(o.message)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{a.flag=t.Flag.codec().decode(o);break}case 2:{a.message=o.bytes();break}default:{o.skipType(u&7);break}}}return a})),n),t.encode=o=>Ge(o,t.codec()),t.decode=(o,s)=>We(o,t.codec(),s)})(Le||(Le={}));var Sf=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],ha=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),vf="libp2p+webrtc+v1/",Af=2*1024*1024,Br=16*1024;function Np(t=Br){let e=se(t-se(t)),r=1+se(Object.keys(Le.Flag).length-1),n=1,o=t-e-r-n,s=se(o);return e+r+n+s}var Cf=Np();var _f=1e4,da="/webrtc",xn="/webrtc-signaling/0.0.1";function pa(t){let e=t.getComponents(),r={},n=0;if(e[n]?.name==="ip6zone"&&(r.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(r.type=e[n].name,r.host=e[n].value,n++):e[n].name==="dnsaddr"&&(r.type=e[n].name,r.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(r.protocol=e[n].name==="tcp"?"tcp":"udp",r.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(r.type==="ip4"?r.cidr=parseInt(`${e[n].value}`):r.type==="ip6"&&(r.cidr=`${e[n].value}`),n++),r.type==null||r.host==null)throw new Y(`Multiaddr ${t} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(r.sni=e[n+1].value,n+=2),r}function _o(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var Lo=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Dr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Lo(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new Lo(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var ma=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Tr(t={}){return Up(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function Up(t,e){e=e??{};let r=e.onEnd,n=new Dr,o,s,i,a=_o(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,b)=>{s=A=>{s=null,n.push(A);try{h(t(n))}catch(x){b(x)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=_o()})}},u=h=>s!=null?s(h):(n.push(h),o),l=h=>(n=new Dr,s!=null?s({error:h}):(n.push({error:h}),o)),f=h=>{if(i)return o;if(e?.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})},p=h=>i?o:(i=!0,h!=null?l(h):u({done:!0})),m=()=>(n=new Dr,p(),{done:!0}),d=h=>(p(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:d,push:f,end:p,get readableLength(){return n.size},onEmpty:async h=>{let b=h?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let A,x;b!=null&&(A=new Promise((D,M)=>{x=()=>{M(new ma)},b.addEventListener("abort",x)}));try{await Promise.race([a.promise,A])}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:f,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 ga=class t extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,t)}},Lf=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function ya(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,l=new Promise((f,p)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){p(Lf(i));return}if(i&&(c=()=>{p(Lf(i))},i.addEventListener("abort",c,{once:!0})),t.then(f,p),r===Number.POSITIVE_INFINITY)return;let m=new ga;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(d){p(d)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?f():o instanceof Error?p(o):(m.message=o??`Promise timed out after ${r} milliseconds`,p(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 Mp=t=>{let e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function Kp(t,e,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=[e].flat(),c=[],{addListener:u,removeListener:l}=Mp(t),f=async(...m)=>{let d=r.multiArgs?m:m[0];if(r.filter)try{if(!await r.filter(d))return}catch(E){n(),i(E);return}c.push(d),r.count===c.length&&(n(),s(c))},p=(...m)=>{n(),i(r.rejectionMultiArgs?m:m[0])};n=()=>{for(let m of a)l(m,f);for(let m of r.rejectionEvents)a.includes(m)||l(m,p)};for(let m of a)u(m,f);for(let m of r.rejectionEvents)a.includes(m)||u(m,p);r.signal&&r.signal.addEventListener("abort",()=>{p(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){let s=ya(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Se(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Kp(t,e,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var Yt=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},Io=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},Bo=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function kp(t){return t.reason}async function ht(t,e,r){if(e==null)return t;let n=r?.translateError??kp;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([t,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Hp=Math.pow(2,20)*4,Bt=class extends mt{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??Hp,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new q,this.writeBuffer=new q,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 Bo)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),ht(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Tr(),r=s=>{e.push(s.data)};this.addEventListener("message",r);let n=s=>{e.end(s.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new je(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new Hn(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new je("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 je("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new je(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new je(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new tr;this.dispatchEvent(new Fn(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new rr))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,r=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let s=this.writeBuffer.sublist(0,o),i=new q(s);this.writeBuffer.consume(s.byteLength);let a=this.sendData(s);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,r,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new kn(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Hr(`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 Hr(`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 Do=class extends Bt{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",r=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),r.error!=null?r.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):r.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Se(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Se(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function If(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var To=class extends mt{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,r){super(),this.maConn=e,this.protocol=r.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.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(e){let r=this.maConn.send(e);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(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await ht(Promise.all([...this.streams].map(async r=>{await r.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(r=>{r.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(r=>{r.onTransportClosed(e)})}catch(r){this.abort(r)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new On;let r=this.onCreateStream({...this.streamOptions,...e});return If(r)&&(r=await r),this.streams.push(r),this.cleanUpStream(r),r}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new Io(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let r=n=>{let o=this.streams.findIndex(s=>s===e);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",r),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(r=>{this.safeDispatchEvent("stream",{detail:r})}),this.earlyStreams=[]})}};var Ro=class extends Bt{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){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 Se(this,"idle",{...e,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 Se(this,"drain",{...e,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(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};var Fp=4194304,Po=class extends Error{static name="UnwrappedError";name="UnwrappedError"},En=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},wa=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},xa=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Vp(t){return typeof t?.closeRead=="function"}function $p(t){return typeof t?.close=="function"}function ba(t){return Vp(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:$p(t)?t.status!=="open":!1}function qp(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function Wp(t,e){let r=e?.maxBufferSize??Fp,n=new q,o,s=!1;if(!qp(t))throw new Y("Argument should be a Stream or a Multiaddr");let i=l=>{if(n.append(l.data),n.byteLength>r){let f=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${f} > ${r}`))}o?.resolve()};t.addEventListener("message",i);let a=l=>{l.error!=null?o?.reject(l.error):o?.resolve()};t.addEventListener("close",a);let c=()=>{o?.resolve()};t.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(l){if(s===!0)throw new Po("Stream was unwrapped");if(ba(t)){if(n.byteLength===0&&l?.bytes==null)return null;if(l?.bytes!=null&&n.byteLength<l.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,l.bytes),new Yt(`Unexpected EOF - stream closed after reading ${n.byteLength}/${l.bytes} bytes`)}let f=l?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=f){o.resolve();break}if(await ht(o.promise,l?.signal),ba(t)){if(n.byteLength===0&&l?.bytes==null)return null;break}o=Promise.withResolvers()}let p=l?.bytes??n.byteLength;if(n.byteLength<p){if(ba(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,p),new Yt(`Unexpected EOF - stream closed while reading ${n.byteLength}/${p} bytes`);return u.read(l)}let m=n.sublist(0,p);return n.consume(p),m},async write(l,f){if(s===!0)throw new Po("Stream was unwrapped");t.send(l)||await Se(t,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",i),t.removeEventListener("close",a),t.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.push(n))),t}};return u}function Oo(t,e={}){let r=Wp(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=se(e.maxDataLength));let n=e?.lengthDecoder??ct,o=e?.lengthEncoder??oo;return{async read(i){let a=-1,c=new q;for(;;){let l=await r.read({...i,bytes:1});if(l==null)break;c.append(l);try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new En("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new xa(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new wa(`Message length too long - ${a} > ${e.maxDataLength}`);let u=await r.read({...i,bytes:a});if(u==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new Yt(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(u.byteLength!==a)throw t.log.error("read %d/%d bytes before the stream closed",u.byteLength,a),new Yt(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await r.write(new q(o(i.byteLength),i),a)},async writeV(i,a){let c=new q(...i.flatMap(u=>[o(u.byteLength),u]));await r.write(c,a)},unwrap(){return r.unwrap()}}}function No(t,e){let r=Oo(t,e),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 Gp=1024*1024*4,zp=1024*1024*4,Uo=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new q,this.maxBufferSize=e.maxBufferSize??Gp,this.maxDataLength=e.maxDataLength??zp,this.lengthDecoder=e.lengthDecoder??ct,this.encodingLength=e.encodingLength??se}*decode(e){if(this.buffer.append(e),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 En("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 Mo=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Rr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ko=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Sn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ko(t){return t[Symbol.asyncIterator]!=null}function Bf(t,e){if(t.byteLength>e)throw new Rr("Message length too long")}var Fo=t=>{let e=se(t),r=pe(e);return oo(t,r),Fo.bytes=e,r};Fo.bytes=0;function vn(t,e){e=e??{};let r=e.lengthEncoder??Fo,n=e?.maxDataLength??4194304;function*o(s){Bf(s,n);let i=r(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return ko(t)?(async function*(){for await(let s of t)yield*o(s)})():(function*(){for(let s of t)yield*o(s)})()}vn.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??Fo,n=e?.maxDataLength??4194304;return Bf(t,n),new q(r(t.byteLength),t)};var Zt;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(Zt||(Zt={}));var Ea=t=>{let e=ct(t);return Ea.bytes=se(e),e};Ea.bytes=0;function An(t,e){let r=new q,n=Zt.LENGTH,o=-1,s=e?.lengthDecoder??Ea,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===Zt.LENGTH)try{if(o=s(r),o<0)throw new Mo("Invalid message length");if(o>a)throw new Rr("Message length too long");let u=s.bytes;r.consume(u),e?.onLength!=null&&e.onLength(o),n=Zt.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>i)throw new Ko("Message length length too long");break}throw u}if(n===Zt.DATA){if(r.byteLength<o)break;let u=r.sublist(0,o);r.consume(o),e?.onData!=null&&e.onData(u),yield u,n=Zt.LENGTH}}}return ko(t)?(async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw new Sn("Unexpected end of input")})():(function*(){for(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw new Sn("Unexpected end of input")})()}An.fromReader=(t,e)=>{let r=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await t.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 An(n,{...e??{},onLength:s=>{r=s}})};var Df=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,s;n<o;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))},Yp=(function(){function t(e,r,n){this.name=e,this.version=r,this.os=n,this.type="browser"}return t})();var Zp=(function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t})();var Qp=(function(){function t(e,r,n,o){this.name=e,this.version=r,this.os=n,this.bot=o,this.type="bot-device"}return t})();var Jp=(function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t})();var em=(function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t})();var tm=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,rm=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Tf=3,nm=[["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",tm]],Rf=[["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 Of(t){return t?Pf(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new em:typeof navigator<"u"?Pf(navigator.userAgent):im()}function om(t){return t!==""&&nm.reduce(function(e,r){var n=r[0],o=r[1];if(e)return e;var s=o.exec(t);return!!s&&[n,s]},!1)}function Pf(t){var e=om(t);if(!e)return null;var r=e[0],n=e[1];if(r==="searchbot")return new Jp;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<Tf&&(o=Df(Df([],o,!0),am(Tf-o.length),!0)):o=[];var s=o.join("."),i=sm(t),a=rm.exec(t);return a&&a[1]?new Qp(r,s,i,a[1]):new Yp(r,s,i)}function sm(t){for(var e=0,r=Rf.length;e<r;e++){var n=Rf[e],o=n[0],s=n[1],i=s.exec(t);if(i)return o}return null}function im(){var t=typeof process<"u"&&process.version;return t?new Zp(process.version.slice(1)):null}function am(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var Nf=Of(),Vo=Nf!=null&&Nf.name==="firefox";async function Sa(t){return t=t??{},typeof t=="function"&&(t=await t()),t.iceServers=t.iceServers??Sf.map(e=>({urls:[e]})),t}var Uf=(t=32)=>vf+[...Array(t)].map(()=>ha.at(Math.floor(Math.random()*ha.length))).join("");var va=class extends Ro{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(e){super({...e,maxMessageSize:(e.maxMessageSize??Br)-Cf}),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=Tr(),this.maxBufferedAmount=e.maxBufferedAmount??Af,this.finAckTimeout=e.finAckTimeout??_f,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 An(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),Se(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(e){if(this.channel.readyState!=="open")throw new je(`Invalid datachannel state - ${this.channel.readyState}`);if(this.log.trace('sending message, channel state "%s"',this.channel.readyState),Vo){this.channel.send(e.subarray());return}for(let r of e)this.channel.send(r)}sendData(e){return this.channel.readyState!=="open"?{sentBytes:0,canSendMore:!1}:(this._sendMessage(vn.single(Le.encode({message:e.subarray()}))),{sentBytes:e.byteLength,canSendMore:this.channel.bufferedAmount<this.maxBufferedAmount})}sendReset(e){try{this.log.error("sending reset - %e",e),this._sendFlag(Le.Flag.RESET),this.receivedFinAck?.reject(e)}catch(r){this.log.error("failed to send reset - %e",r)}}async sendCloseWrite(e){this._sendFlag(Le.Flag.FIN),e?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let r=e?.signal??AbortSignal.timeout(this.finAckTimeout),n=[Se(this.channel,"close",{signal:r}),Se(this.channel,"error",{signal:r})];await Promise.any([ht(this.receivedFinAck.promise,r),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(e){this._sendFlag(Le.Flag.STOP_SENDING),e?.signal?.throwIfAborted()}processIncomingProtobuf(e){let r=Le.decode(e);r.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new q(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===Le.Flag.FIN&&(this._sendFlag(Le.Flag.FIN_ACK),this.onRemoteCloseWrite()),r.flag===Le.Flag.RESET&&(this.receivedFinAck?.reject(new tr("The stream was reset")),this.onRemoteReset()),r.flag===Le.Flag.STOP_SENDING&&this.onRemoteCloseRead(),r.flag===Le.Flag.FIN_ACK&&this.receivedFinAck?.resolve())}_sendFlag(e){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',e.toString(),this.channel.readyState),!1;this.log.trace("sending flag %s",e.toString());let r=Le.encode({flag:e}),n=vn.single(r);try{return this._sendMessage(n),!0}catch(o){this.log.error("could not send flag %s - %e",e.toString(),o)}return!1}sendPause(){}sendResume(){}};function Cn(t){let{channel:e,direction:r,isHandshake:n}=t;return new va({...t,id:`${e.id}`,log:t.log.newScope(`${n===!0?"handshake":r}:${e.id}`),protocol:""})}var Dt=class{protocol;peerConnection;metrics;dataChannelOptions;earlyDataChannels;constructor(e){this.onEarlyDataChannel=this.onEarlyDataChannel.bind(this),this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??da,this.dataChannelOptions=e.dataChannelOptions??{},this.peerConnection.addEventListener("datachannel",this.onEarlyDataChannel),this.earlyDataChannels=[]}onEarlyDataChannel(e){this.earlyDataChannels.push(e.channel)}createStreamMuxer(e){return this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel),new Aa(e,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,earlyDataChannels:this.earlyDataChannels})}},Aa=class extends To{peerConnection;dataChannelOptions;constructor(e,r){super(e,{...r,name:"muxer"}),this.peerConnection=r.peerConnection,this.protocol=r.protocol??da,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(e){if(this.log("incoming datachannel with channel id %d, protocol %s and status %s",e.id,e.protocol,e.readyState),e.label==="init"){this.log.trace("closing init channel %d",e.id),e.close();return}let r=Cn({...this.streamOptions,...this.dataChannelOptions,channel:e,direction:"inbound",log:this.log});this.onRemoteStream(r)}async onCreateStream(e){let r=this.peerConnection.createDataChannel("",{});return this.log("open channel %d for protocol %s",r.id,e?.protocol),Cn({...e,...this.dataChannelOptions,channel:r,direction:"outbound",log:this.log})}onData(){}};var Ca=class extends Do{peerConnection;constructor(e){super(e),this.peerConnection=e.peerConnection;let r=e.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(e){return{sentBytes:e.byteLength,canSendMore:!0}}async sendClose(e){this.peerConnection.close(),e?.signal?.throwIfAborted()}sendReset(){this.peerConnection.close()}sendPause(){}sendResume(){}},_n=t=>new Ca(t);var $o=globalThis.RTCPeerConnection,qo=globalThis.RTCSessionDescription,Mf=globalThis.RTCIceCandidate;var Ue=class extends Event{type;detail;constructor(e,r){super(e),this.type=e,this.detail=r}};var Tt=class extends Error{constructor(e){super(`WebRTC transport error: ${e}`),this.name="WebRTCTransportError"}},ke=class extends Tt{constructor(e="SDP handshake failed"){super(e),this.name="SDPHandshakeFailedError"}};var Wo=class extends Tt{constructor(e,r){super(`Invalid fingerprint "${e}" within ${r}`),this.name="WebRTC/InvalidFingerprintError"}};var Go=class extends Tt{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},zo=class extends Tt{constructor(e){super(`unsupported hash algorithm code: ${e} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var Oe;(function(t){let e;(function(o){o.SDP_OFFER="SDP_OFFER",o.SDP_ANSWER="SDP_ANSWER",o.ICE_CANDIDATE="ICE_CANDIDATE"})(e=t.Type||(t.Type={}));let r;(function(o){o[o.SDP_OFFER=0]="SDP_OFFER",o[o.SDP_ANSWER=1]="SDP_ANSWER",o[o.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(r||(r={})),(function(o){o.codec=()=>Wt(r)})(e=t.Type||(t.Type={}));let n;t.codec=()=>(n==null&&(n=ze((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),t.Type.codec().encode(o.type,s)),o.data!=null&&(s.uint32(18),s.string(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{a.type=t.Type.codec().decode(o);break}case 2:{a.data=o.string();break}default:{o.skipType(u&7);break}}}return a})),n),t.encode=o=>Ge(o,t.codec()),t.decode=(o,s)=>We(o,t.codec(),s)})(Oe||(Oe={}));var jo=async(t,e,r)=>{try{let n=Promise.withResolvers();for(cm(t,n);;){let o=await Promise.race([n.promise,e.read({signal:r.signal})]);if(o==null){r.signal?.throwIfAborted();break}if(o.type!==Oe.Type.ICE_CANDIDATE)throw new Kn("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){r.onProgress?.(new Ue("webrtc:end-of-ice-candidates")),r.log.trace("end-of-candidates received");continue}let i=new Mf(s);r.log.trace("%s received new ICE candidate %o",r.direction,s);try{r.onProgress?.(new Ue("webrtc:add-ice-candidate",i.candidate)),await t.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&&t.connectionState!=="connected")throw n}};function cm(t,e){if(t.connectionState==="connected"){e.resolve();return}t.onconnectionstatechange=r=>{switch(t.connectionState){case"connected":e.resolve();break;case"failed":case"disconnected":case"closed":e.reject(new Pn(`RTCPeerConnection connection state became "${t.connectionState}"`));break;default:break}}}function Xo(t){let e;for(let r of t.getComponents())r.name==="p2p"&&(e=vr(r.value??""));if(e==null)throw new Nn("Remote peerId must be present in multiaddr");return e}async function Kf({rtcConfiguration:t,dataChannel:e,signal:r,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:u}){let{circuitAddress:l,targetPeer:f}=kf(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing circuit address: %a",l);let p=s.getConnections(f),m;p.length===0?(u?.(new Ue("webrtc:dial-relay")),m=await i.dial(l,{signal:r,onProgress:u})):(u?.(new Ue("webrtc:reuse-relay-connection")),m=p[0]),u?.(new Ue("webrtc:open-signaling-stream"));let d=await m.newStream(xn,{signal:r,runOnLimitedConnection:!0}),E=No(d).pb(Oe),h=new $o(t);h.addEventListener("connectionstatechange",()=>{switch(h.connectionState){case"closed":h.close();break;default:break}});let b=new Dt({peerConnection:h,dataChannelOptions:e});try{let A=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:Oe.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 ke("Failed to set createOffer")});a.trace("initiator send SDP offer %s",x.sdp),u?.(new Ue("webrtc:send-sdp-offer")),await E.write({type:Oe.Type.SDP_OFFER,data:x.sdp},{signal:r}),await h.setLocalDescription(x).catch(O=>{throw a.error("could not execute setLocalDescription - %e",O),new ke("Failed to set localDescription")}),u?.(new Ue("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let D=await E.read({signal:r});if(D.type!==Oe.Type.SDP_ANSWER)throw new ke("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",D.data);let M=new qo({type:"answer",sdp:D.data});return await h.setRemoteDescription(M).catch(O=>{throw a.error("could not execute setRemoteDescription - %e",O),new ke("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),u?.(new Ue("webrtc:read-ice-candidates")),await jo(h,E,{direction:"initiator",signal:r,log:a,onProgress:u}),a.trace("initiator connected"),A.readyState!=="open"&&(a.trace("wait for init channel to open"),await Se(A,"open",{signal:r})),a.trace("closing init channel"),A.close(),a.trace("waiting for init channel to close"),await Se(A,"close",{signal:r}),u?.(new Ue("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await d.close({signal:r}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:h,muxerFactory:b}}catch(A){throw a.error("outgoing signaling error - %e",A),h.close(),d.abort(A),A}finally{h.onicecandidate=null,h.onicecandidateerror=null}}var Hf=ne(xf.matchers[0],re(290)),Yo=class t extends mt{transportManager;shutdownController;events;constructor(e,r){super(),this.transportManager=e.transportManager,this.events=e.events,this.shutdownController=r.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(e){e.detail.getAddrs().filter(n=>Hf.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(e=>!(e instanceof t)).map(e=>e.getAddrs().filter(r=>Hf.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 Ff(t,e,{peerConnection:r,signal:n,log:o}){o.trace("new inbound signaling stream");let s=No(t).pb(Oe);try{r.onicecandidate=({candidate:f})=>{if(r.connectionState==="connected"){o.trace("ignore new ice candidate as peer connection is already connected");return}if(f==null||f?.candidate===""){o.trace("recipient detected end of ICE candidates");return}let p=JSON.stringify(f?.toJSON()??null);o.trace("recipient sending ICE candidate %s",p),s.write({type:Oe.Type.ICE_CANDIDATE,data:p},{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!==Oe.Type.SDP_OFFER)throw new ke(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let u=new qo({type:"offer",sdp:c.data});await r.setRemoteDescription(u).catch(f=>{throw o.error("could not execute setRemoteDescription - %e",f),new ke("Failed to set remoteDescription")});let l=await r.createAnswer().catch(f=>{throw o.error("could not execute createAnswer - %e",f),new ke("Failed to create answer")});o.trace("recipient send SDP answer %s",l.sdp),await s.write({type:Oe.Type.SDP_ANSWER,data:l.sdp},{signal:n}),await r.setLocalDescription(l).catch(f=>{throw o.error("could not execute setLocalDescription - %e",f),new ke("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await jo(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",e.remoteAddr,c),r.close(),c;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",e.remoteAddr,c)}let i=Xo(e.remoteAddr),a=Ir(`/webrtc/p2p/${i}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:i}}var Zo=class{components;init;log;_started=!1;metrics;shutdownController;constructor(e,r={}){this.components=e,this.init=r,this.log=e.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[Vn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[nr]=["@libp2p/transport"];[ec]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(xn,(e,r)=>{let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(e,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(xn),this._started=!1}createListener(e){return new Yo(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(Ef.exactMatch)}dialFilter(e){return this.listenFilter(e)}async dial(e,r){this.log.trace("dialing address: %a",e);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await Kf({rtcConfiguration:await Sa(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:e,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=_n({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:Xo(e),muxerFactory:s,onProgress:r.onProgress,signal:r.signal});return this._closeOnShutdown(o,i),a}async _onProtocol(e,r,n){let o=new $o(await Sa(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{switch(o.connectionState){case"closed":o.close();break;default:break}});let s=new Dt({peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i,remotePeer:a}=await Ff(e,r,{peerConnection:o,signal:n,log:this.log});await e.close({signal:n});let c=_n({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(),e.abort(i),i}}_closeOnShutdown(e,r){let n=()=>{r.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection - %e",o)})};this.shutdownController.signal.addEventListener("abort",n),e.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function kf(t){let e=t.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(e==null)throw new Y("Destination peer id was missing");return{circuitAddress:Ir(t.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:vr(e)}}var Pr=!!globalThis.process?.env?.DUMP_SESSION_KEYS,_a=16;function um(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Qo(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function Jo(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function be(t,e,r=""){let n=um(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){let i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function La(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Vf(t,e){be(t,void 0,"output");let r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function dt(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function pt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function fm(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var lm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function $f(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function qf(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}var Ia=(t,e)=>{function r(n,...o){if(be(n,void 0,"key"),!lm)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){let l=o[0];be(l,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let s=t.tagLength;s&&o[1]!==void 0&&be(o[1],void 0,"AAD");let i=e(n,...o),a=(l,f)=>{if(f!==void 0){if(l!==2)throw new Error("cipher output not supported");be(f,void 0,"output")}},c=!1;return{encrypt(l,f){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,be(l),a(i.encrypt.length,f),i.encrypt(l,f)},decrypt(l,f){if(be(l),s&&l.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,f),i.decrypt(l,f)}}}return Object.assign(r,t),r};function Ba(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(r&&!hm(e))throw new Error("invalid output, must be aligned");return e}function Wf(t,e,r){Qo(r);let n=new Uint8Array(16),o=fm(n);return o.setBigUint64(0,BigInt(e),r),o.setBigUint64(8,BigInt(t),r),n}function hm(t){return t.byteOffset%4===0}function Or(t){return Uint8Array.from(t)}var zf=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),dm=zf("expand 16-byte k"),pm=zf("expand 32-byte k"),mm=dt(dm),gm=dt(pm);function U(t,e){return t<<e|t>>>32-e}function Da(t){return t.byteOffset%4===0}var es=64,ym=16,jf=2**32-1,Gf=Uint32Array.of();function bm(t,e,r,n,o,s,i,a){let c=o.length,u=new Uint8Array(es),l=dt(u),f=Da(o)&&Da(s),p=f?dt(o):Gf,m=f?dt(s):Gf;for(let d=0;d<c;i++){if(t(e,r,n,l,i,a),i>=jf)throw new Error("arx: counter overflow");let E=Math.min(es,c-d);if(f&&E===es){let h=d/4;if(d%4!==0)throw new Error("arx: invalid block position");for(let b=0,A;b<ym;b++)A=h+b,m[A]=p[A]^l[b];d+=es;continue}for(let h=0,b;h<E;h++)b=d+h,s[b]=o[b]^u[h];d+=E}}function Ta(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=$f({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Jo(o),Jo(i),Qo(s),Qo(r),(a,c,u,l,f=0)=>{be(a,void 0,"key"),be(c,void 0,"nonce"),be(u,void 0,"data");let p=u.length;if(l===void 0&&(l=new Uint8Array(p)),be(l,void 0,"output"),Jo(f),f<0||f>=jf)throw new Error("arx: counter overflow");if(l.length<p)throw new Error(`arx: output (${l.length}) is shorter than data (${p})`);let m=[],d=a.length,E,h;if(d===32)m.push(E=Or(a)),h=gm;else if(d===16&&r)E=new Uint8Array(32),E.set(a),E.set(a,16),h=mm,m.push(E);else throw be(a,32,"arx key"),new Error("invalid key size");Da(c)||m.push(c=Or(c));let b=dt(E);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,b,dt(c.subarray(0,16)),b),c=c.subarray(16)}let A=16-o;if(A!==c.length)throw new Error(`arx: nonce must be ${A} or 16 bytes`);if(A!==12){let D=new Uint8Array(12);D.set(c,s?0:12-c.length),c=D,m.push(c)}let x=dt(c);return bm(t,h,b,x,u,l,f,i),pt(...m),l}}function ve(t,e){return t[e++]&255|(t[e++]&255)<<8}var Ra=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(e){e=Or(be(e,32,"key"));let r=ve(e,0),n=ve(e,2),o=ve(e,4),s=ve(e,6),i=ve(e,8),a=ve(e,10),c=ve(e,12),u=ve(e,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 l=0;l<8;l++)this.pad[l]=ve(e,16+2*l)}process(e,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],u=i[2],l=i[3],f=i[4],p=i[5],m=i[6],d=i[7],E=i[8],h=i[9],b=ve(e,r+0),A=ve(e,r+2),x=ve(e,r+4),D=ve(e,r+6),M=ve(e,r+8),O=ve(e,r+10),k=ve(e,r+12),_=ve(e,r+14),v=s[0]+(b&8191),N=s[1]+((b>>>13|A<<3)&8191),K=s[2]+((A>>>10|x<<6)&8191),T=s[3]+((x>>>7|D<<9)&8191),w=s[4]+((D>>>4|M<<12)&8191),g=s[5]+(M>>>1&8191),y=s[6]+((M>>>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+v*a+N*(5*h)+K*(5*E)+T*(5*d)+w*(5*m);S=B>>>13,B&=8191,B+=g*(5*p)+y*(5*f)+C*(5*l)+I*(5*u)+L*(5*c),S+=B>>>13,B&=8191;let R=S+v*c+N*a+K*(5*h)+T*(5*E)+w*(5*d);S=R>>>13,R&=8191,R+=g*(5*m)+y*(5*p)+C*(5*f)+I*(5*l)+L*(5*u),S+=R>>>13,R&=8191;let P=S+v*u+N*c+K*a+T*(5*h)+w*(5*E);S=P>>>13,P&=8191,P+=g*(5*d)+y*(5*m)+C*(5*p)+I*(5*f)+L*(5*l),S+=P>>>13,P&=8191;let z=S+v*l+N*u+K*c+T*a+w*(5*h);S=z>>>13,z&=8191,z+=g*(5*E)+y*(5*d)+C*(5*m)+I*(5*p)+L*(5*f),S+=z>>>13,z&=8191;let W=S+v*f+N*l+K*u+T*c+w*a;S=W>>>13,W&=8191,W+=g*(5*h)+y*(5*E)+C*(5*d)+I*(5*m)+L*(5*p),S+=W>>>13,W&=8191;let V=S+v*p+N*f+K*l+T*u+w*c;S=V>>>13,V&=8191,V+=g*a+y*(5*h)+C*(5*E)+I*(5*d)+L*(5*m),S+=V>>>13,V&=8191;let X=S+v*m+N*p+K*f+T*l+w*u;S=X>>>13,X&=8191,X+=g*c+y*a+C*(5*h)+I*(5*E)+L*(5*d),S+=X>>>13,X&=8191;let te=S+v*d+N*m+K*p+T*f+w*l;S=te>>>13,te&=8191,te+=g*u+y*c+C*a+I*(5*h)+L*(5*E),S+=te>>>13,te&=8191;let ue=S+v*E+N*d+K*m+T*p+w*f;S=ue>>>13,ue&=8191,ue+=g*l+y*u+C*c+I*a+L*(5*h),S+=ue>>>13,ue&=8191;let Z=S+v*h+N*E+K*d+T*m+w*p;S=Z>>>13,Z&=8191,Z+=g*f+y*l+C*u+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]=z,s[4]=W,s[5]=V,s[6]=X,s[7]=te,s[8]=ue,s[9]=Z}finalize(){let{h:e,pad:r}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[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++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+r[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+r[a]|0)+(i>>>16)|0,e[a]=i&65535;pt(n)}update(e){La(this),be(e),e=Or(e);let{buffer:r,blockLen:n}=this,o=e.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(e,s);continue}r.set(e.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(){pt(this.h,this.r,this.buffer,this.pad)}digestInto(e){La(this),Vf(e,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++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8;return e}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}};function wm(t){let e=(n,o)=>t(o).update(n).digest(),r=t(new Uint8Array(32));return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}var Xf=wm(t=>new Ra(t));function Qf(t,e,r,n,o,s=20){let i=t[0],a=t[1],c=t[2],u=t[3],l=e[0],f=e[1],p=e[2],m=e[3],d=e[4],E=e[5],h=e[6],b=e[7],A=o,x=r[0],D=r[1],M=r[2],O=i,k=a,_=c,v=u,N=l,K=f,T=p,w=m,g=d,y=E,C=h,I=b,L=A,S=x,B=D,R=M;for(let z=0;z<s;z+=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+K|0,S=U(S^k,16),y=y+S|0,K=U(K^y,12),k=k+K|0,S=U(S^k,8),y=y+S|0,K=U(K^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),v=v+w|0,R=U(R^v,16),I=I+R|0,w=U(w^I,12),v=v+w|0,R=U(R^v,8),I=I+R|0,w=U(w^I,7),O=O+K|0,R=U(R^O,16),C=C+R|0,K=U(K^C,12),O=O+K|0,R=U(R^O,8),C=C+R|0,K=U(K^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),_=_+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),v=v+N|0,B=U(B^v,16),y=y+B|0,N=U(N^y,12),v=v+N|0,B=U(B^v,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+v|0,n[P++]=l+N|0,n[P++]=f+K|0,n[P++]=p+T|0,n[P++]=m+w|0,n[P++]=d+g|0,n[P++]=E+y|0,n[P++]=h+C|0,n[P++]=b+I|0,n[P++]=A+L|0,n[P++]=x+S|0,n[P++]=D+B|0,n[P++]=M+R|0}function xm(t,e,r,n){let o=t[0],s=t[1],i=t[2],a=t[3],c=e[0],u=e[1],l=e[2],f=e[3],p=e[4],m=e[5],d=e[6],E=e[7],h=r[0],b=r[1],A=r[2],x=r[3];for(let M=0;M<20;M+=2)o=o+c|0,h=U(h^o,16),p=p+h|0,c=U(c^p,12),o=o+c|0,h=U(h^o,8),p=p+h|0,c=U(c^p,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+l|0,A=U(A^i,16),d=d+A|0,l=U(l^d,12),i=i+l|0,A=U(A^i,8),d=d+A|0,l=U(l^d,7),a=a+f|0,x=U(x^a,16),E=E+x|0,f=U(f^E,12),a=a+f|0,x=U(x^a,8),E=E+x|0,f=U(f^E,7),o=o+u|0,x=U(x^o,16),d=d+x|0,u=U(u^d,12),o=o+u|0,x=U(x^o,8),d=d+x|0,u=U(u^d,7),s=s+l|0,h=U(h^s,16),E=E+h|0,l=U(l^E,12),s=s+l|0,h=U(h^s,8),E=E+h|0,l=U(l^E,7),i=i+f|0,b=U(b^i,16),p=p+b|0,f=U(f^p,12),i=i+f|0,b=U(b^i,8),p=p+b|0,f=U(f^p,7),a=a+c|0,A=U(A^a,16),m=m+A|0,c=U(c^m,12),a=a+c|0,A=U(A^a,8),m=m+A|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++]=A,n[D++]=x}var Em=Ta(Qf,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Sm=Ta(Qf,{counterRight:!1,counterLength:8,extendNonceFn:xm,allowShortKeys:!1});var vm=new Uint8Array(16),Yf=(t,e)=>{t.update(e);let r=e.length%16;r&&t.update(vm.subarray(r))},Am=new Uint8Array(32);function Zf(t,e,r,n,o){o!==void 0&&be(o,void 0,"AAD");let s=t(e,r,Am),i=Wf(n.length,o?o.length:0,!0),a=Xf.create(s);o&&Yf(a,o),Yf(a,n),a.update(i);let c=a.digest();return pt(s,i),c}var Jf=t=>(e,r,n)=>({encrypt(s,i){let a=s.length;i=Ba(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);t(e,r,c,c,1);let u=Zf(t,e,r,c,n);return i.set(u,a),pt(u),i},decrypt(s,i){i=Ba(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),u=Zf(t,e,r,a,n);if(!qf(c,u))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,r,i,i,1),pt(u),i}}),Pa=Ia({blockSize:64,nonceLength:12,tagLength:16},Jf(Em)),fS=Ia({blockSize:64,nonceLength:24,tagLength:16},Jf(Sm));function tl(t,e,r){return Ut(t),r===void 0&&(r=new Uint8Array(t.outputLen)),xr(t,r,e)}var Oa=Uint8Array.of(0),el=Uint8Array.of();function rl(t,e,r,n=32){Ut(t),Me(n,"length");let o=t.outputLen;if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);r===void 0?r=el:F(r,void 0,"info");let i=new Uint8Array(s*o),a=xr.create(t,e),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let l=0;l<s;l++)Oa[0]=l+1,c.update(l===0?el:u).update(r).update(Oa).digestInto(u),i.set(u,o*l),a._cloneInto(c);return a.destroy(),c.destroy(),Ve(u,Oa),i.slice(0,n)}var Na={hashSHA256(t){return Ye(t.subarray())},getHKDF(t,e){let r=tl(Ye,e,t),o=rl(Ye,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 t=nn.utils.randomSecretKey();return{publicKey:nn.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:nn.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return nn.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,r,n){return Pa(n,e,r).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,r,n,o){return Pa(n,e,r).decrypt(t.subarray(),o)}};var nl=Na;function ol(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,r)=>t.generateX25519SharedKey(e.privateKey,r).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}var Nr=t=>{let e=pe(2);return e[0]=t>>8,e[1]=t,e};Nr.bytes=2;var Ur=t=>{if(t.length<2)throw RangeError("Could not decode int16BE");if(t instanceof Uint8Array){let e=0;return e+=t[0]<<8,e+=t[1],e}return t.getUint16(0)};Ur.bytes=2;function sl(t){return{xxHandshakeSuccesses:t.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:t.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:t.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:t.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:t.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Ua(t,e){!e.enabled||!Pr||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${$(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${$(t.privateKey,"hex")}`)):e("Missing local static keys."))}function Ma(t,e){!e.enabled||!Pr||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${$(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${$(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function il(t,e){!e.enabled||!Pr||e(t?`REMOTE_STATIC_PUBLIC_KEY ${$(t.subarray(),"hex")}`:"Missing remote static public key.")}function Ka(t,e){!e.enabled||!Pr||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${$(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function ka(t,e,r){!r.enabled||!Pr||(r(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&$(t.k,"hex")}`),r(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&$(e.k,"hex")}`))}var Mr=class t extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=t.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var Cm=0,_m=4294967295,Lm="Cipherstate has reached maximum n, a new handshake must be performed",ts=class{n;bytes;view;constructor(e=Cm){this.n=e,this.bytes=de(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>_m)throw new Error(Lm)}};var Qt=de(0),Kr=class{k;n;crypto;constructor(e,r=void 0,n=0){this.crypto=e,this.k=r,this.n=new ts(n)}hasKey(){return!!this.k}encryptWithAd(e,r){if(!this.hasKey())return r;this.n.assertValue();let n=this.crypto.encrypt(r,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,r,n){if(!this.hasKey())return r;this.n.assertValue();let o=this.crypto.decrypt(r,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},Ha=class{cs;ck;h;crypto;constructor(e,r){this.crypto=e;let n=j(r,"utf-8");this.h=Im(e,n),this.ck=this.h,this.cs=new Kr(e)}mixKey(e){let[r,n]=this.crypto.hkdf(this.ck,e);this.ck=r,this.cs=new Kr(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new q(this.h,e))}encryptAndHash(e){let r=this.cs.encryptWithAd(this.h,e);return this.mixHash(r),r}decryptAndHash(e){let r=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),r}split(){let[e,r]=this.crypto.hkdf(this.ck,Qt);return[new Kr(this.crypto,e),new Kr(this.crypto,r)]}},Fa=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:r,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:u}=e;this.crypto=r,this.ss=new Ha(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 e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.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(e,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<r+32)throw new Error("message is not long enough");this.re=e.sublist(r,r+32),this.ss.mixHash(this.re)}readS(e,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(e.byteLength<r+n)throw new Error("message is not long enough");let o=e.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Ln=class extends Fa{writeMessageA(e){return new q(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let r=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new q(r,n,this.ss.encryptAndHash(e))}writeMessageC(e){let r=this.writeS();return this.writeSE(),new q(r,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(r){throw new Mr(`handshake stage 0 validation fail: ${r.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let r=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+r))}catch(r){throw new Mr(`handshake stage 1 validation fail: ${r.message}`)}}readMessageC(e){try{let r=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(r))}catch(r){throw new Mr(`handshake stage 2 validation fail: ${r.message}`)}}};function Im(t,e){if(e.length<=32){let r=de(32);return r.set(e),r}else return t.hash(e)}var rs;(function(t){let e;t.codec=()=>(e==null&&(e=ze((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 un('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 un('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(r.string());break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ge(r,t.codec()),t.decode=(r,n)=>We(r,t.codec(),n)})(rs||(rs={}));var In;(function(t){let e;t.codec=()=>(e==null&&(e=ze((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),rs.codec().encode(r.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={identityKey:de(0),identitySig:de(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=rs.codec().decode(r,r.uint32(),{limits:o.limits?.extensions});break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ge(r,t.codec()),t.decode=(r,n)=>We(r,t.codec(),n)})(In||(In={}));async function $a(t,e,r){let n=await t.sign(cl(e));return In.encode({identityKey:wt(t.publicKey),identitySig:n,extensions:r})}async function qa(t,e,r){try{let n=In.decode(t),o=hn(n.identityKey);if(r?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${r}`);if(!e)throw new Error("Remote static does not exist");let s=cl(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Tn(n.message)}}function cl(t){let e=j("noise-libp2p-static-key:");return t instanceof Uint8Array?De([e,t],e.length+t.length):(t.prepend(e),t)}var Va=class extends Bt{stream;handshake;metrics;decoder;constructor(e,r,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=r,this.metrics=n,this.decoder=new Uo({lengthDecoder:Ur,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(e){let r=new q;for(let n=0;n<e.byteLength;n+=65519){let o=n+65519;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),r.append(Nr(s.byteLength)),r.append(s)}return r}decrypt(e){let r=new q;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-_a<n)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(n,o):s=e.sublist(n,o);let i=e.subarray(n,o-_a);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(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function Wa(t,e,r){return new Va(t,e,r)}async function ul(t,e){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:u}=t,l=await $a(s,a.publicKey,u),f=new Ln({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Ua(f.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(f.writeMessageA(Qt),e),r.trace("Stage 0 - Initiator finished sending first message."),Ma(f.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");let p=f.readMessageB(await n.read(e));r.trace("Stage 1 - Initiator received the message."),Ka(f.re,r),il(f.rs,r),r.trace("Initiator going to check remote's signature...");let m=await qa(p,f.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(f.writeMessageC(l),e),r.trace("Stage 2 - Initiator sent message with signed payload.");let[d,E]=f.ss.split();return ka(d,E,r),{payload:m,encrypt:h=>d.encryptWithAd(Qt,h),decrypt:(h,b)=>E.decryptWithAd(Qt,h,b)}}async function fl(t,e){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:u}=t,l=await $a(s,a.publicKey,u),f=new Ln({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Ua(f.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),f.readMessageA(await n.read(e)),r.trace("Stage 0 - Responder received first message."),Ka(f.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(f.writeMessageB(l),e),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Ma(f.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");let p=f.readMessageC(await n.read(e));r.trace("Stage 2 - Responder received the message, finished handshake.");let m=await qa(p,f.rs,c),[d,E]=f.ss.split();return ka(d,E,r),{payload:m,encrypt:h=>E.encryptWithAd(Qt,h),decrypt:(h,b)=>d.decryptWithAd(Qt,h,b)}}var ns=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,r={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=r,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=s??nl;this.crypto=ol(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?sl(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??de(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[nr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,r){let n=e.log?.newScope("noise")??this.log,o=Oo(e,{lengthEncoder:Nr,lengthDecoder:Ur,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=hn(s.payload.identityKey);return{connection:Wa(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Mi(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let r=this.components.upgrader.getStreamMuxers();if(r!=null)for(let n of e){let o=r.get(n);if(o!=null)return o}if(e.length)throw new Rn("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,r){let n=e.log?.newScope("noise")??this.log,o=Oo(e,{lengthEncoder:Nr,lengthDecoder:Ur,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=hn(s.payload.identityKey);return{connection:Wa(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Mi(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await ul({connection:e,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(e,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await fl({connection:e,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 ll(t={}){return e=>new ns(e,t)}var Ga=Object.values(Ot).map(t=>t.decoder).reduce((t,e)=>t.or(e)),Bm=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function hl(t){return t?.match(Bm)?.groups?.fingerprint}function za(t){let r=t.getComponents().find(n=>n.code===466)?.value;if(r===void 0||r==="")throw new Y(`Couldn't find a certhash component of multiaddr: ${t.toString()}`);return r}function Dm(t){return He.decode(Ga.decode(t))}function Tm(t){let e=Dm(za(t)),r=Rm(e.code),n=e.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new Wo(n,t.toString());return`${r} ${o.join(":").toUpperCase()}`}function dl(t){let e=t.split(":").map(o=>parseInt(o,16)),r=Uint8Array.from(e),n=Be(tt.code,r);return Ir(`/certhash/${Wr.encode(n.bytes)}`)}function Rm(t){switch(t){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new zo(t)}}function pl(t,e){let{host:r,port:n,type:o}=pa(t);if(o!=="ip4"&&o!=="ip6")throw new Y(`Multiaddr ${t} was not an IPv4 or IPv6 address`);let s=Tm(t);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
|
|
@@ -16,7 +16,7 @@ a=sctp-port:5000
|
|
|
16
16
|
a=max-message-size:${Br}
|
|
17
17
|
a=candidate:1467250027 1 UDP 1467250027 ${r} ${n} typ host
|
|
18
18
|
a=end-of-candidates
|
|
19
|
-
`}}function
|
|
19
|
+
`}}function ml(t,e){let{host:r,port:n,type:o}=pa(t);if(o!=="ip4"&&o!=="ip6")throw new Y(`Multiaddr ${t} 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}
|
|
@@ -32,12 +32,12 @@ a=sctp-port:5000
|
|
|
32
32
|
a=max-message-size:${Br}
|
|
33
33
|
a=candidate:1467250027 1 UDP 1467250027 ${r} ${n} typ host
|
|
34
34
|
a=end-of-candidates
|
|
35
|
-
`}}function
|
|
35
|
+
`}}function ja(t,e){if(t.sdp===void 0)throw new Y("Can't munge a missing SDP");let r=t.sdp.includes(`\r
|
|
36
36
|
`)?`\r
|
|
37
37
|
`:`
|
|
38
38
|
`;try{t.sdp=t.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
|
|
39
39
|
a=ice-ufrag:`+e+r).replace(/\na=ice-pwd:[^\n]*\n/,`
|
|
40
|
-
a=ice-pwd:`+e+r)}catch{}return t}var
|
|
40
|
+
a=ice-pwd:`+e+r)}catch{}return t}var Xa=j("libp2p-webrtc-noise:");function yl(t,e,r){let n=t.trim().toLowerCase().replaceAll(":",""),o=j(n,"hex"),s=Be(tt.code,o),i=Ga.decode(za(e)),a=Xa.byteLength+s.bytes.byteLength+i.byteLength;return r==="server"?De([Xa,i,s.bytes],a):De([Xa,s.bytes,i],a)}var Pm=Vo?"iceconnectionstatechange":"connectionstatechange";function Om(t,e){return t.role==="server"}async function bl(t,e,r,n){let o=t.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let f=await t.createOffer();n.log.trace("client created local offer %s",f.sdp);let p=ja(f,r);n.log.trace("client setting local offer %s",p.sdp),await t.setLocalDescription(p);let m=pl(n.remoteAddr,r);n.log.trace("client setting server description %s",m.sdp),await t.setRemoteDescription(m)}else{let f=ml(n.remoteAddr,r);n.log.trace("server setting client %s %s",f.type,f.sdp),await t.setRemoteDescription(f),n.log.trace("server creating local answer");let p=await t.createAnswer();n.log.trace("server created local answer");let m=ja(p,r);n.log.trace("server setting local description %s",p.sdp),await t.setLocalDescription(m)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await Se(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),Om(n,t)){let f=t.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(dl(f))}let s=hl(t.localDescription?.sdp);if(s==null)throw new Tt("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=yl(s,n.remoteAddr,n.role),a=ll({prologueBytes:i})(n),c=Cn({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),u=_n({peerConnection:t,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(t.addEventListener(Pm,()=>{switch(t.connectionState){case"failed":case"disconnected":case"closed":u.close().catch(f=>{n.log.error("error closing connection - %e",f),u.abort(f)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let f=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(u,{skipProtection:!0,skipEncryption:!0,remotePeer:f.remotePeer,muxerFactory:e,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});u.remoteAddr=u.remoteAddr.encapsulate(`/p2p/${l.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(u,{skipProtection:!0,skipEncryption:!0,remotePeer:l.remotePeer,muxerFactory:e,signal:n.signal})}catch(s){throw o.close(),t.close(),s}}async function wl(t,e,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 Dt({peerConnection:s,metrics:r.events,dataChannelOptions:r.dataChannel});return{peerConnection:s,muxerFactory:i}}var os=class{log;metrics;components;init;constructor(e,r={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=r,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[Vn]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[nr]=["@libp2p/transport"];async dial(e,r){this.log("dial %a",e),r.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=vr(o));let s=Uf(),{peerConnection:i,muxerFactory:a}=await wl("client",s,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await bl(i,a,s,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:r.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:r.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw i.close(),c}}createListener(e){throw new Go("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(bf.exactMatch)}};function Nm(t){return e=>new os(e,t)}function Um(t){return e=>new Zo(e,t)}return Al(Mm);})();
|
|
41
41
|
/*! Bundled license information:
|
|
42
42
|
|
|
43
43
|
@noble/hashes/utils.js:
|