@libp2p/gossipsub 16.1.1-47cf9cdc1 → 16.1.1-d5534174d

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 CHANGED
@@ -1,5 +1,5 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PGossipsub = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var Libp2PGossipsub=(()=>{var Cc=Object.create;var Os=Object.defineProperty;var Fc=Object.getOwnPropertyDescriptor;var Nc=Object.getOwnPropertyNames;var Oc=Object.getPrototypeOf,Uc=Object.prototype.hasOwnProperty;var Kc=(s,e)=>()=>{try{return e||s((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},_e=(s,e)=>{for(var t in e)Os(s,t,{get:e[t],enumerable:!0})},Vi=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Nc(e))!Uc.call(s,n)&&n!==t&&Os(s,n,{get:()=>e[n],enumerable:!(r=Fc(e,n))||r.enumerable});return s};var zc=(s,e,t)=>(t=s!=null?Cc(Oc(s)):{},Vi(e||!s||!s.__esModule?Os(t,"default",{value:s,enumerable:!0}):t,s)),qc=s=>Vi(Os({},"__esModule",{value:!0}),s);var mc=Kc(($0,pc)=>{"use strict";function ee(s,t){var t=t||{};this._capacity=t.capacity,this._head=0,this._tail=0,Array.isArray(s)?this._fromArray(s):(this._capacityMask=3,this._list=new Array(4))}ee.prototype.peekAt=function(e){var t=e;if(t===(t|0)){var r=this.size();if(!(t>=r||t<-r))return t<0&&(t+=r),t=this._head+t&this._capacityMask,this._list[t]}};ee.prototype.get=function(e){return this.peekAt(e)};ee.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};ee.prototype.peekFront=function(){return this.peek()};ee.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(ee.prototype,"length",{get:function(){return this.size()}});ee.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ee.prototype.unshift=function(e){if(arguments.length===0)return this.size();var t=this._list.length;return this._head=this._head-1+t&this._capacityMask,this._list[this._head]=e,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.pop(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ee.prototype.shift=function(){var e=this._head;if(e!==this._tail){var t=this._list[e];return this._list[e]=void 0,this._head=e+1&this._capacityMask,e<2&&this._tail>1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}};ee.prototype.push=function(e){if(arguments.length===0)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ee.prototype.pop=function(){var e=this._tail;if(e!==this._head){var t=this._list.length;this._tail=e-1+t&this._capacityMask;var r=this._list[this._tail];return this._list[this._tail]=void 0,this._head<2&&e>1e4&&e<=t>>>2&&this._shrinkArray(),r}};ee.prototype.removeOne=function(e){var t=e;if(t===(t|0)&&this._head!==this._tail){var r=this.size(),n=this._list.length;if(!(t>=r||t<-r)){t<0&&(t+=r),t=this._head+t&this._capacityMask;var i=this._list[t],o;if(e<r/2){for(o=e;o>0;o--)this._list[t]=this._list[t=t-1+n&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+n&this._capacityMask}else{for(o=r-1-e;o>0;o--)this._list[t]=this._list[t=t+1+n&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+n&this._capacityMask}return i}}};ee.prototype.remove=function(e,t){var r=e,n,i=t;if(r===(r|0)&&this._head!==this._tail){var o=this.size(),a=this._list.length;if(!(r>=o||r<-o||t<1)){if(r<0&&(r+=o),t===1||!t)return n=new Array(1),n[0]=this.removeOne(r),n;if(r===0&&r+t>=o)return n=this.toArray(),this.clear(),n;r+t>o&&(t=o-r);var l;for(n=new Array(t),l=0;l<t;l++)n[l]=this._list[this._head+r+l&this._capacityMask];if(r=this._head+r&this._capacityMask,e+t===o){for(this._tail=this._tail-t+a&this._capacityMask,l=t;l>0;l--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(e===0){for(this._head=this._head+t+a&this._capacityMask,l=t-1;l>0;l--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(r<o/2){for(this._head=this._head+e+t+a&this._capacityMask,l=e;l>0;l--)this.unshift(this._list[r=r-1+a&this._capacityMask]);for(r=this._head-1+a&this._capacityMask;i>0;)this._list[r=r-1+a&this._capacityMask]=void 0,i--;e<0&&(this._tail=r)}else{for(this._tail=r,r=r+t+a&this._capacityMask,l=o-(t+e);l>0;l--)this.push(this._list[r++]);for(r=this._tail;i>0;)this._list[r=r+1+a&this._capacityMask]=void 0,i--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),n}}};ee.prototype.splice=function(e,t){var r=e;if(r===(r|0)){var n=this.size();if(r<0&&(r+=n),!(r>n))if(arguments.length>2){var i,o,a,l=arguments.length,u=this._list.length,p=2;if(!n||r<n/2){for(o=new Array(r),i=0;i<r;i++)o[i]=this._list[this._head+i&this._capacityMask];for(t===0?(a=[],r>0&&(this._head=this._head+r+u&this._capacityMask)):(a=this.remove(r,t),this._head=this._head+r+u&this._capacityMask);l>p;)this.unshift(arguments[--l]);for(i=r;i>0;i--)this.unshift(o[i-1])}else{o=new Array(n-(r+t));var m=o.length;for(i=0;i<m;i++)o[i]=this._list[this._head+r+t+i&this._capacityMask];for(t===0?(a=[],r!=n&&(this._tail=this._head+r+u&this._capacityMask)):(a=this.remove(r,t),this._tail=this._tail-m+u&this._capacityMask);p<l;)this.push(arguments[p++]);for(i=0;i<m;i++)this.push(o[i])}return a}else return this.remove(r,t)}};ee.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0};ee.prototype.isEmpty=function(){return this._head===this._tail};ee.prototype.toArray=function(){return this._copyArray(!1)};ee.prototype._fromArray=function(e){var t=e.length,r=this._nextPowerOf2(t);this._list=new Array(r),this._capacityMask=r-1,this._tail=t;for(var n=0;n<t;n++)this._list[n]=e[n]};ee.prototype._copyArray=function(e,t){var r=this._list,n=r.length,i=this.length;if(t=t|i,t==i&&this._head<this._tail)return this._list.slice(this._head,this._tail);var o=new Array(t),a=0,l;if(e||this._head>this._tail){for(l=this._head;l<n;l++)o[a++]=r[l];for(l=0;l<this._tail;l++)o[a++]=r[l]}else for(l=this._head;l<this._tail;l++)o[a++]=r[l];return o};ee.prototype._growArray=function(){if(this._head!=0){var e=this._copyArray(!0,this._list.length<<1);this._tail=this._list.length,this._head=0,this._list=e}else this._tail=this._list.length,this._list.length<<=1;this._capacityMask=this._capacityMask<<1|1};ee.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1};ee.prototype._nextPowerOf2=function(e){var t=Math.log(e)/Math.log(2),r=1<<t+1;return Math.max(r,4)};pc.exports=ee});var Ff={};_e(Ff,{StrictNoSign:()=>Ft,StrictSign:()=>wt,TopicValidatorResult:()=>me,gossipsub:()=>Cf,multicodec:()=>Lf});var Hr="/floodsub/1.0.0",Wr="/meshsub/1.0.0",$i="/meshsub/1.1.0",Ot="/meshsub/1.2.0";var ji="ERR_TOPIC_VALIDATOR_REJECT",Zi="ERR_TOPIC_VALIDATOR_IGNORE";var re=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Ut=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Us=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Ks=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Kt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Vr=Symbol.for("@libp2p/peer-id");function Gc(s){return typeof s?.handleEvent=="function"}function Hc(s){return(s!==!0&&s!==!1&&s?.once)??!1}var zs=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,r){let n=Hc(r);super.addEventListener(e,o=>{if(n){let a=this.#e.get(o.type);a!=null&&(a=a.filter(({callback:l})=>l!==t),this.#e.set(o.type,a))}Gc(t)?t.handleEvent(o):t(o)},r);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:t,once:n})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),t??null,r);let n=this.#e.get(e);n!=null&&(n=n.filter(({callback:i})=>i!==t),this.#e.set(e,n))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Xi=Symbol.for("@libp2p/service-capabilities"),Ji=Symbol.for("@libp2p/service-dependencies");var Xr={};_e(Xr,{base58btc:()=>ie,base58flickr:()=>Jc});var fd=new Uint8Array(0);function eo(s,e){if(s===e)return!0;if(s.byteLength!==e.byteLength)return!1;for(let t=0;t<s.byteLength;t++)if(s[t]!==e[t])return!1;return!0}function Be(s){if(s instanceof Uint8Array&&s.constructor.name==="Uint8Array")return vt(s);if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return vt(new Uint8Array(s.buffer,s.byteOffset,s.byteLength));throw new Error("Unknown type, must be binary type")}function to(s){let e=new Uint8Array(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}var Qi=4096;function so(s){let e=s.length;if(e<=Qi)return String.fromCharCode.apply(String,s);let t="",r=0;for(;r<e;)t+=String.fromCharCode.apply(String,s.subarray(r,r+=Qi));return t}function Wc(s){return s?.buffer instanceof ArrayBuffer}function vt(s){return Wc(s)?s:s.slice()}function Vc(s,e,t){if(s.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 i=0;i<s.length;i++){var o=s.charAt(i),a=o.charCodeAt(0);if(r[a]!==255)throw new TypeError(o+" is ambiguous");if(r[a]=i,t){var l=o.toLowerCase().charCodeAt(0),u=o.toUpperCase().charCodeAt(0);l!==a&&(r[l]=i),u!==a&&(r[u]=i)}}var p=s.length,m=s.charAt(0),x=Math.log(p)/Math.log(256),y=Math.log(256)/Math.log(p);function f(E){if(E instanceof Uint8Array||(ArrayBuffer.isView(E)?E=new Uint8Array(E.buffer,E.byteOffset,E.byteLength):Array.isArray(E)&&(E=Uint8Array.from(E))),!(E instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(E.length===0)return"";for(var S=0,c=0,h=0,d=E.length;h!==d&&E[h]===0;)h++,S++;for(var b=(d-h)*y+1>>>0,v=new Uint8Array(b);h!==d;){for(var _=E[h],D=0,P=b-1;(_!==0||D<c)&&P!==-1;P--,D++)_+=256*v[P]>>>0,v[P]=_%p>>>0,_=_/p>>>0;if(_!==0)throw new Error("Non-zero carry");c=D,h++}for(var K=b-c;K!==b&&v[K]===0;)K++;for(var F=m.repeat(S);K<b;++K)F+=s.charAt(v[K]);return F}function g(E){if(typeof E!="string")throw new TypeError("Expected String");if(E.length===0)return new Uint8Array;var S=0;if(E[S]!==" "){for(var c=0,h=0;E[S]===m;)c++,S++;for(var d=(E.length-S)*x+1>>>0,b=new Uint8Array(d);E[S];){var v=r[E.charCodeAt(S)];if(v===255)return;for(var _=0,D=d-1;(v!==0||_<h)&&D!==-1;D--,_++)v+=p*b[D]>>>0,b[D]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");h=_,S++}if(E[S]!==" "){for(var P=d-h;P!==d&&b[P]===0;)P++;for(var K=new Uint8Array(c+(d-P)),F=c;P!==d;)K[F++]=b[P++];return K}}}function w(E){var S=g(E);if(S)return S;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:g,decode:w}}var $c=Vc,jc=$c,no=jc;var $r=class{name;prefix;baseEncode;constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},jr=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,r){this.name=e,this.prefix=t;let n=t.codePointAt(0);if(n===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=r}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 io(this,e)}},Zr=class{decoders;constructor(e){this.decoders=e}or(e){return io(this,e)}decode(e){let t=e[0],r=this.decoders[t];if(r!=null)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function io(s,e){return new Zr({...s.decoders??{[s.prefix]:s},...e.decoders??{[e.prefix]:e}})}var Yr=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,r,n){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new $r(e,t,r),this.decoder=new jr(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function zt({name:s,prefix:e,encode:t,decode:r}){return new Yr(s,e,t,r)}function it({name:s,prefix:e,alphabet:t,caseInsensitive:r=!1}){let{encode:n,decode:i}=no(t,s,r);return zt({prefix:e,name:s,encode:n,decode:o=>Be(i(o))})}function Zc(s,e,t,r){let n=s.length;for(;s[n-1]==="=";)--n;let i=new Uint8Array(n*t/8|0),o=0,a=0,l=0;for(let u=0;u<n;++u){let p=e[s[u]];if(p===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<t|p,o+=t,o>=8&&(o-=8,i[l++]=255&a>>o)}if(o>=t||(255&a<<8-o)!==0)throw new SyntaxError("Unexpected end of data");return i}function Yc(s,e,t){let r=e[e.length-1]==="=",n=(1<<t)-1,i="",o=0,a=0;for(let l=0;l<s.length;++l)for(a=a<<8|s[l],o+=8;o>t;)o-=t,i+=e[n&a>>o];if(o!==0&&(i+=e[n&a<<t-o]),r)for(;(i.length*t&7)!==0;)i+="=";return i}function Xc(s,e){let t={};for(let r=0;r<s.length;++r)if(t[s[r]]=r,e){let n=s[r].toLowerCase(),i=s[r].toUpperCase();n!==s[r]&&(t[n]=r),i!==s[r]&&(t[i]=r)}return t}function ne({name:s,prefix:e,bitsPerChar:t,alphabet:r,caseInsensitive:n=!1}){let i=Xc(r,n);return zt({prefix:e,name:s,encode(o){return Yc(o,r,t)},decode(o){return Zc(o,i,t,s)}})}var ie=it({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Jc=it({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Jr={};_e(Jr,{base32:()=>qt,base32hex:()=>sl,base32hexpad:()=>nl,base32hexpadupper:()=>il,base32hexupper:()=>rl,base32pad:()=>el,base32padupper:()=>tl,base32upper:()=>Qc,base32z:()=>ol});var qt=ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),Qc=ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),el=ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),tl=ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),sl=ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),rl=ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),nl=ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),il=ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),ol=ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Qr={};_e(Qr,{base36:()=>ds,base36upper:()=>al});var ds=it({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),al=it({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var cl=co,oo=128,ll=127,ul=~ll,hl=Math.pow(2,31);function co(s,e,t){e=e||[],t=t||0;for(var r=t;s>=hl;)e[t++]=s&255|oo,s/=128;for(;s&ul;)e[t++]=s&255|oo,s>>>=7;return e[t]=s|0,co.bytes=t-r+1,e}var fl=en,dl=128,ao=127;function en(s,r){var t=0,r=r||0,n=0,i=r,o,a=s.length;do{if(i>=a)throw en.bytes=0,new RangeError("Could not decode varint");o=s[i++],t+=n<28?(o&ao)<<n:(o&ao)*Math.pow(2,n),n+=7}while(o>=dl);return en.bytes=i-r,t}var pl=Math.pow(2,7),ml=Math.pow(2,14),gl=Math.pow(2,21),bl=Math.pow(2,28),yl=Math.pow(2,35),wl=Math.pow(2,42),xl=Math.pow(2,49),vl=Math.pow(2,56),El=Math.pow(2,63),Sl=function(s){return s<pl?1:s<ml?2:s<gl?3:s<bl?4:s<yl?5:s<wl?6:s<xl?7:s<vl?8:s<El?9:10},_l={encode:cl,decode:fl,encodingLength:Sl},Il=_l,ps=Il;function ms(s,e=0){let t=ps.decode(s,e),r=ps.decode.bytes;if(r>9)throw new RangeError("Invalid varint: too long");if(r>1&&s[e+r-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[t,r]}function Gt(s,e,t=0){return ps.encode(s,e,t),e}function Ht(s){return ps.encodingLength(s)}function He(s,e){let t=e.byteLength,r=Ht(s),n=r+Ht(t),i=new Uint8Array(n+t);return Gt(s,i,0),Gt(t,i,r),i.set(e,n),new Wt(s,t,e,i)}function Ye(s){let e=Be(s),[t,r]=ms(e),[n,i]=ms(e.subarray(r)),o=e.subarray(r+i);if(o.byteLength!==n)throw new Error("Incorrect length");return new Wt(t,n,o,e)}function lo(s,e){if(s===e)return!0;{let t=e;return s.code===t.code&&s.size===t.size&&t.bytes instanceof Uint8Array&&eo(s.bytes,t.bytes)}}var Wt=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=vt(r),this.bytes=vt(n)}};function uo(s,e){let{bytes:t,version:r}=s;return r===0?Dl(t,tn(s),e??ie.encoder):Al(t,tn(s),e??qt.encoder)}var ho=new WeakMap;function tn(s){let e=ho.get(s);if(e==null){let t=new Map;return ho.set(s,t),t}return e}var ce=class s{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=vt(n),this["/"]=this.bytes}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:t}=this;if(e!==gs)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ml)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return s.createV0(t)}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:t}=this.multihash,r=He(e,t);return s.createV1(this.code,r)}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 s.equals(this,e)}static equals(e,t){let r=t;return r!=null&&e.code===r.code&&e.version===r.version&&lo(e.multihash,r.multihash)}toString(e){return uo(this,e)}toJSON(){return{"/":uo(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 t=e;if(t instanceof s)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:r,code:n,multihash:i,bytes:o}=t;return new s(r,n,i,o??fo(r,n,i.bytes))}else if(t[Pl]===!0){let{version:r,multihash:n,code:i}=t,o=Ye(n);return s.create(r,i,o)}else return null}static create(e,t,r){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==gs)throw new Error(`Version 0 CID must use dag-pb (code: ${gs}) block encoding`);return new s(e,t,r,r.bytes)}case 1:{let n=fo(e,t,r.bytes);return new s(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return s.create(0,gs,e)}static createV1(e,t){return s.create(1,e,t)}static decode(e){let[t,r]=s.decodeFirst(e);if(r.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=s.inspectBytes(e),r=t.size-t.multihashSize,n=Be(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=n.subarray(t.multihashSize-t.digestSize),o=new Wt(t.multihashCode,t.digestSize,i,n);return[t.version===0?s.createV0(o):s.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,r=()=>{let[m,x]=ms(e.subarray(t));return t+=x,m},n=r(),i=gs;if(n===18?(n=0,t=0):i=r(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let o=t,a=r(),l=r(),u=t+l,p=u-o;return{version:n,codec:i,multihashCode:a,digestSize:l,multihashSize:p,size:u}}static parse(e,t){let[r,n]=Tl(e,t),i=s.decode(n);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return tn(i).set(r,e),i}};function Tl(s,e){switch(s[0]){case"Q":{let t=e??ie;return[ie.prefix,t.decode(`${ie.prefix}${s}`)]}case ie.prefix:{let t=e??ie;return[ie.prefix,t.decode(s)]}case qt.prefix:{let t=e??qt;return[qt.prefix,t.decode(s)]}case ds.prefix:{let t=e??ds;return[ds.prefix,t.decode(s)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[s[0],e.decode(s)]}}}function Dl(s,e,t){let{prefix:r}=t;if(r!==ie.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let n=e.get(r);if(n==null){let i=t.encode(s).slice(1);return e.set(r,i),i}else return n}function Al(s,e,t){let{prefix:r}=t,n=e.get(r);if(n==null){let i=t.encode(s);return e.set(r,i),i}else return n}var gs=112,Ml=18;function fo(s,e,t){let r=Ht(s),n=r+Ht(e),i=new Uint8Array(n+t.byteLength);return Gt(s,i,0),Gt(e,i,r),i.set(t,n),i}var Pl=Symbol.for("@ipld/js-cid/CID");var sn={};_e(sn,{identity:()=>Ne});var po=0,Bl="identity",mo=Be;function kl(s,e){if(e?.truncate!=null&&e.truncate!==s.byteLength){if(e.truncate<0||e.truncate>s.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${s.byteLength}`);s=s.subarray(0,e.truncate)}return He(po,mo(s))}var Ne={code:po,name:Bl,encode:mo,digest:kl};function Ie(s,e){if(s===e)return!0;if(s.byteLength!==e.byteLength)return!1;for(let t=0;t<s.byteLength;t++)if(s[t]!==e[t])return!1;return!0}function Rl(s){return s.buffer instanceof ArrayBuffer}function ke(s){return Rl(s)?s:s.slice()}async function go(s,e,t,r){let n=await crypto.subtle.importKey("jwk",s,{name:"ECDSA",namedCurve:s.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();let i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,ke(e),ke(t.subarray()));return r?.signal?.throwIfAborted(),i}function Xe(s=0){return new Uint8Array(s)}function he(s=0){return new Uint8Array(s)}function Ll(s){return s?.buffer instanceof ArrayBuffer}function bo(s){if(Ll(s))return s;let e=s.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Et(s,e){e==null&&(e=s.reduce((n,i)=>n+i.length,0));let t=he(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return bo(t)}var wo=Symbol.for("@achingbrain/uint8arraylist");function yo(s,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let r of s){let n=t+r.byteLength;if(e<n)return{buf:r,index:e-t};t=n}throw new RangeError("index is out of bounds")}function Gs(s){return!!s?.[wo]}var ae=class s{bufs;length;[wo]=!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 t=0;for(let r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else if(Gs(r)){t+=r.byteLength;for(let n of r.bufs)this.bufs.push(n)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else if(Gs(r))t+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=yo(this.bufs,e);return t.buf[t.index]}set(e,t){let r=yo(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(t+r,e[r]);else if(Gs(e))for(let r=0;r<e.length;r++)this.set(t+r,e.get(r));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,t){let{bufs:r,length:n}=this._subList(e,t);return Et(r,n)}subarray(e,t){let{bufs:r,length:n}=this._subList(e,t);return r.length===1?r[0]:Et(r,n)}sublist(e,t){let{bufs:r,length:n}=this._subList(e,t),i=new s;return i.length=n,i.bufs=r,i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let r=[],n=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],a=n,l=a+o.byteLength;if(n=l,e>=l)continue;let u=e>=a&&e<l,p=t>a&&t<=l;if(u&&p){if(e===a&&t===l){r.push(o);break}let m=e-a;r.push(o.subarray(m,m+(t-e)));break}if(u){if(e===0){r.push(o);continue}r.push(o.subarray(e-a));continue}if(p){if(t===l){r.push(o);break}r.push(o.subarray(0,t-a));break}r.push(o)}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!Gs(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let r=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let n=r.byteLength;if(n===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let m=0;m<i;m++)o[m]=-1;for(let m=0;m<n;m++)o[r[m]]=m;let a=o,l=this.byteLength-r.byteLength,u=r.byteLength-1,p;for(let m=t;m<=l;m+=p){p=0;for(let x=u;x>=0;x--){let y=this.get(m+x);if(r[x]!==y){p=Math.max(1,x-a[y]);break}}if(p===0)return m}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let r=he(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){let n=Xe(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){let n=Xe(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){let n=Xe(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let r=he(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){let n=Xe(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){let n=Xe(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){let n=Xe(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){let n=Xe(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){let n=Xe(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(e==null||!(e instanceof s)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Ie(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let r=new s;return r.bufs=e,t==null&&(t=e.reduce((n,i)=>n+i.byteLength,0)),r.length=t,r}};var rn={};_e(rn,{base10:()=>Cl});var Cl=it({prefix:"9",name:"base10",alphabet:"0123456789"});var nn={};_e(nn,{base16:()=>Fl,base16upper:()=>Nl});var Fl=ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),Nl=ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var on={};_e(on,{base2:()=>Ol});var Ol=ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var an={};_e(an,{base256emoji:()=>Gl});var xo=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}"),Ul=xo.reduce((s,e,t)=>(s[t]=e,s),[]),Kl=xo.reduce((s,e,t)=>{let r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return s[r]=t,s},[]);function zl(s){return s.reduce((e,t)=>(e+=Ul[t],e),"")}function ql(s){let e=[];for(let t of s){let r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);let n=Kl[r];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Gl=zt({prefix:"\u{1F680}",name:"base256emoji",encode:zl,decode:ql});var cn={};_e(cn,{base64:()=>Hl,base64pad:()=>Wl,base64url:()=>Vl,base64urlpad:()=>$l});var Hl=ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Wl=ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Vl=ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),$l=ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ln={};_e(ln,{base8:()=>jl});var jl=ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var un={};_e(un,{identity:()=>Zl});var Zl=zt({prefix:"\0",name:"identity",encode:s=>so(Be(s)),decode:s=>Be(to(s))});var Xd=new TextEncoder,Jd=new TextDecoder;var dn={};_e(dn,{sha256:()=>St,sha512:()=>Ql});var Jl=20;function fn({name:s,code:e,encode:t,minDigestLength:r,maxDigestLength:n}){return new hn(s,e,t,r,n)}var hn=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,r,n,i){this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??Jl,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?vo(r,this.code,t?.truncate):r.then(n=>vo(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function vo(s,e,t){if(t!=null&&t!==s.byteLength){if(t>s.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${s.byteLength}`);s=s.subarray(0,t)}return He(e,s)}function So(s){return async e=>new Uint8Array(await crypto.subtle.digest(s,e))}var St=fn({name:"sha2-256",code:18,encode:So("SHA-256")}),Ql=fn({name:"sha2-512",code:19,encode:So("SHA-512")});var pn={...un,...on,...ln,...rn,...nn,...Jr,...Qr,...Xr,...cn,...an},up={...dn,...sn};function Io(s,e,t,r){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:r}}}var _o=Io("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),mn=Io("ascii","a",s=>{let e="a";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return e},s=>{s=s.substring(1);let e=he(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),eu={utf8:_o,"utf-8":_o,hex:pn.base16,latin1:mn,ascii:mn,binary:mn,...pn},Hs=eu;function j(s,e="utf8"){let t=Hs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${s}`)}function $(s,e="utf8"){let t=Hs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(s).substring(1)}var tu=parseInt("11111",2),gn=parseInt("10000000",2),su=parseInt("01111111",2),To={0:bs,1:bs,2:ru,3:ou,4:au,5:iu,6:nu,16:bs,22:bs,48:bs};function Je(s,e={offset:0}){let t=s[e.offset]&tu;if(e.offset++,To[t]!=null)return To[t](s,e);throw new Error("No decoder for tag "+t)}function ys(s,e){let t=0;if((s[e.offset]&gn)===gn){let r=s[e.offset]&su,n="0x";e.offset++;for(let i=0;i<r;i++,e.offset++){if(e.offset>=s.byteLength)throw new Error("invalid DER element length");n+=s[e.offset].toString(16).padStart(2,"0")}t=parseInt(n,16)}else t=s[e.offset],e.offset++;if(!Number.isInteger(t)||t<0||t>s.byteLength-e.offset)throw new Error("invalid DER element length");return t}function bs(s,e){ys(s,e);let t=[];for(;!(e.offset>=s.byteLength);){let r=Je(s,e);if(r===null)break;t.push(r)}return t}function ru(s,e){let t=ys(s,e),r=e.offset,n=e.offset+t,i=[];for(let o=r;o<n;o++)o===r&&s[o]===0||i.push(s[o]);return e.offset+=t,Uint8Array.from(i)}function nu(s,e){let t=ys(s,e),r=e.offset+t,n=s[e.offset];e.offset++;let i=0,o=0;n<40?(i=0,o=n):n<80?(i=1,o=n-40):(i=2,o=n-80);let a=`${i}.${o}`,l=[];for(;e.offset<r;){let u=s[e.offset];if(e.offset++,l.push(u&127),u<128){l.reverse();let p=0;for(let m=0;m<l.length;m++)p+=l[m]<<m*7;a+=`.${p}`,l=[]}}return a}function iu(s,e){return e.offset++,null}function ou(s,e){let t=ys(s,e),r=s[e.offset];e.offset++;let n=s.subarray(e.offset,e.offset+t-1);if(e.offset+=t,r!==0)throw new Error("Unused bits in bit string is unimplemented");return n}function au(s,e){let t=ys(s,e),r=s.subarray(e.offset,e.offset+t);return e.offset+=t,r}function cu(s){let e=s.toString(16);e.length%2===1&&(e="0"+e);let t=new ae;for(let r=0;r<e.length;r+=2)t.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return t}function bn(s){if(s.byteLength<128)return Uint8Array.from([s.byteLength]);let e=cu(s.byteLength);return new ae(Uint8Array.from([e.byteLength|gn]),e)}function Te(s){let e=new ae,t=128;return(s.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(s),new ae(Uint8Array.from([2]),bn(e),e)}function Ws(s){let e=Uint8Array.from([0]),t=new ae(e,s);return new ae(Uint8Array.from([3]),bn(t),t)}function at(s,e=48){let t=new ae;for(let r of s)t.append(r);return new ae(Uint8Array.from([e]),bn(t),t)}var lu=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),uu=Uint8Array.from([6,5,43,129,4,0,34]),hu=Uint8Array.from([6,5,43,129,4,0,35]),fu={ext:!0,kty:"EC",crv:"P-256"},du={ext:!0,kty:"EC",crv:"P-384"},pu={ext:!0,kty:"EC",crv:"P-521"},yn=32,wn=48,xn=66;function vn(s){let e=Je(s);return Do(e)}function Do(s){let e=s[1][1][0],t=1,r,n;if(e.byteLength===yn*2+1)return r=$(e.subarray(t,t+yn),"base64url"),n=$(e.subarray(t+yn),"base64url"),new Vt({...fu,key_ops:["verify"],x:r,y:n});if(e.byteLength===wn*2+1)return r=$(e.subarray(t,t+wn),"base64url"),n=$(e.subarray(t+wn),"base64url"),new Vt({...du,key_ops:["verify"],x:r,y:n});if(e.byteLength===xn*2+1)return r=$(e.subarray(t,t+xn),"base64url"),n=$(e.subarray(t+xn),"base64url"),new Vt({...pu,key_ops:["verify"],x:r,y:n});throw new re(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Ao(s){return at([Te(Uint8Array.from([1])),at([mu(s.crv)],160),at([Ws(new ae(Uint8Array.from([4]),j(s.x??"","base64url"),j(s.y??"","base64url")))],161)]).subarray()}function mu(s){if(s==="P-256")return lu;if(s==="P-384")return uu;if(s==="P-521")return hu;throw new re(`Invalid curve ${s}`)}var Vt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Ao(this.jwk)),this._raw}toMultihash(){return Ne.digest(We(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}async verify(e,t,r){return go(this.jwk,t,e,r)}};var Vs=BigInt(4294967295),Mo=BigInt(32);function gu(s,e=!1){return e?{h:Number(s&Vs),l:Number(s>>Mo&Vs)}:{h:Number(s>>Mo&Vs)|0,l:Number(s&Vs)|0}}function Po(s,e=!1){let t=s.length,r=new Uint32Array(t),n=new Uint32Array(t);for(let i=0;i<t;i++){let{h:o,l:a}=gu(s[i],e);[r[i],n[i]]=[o,a]}return[r,n]}var bu=s=>s/2**32|0,yu=s=>s>>>0;function Bo(s,e,t,r){let n=bu(t),i=yu(t);s.setUint32(e,r?i:n,r),s.setUint32(e+4,r?n:i,r)}var En=(s,e,t)=>s>>>t,Sn=(s,e,t)=>s<<32-t|e>>>t,_t=(s,e,t)=>s>>>t|e<<32-t,It=(s,e,t)=>s<<32-t|e>>>t,ws=(s,e,t)=>s<<64-t|e>>>t-32,xs=(s,e,t)=>s>>>t-32|e<<64-t;function Ve(s,e,t,r){let n=(e>>>0)+(r>>>0);return{h:s+t+(n/2**32|0)|0,l:n|0}}var ko=(s,e,t)=>(s>>>0)+(e>>>0)+(t>>>0),Ro=(s,e,t,r)=>e+t+r+(s/2**32|0)|0,Lo=(s,e,t,r)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0),Co=(s,e,t,r,n)=>e+t+r+n+(s/2**32|0)|0,Fo=(s,e,t,r,n)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),No=(s,e,t,r,n,i)=>e+t+r+n+i+(s/2**32|0)|0;function $s(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in s&&s.BYTES_PER_ELEMENT===1}var _n=s=>s?`"${s}" `:"";function Qe(s,e=""){if(typeof s!="number")throw new TypeError(_n(e)+"expected number, got "+typeof s);if(!Number.isSafeInteger(s)||s<0)throw new RangeError(_n(e)+"expected integer >= 0, got "+s);return s}function Re(s,e,t=""){if($s(s)&&(e===void 0||s.length===e))return s;e!==void 0&&Qe(e,"length");let r=$s(s),n=e!==void 0?` of length ${e}`:"",i=r?`length=${s.length}`:`type=${typeof s}`,o=_n(t)+"expected Uint8Array"+n+", got "+i;throw r?new RangeError(o):new TypeError(o)}function js(s){if(typeof s!="function"||typeof s.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Qe(s.outputLen),Qe(s.blockLen),s.outputLen<1||s.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var Oo=(s,e)=>{if(s===null||typeof s!="object"||Array.isArray(s))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof s)};function $t(s,e=!0){if(s.destroyed)throw new Error("hash was destroyed");if(e&&s.finished)throw new Error("digest() was already called")}function Zs(s,e){Re(s,void 0,"output");let t=e.outputLen;if(!(s.length>=t))throw new RangeError('"output" expected length >= '+t)}function Tt(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Ys(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Oe(s,e){return s<<32-e|s>>>e}var Ko=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",xu=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Xs(s){if(Re(s),Ko)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=xu[s[t]];return e}function Uo(s){return s>=48&&s<=57?s-48:s>=65&&s<=70?s-55:s>=97&&s<=102?s-87:void 0}function Js(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);if(Ko)try{return Uint8Array.fromHex(s)}catch(n){throw n instanceof SyntaxError?new RangeError(n.message):n}let e=s.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let n=0,i=0;n<t;n++,i+=2){let o=Uo(s.charCodeAt(i)),a=Uo(s.charCodeAt(i+1));if(o===void 0||a===void 0){let l=s[i]+s[i+1];throw new RangeError('hex string expected, got non-hex character "'+l+'" at index '+i)}r[n]=o*16+a}return r}function In(...s){let e=0;for(let r=0;r<s.length;r++){let n=s[r];Re(n),e+=n.length}let t=new Uint8Array(e);for(let r=0,n=0;r<s.length;r++){let i=s[r];t.set(i,n),n+=i.length}return t}function vu(s,e,t="opts"){return Oo(s,"defaults"),e!==void 0&&Oo(e,t),Object.assign(s,e)}function Tn(s,e={}){if(typeof s!="function")throw new TypeError('"hashCons" expected function, got type='+typeof s);e=vu({},e,"info");let t=(n,i)=>s(i).update(n).digest(),r=s(void 0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.canXOF=r.canXOF,t.create=n=>s(n),Object.assign(t,e),Object.freeze(t)}function zo(s=32){Qe(s,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(s>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${s}`);return e.getRandomValues(new Uint8Array(s))}var Dn=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function qo(s,e,t){return s&e^~s&t}function Go(s,e,t){return s&e^s&t^e&t}var vs=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Ys(this.buffer)}update(e){$t(this),Re(e);let{view:t,buffer:r,blockLen:n}=this,i=e.length,o=!1;for(let a=0;a<i;){let l=Math.min(n-this.pos,i-a);if(l===n){let u=Ys(e);for(;n<=i-a;a+=n)this.process(u,a);o=!0;continue}r.set(a===0&&l===i?e:e.subarray(a,a+l),this.pos),this.pos+=l,a+=l,this.pos===n&&(this.process(t,0),this.pos=0,o=!0)}return this.length+=e.length,o&&this.roundClean(),this}digestInto(e){$t(this),Zs(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,t.fill(0,o),this.padOffset>n-o&&(this.process(r,0),t.fill(0)),Bo(r,n-8,this.length*8,i),this.process(r,0),this.roundClean();let a=e===t?r:Ys(e),l=this.outputLen,u=l/4,p=this.get();if(l%4||u>p.length)throw new Error("invalid outputLen");for(let m=0;m<u;m++)a.setUint32(4*m,p[m],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:i,pos:o}=this;return e.destroyed=i,e.finished=n,e.length=r,e.pos=o,o&&e.buffer.set(t),e}clone(){return this._cloneInto()}},Ho=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Wo=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Eu=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]),ct=new Uint32Array(64),An=class extends vs{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:i,F:o,G:a,H:l}=this;return[e,t,r,n,i,o,a,l]}set(e,t,r,n,i,o,a,l){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=l|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let m=0;m<16;m++,t+=4)ct[m]=e.getUint32(t,!1);for(let m=16;m<64;m++){let x=ct[m-15],y=ct[m-2],f=Oe(x,7)^Oe(x,18)^x>>>3,g=Oe(y,17)^Oe(y,19)^y>>>10;ct[m]=g+ct[m-7]+f+ct[m-16]|0}let{A:r,B:n,C:i,D:o,E:a,F:l,G:u,H:p}=this;for(let m=0;m<64;m++){let x=Oe(a,6)^Oe(a,11)^Oe(a,25),y=p+x+qo(a,l,u)+Eu[m]+ct[m]|0,g=(Oe(r,2)^Oe(r,13)^Oe(r,22))+Go(r,n,i)|0;p=u,u=l,l=a,a=o+y|0,o=i,i=n,n=r,r=y+g|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,l=l+this.F|0,u=u+this.G|0,p=p+this.H|0,this.set(r,n,i,o,a,l,u,p)}roundClean(){Tt(ct)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Tt(this.buffer)}},Mn=class extends An{constructor(){super(32,Ho)}};var Vo=Po(["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(s=>BigInt(s))),Su=Vo[0],_u=Vo[1],lt=new Uint32Array(80),ut=new Uint32Array(80),Pn=class extends vs{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:o,Dh:a,Dl:l,Eh:u,El:p,Fh:m,Fl:x,Gh:y,Gl:f,Hh:g,Hl:w}=this;return[e,t,r,n,i,o,a,l,u,p,m,x,y,f,g,w]}set(e,t,r,n,i,o,a,l,u,p,m,x,y,f,g,w){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=n|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=l|0,this.Eh=u|0,this.El=p|0,this.Fh=m|0,this.Fl=x|0,this.Gh=y|0,this.Gl=f|0,this.Hh=g|0,this.Hl=w|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let c=0;c<16;c++,t+=4)lt[c]=e.getUint32(t),ut[c]=e.getUint32(t+=4);for(let c=16;c<80;c++){let h=lt[c-15]|0,d=ut[c-15]|0,b=_t(h,d,1)^_t(h,d,8)^En(h,d,7),v=It(h,d,1)^It(h,d,8)^Sn(h,d,7),_=lt[c-2]|0,D=ut[c-2]|0,P=_t(_,D,19)^ws(_,D,61)^En(_,D,6),K=It(_,D,19)^xs(_,D,61)^Sn(_,D,6),F=Lo(v,K,ut[c-7],ut[c-16]),Y=Co(F,b,P,lt[c-7],lt[c-16]);lt[c]=Y|0,ut[c]=F|0}let{Ah:r,Al:n,Bh:i,Bl:o,Ch:a,Cl:l,Dh:u,Dl:p,Eh:m,El:x,Fh:y,Fl:f,Gh:g,Gl:w,Hh:E,Hl:S}=this;for(let c=0;c<80;c++){let h=_t(m,x,14)^_t(m,x,18)^ws(m,x,41),d=It(m,x,14)^It(m,x,18)^xs(m,x,41),b=m&y^~m&g,v=x&f^~x&w,_=Fo(S,d,v,_u[c],ut[c]),D=No(_,E,h,b,Su[c],lt[c]),P=_|0,K=_t(r,n,28)^ws(r,n,34)^ws(r,n,39),F=It(r,n,28)^xs(r,n,34)^xs(r,n,39),Y=r&i^r&a^i&a,C=n&o^n&l^o&l;E=g|0,S=w|0,g=y|0,w=f|0,y=m|0,f=x|0,{h:m,l:x}=Ve(u|0,p|0,D|0,P|0),u=a|0,p=l|0,a=i|0,l=o|0,i=r|0,o=n|0;let L=ko(P,F,C);r=Ro(L,D,K,Y),n=L|0}({h:r,l:n}=Ve(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=Ve(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l}=Ve(this.Ch|0,this.Cl|0,a|0,l|0),{h:u,l:p}=Ve(this.Dh|0,this.Dl|0,u|0,p|0),{h:m,l:x}=Ve(this.Eh|0,this.El|0,m|0,x|0),{h:y,l:f}=Ve(this.Fh|0,this.Fl|0,y|0,f|0),{h:g,l:w}=Ve(this.Gh|0,this.Gl|0,g|0,w|0),{h:E,l:S}=Ve(this.Hh|0,this.Hl|0,E|0,S|0),this.set(r,n,i,o,a,l,u,p,m,x,y,f,g,w,E,S)}roundClean(){Tt(lt,ut)}destroy(){this.destroyed=!0,Tt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Bn=class extends Pn{constructor(){super(64,Wo)}};var jt=Tn(()=>new Mn,Dn(1));var kn=Tn(()=>new Bn,Dn(3));function er(s,e,t=()=>{}){if(!Array.isArray(s))throw new TypeError(`"${e}" expected array, got type=${typeof s}`);for(let r=0;r<s.length;r++)t(s[r],`${e}[${r}]`);return s}var G=(s,e,t)=>Re(s,e,t),Rn=Qe;function jo(s,e=""){if(typeof s!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof s)}return s}function ht(s,e="object"){if(s===null||typeof s!="object"||Array.isArray(s))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof s}`);return s}function Dt(s,e){if(typeof s!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof s}`);return s}var Es=Xs,Le=(...s)=>In(...s),Zt=s=>Js(s),dt=$s,At=s=>zo(s),Qs=BigInt(0),$o=BigInt(1),Iu=s=>s?`"${s}" `:"";function De(s,e=""){if(typeof s!="boolean")throw new TypeError(Iu(e)+"expected boolean, got type="+typeof s);return s}function tr(s){if(typeof s=="bigint"){if(!ft(s))throw new RangeError("positive bigint expected, got "+s)}else Rn(s);return s}function pt(s,e=""){if(typeof s!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof s)}if(!Number.isSafeInteger(s)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+s)}}function Ss(s){let e=tr(s).toString(16);return e.length&1?"0"+e:e}function Zo(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);return s===""?Qs:BigInt("0x"+s)}function $e(s){return Zo(Xs(s))}function Mt(s){return Zo(Xs(rr(Re(s)).reverse()))}function sr(s,e){if(Qe(e),e===0)throw new Error("zero output length is invalid");s=tr(s);let t=e*2,r=s.toString(16);if(r.length>t)throw new RangeError("number is too large");return Js(r.padStart(t,"0"))}function Ln(s,e){return sr(s,e).reverse()}function rr(s){return Uint8Array.from(G(s))}function ft(s){return typeof s=="bigint"&&Qs<=s}function Cn(s,e,t){return ft(s)&&ft(e)&&ft(t)&&e<=s&&s<t}function Yt(s,e,t,r){if(!Cn(e,t,r))throw new RangeError("expected valid "+s+": "+t+" <= n < "+r+", got "+e)}function Xt(s){if(s<Qs)throw new Error("expected non-negative bigint, got "+s);return s===Qs?0:s.toString(2).length}var _s=s=>(pt(s,"n"),($o<<BigInt(s))-$o);function Yo(s,e,t){if(Qe(s,"hashLen"),Qe(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let r=w=>new Uint8Array(w),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3,l=r(s),u=r(s),p=0,m=()=>{l.fill(1),u.fill(0),p=0},x=(...w)=>t(u,Le(l,...w)),y=(w=n)=>{u=x(i,w),l=x(),w.length!==0&&(u=x(o,w),l=x())},f=()=>{if(p++>=a)throw new Error("drbg: tried max amount of iterations");let w=0,E=[];for(;w<e;){l=x();let S=l.slice();E.push(S),w+=l.length}return Le(...E)};return(w,E)=>{m(),y(w);let S;for(;(S=E(f()))===void 0;)y();return m(),S}}function Ae(s,e={},t={},r="object"){ht(s,r),ht(e,"fields"),ht(t,"optFields");function n(o,a,l){let u=r==="object"?`param "${String(o)}"`:`"${r}.${String(o)}"`,p=s[o];if(!Object.hasOwn(s,o)&&(l?p!==void 0:a!=="function"))throw new TypeError(`${u} is invalid: expected own property`);if(l&&p===void 0)return;let m=typeof p;if(m!==a||p===null)throw new TypeError(`${u} is invalid: expected ${a}, got ${m}`)}let i=(o,a)=>Object.entries(o).forEach(([l,u])=>n(l,u,a));i(e,!1),i(t,!0)}var oe=BigInt(0),H=BigInt(1),mt=BigInt(2),Qo=BigInt(3),Fn=BigInt(4),ea=BigInt(5),Tu=BigInt(7),ta=BigInt(8),Du=BigInt(9),Au=BigInt(15),sa=BigInt(16),Mu=BigInt("0x10000000000000000");function J(s,e){if(e<=oe)throw new Error("mod: expected positive modulus, got "+e);let t=s%e;return t>=oe?t:e+t}function ra(s,e,t){if(t<=H)throw new Error("pow: expected modulus > 1, got "+t);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<oe)throw new Error("invalid exponent, negatives unsupported");if(e===oe)return H;if(e===H)return s;let r=s%t;if(r<oe&&(r+=t),e<Mu){let a=H;for(;e>oe;)e&H&&(a=a*r%t),r=r*r%t,e>>=H;return a}let n=[];for(;e>oe;)n.push(Number(e&Au)),e>>=Fn;let i=new Array(16);i[0]=H,i[1]=r;for(let a=2;a<16;a++)i[a]=i[a-1]*r%t;let o=i[n[n.length-1]];for(let a=n.length-2;a>=0;a--){o=o*o%t,o=o*o%t,o=o*o%t,o=o*o%t;let l=n[a];l!==0&&(o=o*i[l]%t)}return o}function X(s,e,t){if(t<=H)throw new Error("pow2: expected modulus > 1, got "+t);if(e<oe)throw new Error("pow2: expected non-negative exponent, got "+e);let r=s;for(;e-- >oe;)r*=r,r%=t;return r}function Xo(s,e){if(s===oe)throw new Error("invert: expected non-zero number");if(e<=H)throw new Error("invert: expected modulus > 1, got "+e);let t=J(s,e),r=e,n=oe,i=H;for(;t!==oe;){let a=r/t,l=r-t*a,u=n-i*a;r=t,t=l,n=i,i=u}if(r!==H)throw new Error("invert: does not exist");return J(n,e)}function na(s,e){if(e<=H)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=J(s,e);if(t===oe)throw new Error("invertCt: expected non-zero number");let r=ra(t,e-mt,e);if(J(t*r,e)!==H)throw new Error("invertCt: does not exist");return r}function Nn(s,e,t){let r=s;if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function On(s,e){if((s&H)===oe)throw new Error(e+": expected odd modulus, got "+s)}function ia(s,e){let t=s,r=(t.ORDER+H)/Fn,n=t.pow(e,r);return Nn(t,n,e),n}function Pu(s,e){let t=s,r=(t.ORDER-ea)/ta,n=t.mul(e,mt),i=t.pow(n,r),o=t.mul(e,i),a=t.mul(t.mul(o,mt),i),l=t.mul(o,t.sub(a,t.ONE));return Nn(t,l,e),l}function Bu(s){let e=Qt(s),t=oa(s),r=t(e,e.neg(e.ONE)),n=t(e,r),i=t(e,e.neg(r)),o=(s+Tu)/sa;return((a,l)=>{let u=a,p=u.pow(l,o),m=u.mul(p,r),x=u.mul(p,n),y=u.mul(p,i),f=u.eql(u.sqr(m),l),g=u.eql(u.sqr(x),l);p=u.cmov(p,m,f),m=u.cmov(y,x,g);let w=u.eql(u.sqr(m),l),E=u.cmov(p,m,w);return Nn(u,E,l),E})}function oa(s){if(s<Qo)throw new Error("sqrt is not defined for small field");On(s,"tonelliShanks");let e=s-H,t=0;for(;e%mt===oe;)e/=mt,t++;let r=mt,n=Qt(s);for(;Is(n,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return ia;let i=n.pow(r,e),o=(e+H)/mt;return function(l,u){let p=l;if(p.is0(u))return u;if(Is(p,u)!==1)throw new Error("Cannot find square root");let m=t,x=p.mul(p.ONE,i),y=p.pow(u,e),f=p.pow(u,o);for(;!p.eql(y,p.ONE);){if(p.is0(y))throw new Error("Cannot find square root: probably non-prime P");let g=1,w=p.sqr(y);for(;!p.eql(w,p.ONE);)if(g++,w=p.sqr(w),g===m)throw new Error("Cannot find square root");let E=H<<BigInt(m-g-1),S=p.pow(x,E);m=g,x=p.sqr(S),y=p.mul(y,x),f=p.mul(f,S)}return f}}function ku(s){return On(s,"Fp.sqrt"),s%Fn===Qo?ia:s%ta===ea?Pu:s%sa===Du?Bu(s):oa(s)}var aa=(s,e)=>(J(s,e)&H)===H,Ru=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Jt(s){if(ht(s,"field"),typeof s.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof s.ORDER);pt(s.BYTES,"BYTES"),pt(s.BITS,"BITS");for(let e of Ru)Dt(s[e],"field."+e);if(s.BYTES<1||s.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(s.ORDER<=H)throw new Error("invalid field: expected ORDER > 1, got "+s.ORDER);return s}function ir(s,e,t=!1){Jt(s),er(e,"nums"),De(t,"passZero");let r=s,n=new Array(e.length).fill(t?r.ZERO:void 0),i=e.reduce((a,l,u)=>r.is0(l)?a:(n[u]=a,r.mul(a,l)),r.ONE),o=r.inv(i);return e.reduceRight((a,l,u)=>r.is0(l)?a:(n[u]=r.mul(a,n[u]),r.mul(a,l)),o),n}function Is(s,e){Jt(s);let t=s;On(t.ORDER,"FpLegendre");let r=(t.ORDER-H)/mt,n=t.pow(e,r),i=t.eql(n,t.ONE),o=t.eql(n,t.ZERO),a=t.eql(n,t.neg(t.ONE));if(!i&&!o&&!a)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function Lu(s,e){if(e!==void 0&&Rn(e),s<=oe)throw new Error("invalid n length: expected positive n, got "+s);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Xt(s);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let r=e!==void 0?e:t,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var Jo=new WeakMap,nr=class{ORDER;BITS;BYTES;isLE;ZERO=oe;ONE=H;_lengths;_mod;constructor(e,t={}){if(e<=H)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:n,nByteLength:i}=Lu(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,Object.freeze(this)}create(e){return J(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return oe<=e&&e<this.ORDER}is0(e){return e===oe}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&H)===H}neg(e){return J(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return J(e*e,this.ORDER)}add(e,t){return J(e+t,this.ORDER)}sub(e,t){return J(e-t,this.ORDER)}mul(e,t){return J(e*t,this.ORDER)}pow(e,t){return ra(e,t,this.ORDER)}div(e,t){return J(e*Xo(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Xo(e,this.ORDER)}sqrt(e){let t=Jo.get(this);return t||Jo.set(this,t=ku(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Ln(e,this.BYTES):sr(e,this.BYTES)}fromBytes(e,t=!1){G(e);let{_lengths:r,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let u=new Uint8Array(n);u.set(e,i?0:u.length-e.length),e=u}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=i?Mt(e):$e(e);if(a&&(l=J(l,o)),!t&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return ir(this,e,!0)}cmov(e,t,r){return De(r,"condition"),r?t:e}};function Qt(s,e={}){return Object.freeze(nr.prototype),new nr(s,e)}function ca(s){if(typeof s!="bigint")throw new Error("field order must be bigint");if(s<=H)throw new Error("field order must be greater than 1");let e=Xt(s-H);return Math.ceil(e/8)}function or(s){let e=ca(s);return e+Math.ceil(e/2)}function ar(s,e,t=!1){G(s);let r=s.length,n=ca(e),i=Math.max(or(e),16);if(r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let o=t?Mt(s):$e(s),a=J(o,e-H)+H;return t?Ln(a,n):sr(a,n)}var zn=BigInt(0),Ts=BigInt(1),Cu=BigInt(4),Un=16,la=128,Fu=5,ua=2**31;function gt(s){let e=s;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof s);Dt(e.fromAffine,"Point.fromAffine"),Dt(e.fromBytes,"Point.fromBytes"),Dt(e.fromHex,"Point.fromHex"),ht(e.BASE,"Point.BASE"),ht(e.ZERO,"Point.ZERO"),Jt(e.Fp),Jt(e.Fn)}function cr(s,e){gt(s),fa(e,s);let t=ir(s.Fp,e.map(r=>r.Z));return e.map((r,n)=>s.fromAffine(r.toAffine(t[n])))}function Nu(s,e,t=1){if(!Number.isSafeInteger(s)||s<t||s>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+s)}function Ou(s,e){let t=s*(4*e+128);if(t>ua)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+ua/2**20+" MiB")}function qn(s,e){if(s!==void 0){Dt(s,"randomBytes");try{let t=s(e);if(!dt(t)||t.length!==e)return}catch{return}return s}}function fa(s,e){er(s,"points"),s.forEach((t,r)=>{if(!(t instanceof e))throw new Error("invalid point at index "+r)})}function Uu(s,e,t){if(!Array.isArray(s))throw new Error("array of scalars expected");s.forEach((r,n)=>{if(!(t===void 0?e.isValid(r):ft(r)&&r<t))throw new Error("invalid scalar at index "+n)})}var da=new WeakMap;function Kn(s){return da.get(s)||1}function Ku(s,e){let t=s.double(),r=[s];for(let n=1;n<e;n++)r.push(r[n-1].add(t));return r}function zu(s,e){let t=2**e,r=t/2,n=BigInt(t-1),i=[];for(;s>zn;){let o=0;s&Ts&&(o=Number(s&n),o>=r&&(o-=t),s-=BigInt(o)),i.push(o),s>>=Ts}return i}function qu(s,e,t){let r=2**e,n=r/2,i=BigInt(r-1),o=BigInt(e),a=[];for(let l=0;l<t;l++){let u=Number(s&i);s>>=o,u>n&&(u-=r,s+=Ts),a.push(u)}if(s!==zn)throw new Error("invalid wnaf");return a}function Gu(s,e,t){let r=0;for(let i of t)r=Math.max(r,i.length);let n=s;for(let i=r-1;i>=0;i--){i!==r-1&&(n=n.double());for(let o=0;o<t.length;o++){let a=t[o][i];if(a){let l=e[o][Math.abs(a)-1>>1];n=n.add(a<0?l.negate():l)}}}return n}var es=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){gt(e),this.randomBytes=qn(t,Un),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,r){let n=Math.ceil(r/t)+1,i=2**(t-1),o=[],a=e;for(let l=0;l<n;l++){let u=a;for(let p=0;p<i;p++)o.push(u),u=u.add(a);a=o[o.length-1].double()}return{W:t,bits:r,windows:n,comp:o}}wnafCachedCT(e,t){let{W:r,windows:n,comp:i}=e,o=2**(r-1),a=qu(t,r,n),l=this.ZERO,u=this.BASE;for(let p=0;p<n;p++){let m=a[p],x=p*o,y=Math.abs(m)-1,f=i[x];for(let w=1;w<o;w++)f=w===y?i[x+w]:f;let g=f.negate();m===0?u=u.add(i[x]):l=l.add(m<0?g:f)}return{p:l,f:u}}getWnafPrecomputes(e,t,r,n){let i=this.wnafPrecomputes.get(t),o=i?.find(a=>a.W===e&&a.bits===r);return o||(o=this.buildWnafTable(t,e,r),typeof n=="function"&&(o={...o,comp:n(o.comp)}),i||(i=[],this.wnafPrecomputes.set(t,i)),i.push(o)),o}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!Cn(t,Ts,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,r,n){let i=Kn(e);return i===1?this.fixedWindowCT(e,t,r):this.wnafCachedCT(this.getWnafPrecomputes(i,e,r,n),t)}mulCT(e,t,r){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,r)}mulCTBlinded(e,t,r){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let n=this.Point.Fn.BITS+la,i=this.randomBytes(Un);if(!dt(i)||i.length!==Un)throw new Error("randomBytes returned invalid byte array");i[0]=i[0]&63|128;let o=t+$e(i)*this.Point.Fn.ORDER;return this.runCT(e,o,n,r)}fixedWindowCT(e,t,r){let n=Fu,i=1<<n,o=_s(n),a=new Array(i);a[0]=this.ZERO;for(let p=1;p<i;p++)a[p]=a[p-1].add(e);let l=Math.ceil(r/n),u=this.ZERO;for(let p=l-1;p>=0;p--){if(p!==l-1)for(let y=0;y<n;y++)u=u.double();let m=Number(t>>BigInt(p*n)&o),x=a[0];for(let y=1;y<i;y++)x=y===m?a[y]:x;u=u.add(x)}return{p:u,f:u}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===Ts?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,r,n){return this.shouldBlind(e,r)?this.mulCTBlinded(e,t,n):this.mulCT(e,t,n)}mulUnsafe(e,t,r){if(this.assertPoint(e),!ft(t))throw new Error("invalid scalar");let n=Kn(e);if(n===1||t>=this.Point.Fn.ORDER)return lr(this.Point,[e],[t],!0);let i=this.getWnafPrecomputes(n,e,this.bits,r);return this.wnafCachedCT(i,t).p}setWindowSize(e,t){this.assertPoint(e),Nu(t,this.bits);let r=Math.ceil((this.bits+la)/t)+1;Ou(r*2**(t-1),this.Point.Fp.BYTES),da.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Kn(e)!==1}};function lr(s,e,t,r=!1){if(gt(s),fa(e,s),De(r,"allowOversized"),Uu(t,s.Fn,r?s.Fn.ORDER**Cu:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let n=e.map(o=>Ku(o,4)),i=t.map(o=>zu(o,4));return Gu(s.ZERO,n,i)}function ha(s,e,t){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Jt(e),e}else return Qt(s,{isLE:t})}function ur(s,e,t={},r){if(s!=="weierstrass"&&s!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(r===void 0&&(r=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);Ae(t);for(let l of["p","n","h"]){let u=e[l];if(!(ft(u)&&u!==zn))throw new Error(`CURVE.${l} must be positive bigint`)}let n=ha(e.p,t.Fp,r),i=ha(e.n,t.Fn,r),a=["Gx","Gy","a",s==="weierstrass"?"b":"d"];for(let l of a)if(!n.isValid(e[l]))throw new Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function hr(s,e){return function(r){let n=s(r);return{secretKey:n,publicKey:e(n)}}}var fr=BigInt(0),dr=BigInt(1),pr=BigInt(2),Hu=BigInt(4),pa=BigInt(8);function Wu(s,e,t,r){let n=s.sqr(t),i=s.sqr(r),o=s.add(s.mul(e.a,n),i),a=s.add(s.ONE,s.mul(e.d,s.mul(n,i)));return s.eql(o,a)}function ma(s,e={}){Ae(e,{},{},"extraOpts");let t=e,r=ur("edwards",s,t,t.FpFnLE),{Fp:n,Fn:i}=r,o=r.CURVE,{h:a}=o;if(Is(n,o.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Is(n,o.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Ae(t,{},{uvRatio:"function",randomBytes:"function"});let l=t.randomBytes===void 0?At:t.randomBytes,u=pr<<BigInt(n.BYTES*8)-dr;function p(S){if(!n.isOdd)throw new Error("Field does not have .isOdd()");return n.isOdd(S)}let m=t.uvRatio===void 0?(S,c)=>{try{return{isValid:!0,value:n.sqrt(n.div(S,c))}}catch{return{isValid:!1,value:fr}}}:t.uvRatio;if(!Wu(n,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");let x=n.eql(o.a,n.neg(n.ONE))?S=>n.neg(S):n.eql(o.a,n.ONE)?S=>S:S=>n.mul(o.a,S);function y(S,c,h=!1){let d=h?dr:fr;return Yt("coordinate "+S,c,d,u),c}function f(S){if(!(S instanceof g))throw new Error("EdwardsPoint expected")}class g{static BASE=new g(o.Gx,o.Gy,n.ONE,n.mul(o.Gx,o.Gy));static ZERO=new g(n.ZERO,n.ONE,n.ONE,n.ZERO);static Fp=n;static Fn=i;X;Y;Z;T;constructor(c,h,d,b){this.X=y("x",c),this.Y=y("y",h),this.Z=y("z",d,!0),this.T=y("t",b),Object.freeze(this)}static CURVE(){return o}static fromAffine(c){if(c instanceof g)throw new Error("extended point not allowed");let{x:h,y:d}=c||{};return y("x",h),y("y",d),new g(h,d,n.ONE,n.mul(h,d))}static fromBytes(c,h=!1){let d=n.BYTES,{a:b,d:v}=o;c=rr(G(c,d,"point")),De(h,"zip215");let _=rr(c),D=c[d-1];_[d-1]=D&-129;let P=Mt(_),K=h?u:n.ORDER;Yt("point.y",P,fr,K);let F=n.sqr(P),Y=n.sub(F,n.ONE),C=n.sub(n.mulN(v,F),b),{isValid:L,value:I}=m(Y,C);if(!L)throw new Error("bad point: invalid y coordinate");let A=p(I),B=(D&128)!==0;if(!h&&n.is0(I)&&B)throw new Error("bad point: x=0 and x_0=1");return B!==A&&(I=n.neg(I)),g.fromAffine({x:I,y:P})}static fromHex(c,h=!1){return g.fromBytes(Zt(c),h)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(c=6,h=!0){return E.setWindowSize(this,c),h||this.multiply(pr),this}assertValidity(){let c=this,{a:h,d}=o;if(c.is0())throw new Error("bad point: ZERO");let{X:b,Y:v,Z:_,T:D}=c,P=n.sqr(b),K=n.sqr(v),F=n.sqr(_),Y=n.sqr(F),C=n.mul(P,h),L=n.mul(n.add(C,K),F),I=n.add(Y,n.mul(d,n.mul(P,K)));if(!n.eql(L,I))throw new Error("bad point: equation left != right (1)");let A=n.mul(b,v),B=n.mul(_,D);if(!n.eql(A,B))throw new Error("bad point: equation left != right (2)")}equals(c){f(c);let{X:h,Y:d,Z:b}=this,{X:v,Y:_,Z:D}=c,P=n.mul(h,D),K=n.mul(v,b),F=n.mul(d,D),Y=n.mul(_,b);return n.eql(P,K)&&n.eql(F,Y)}is0(){return this.equals(g.ZERO)}negate(){return new g(n.neg(this.X),this.Y,this.Z,n.neg(this.T))}double(){let{X:c,Y:h,Z:d}=this,b=n.sqr(c),v=n.sqr(h),_=n.mul(n.sqr(d),pr),D=x(b),P=n.addN(c,h),K=n.sub(n.subN(n.sqr(P),b),v),F=n.addN(D,v),Y=n.subN(F,_),C=n.subN(D,v),L=n.mul(K,Y),I=n.mul(F,C),A=n.mul(K,C),B=n.mul(Y,F);return new g(L,I,B,A)}add(c){f(c);let{d:h}=o,{X:d,Y:b,Z:v,T:_}=this,{X:D,Y:P,Z:K,T:F}=c,Y=n.mul(d,D),C=n.mul(b,P),L=n.mul(n.mulN(_,h),F),I=n.mul(v,K),A=n.sub(n.subN(n.mulN(n.addN(d,b),n.addN(D,P)),Y),C),B=n.subN(I,L),N=n.addN(I,L),M=n.sub(C,x(Y)),T=n.mul(A,B),k=n.mul(N,M),R=n.mul(A,M),O=n.mul(B,N);return new g(T,k,O,R)}subtract(c){return f(c),this.add(c.negate())}multiply(c){if(!i.isValidNot0(c))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:h,f:d}=E.mulSecret(this,c,a,w);return w([h,d])[0]}multiplyUnsafe(c){if(!i.isValid(c))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return c===fr?g.ZERO:this.is0()||c===dr?this:E.mulUnsafe(this,c,w)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return E.mulUnsafe(this,o.n).is0()}toAffine(c){let h=this,d=c;if(d!=null&&typeof d!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof d);let{X:b,Y:v,Z:_}=h,D=h.is0();d==null&&(d=D?n.create(pa):n.inv(_));let P=n.mul(b,d),K=n.mul(v,d),F=n.mul(_,d);if(D)return{x:n.ZERO,y:n.ONE};if(!n.eql(F,n.ONE))throw new Error("invZ was invalid");return{x:P,y:K}}clearCofactor(){return a===dr?this:a===pr?this.double():a===Hu?this.double().double():a===pa?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:c,y:h}=this.toAffine(),d=n.toBytes(h);return d[d.length-1]|=p(c)?128:0,d}toHex(){return Es(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let w=S=>cr(g,S),E=new es(g,l);return E.bits>=6&&g.BASE.precompute(6),Object.freeze(g.prototype),Object.freeze(g),g}function ga(s,e,t={}){if(gt(s),typeof e!="function")throw new Error('"hash" function param is required');let r=e,n=t;Ae(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:i}=n,{BASE:o,Fp:a,Fn:l}=s,u=r.outputLen,p=2*a.BYTES;if(u!==void 0&&(pt(u,"hash.outputLen"),u!==p))throw new Error(`hash.outputLen must be ${p}, got ${u}`);let m=n.randomBytes===void 0?At:n.randomBytes,x=n.toMontgomery,y=n.toMontgomerySecret,f=n.adjustScalarBytes===void 0?C=>C:n.adjustScalarBytes,g=n.domain===void 0?(C,L,I)=>{if(De(I,"phflag"),L.length||I)throw new Error("Contexts/pre-hash are not supported");return C}:n.domain;function w(C){return l.create(Mt(C))}function E(C){let L=D.secretKey;G(C,D.secretKey,"secretKey");let I=G(r(C),2*L,"hashedSecretKey"),A=f(I.slice(0,L)),B=I.slice(L,2*L),N=w(A);return{head:A,prefix:B,scalar:N}}function S(C){let{head:L,prefix:I,scalar:A}=E(C),B=o.multiply(A),N=B.toBytes();return{head:L,prefix:I,scalar:A,point:B,pointBytes:N}}function c(C){return S(C).pointBytes}function h(C=Uint8Array.of(),...L){let I=Le(...L);return w(r(g(I,G(C,void 0,"context"),!!i)))}function d(C,L,I={}){Ae(I,{},{},"options"),C=G(C,void 0,"message"),i&&(C=i(C));let{prefix:A,scalar:B,pointBytes:N}=S(L),M=h(I.context,A,C),T=o.multiply(M).toBytes(),k=h(I.context,T,N,C),R=l.create(M+k*B);if(!l.isValid(R))throw new Error("sign failed: invalid s");let O=Le(T,l.toBytes(R));return G(O,D.signature,"result")}let b={zip215:n.zip215};function v(C,L,I,A=b){Ae(A);let{context:B}=A,N=A.zip215===void 0?!!b.zip215:A.zip215,M=D.signature;C=G(C,M,"signature"),L=G(L,void 0,"message"),I=G(I,D.publicKey,"publicKey"),N!==void 0&&De(N,"zip215"),i&&(L=i(L));let T=M/2,k=C.subarray(0,T),R=Mt(C.subarray(T,M)),O,U,q;try{O=s.fromBytes(I,N),U=s.fromBytes(k,N),q=o.multiplyUnsafe(R)}catch{return!1}if(!N&&O.isSmallOrder())return!1;let z=h(B,k,I,L);return U.add(O.multiplyUnsafe(z)).subtract(q).clearCofactor().is0()}let _=a.BYTES,D={secretKey:_,publicKey:_,signature:2*_,seed:_};function P(C){return C=C===void 0?m(D.seed):C,G(C,D.seed,"seed")}function K(C){return dt(C)&&C.length===D.secretKey}function F(C,L){try{return!!s.fromBytes(C,L===void 0?b.zip215:L)}catch{return!1}}let Y={getExtendedPublicKey:S,randomSecretKey:P,isValidSecretKey:K,isValidPublicKey:F,toMontgomery(C){if(x===void 0)throw new Error("Montgomery conversion is not supported for this curve");return x(s.fromBytes(C))},toMontgomerySecret(C){if(y===void 0)throw new Error("Montgomery conversion is not supported for this curve");return y(C)}};return Object.freeze(D),Object.freeze(Y),Object.freeze({keygen:hr(P,c),getPublicKey:c,sign:d,verify:v,utils:Y,Point:s,lengths:D})}var Gn=BigInt(1),ba=BigInt(2);var Vu=BigInt(5),$u=BigInt(8),Hn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ju={p:Hn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:$u,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Zu(s){let e=BigInt(10),t=BigInt(20),r=BigInt(40),n=BigInt(80),i=Hn,a=s*s%i*s%i,l=X(a,ba,i)*a%i,u=X(l,Gn,i)*s%i,p=X(u,Vu,i)*u%i,m=X(p,e,i)*p%i,x=X(m,t,i)*m%i,y=X(x,r,i)*x%i,f=X(y,n,i)*y%i,g=X(f,n,i)*y%i,w=X(g,e,i)*p%i;return{pow_p_5_8:X(w,ba,i)*s%i,b2:a}}function xa(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}var ya=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Yu(s,e){let t=Hn,r=J(e*e*e,t),n=J(r*r*e,t),i=Zu(s*n).pow_p_5_8,o=J(s*r*i,t),a=J(e*o*o,t),l=o,u=J(o*ya,t),p=a===s,m=a===J(-s,t),x=a===J(-s*ya,t);return p&&(o=l),(m||x)&&(o=u),aa(o,t)&&(o=J(-o,t)),{isValid:p||m,value:o}}var Wn=ma(ju,{uvRatio:Yu}),wa=Wn.Fp;function Xu(s){let{y:e}=s;return wa.toBytes(wa.div(Gn+e,Gn-e))}function Ju(s){let e=Wn.Fp.BYTES;return Re(s,e),xa(kn(s.subarray(0,e))).subarray(0,e)}function Qu(s){return ga(Wn,kn,Object.assign({adjustScalarBytes:xa,toMontgomery:Xu,toMontgomerySecret:Ju,zip215:!0},s))}var va=Qu({});var Ds=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},mr=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ce={get(s=globalThis){let e=s.crypto;if(e?.subtle==null)throw new mr("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 gr=32;var Vn,eh=(async()=>{try{return await Ce.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function th(s,e,t){if(s.buffer instanceof ArrayBuffer){let r=await Ce.get().subtle.importKey("raw",s.buffer,{name:"Ed25519"},!1,["verify"]);return await Ce.get().subtle.verify({name:"Ed25519"},r,ke(e),ke(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function sh(s,e,t){return va.verify(e,t instanceof Uint8Array?t:t.subarray(),s)}async function Ea(s,e,t){return Vn==null&&(Vn=await eh),Vn?th(s,e,t):sh(s,e,t)}function br(s){return s==null?!1:typeof s.then=="function"&&typeof s.catch=="function"&&typeof s.finally=="function"}var yr=class{type="Ed25519";raw;constructor(e){this.raw=$n(e,gr)}toMultihash(){return Ne.digest(We(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();let n=Ea(this.raw,t,e);return br(n)?n.then(i=>(r?.signal?.throwIfAborted(),i)):n}};function jn(s){return s=$n(s,gr),new yr(s)}function $n(s,e){if(s=Uint8Array.from(s??[]),s.length!==e)throw new re(`Key must be a Uint8Array of length ${e}, got ${s.length}`);return s}var nh=Math.pow(2,7),ih=Math.pow(2,14),oh=Math.pow(2,21),Zn=Math.pow(2,28),Yn=Math.pow(2,35),Xn=Math.pow(2,42),Jn=Math.pow(2,49),W=128,fe=127;function Fe(s){if(s<nh)return 1;if(s<ih)return 2;if(s<oh)return 3;if(s<Zn)return 4;if(s<Yn)return 5;if(s<Xn)return 6;if(s<Jn)return 7;if(Number.MAX_SAFE_INTEGER!=null&&s>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Qn(s,e,t=0){switch(Fe(s)){case 8:e[t++]=s&255|W,s/=128;case 7:e[t++]=s&255|W,s/=128;case 6:e[t++]=s&255|W,s/=128;case 5:e[t++]=s&255|W,s/=128;case 4:e[t++]=s&255|W,s>>>=7;case 3:e[t++]=s&255|W,s>>>=7;case 2:e[t++]=s&255|W,s>>>=7;case 1:{e[t++]=s&255,s>>>=7;break}default:throw new Error("unreachable")}return e}function ah(s,e,t=0){switch(Fe(s)){case 8:e.set(t++,s&255|W),s/=128;case 7:e.set(t++,s&255|W),s/=128;case 6:e.set(t++,s&255|W),s/=128;case 5:e.set(t++,s&255|W),s/=128;case 4:e.set(t++,s&255|W),s>>>=7;case 3:e.set(t++,s&255|W),s>>>=7;case 2:e.set(t++,s&255|W),s>>>=7;case 1:{e.set(t++,s&255),s>>>=7;break}default:throw new Error("unreachable")}return e}function ei(s,e){let t=s[e],r=0;if(r+=t&fe,t<W||(t=s[e+1],r+=(t&fe)<<7,t<W)||(t=s[e+2],r+=(t&fe)<<14,t<W)||(t=s[e+3],r+=(t&fe)<<21,t<W)||(t=s[e+4],r+=(t&fe)*Zn,t<W)||(t=s[e+5],r+=(t&fe)*Yn,t<W)||(t=s[e+6],r+=(t&fe)*Xn,t<W)||(t=s[e+7],r+=(t&fe)*Jn,t<W))return r;throw new RangeError("Could not decode varint")}function ch(s,e){let t=s.get(e),r=0;if(r+=t&fe,t<W||(t=s.get(e+1),r+=(t&fe)<<7,t<W)||(t=s.get(e+2),r+=(t&fe)<<14,t<W)||(t=s.get(e+3),r+=(t&fe)<<21,t<W)||(t=s.get(e+4),r+=(t&fe)*Zn,t<W)||(t=s.get(e+5),r+=(t&fe)*Yn,t<W)||(t=s.get(e+6),r+=(t&fe)*Xn,t<W)||(t=s.get(e+7),r+=(t&fe)*Jn,t<W))return r;throw new RangeError("Could not decode varint")}function ti(s,e,t=0){return e==null&&(e=he(Fe(s))),e instanceof Uint8Array?Qn(s,e,t):ah(s,e,t)}function si(s,e=0){return s instanceof Uint8Array?ei(s,e):ch(s,e)}var ni=new Float32Array([-0]),bt=new Uint8Array(ni.buffer);function _a(s,e,t){ni[0]=s,e[t]=bt[0],e[t+1]=bt[1],e[t+2]=bt[2],e[t+3]=bt[3]}function Ia(s,e){return bt[0]=s[e],bt[1]=s[e+1],bt[2]=s[e+2],bt[3]=s[e+3],ni[0]}var ii=new Float64Array([-0]),de=new Uint8Array(ii.buffer);function Ta(s,e,t){ii[0]=s,e[t]=de[0],e[t+1]=de[1],e[t+2]=de[2],e[t+3]=de[3],e[t+4]=de[4],e[t+5]=de[5],e[t+6]=de[6],e[t+7]=de[7]}function Da(s,e){return de[0]=s[e],de[1]=s[e+1],de[2]=s[e+2],de[3]=s[e+3],de[4]=s[e+4],de[5]=s[e+5],de[6]=s[e+6],de[7]=s[e+7],ii[0]}var lh=BigInt(Number.MAX_SAFE_INTEGER),uh=BigInt(Number.MIN_SAFE_INTEGER),Me=class s{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,r=~this.hi>>>0;return t===0&&(r=r+1>>>0),-(t+r*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 t=~this.lo+1>>>0,r=~this.hi>>>0;return t===0&&(r=r+1>>>0),-(BigInt(t)+(BigInt(r)<<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,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(e===0n)return Pt;if(e<lh&&e>uh)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let r=e>>32n,n=e-(r<<32n);return t&&(r=~r|0n,n=~n|0n,++n>Aa&&(n=0n,++r>Aa&&(r=0n))),new s(Number(n),Number(r))}static fromNumber(e){if(e===0)return Pt;let t=e<0;t&&(e=-e);let r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new s(r,n)}static from(e){return typeof e=="number"?s.fromNumber(e):typeof e=="bigint"?s.fromBigInt(e):typeof e=="string"?s.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new s(e.low>>>0,e.high>>>0):Pt}},Pt=new Me(0,0);Pt.toBigInt=function(){return 0n};Pt.zzEncode=Pt.zzDecode=function(){return this};Pt.length=function(){return 1};var Aa=4294967296n;function Ma(s){let e=0,t=0;for(let r=0;r<s.length;++r)t=s.charCodeAt(r),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(s.charCodeAt(r+1)&64512)===56320?(++r,e+=4):e+=3;return e}function Pa(s,e,t){if(t-e<1)return"";let n,i=[],o=0,a;for(;e<t;)a=s[e++],a<128?i[o++]=a:a>191&&a<224?i[o++]=(a&31)<<6|s[e++]&63:a>239&&a<365?(a=((a&7)<<18|(s[e++]&63)<<12|(s[e++]&63)<<6|s[e++]&63)-65536,i[o++]=55296+(a>>10),i[o++]=56320+(a&1023)):i[o++]=(a&15)<<12|(s[e++]&63)<<6|s[e++]&63,o>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,i)),o=0);return n!=null?(o>0&&n.push(String.fromCharCode.apply(String,i.slice(0,o))),n.join("")):String.fromCharCode.apply(String,i.slice(0,o))}function oi(s,e,t){let r=t,n,i;for(let o=0;o<s.length;++o)n=s.charCodeAt(o),n<128?e[t++]=n:n<2048?(e[t++]=n>>6|192,e[t++]=n&63|128):(n&64512)===55296&&((i=s.charCodeAt(o+1))&64512)===56320?(n=65536+((n&1023)<<10)+(i&1023),++o,e[t++]=n>>18|240,e[t++]=n>>12&63|128,e[t++]=n>>6&63|128,e[t++]=n&63|128):(e[t++]=n>>12|224,e[t++]=n>>6&63|128,e[t++]=n&63|128);return t-r}function Ue(s,e){return RangeError(`index out of range: ${s.pos} + ${e??1} > ${s.len}`)}function wr(s,e){return(s[e-4]|s[e-3]<<8|s[e-2]<<16|s[e-1]<<24)>>>0}var ai=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=ke(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,Ue(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 Ue(this,4);return wr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ue(this,4);return wr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ue(this,4);let e=Ia(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ue(this,4);let e=Da(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw Ue(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){let e=this.bytes();return Pa(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Ue(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Ue(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 Me(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*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;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Ue(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Ue(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Ue(this,8);let e=wr(this.buf,this.pos+=4),t=wr(this.buf,this.pos+=4);return new Me(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=ei(this.buf,this.pos);return this.pos+=Fe(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 As(s){return new ai(s instanceof Uint8Array?s:s.subarray())}function ye(s,e,t){let r=As(s);return e.decode(r,void 0,t)}function ci(s){let e=s??8192,t=e>>>1,r,n=e;return function(o){if(o<1||o>t)return he(o);n+o>e&&(r=he(e),n=0);let a=r.subarray(n,n+=o);return(n&7)!==0&&(n=(n|7)+1),a}}var Bt=class{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}};function li(){}var hi=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},hh=ci();function fh(s){return globalThis.Buffer!=null?he(s):hh(s)}var Ps=class{len;head;tail;states;constructor(){this.len=0,this.head=new Bt(li,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new Bt(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new fi((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(xr,10,Me.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Me.fromBigInt(e);return this._push(xr,t.length(),t)}uint64Number(e){return this._push(Qn,Fe(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 t=Me.fromBigInt(e).zzEncode();return this._push(xr,t.length(),t)}sint64Number(e){let t=Me.fromNumber(e).zzEncode();return this._push(xr,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(ui,1,e?1:0)}fixed32(e){return this._push(Ms,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Me.fromBigInt(e);return this._push(Ms,4,t.lo)._push(Ms,4,t.hi)}fixed64Number(e){let t=Me.fromNumber(e);return this._push(Ms,4,t.lo)._push(Ms,4,t.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(_a,4,e)}double(e){return this._push(Ta,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(ui,1,0):this.uint32(t)._push(ph,t,e)}string(e){let t=Ma(e);return t!==0?this.uint32(t)._push(oi,t,e):this._push(ui,1,0)}fork(){return this.states=new hi(this),this.head=this.tail=new Bt(li,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 Bt(li,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r!==0&&(this.tail.next=e.next,this.tail=t,this.len+=r),this}finish(){let e=this.head.next,t=fh(this.len),r=0;for(;e!=null;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}};function ui(s,e,t){e[t]=s&255}function dh(s,e,t){for(;s>127;)e[t++]=s&127|128,s>>>=7;e[t]=s}var fi=class extends Bt{next;constructor(e,t){super(dh,e,t),this.next=void 0}};function xr(s,e,t){for(;s.hi!==0;)e[t++]=s.lo&127|128,s.lo=(s.lo>>>7|s.hi<<25)>>>0,s.hi>>>=7;for(;s.lo>127;)e[t++]=s.lo&127|128,s.lo=s.lo>>>7;e[t++]=s.lo}function Ms(s,e,t){e[t]=s&255,e[t+1]=s>>>8&255,e[t+2]=s>>>16&255,e[t+3]=s>>>24}function ph(s,e,t){e.set(s,t)}globalThis.Buffer!=null&&(Ps.prototype.bytes=function(s){let e=s.length>>>0;return this.uint32(e),e>0&&this._push(mh,e,s),this},Ps.prototype.string=function(s){let e=globalThis.Buffer.byteLength(s);return this.uint32(e),e>0&&this._push(gh,e,s),this});function mh(s,e,t){e.set(s,t)}function gh(s,e,t){s.length<40?oi(s,e,t):e.utf8Write!=null?e.utf8Write(s,t):e.set(j(s),t)}function di(){return new Ps}function we(s,e){let t=di();return e.encode(s,t,{lengthDelimited:!1}),t.finish()}function*xe(s,e,t){let r=As(s);yield*e.stream(r,void 0,"$",t)}var vr={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Er(s,e,t,r,n){return{name:s,type:e,encode:t,decode:r,stream:n}}function pi(s){function e(i){if(s[i.toString()]==null)throw new Error("Invalid enum value");return s[i]}let t=function(o,a){let l=e(o);a.int32(l)},r=function(o){let a=o.int32();return e(a)},n=function*(o){let a=o.int32();yield e(a)};return Er("enum",vr.VARINT,t,r,n)}function ve(s,e,t){return Er("message",vr.LENGTH_DELIMITED,s,e,t)}var Z=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var Q;(function(s){s.RSA="RSA",s.Ed25519="Ed25519",s.secp256k1="secp256k1",s.ECDSA="ECDSA"})(Q||(Q={}));var mi;(function(s){s[s.RSA=0]="RSA",s[s.Ed25519=1]="Ed25519",s[s.secp256k1=2]="secp256k1",s[s.ECDSA=3]="ECDSA"})(mi||(mi={}));(function(s){s.codec=()=>pi(mi)})(Q||(Q={}));var je;(function(s){let e;s.codec=()=>(e==null&&(e=ve((i,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),i.Type!=null&&(o.uint32(8),Q.codec().encode(i.Type,o)),i.Data!=null&&(o.uint32(18),o.bytes(i.Data)),a.lengthDelimited!==!1&&o.ldelim()},(i,o,a={})=>{let l={},u=o==null?i.len:i.pos+o;for(;i.pos<u;){let p=i.uint32();switch(p>>>3){case 1:{l.Type=Q.codec().decode(i);break}case 2:{l.Data=i.bytes();break}default:{i.skipType(p&7);break}}}return l},function*(i,o,a,l={}){let u=o==null?i.len:i.pos+o;for(;i.pos<u;){let p=i.uint32();switch(p>>>3){case 1:{yield{field:`${a}.Type`,value:Q.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(p&7);break}}}})),e);function t(i){return we(i,s.codec())}s.encode=t;function r(i,o){return ye(i,s.codec(),o)}s.decode=r;function n(i,o){return xe(i,s.codec(),o)}s.stream=n})(je||(je={}));var gi;(function(s){let e;s.codec=()=>(e==null&&(e=ve((i,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),i.Type!=null&&(o.uint32(8),Q.codec().encode(i.Type,o)),i.Data!=null&&(o.uint32(18),o.bytes(i.Data)),a.lengthDelimited!==!1&&o.ldelim()},(i,o,a={})=>{let l={},u=o==null?i.len:i.pos+o;for(;i.pos<u;){let p=i.uint32();switch(p>>>3){case 1:{l.Type=Q.codec().decode(i);break}case 2:{l.Data=i.bytes();break}default:{i.skipType(p&7);break}}}return l},function*(i,o,a,l={}){let u=o==null?i.len:i.pos+o;for(;i.pos<u;){let p=i.uint32();switch(p>>>3){case 1:{yield{field:`${a}.Type`,value:Q.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(p&7);break}}}})),e);function t(i){return we(i,s.codec())}s.encode=t;function r(i,o){return ye(i,s.codec(),o)}s.decode=r;function n(i,o){return xe(i,s.codec(),o)}s.stream=n})(gi||(gi={}));var ks={};_e(ks,{MAX_RSA_KEY_SIZE:()=>bi,generateRSAKeyPair:()=>Fa,jwkToJWKKeyPair:()=>Na,jwkToPkcs1:()=>xh,jwkToPkix:()=>vi,jwkToRSAPrivateKey:()=>Ii,pkcs1MessageToJwk:()=>wi,pkcs1MessageToRSAPrivateKey:()=>Ei,pkcs1ToJwk:()=>wh,pkcs1ToRSAPrivateKey:()=>Ca,pkixMessageToJwk:()=>xi,pkixMessageToRSAPublicKey:()=>_i,pkixToJwk:()=>vh,pkixToRSAPublicKey:()=>Si});var ts=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=ks.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ce.createV1(114,this._multihash)}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}verify(e,t,r){return La(this.jwk,t,e,r)}},Bs=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=ks.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}sign(e,t){return Ra(this.jwk,e,t)}};var bi=8192,yi=18,bh=1062,yh=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function wh(s){let e=Je(s);return wi(e)}function wi(s){return{n:$(s[1],"base64url"),e:$(s[2],"base64url"),d:$(s[3],"base64url"),p:$(s[4],"base64url"),q:$(s[5],"base64url"),dp:$(s[6],"base64url"),dq:$(s[7],"base64url"),qi:$(s[8],"base64url"),kty:"RSA"}}function xh(s){if(s.n==null||s.e==null||s.d==null||s.p==null||s.q==null||s.dp==null||s.dq==null||s.qi==null)throw new re("JWK was missing components");return at([Te(Uint8Array.from([0])),Te(j(s.n,"base64url")),Te(j(s.e,"base64url")),Te(j(s.d,"base64url")),Te(j(s.p,"base64url")),Te(j(s.q,"base64url")),Te(j(s.dp,"base64url")),Te(j(s.dq,"base64url")),Te(j(s.qi,"base64url"))]).subarray()}function vh(s){let e=Je(s,{offset:0});return xi(e)}function xi(s){let e=Je(s[1],{offset:0});return{kty:"RSA",n:$(e[0],"base64url"),e:$(e[1],"base64url")}}function vi(s){if(s.n==null||s.e==null)throw new re("JWK was missing components");return at([yh,Ws(at([Te(j(s.n,"base64url")),Te(j(s.e,"base64url"))]))]).subarray()}function Ca(s){let e=Je(s);return Ei(e)}function Ei(s){let e=wi(s);return Ii(e)}function Si(s,e){if(s.byteLength>=bh)throw new Ut("Key size is too large");let t=Je(s,{offset:0});return _i(t,s,e)}function _i(s,e,t){let r=xi(s);if(t==null){let n=jt(je.encode({Type:Q.RSA,Data:e}));t=He(yi,n)}return new ts(r,t)}function Ii(s){if(Ua(s)>bi)throw new re("Key size is too large");let e=Na(s),t=jt(je.encode({Type:Q.RSA,Data:vi(e.publicKey)})),r=He(yi,t);return new Bs(e.privateKey,new ts(e.publicKey,r))}async function Fa(s){if(s>bi)throw new re("Key size is too large");let e=await Oa(s),t=jt(je.encode({Type:Q.RSA,Data:vi(e.publicKey)})),r=He(yi,t);return new Bs(e.privateKey,new ts(e.publicKey,r))}function Na(s){if(s==null)throw new re("Missing key parameter");return{privateKey:s,publicKey:{kty:s.kty,n:s.n,e:s.e}}}async function Oa(s,e){let t=await Ce.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:s,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let r=await Eh(t,e);return{privateKey:r[0],publicKey:r[1]}}async function Ra(s,e,t){let r=await Ce.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let n=await Ce.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,ke(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(n,0,n.byteLength)}async function La(s,e,t,r){let n=await Ce.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();let i=await Ce.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,ke(e),ke(t instanceof Uint8Array?t:t.subarray()));return r?.signal?.throwIfAborted(),i}async function Eh(s,e){if(s.privateKey==null||s.publicKey==null)throw new re("Private and public key are required");let t=await Promise.all([Ce.get().subtle.exportKey("jwk",s.privateKey),Ce.get().subtle.exportKey("jwk",s.publicKey)]);return e?.signal?.throwIfAborted(),t}function Ua(s){if(s.kty!=="RSA")throw new re("invalid key type");if(s.n==null)throw new re("invalid key modulus");return j(s.n,"base64url").length*8}var Sr=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(js(e),Re(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,n=new Uint8Array(r);n.set(t.length>r?e.create().update(t).digest():t);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),Tt(n)}update(e){return $t(this),this.iHash.update(e),this}digestInto(e){$t(this),Zs(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),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:t,iHash:r,finished:n,destroyed:i,blockLen:o,outputLen:a,canXOF:l}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.canXOF=l,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ka=(()=>{let s=((e,t,r)=>new Sr(e,t).update(r).digest());return s.create=(e,t)=>new Sr(e,t),s})();var Sh=BigInt(0),Ti=class extends Error{constructor(e=""){super(e)}},et={Err:Ti,_tlv:{encode:(s,e)=>{let{Err:t}=et;if(pt(s,"tag"),s<0||s>255)throw new t("tlv.encode: wrong tag");if(jo(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let r=e.length/2,n=Ss(r);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let i=r>127?Ss(n.length/2|128):"";return Ss(s)+i+n+e},decode(s,e){let{Err:t}=et;e=G(e,void 0,"DER data");let r=0;if(s<0||s>255)throw new t("tlv.decode: wrong tag");if(e.length<2||e[r++]!==s)throw new t("tlv.decode: wrong tlv");let n=e[r++],i=!!(n&128),o=0;if(!i)o=n;else{let l=n&127;if(!l)throw new t("tlv.decode(long): indefinite length not supported");if(l>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(r,r+l);if(u.length!==l)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let p of u)o=o<<8|p;if(r+=l,o<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(s){let{Err:e}=et;if(tr(s),s<Sh)throw new e("integer: negative integers are not allowed");let t=Ss(s);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(s){let{Err:e}=et;if(s.length<1)throw new e("invalid signature integer: empty");if(s[0]&128)throw new e("invalid signature integer: negative");if(s.length>1&&s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return $e(s)}},toSig(s){let{Err:e,_int:t,_tlv:r}=et,n=G(s,void 0,"signature"),{v:i,l:o}=r.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l}=r.decode(2,i),{v:u,l:p}=r.decode(2,l);if(p.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(s){let{_tlv:e,_int:t}=et;Ae(s,{r:"bigint",s:"bigint"},{},"sig");let r=e.encode(2,t.encode(s.r)),n=e.encode(2,t.encode(s.s)),i=r+n;return e.encode(48,i)}},Di=(Object.freeze(et._tlv),Object.freeze(et._int),Object.freeze(et));var za=(s,e)=>(s+(s>=0?e:-e)/qa)/e;function _h(s,e,t){Yt("scalar",s,tt,t);let[[r,n],[i,o]]=e,a=za(o*s,t),l=za(-n*s,t),u=s-a*r-l*i,p=-a*n-l*o,m=u<tt,x=p<tt;m&&(u=-u),x&&(p=-p);let y=_s(Math.ceil(Xt(t)/2))+kt;if(u<tt||u>=y||p<tt||p>=y)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:m,k1:u,k2neg:x,k2:p}}function Pi(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function Ai(s,e){Ae(s);let t={};for(let r of Object.keys(e))t[r]=s[r]===void 0?e[r]:s[r];return De(t.lowS,"lowS"),De(t.prehash,"prehash"),t.format!==void 0&&Pi(t.format),t}var tt=BigInt(0),kt=BigInt(1),qa=BigInt(2),Mi=BigInt(3),Ih=BigInt(4);function Ga(s,e={}){let t=ur("weierstrass",s,e),r=t.Fp,n=t.Fn,i=t.CURVE,{h:o,n:a}=i;Ae(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:l,allowInfinityPoint:u}=e,p=e.randomBytes===void 0?At:e.randomBytes;if(l&&(!r.is0(i.a)||typeof l.beta!="bigint"||!Array.isArray(l.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let m=Wa(r,n);function x(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function y(L,I,A){if(u&&I.is0())return Uint8Array.of(0);let{x:B,y:N}=I.toAffine(),M=r.toBytes(B);if(De(A,"isCompressed"),A){x();let T=!r.isOdd(N);return Le(Ha(T),M)}else return Le(Uint8Array.of(4),M,r.toBytes(N))}function f(L){G(L,void 0,"Point");let{publicKey:I,publicKeyUncompressed:A}=m,B=L.length,N=L[0],M=L.subarray(1);if(u&&B===1&&N===0)return{x:r.ZERO,y:r.ZERO};if(B===I&&(N===2||N===3)){let T=r.fromBytes(M);if(!r.isValid(T))throw new Error("bad point: is not on curve, wrong x");let k=c(T),R;try{R=r.sqrt(k)}catch(q){let z=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}x();let O=r.isOdd(R);return(N&1)===1!==O&&(R=r.neg(R)),{x:T,y:R}}else if(B===A&&N===4){let T=r.BYTES,k=r.fromBytes(M.subarray(0,T)),R=r.fromBytes(M.subarray(T,T*2));if(!h(k,R))throw new Error("bad point: is not on curve");return{x:k,y:R}}else throw new Error(`bad point: got length ${B}, expected compressed=${I} or uncompressed=${A}`)}let g=e.toBytes===void 0?y:e.toBytes,w=e.fromBytes===void 0?f:e.fromBytes,E=r.mul(i.b,Mi),S=r.is0(i.a)?L=>r.ZERO:L=>r.mul(i.a,L);function c(L){let I=r.sqr(L),A=r.mul(I,L);return r.add(r.add(A,r.mul(L,i.a)),i.b)}function h(L,I){let A=r.sqr(I),B=c(L);return r.eql(A,B)}if(!h(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let d=r.mul(r.pow(i.a,Mi),Ih),b=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(d,b)))throw new Error("bad curve params: a or b");function v(L,I,A=!1){if(!r.isValid(I)||A&&r.is0(I))throw new Error(`bad point coordinate ${L}`);return I}function _(L){if(!(L instanceof F))throw new Error("Weierstrass Point expected")}function D(L){if(!l||!l.basises)throw new Error("no endo");return _h(L,l.basises,n.ORDER)}function P(L,I,A,B){if(!n.isValid(B))throw new RangeError("invalid scalar: out of range");if(l){let{k1neg:N,k1:M,k2neg:T,k2:k}=D(B),R=new F(r.mul(A.X,l.beta),A.Y,A.Z);L.push(N?A.negate():A,T?R.negate():R),I.push(M,k)}else L.push(A),I.push(B)}let K=new WeakSet;class F{static BASE=new F(i.Gx,i.Gy,r.ONE);static ZERO=new F(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=n;X;Y;Z;constructor(I,A,B){this.X=v("x",I),this.Y=v("y",A,!0),this.Z=v("z",B),Object.freeze(this)}static CURVE(){return i}static fromAffine(I){let{x:A,y:B}=I||{};if(!I||!r.isValid(A)||!r.isValid(B))throw new Error("invalid affine point");if(I instanceof F)throw new Error("projective point not allowed");return r.is0(A)&&r.is0(B)?F.ZERO:new F(A,B,r.ONE)}static fromBytes(I){let A=F.fromAffine(w(G(I,void 0,"point")));return A.assertValidity(),A}static fromHex(I){return F.fromBytes(Zt(I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=6,A=!0){return C.setWindowSize(this,I),A||this.multiply(Mi),this}assertValidity(){let I=this;if(I.is0()){if(e.allowInfinityPoint&&r.is0(I.X)&&r.eql(I.Y,r.ONE)&&r.is0(I.Z))return;throw new Error("bad point: ZERO")}if(K.has(I))return;let{x:A,y:B}=I.toAffine();if(!r.isValid(A)||!r.isValid(B))throw new Error("bad point: x or y not field elements");if(!h(A,B))throw new Error("bad point: equation left != right");if(!I.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");K.add(I)}hasEvenY(){let{y:I}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(I)}equals(I){_(I);let{X:A,Y:B,Z:N}=this,{X:M,Y:T,Z:k}=I,R=r.eql(r.mul(A,k),r.mul(M,N)),O=r.eql(r.mul(B,k),r.mul(T,N));return R&&O}negate(){return new F(this.X,r.neg(this.Y),this.Z)}double(){let{X:I,Y:A,Z:B}=this,N=r.ZERO,M=r.ZERO,T=r.ZERO,k=r.mul(I,I),R=r.mul(A,A),O=r.mul(B,B),U=r.mul(I,A);return U=r.add(U,U),T=r.mul(I,B),T=r.add(T,T),N=S(T),M=r.mul(E,O),M=r.add(N,M),N=r.sub(R,M),M=r.add(R,M),M=r.mul(N,M),N=r.mul(U,N),T=r.mul(E,T),O=S(O),U=r.sub(k,O),U=S(U),U=r.add(U,T),T=r.add(k,k),k=r.add(T,k),k=r.add(k,O),k=r.mul(k,U),M=r.add(M,k),O=r.mul(A,B),O=r.add(O,O),k=r.mul(O,U),N=r.sub(N,k),T=r.mul(O,R),T=r.add(T,T),T=r.add(T,T),new F(N,M,T)}add(I){_(I);let{X:A,Y:B,Z:N}=this,{X:M,Y:T,Z:k}=I,R=r.ZERO,O=r.ZERO,U=r.ZERO,q=r.mul(A,M),z=r.mul(B,T),te=r.mul(N,k),be=r.add(A,B),se=r.add(M,T);be=r.mul(be,se),se=r.add(q,z),be=r.sub(be,se),se=r.add(A,N);let ue=r.add(M,k);return se=r.mul(se,ue),ue=r.add(q,te),se=r.sub(se,ue),ue=r.add(B,N),R=r.add(T,k),ue=r.mul(ue,R),R=r.add(z,te),ue=r.sub(ue,R),U=S(se),R=r.mul(E,te),U=r.add(R,U),R=r.sub(z,U),U=r.add(z,U),O=r.mul(R,U),z=r.add(q,q),z=r.add(z,q),te=S(te),se=r.mul(E,se),z=r.add(z,te),te=r.sub(q,te),te=S(te),se=r.add(se,te),q=r.mul(z,se),O=r.add(O,q),q=r.mul(ue,se),R=r.mul(be,R),R=r.sub(R,q),q=r.mul(be,z),U=r.mul(ue,U),U=r.add(U,q),new F(R,O,U)}subtract(I){return _(I),this.add(I.negate())}is0(){return this.equals(F.ZERO)}multiply(I){if(!n.isValidNot0(I))throw new RangeError("invalid scalar: out of range");let{p:A,f:B}=C.mulSecret(this,I,o,Y);return Y([A,B])[0]}multiplyUnsafe(I){let A=this,B=I;if(!n.isValid(B))throw new RangeError("invalid scalar: out of range");if(B===tt||A.is0())return F.ZERO;if(B===kt)return A;if(C.hasWindowSize(this))return C.mulUnsafe(A,B,Y);let N=[],M=[];return P(N,M,A,B),lr(F,N,M)}mulAddUnsafe(I,A,B){_(A);let N=[],M=[];return P(N,M,this,I),P(N,M,A,B),lr(F,N,M)}toAffine(I){let A=this,B=I;if(B!=null&&!r.isValid(B))throw new RangeError('"invertedZ" expected valid field element');let{X:N,Y:M,Z:T}=A;if(r.eql(T,r.ONE))return{x:N,y:M};let k=A.is0();B==null&&(B=k?r.ONE:r.inv(T));let R=r.mul(N,B),O=r.mul(M,B),U=r.mul(T,B);if(k)return{x:r.ZERO,y:r.ZERO};if(!r.eql(U,r.ONE))throw new Error("invZ was invalid");return{x:R,y:O}}isTorsionFree(){let{isTorsionFree:I}=e;return o===kt?!0:I?I(F,this):C.mulUnsafe(this,a).is0()}clearCofactor(){let{clearCofactor:I}=e;return o===kt?this:I?I(F,this):this.multiplyUnsafe(o)}isSmallOrder(){return o===kt?this.is0():this.clearCofactor().is0()}toBytes(I=!0){return De(I,"isCompressed"),this.assertValidity(),g(F,this,I)}toHex(I=!0){return Es(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let Y=L=>cr(F,L),C=new es(F,p);return C.bits>=6&&F.BASE.precompute(6),Object.freeze(F.prototype),Object.freeze(F),F}function Ha(s){return Uint8Array.of(s?2:3)}function Wa(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Th(s,e={}){gt(s);let{Fn:t}=s,r=e.randomBytes===void 0?At:e.randomBytes,n=Object.assign(Wa(s.Fp,t),{seed:Math.max(or(t.ORDER),16)});function i(y){try{let f=t.fromBytes(y);return t.isValidNot0(f)}catch{return!1}}function o(y,f){let{publicKey:g,publicKeyUncompressed:w}=n;try{let E=y.length;return f===!0&&E!==g||f===!1&&E!==w?!1:!!s.fromBytes(y)}catch{return!1}}function a(y){return y=y===void 0?r(n.seed):y,ar(G(y,n.seed,"seed"),t.ORDER)}function l(y,f=!0){return s.BASE.multiply(t.fromBytes(y)).toBytes(f)}function u(y){let{secretKey:f,publicKey:g,publicKeyUncompressed:w}=n,E=t._lengths;if(!dt(y))return;let S=G(y,void 0,"key").length,c=S===g||S===w,h=S===f||!!E?.includes(S);if(!(c&&h))return c}function p(y,f,g=!0){if(u(y)===!0)throw new Error("first arg must be private key");if(u(f)===!1)throw new Error("second arg must be public key");let w=t.fromBytes(y);return s.fromBytes(f).multiply(w).toBytes(g)}let m={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},x=hr(a,l);return Object.freeze(m),Object.freeze(n),Object.freeze({getPublicKey:l,getSharedSecret:p,keygen:x,Point:s,utils:m,lengths:n})}function Va(s,e,t={}){gt(s);let r=e;js(r),Ae(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=Object.assign({},t),i=n.randomBytes===void 0?At:n.randomBytes,o=n.hmac===void 0?(M,T)=>Ka(r,M,T):n.hmac,{Fp:a,Fn:l}=s,{ORDER:u,BITS:p}=l,m=or(u),x=qn(i,m),{keygen:y,getPublicKey:f,getSharedSecret:g,utils:w,lengths:E}=Th(s,n),S={prehash:!0,lowS:typeof n.lowS=="boolean"?n.lowS:!0,format:"compact",extraEntropy:!1},c=u*qa+kt<a.ORDER;function h(M){let T=u>>kt;return M>T}function d(M,T){if(!l.isValidNot0(T))throw new Error(`invalid signature ${M}: out of range 1..Point.Fn.ORDER`);return T}function b(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function v(M,T,k){return b(),(M===k?0:2)|Number(a.isOdd(T))}function _(){if(c)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function D(M,T){Pi(T);let k=E.signature,R=T==="compact"?k:T==="recovered"?k+1:void 0;return G(M,R)}class P{r;s;recovery;constructor(T,k,R){if(this.r=d("r",T),this.s=d("s",k),R!=null){if(_(),![0,1,2,3].includes(R))throw new Error("invalid recovery id");this.recovery=R}Object.freeze(this)}static fromBytes(T,k=S.format){D(T,k);let R;if(k==="der"){let{r:z,s:te}=Di.toSig(G(T));return new P(z,te)}k==="recovered"&&(R=T[0],k="compact",T=T.subarray(1));let O=E.signature/2,U=T.subarray(0,O),q=T.subarray(O,O*2);return new P(l.fromBytes(U),l.fromBytes(q),R)}static fromHex(T,k){return this.fromBytes(Zt(T),k)}assertRecovery(){let{recovery:T}=this;if(T==null)throw new Error("invalid recovery id: must be present");return T}addRecoveryBit(T){return new P(this.r,this.s,T)}recoverPublicKey(T){let{r:k,s:R}=this,O=this.assertRecovery(),U=O===2||O===3?k+u:k;if(!a.isValid(U))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let q=a.toBytes(U),z=s.fromBytes(Le(Ha((O&1)===0),q)),te=l.inv(U),be=F(G(T,void 0,"msgHash")),se=l.create(-be*te),ue=l.create(R*te),qe=s.BASE.mulAddUnsafe(se,z,ue);if(qe.is0())throw new Error("invalid recovery: point at infinify");return qe.assertValidity(),qe}hasHighS(){return h(this.s)}toBytes(T=S.format){if(Pi(T),T==="der")return Zt(Di.hexFromSig(this));let{r:k,s:R}=this,O=l.toBytes(k),U=l.toBytes(R);return T==="recovered"?(_(),Le(Uint8Array.of(this.assertRecovery()),O,U)):Le(O,U)}toHex(T){return Es(this.toBytes(T))}}Object.freeze(P.prototype),Object.freeze(P);let K=n.bits2int===void 0?function(T){if(T.length>8192)throw new Error("input is too large");let k=$e(T),R=T.length*8-p;return R>0?k>>BigInt(R):k}:n.bits2int,F=n.bits2int_modN===void 0?function(T){return l.create(K(T))}:n.bits2int_modN,Y=_s(p);function C(M){return Yt("num < 2^"+p,M,tt,Y),l.toBytes(M)}function L(M,T){return G(M,void 0,"message"),T?G(r(M),void 0,"prehashed message"):M}function I(M,T,k){let{lowS:R,prehash:O,extraEntropy:U}=Ai(k,S);M=L(M,O);let q=F(M),z=l.fromBytes(T);if(!l.isValidNot0(z))throw new Error("invalid private key");let te=[C(z),C(q)];if(U!=null&&U!==!1){let qe=U===!0?i(E.secretKey):U;te.push(G(qe,void 0,"extraEntropy"))}let be=Le(...te),se=q;function ue(qe){let Nt=K(qe);if(!l.isValidNot0(Nt))return;let hs=s.BASE.multiply(Nt).toAffine(),nt=l.create(hs.x);if(nt===tt)return;let Ge;if(x!==void 0){let fs=$e(ar(x(m),u)),kc=l.inv(l.mul(fs,Nt)),Rc=l.mul(fs,se),Lc=l.mul(fs,z);Ge=l.create(kc*l.create(Rc+Lc*nt))}else{let fs=na(Nt,u);Ge=l.create(fs*l.create(se+nt*z))}if(Ge===tt)return;let Gr=v(hs.x,hs.y,nt),Wi=Ge;return R&&h(Ge)&&(Wi=l.neg(Ge),Gr^=1),new P(nt,Wi,c?void 0:Gr)}return{seed:be,k2sig:ue}}function A(M,T,k={}){let{seed:R,k2sig:O}=I(M,T,k);return Yo(r.outputLen,l.BYTES,o)(R,O).toBytes(k.format)}function B(M,T,k,R={}){let{lowS:O,prehash:U,format:q}=Ai(R,S);if(k=G(k,void 0,"publicKey"),T=L(T,U),!dt(M)){let z=M instanceof P?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+z)}D(M,q);try{let z=P.fromBytes(M,q),te=s.fromBytes(k);if(O&&z.hasHighS())return!1;let{r:be,s:se}=z,ue=F(T),qe=l.inv(se),Nt=l.create(ue*qe),hs=l.create(be*qe),nt=s.BASE.mulAddUnsafe(Nt,te,hs);if(nt.is0())return!1;let Ge=nt.toAffine();return!(l.create(Ge.x)!==be||q==="recovered"&&z.recovery!==v(Ge.x,Ge.y,be))}catch{return!1}}function N(M,T,k={}){let{prehash:R}=Ai(k,S);return T=L(T,R),P.fromBytes(M,"recovered").recoverPublicKey(T).toBytes()}return Object.freeze({keygen:y,getPublicKey:f,getSharedSecret:g,utils:w,lengths:E,Point:s,sign:A,verify:B,recoverPublicKey:N,Signature:P,hash:r})}var ki={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Dh={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var $a=BigInt(2);function Ah(s){let e=ki.p,t=BigInt(3),r=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),l=BigInt(88),u=s*s*s%e,p=u*u*s%e,m=X(p,t,e)*p%e,x=X(m,t,e)*p%e,y=X(x,$a,e)*u%e,f=X(y,n,e)*y%e,g=X(f,i,e)*f%e,w=X(g,a,e)*g%e,E=X(w,l,e)*w%e,S=X(E,a,e)*g%e,c=X(S,t,e)*p%e,h=X(c,o,e)*f%e,d=X(h,r,e)*u%e,b=X(d,$a,e);if(!Bi.eql(Bi.sqr(b),s))throw new Error("Cannot find square root");return b}var Bi=Qt(ki.p,{sqrt:Ah}),Mh=Ga(ki,{Fp:Bi,endo:Dh}),ss=Va(Mh,jt);function ja(s,e,t,r){let n=St.digest(t instanceof Uint8Array?t:t.subarray());if(br(n))return n.then(({digest:i})=>(r?.signal?.throwIfAborted(),ss.verify(e,i,s,{prehash:!1,format:"der"}))).catch(i=>{throw i.name==="AbortError"?i:new Ds(String(i))});try{return r?.signal?.throwIfAborted(),ss.verify(e,n.digest,s,{prehash:!1,format:"der"})}catch(i){throw new Ds(String(i))}}var _r=class{type="secp256k1";raw;_key;constructor(e){this._key=Ya(e),this.raw=Za(this._key)}toMultihash(){return Ne.digest(We(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}verify(e,t,r){return ja(this._key,t,e,r)}};function Ri(s){return new _r(s)}function Za(s){return ss.Point.fromBytes(s).toBytes()}function Ya(s){try{return ss.Point.fromBytes(s),s}catch(e){throw new Ut(String(e))}}function Li(s,e){let{Type:t,Data:r}=je.decode(s),n=r??new Uint8Array;switch(t){case Q.RSA:return Si(n,e);case Q.Ed25519:return jn(n);case Q.secp256k1:return Ri(n);case Q.ECDSA:return vn(n);default:throw new Kt}}function Xa(s){let{Type:e,Data:t}=je.decode(s.digest),r=t??new Uint8Array;switch(e){case Q.Ed25519:return jn(r);case Q.secp256k1:return Ri(r);case Q.ECDSA:return vn(r);default:throw new Kt}}function We(s){return je.encode({Type:Q[s.type],Data:s.raw})}var Ja=Symbol.for("nodejs.util.inspect.custom"),Ph=114,Rs=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()})`}[Vr]=!0;toString(){return this.string==null&&(this.string=ie.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ce.createV1(Ph,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Ie(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Ie(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Ja](){return`PeerId(${this.toString()})`}},Ir=class extends Rs{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Tr=class extends Rs{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Dr=class extends Rs{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Bh=2336,Ls=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ne.digest(j(this.url))}[Ja](){return`PeerId(${this.url})`}[Vr]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ce.createV1(Bh,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=$(e)),e.toString()===this.toString())}};var kh=114,Qa=2336;function Rt(s,e){let t;if(s.charAt(0)==="1"||s.charAt(0)==="Q")t=Ye(ie.decode(`z${s}`));else{if(s.startsWith("k51qzi5uqu5")||s.startsWith("kzwfwjn5ji4")||s.startsWith("k2k4r8")||s.startsWith("bafz"))return Rh(ce.parse(s));if(e==null)throw new re('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ye(e.decode(s))}return rs(t)}function rs(s){if(Ch(s))return new Ir({multihash:s});if(Lh(s))try{let e=Xa(s);if(e.type==="Ed25519")return new Tr({multihash:s,publicKey:e});if(e.type==="secp256k1")return new Dr({multihash:s,publicKey:e})}catch{let t=$(s.digest);return new Ls(new URL(t))}throw new Ks("Supplied PeerID Multihash is invalid")}function Rh(s){if(s?.multihash==null||s.version==null||s.version===1&&s.code!==kh&&s.code!==Qa)throw new Us("Supplied PeerID CID is invalid");if(s.code===Qa){let e=$(s.multihash.digest);return new Ls(new URL(e))}return rs(s.multihash)}function Lh(s){return s.code===Ne.code}function Ch(s){return s.code===St.code}var Ar=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ns=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Mr=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Cs=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Pr(s){return s[Symbol.asyncIterator]!=null}function ec(s,e){if(s.byteLength>e)throw new ns("Message length too long")}var kr=s=>{let e=Fe(s),t=he(e);return ti(s,t),kr.bytes=e,t};kr.bytes=0;function is(s,e){e=e??{};let t=e.lengthEncoder??kr,r=e?.maxDataLength??4194304;function*n(i){ec(i,r);let o=t(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return Pr(s)?(async function*(){for await(let i of s)yield*n(i)})():(function*(){for(let i of s)yield*n(i)})()}is.single=(s,e)=>{e=e??{};let t=e.lengthEncoder??kr,r=e?.maxDataLength??4194304;return ec(s,r),new ae(t(s.byteLength),s)};var Lt;(function(s){s[s.LENGTH=0]="LENGTH",s[s.DATA=1]="DATA"})(Lt||(Lt={}));var Ci=s=>{let e=si(s);return Ci.bytes=Fe(e),e};Ci.bytes=0;function Fs(s,e){let t=new ae,r=Lt.LENGTH,n=-1,i=e?.lengthDecoder??Ci,o=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*l(){for(;t.byteLength>0;){if(r===Lt.LENGTH)try{if(n=i(t),n<0)throw new Ar("Invalid message length");if(n>a)throw new ns("Message length too long");let u=i.bytes;t.consume(u),e?.onLength!=null&&e.onLength(n),r=Lt.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>o)throw new Mr("Message length length too long");break}throw u}if(r===Lt.DATA){if(t.byteLength<n)break;let u=t.sublist(0,n);t.consume(n),e?.onData!=null&&e.onData(u),yield u,r=Lt.LENGTH}}}return Pr(s)?(async function*(){for await(let u of s)t.append(u),yield*l();if(t.byteLength>0)throw new Cs("Unexpected end of input")})():(function*(){for(let u of s)t.append(u),yield*l();if(t.byteLength>0)throw new Cs("Unexpected end of input")})()}Fs.fromReader=(s,e)=>{let t=1,r=(async function*(){for(;;)try{let{done:i,value:o}=await s.next(t);if(i===!0)return;o!=null&&(yield o)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{t=1}})();return Fs(r,{...e??{},onLength:i=>{t=i}})};function st(){let s={};return s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),s}var Rr=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}},os=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Rr(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 t=this.head;this.head=t.next=new Rr(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Fi=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ct(s={}){return Nh(t=>{let r=t.shift();if(r==null)return{done:!0};if(r.error!=null)throw r.error;return{done:r.done===!0,value:r.value}},s)}function Nh(s,e){e=e??{};let t=e.onEnd,r=new os,n,i,o,a=st(),l=async()=>{try{return r.isEmpty()?o?{done:!0}:await new Promise((w,E)=>{i=S=>{i=null,r.push(S);try{w(s(r))}catch(c){E(c)}return n}}):s(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=st()})}},u=w=>i!=null?i(w):(r.push(w),n),p=w=>(r=new os,i!=null?i({error:w}):(r.push({error:w}),n)),m=w=>{if(o)return n;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:w})},x=w=>o?n:(o=!0,w!=null?p(w):u({done:!0})),y=()=>(r=new os,x(),{done:!0}),f=w=>(x(w),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:l,return:y,throw:f,push:m,end:x,get readableLength(){return r.size},onEmpty:async w=>{let E=w?.signal;if(E?.throwIfAborted(),r.isEmpty())return;let S,c;E!=null&&(S=new Promise((h,d)=>{c=()=>{d(new Fi)},E.addEventListener("abort",c)}));try{await Promise.race([a.promise,S])}finally{c!=null&&E!=null&&E?.removeEventListener("abort",c)}}},t==null)return n;let g=n;return n={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(w){return g.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:m,end(w){return g.end(w),t!=null&&(t(w),t=void 0),n},get readableLength(){return g.readableLength},onEmpty:w=>g.onEmpty(w)},n}function Oh(s){return s.reason}async function Ni(s,e,t){if(e==null)return s;let r=t?.translateError??Oh;if(e.aborted)return s.catch(()=>{}),Promise.reject(r(e));let n;try{return await Promise.race([s,new Promise((i,o)=>{n=()=>{o(r(e))},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Oi=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=st(),this.haveNext=st()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=st(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=st(),await Ni(this.readNext.promise,t?.signal,t)}};function tc(){return new Oi}function Uh(s){return s[Symbol.asyncIterator]!=null}async function Kh(s,e,t){try{await Promise.all(s.map(async r=>{for await(let n of r)await e.push(n,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(r){await e.end(r,{signal:t}).catch(()=>{})}}async function*zh(s){let e=new AbortController,t=tc();Kh(s,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*qh(s){for(let e of s)yield*e}function Gh(...s){let e=[];for(let t of s)Uh(t)||e.push(t);return e.length===s.length?qh(e):zh(s)}var sc=Gh;function Ns(s,...e){if(s==null)throw new Error("Empty pipeline");if(Ui(s)){let r=s;s=()=>r.source}else if(nc(s)||rc(s)){let r=s;s=()=>r}let t=[s,...e];if(t.length>1&&Ui(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let r=1;r<t.length-1;r++)Ui(t[r])&&(t[r]=Wh(t[r]));return Hh(...t)}var Hh=(...s)=>{let e;for(;s.length>0;)e=s.shift()(e);return e},rc=s=>s?.[Symbol.asyncIterator]!=null,nc=s=>s?.[Symbol.iterator]!=null,Ui=s=>s==null?!1:s.sink!=null&&s.source!=null,Wh=s=>e=>{let t=s.sink(e);if(t?.then!=null){let r=Ct({objectMode:!0});t.then(()=>{r.end()},o=>{r.end(o)});let n,i=s.source;if(rc(i))n=async function*(){yield*i,r.end()};else if(nc(i))n=function*(){yield*i,r.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return sc(r,n())}return s.source};var ic={maxSubscriptions:5e3,maxMessages:5e3,maxIhaveMessageIDs:5e3,maxIwantMessageIDs:5e3,maxControlMessages:5e3,maxIdontwantMessageIDs:512,maxPeerInfos:16};var rt;(function(s){let e;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),c.subscribe!=null&&(h.uint32(8),h.bool(c.subscribe)),c.topic!=null&&(h.uint32(18),h.string(c.topic)),d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{b.subscribe=c.bool();break}case 2:{b.topic=c.string();break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{yield{field:`${d}.subscribe`,value:c.bool()};break}case 2:{yield{field:`${d}.topic`,value:c.string()};break}default:{c.skipType(_&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(e=s.SubOpts||(s.SubOpts={}));let t;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),c.from!=null&&(h.uint32(10),h.bytes(c.from)),c.data!=null&&(h.uint32(18),h.bytes(c.data)),c.seqno!=null&&(h.uint32(26),h.bytes(c.seqno)),c.topic!=null&&c.topic!==""&&(h.uint32(34),h.string(c.topic)),c.signature!=null&&(h.uint32(42),h.bytes(c.signature)),c.key!=null&&(h.uint32(50),h.bytes(c.key)),d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={topic:""},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{b.from=c.bytes();break}case 2:{b.data=c.bytes();break}case 3:{b.seqno=c.bytes();break}case 4:{b.topic=c.string();break}case 5:{b.signature=c.bytes();break}case 6:{b.key=c.bytes();break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{yield{field:`${d}.from`,value:c.bytes()};break}case 2:{yield{field:`${d}.data`,value:c.bytes()};break}case 3:{yield{field:`${d}.seqno`,value:c.bytes()};break}case 4:{yield{field:`${d}.topic`,value:c.string()};break}case 5:{yield{field:`${d}.signature`,value:c.bytes()};break}case 6:{yield{field:`${d}.key`,value:c.bytes()};break}default:{c.skipType(_&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(t=s.Message||(s.Message={}));let r;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),c.ihave!=null&&c.ihave.length>0)for(let b of c.ihave)h.uint32(10),s.ControlIHave.codec().encode(b,h);if(c.iwant!=null&&c.iwant.length>0)for(let b of c.iwant)h.uint32(18),s.ControlIWant.codec().encode(b,h);if(c.graft!=null&&c.graft.length>0)for(let b of c.graft)h.uint32(26),s.ControlGraft.codec().encode(b,h);if(c.prune!=null&&c.prune.length>0)for(let b of c.prune)h.uint32(34),s.ControlPrune.codec().encode(b,h);if(c.idontwant!=null&&c.idontwant.length>0)for(let b of c.idontwant)h.uint32(42),s.ControlIDontWant.codec().encode(b,h);d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={ihave:[],iwant:[],graft:[],prune:[],idontwant:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{if(d.limits?.ihave!=null&&b.ihave.length===d.limits.ihave)throw new Z('Decode error - repeated field "ihave" had too many elements');b.ihave.push(s.ControlIHave.codec().decode(c,c.uint32(),{limits:d.limits?.ihave$}));break}case 2:{if(d.limits?.iwant!=null&&b.iwant.length===d.limits.iwant)throw new Z('Decode error - repeated field "iwant" had too many elements');b.iwant.push(s.ControlIWant.codec().decode(c,c.uint32(),{limits:d.limits?.iwant$}));break}case 3:{if(d.limits?.graft!=null&&b.graft.length===d.limits.graft)throw new Z('Decode error - repeated field "graft" had too many elements');b.graft.push(s.ControlGraft.codec().decode(c,c.uint32(),{limits:d.limits?.graft$}));break}case 4:{if(d.limits?.prune!=null&&b.prune.length===d.limits.prune)throw new Z('Decode error - repeated field "prune" had too many elements');b.prune.push(s.ControlPrune.codec().decode(c,c.uint32(),{limits:d.limits?.prune$}));break}case 5:{if(d.limits?.idontwant!=null&&b.idontwant.length===d.limits.idontwant)throw new Z('Decode error - repeated field "idontwant" had too many elements');b.idontwant.push(s.ControlIDontWant.codec().decode(c,c.uint32(),{limits:d.limits?.idontwant$}));break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v={ihave:0,iwant:0,graft:0,prune:0,idontwant:0},_=h==null?c.len:c.pos+h;for(;c.pos<_;){let D=c.uint32();switch(D>>>3){case 1:{if(b.limits?.ihave!=null&&v.ihave===b.limits.ihave)throw new Z('Streaming decode error - repeated field "ihave" had too many elements');for(let P of s.ControlIHave.codec().stream(c,c.uint32(),`${d}.ihave[]`,{limits:b.limits?.ihave$}))yield{...P,index:v.ihave};v.ihave++;break}case 2:{if(b.limits?.iwant!=null&&v.iwant===b.limits.iwant)throw new Z('Streaming decode error - repeated field "iwant" had too many elements');for(let P of s.ControlIWant.codec().stream(c,c.uint32(),`${d}.iwant[]`,{limits:b.limits?.iwant$}))yield{...P,index:v.iwant};v.iwant++;break}case 3:{if(b.limits?.graft!=null&&v.graft===b.limits.graft)throw new Z('Streaming decode error - repeated field "graft" had too many elements');for(let P of s.ControlGraft.codec().stream(c,c.uint32(),`${d}.graft[]`,{limits:b.limits?.graft$}))yield{...P,index:v.graft};v.graft++;break}case 4:{if(b.limits?.prune!=null&&v.prune===b.limits.prune)throw new Z('Streaming decode error - repeated field "prune" had too many elements');for(let P of s.ControlPrune.codec().stream(c,c.uint32(),`${d}.prune[]`,{limits:b.limits?.prune$}))yield{...P,index:v.prune};v.prune++;break}case 5:{if(b.limits?.idontwant!=null&&v.idontwant===b.limits.idontwant)throw new Z('Streaming decode error - repeated field "idontwant" had too many elements');for(let P of s.ControlIDontWant.codec().stream(c,c.uint32(),`${d}.idontwant[]`,{limits:b.limits?.idontwant$}))yield{...P,index:v.idontwant};v.idontwant++;break}default:{c.skipType(D&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(r=s.ControlMessage||(s.ControlMessage={}));let n;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),c.topicID!=null&&(h.uint32(10),h.string(c.topicID)),c.messageIDs!=null&&c.messageIDs.length>0)for(let b of c.messageIDs)h.uint32(18),h.bytes(b);d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={messageIDs:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{b.topicID=c.string();break}case 2:{if(d.limits?.messageIDs!=null&&b.messageIDs.length===d.limits.messageIDs)throw new Z('Decode error - repeated field "messageIDs" had too many elements');b.messageIDs.push(c.bytes());break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v={messageIDs:0},_=h==null?c.len:c.pos+h;for(;c.pos<_;){let D=c.uint32();switch(D>>>3){case 1:{yield{field:`${d}.topicID`,value:c.string()};break}case 2:{if(b.limits?.messageIDs!=null&&v.messageIDs===b.limits.messageIDs)throw new Z('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:c.bytes()},v.messageIDs++;break}default:{c.skipType(D&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(n=s.ControlIHave||(s.ControlIHave={}));let i;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),c.messageIDs!=null&&c.messageIDs.length>0)for(let b of c.messageIDs)h.uint32(10),h.bytes(b);d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={messageIDs:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{if(d.limits?.messageIDs!=null&&b.messageIDs.length===d.limits.messageIDs)throw new Z('Decode error - repeated field "messageIDs" had too many elements');b.messageIDs.push(c.bytes());break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v={messageIDs:0},_=h==null?c.len:c.pos+h;for(;c.pos<_;){let D=c.uint32();switch(D>>>3){case 1:{if(b.limits?.messageIDs!=null&&v.messageIDs===b.limits.messageIDs)throw new Z('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:c.bytes()},v.messageIDs++;break}default:{c.skipType(D&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(i=s.ControlIWant||(s.ControlIWant={}));let o;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),c.topicID!=null&&(h.uint32(10),h.string(c.topicID)),d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();_>>>3===1?b.topicID=c.string():c.skipType(_&7)}return b},function*(c,h,d,b={}){let v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();_>>>3===1?yield{field:`${d}.topicID`,value:c.string()}:c.skipType(_&7)}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(o=s.ControlGraft||(s.ControlGraft={}));let a;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),c.topicID!=null&&(h.uint32(10),h.string(c.topicID)),c.peers!=null&&c.peers.length>0)for(let b of c.peers)h.uint32(18),s.PeerInfo.codec().encode(b,h);c.backoff!=null&&(h.uint32(24),h.uint64Number(c.backoff)),d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={peers:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{b.topicID=c.string();break}case 2:{if(d.limits?.peers!=null&&b.peers.length===d.limits.peers)throw new Z('Decode error - repeated field "peers" had too many elements');b.peers.push(s.PeerInfo.codec().decode(c,c.uint32(),{limits:d.limits?.peers$}));break}case 3:{b.backoff=c.uint64Number();break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v={peers:0},_=h==null?c.len:c.pos+h;for(;c.pos<_;){let D=c.uint32();switch(D>>>3){case 1:{yield{field:`${d}.topicID`,value:c.string()};break}case 2:{if(b.limits?.peers!=null&&v.peers===b.limits.peers)throw new Z('Streaming decode error - repeated field "peers" had too many elements');for(let P of s.PeerInfo.codec().stream(c,c.uint32(),`${d}.peers[]`,{limits:b.limits?.peers$}))yield{...P,index:v.peers};v.peers++;break}case 3:{yield{field:`${d}.backoff`,value:c.uint64Number()};break}default:{c.skipType(D&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(a=s.ControlPrune||(s.ControlPrune={}));let l;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),c.peerID!=null&&(h.uint32(10),h.bytes(c.peerID)),c.signedPeerRecord!=null&&(h.uint32(18),h.bytes(c.signedPeerRecord)),d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{b.peerID=c.bytes();break}case 2:{b.signedPeerRecord=c.bytes();break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{yield{field:`${d}.peerID`,value:c.bytes()};break}case 2:{yield{field:`${d}.signedPeerRecord`,value:c.bytes()};break}default:{c.skipType(_&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(l=s.PeerInfo||(s.PeerInfo={}));let u;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),c.messageIDs!=null&&c.messageIDs.length>0)for(let b of c.messageIDs)h.uint32(10),h.bytes(b);d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={messageIDs:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{if(d.limits?.messageIDs!=null&&b.messageIDs.length===d.limits.messageIDs)throw new Z('Decode error - repeated field "messageIDs" had too many elements');b.messageIDs.push(c.bytes());break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v={messageIDs:0},_=h==null?c.len:c.pos+h;for(;c.pos<_;){let D=c.uint32();switch(D>>>3){case 1:{if(b.limits?.messageIDs!=null&&v.messageIDs===b.limits.messageIDs)throw new Z('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:c.bytes()},v.messageIDs++;break}default:{c.skipType(D&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(u=s.ControlIDontWant||(s.ControlIDontWant={}));let p;s.codec=()=>(p==null&&(p=ve((f,g,w={})=>{if(w.lengthDelimited!==!1&&g.fork(),f.subscriptions!=null&&f.subscriptions.length>0)for(let E of f.subscriptions)g.uint32(10),s.SubOpts.codec().encode(E,g);if(f.messages!=null&&f.messages.length>0)for(let E of f.messages)g.uint32(18),s.Message.codec().encode(E,g);f.control!=null&&(g.uint32(26),s.ControlMessage.codec().encode(f.control,g)),w.lengthDelimited!==!1&&g.ldelim()},(f,g,w={})=>{let E={subscriptions:[],messages:[]},S=g==null?f.len:f.pos+g;for(;f.pos<S;){let c=f.uint32();switch(c>>>3){case 1:{if(w.limits?.subscriptions!=null&&E.subscriptions.length===w.limits.subscriptions)throw new Z('Decode error - repeated field "subscriptions" had too many elements');E.subscriptions.push(s.SubOpts.codec().decode(f,f.uint32(),{limits:w.limits?.subscriptions$}));break}case 2:{if(w.limits?.messages!=null&&E.messages.length===w.limits.messages)throw new Z('Decode error - repeated field "messages" had too many elements');E.messages.push(s.Message.codec().decode(f,f.uint32(),{limits:w.limits?.messages$}));break}case 3:{E.control=s.ControlMessage.codec().decode(f,f.uint32(),{limits:w.limits?.control});break}default:{f.skipType(c&7);break}}}return E},function*(f,g,w,E={}){let S={subscriptions:0,messages:0},c=g==null?f.len:f.pos+g;for(;f.pos<c;){let h=f.uint32();switch(h>>>3){case 1:{if(E.limits?.subscriptions!=null&&S.subscriptions===E.limits.subscriptions)throw new Z('Streaming decode error - repeated field "subscriptions" had too many elements');for(let d of s.SubOpts.codec().stream(f,f.uint32(),`${w}.subscriptions[]`,{limits:E.limits?.subscriptions$}))yield{...d,index:S.subscriptions};S.subscriptions++;break}case 2:{if(E.limits?.messages!=null&&S.messages===E.limits.messages)throw new Z('Streaming decode error - repeated field "messages" had too many elements');for(let d of s.Message.codec().stream(f,f.uint32(),`${w}.messages[]`,{limits:E.limits?.messages$}))yield{...d,index:S.messages};S.messages++;break}case 3:{yield*s.ControlMessage.codec().stream(f,f.uint32(),`${w}.control`,{limits:E.limits?.control});break}default:{f.skipType(h&7);break}}}})),p);function m(f){return we(f,s.codec())}s.encode=m;function x(f,g){return ye(f,s.codec(),g)}s.decode=x;function y(f,g){return xe(f,s.codec(),g)}s.stream=y})(rt||(rt={}));var Lr=class{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,r){this.gossip=e,this.msgIdToStrFn=r;for(let n=0;n<t;n++)this.history[n]=[]}get size(){return this.msgs.size}put(e,t,r=!1){let{msgIdStr:n}=e;return this.msgs.has(n)?!1:(this.msgs.set(n,{message:t,validated:r,originatingPeers:new Set,iwantCounts:new Map}),this.history[0].push({...e,topic:t.topic}),r||this.notValidatedCount++,!0)}observeDuplicate(e,t){let r=this.msgs.get(e);r!=null&&!r.validated&&r.originatingPeers.add(t)}get(e){return this.msgs.get(this.msgIdToStrFn(e))?.message}getWithIWantCount(e,t){let r=this.msgs.get(e);if(r==null)return null;let n=(r.iwantCounts.get(t)??0)+1;return r.iwantCounts.set(t,n),{msg:r.message,count:n}}getGossipIDs(e){let t=new Map;for(let r=0;r<this.gossip;r++)this.history[r].forEach(n=>{if((this.msgs.get(n.msgIdStr)?.validated??!1)&&e.has(n.topic)){let o=t.get(n.topic);o==null&&(o=[],t.set(n.topic,o)),o.push(n.msgId)}});return t}validate(e){let t=this.msgs.get(e);if(t==null)return null;t.validated||this.notValidatedCount--;let{message:r,originatingPeers:n}=t;return t.validated=!0,t.originatingPeers=new Set,{message:r,originatingPeers:n}}shift(){this.history[this.history.length-1].forEach(t=>{let r=this.msgs.get(t.msgIdStr);r!=null&&(this.msgs.delete(t.msgIdStr),r.validated||this.notValidatedCount--)}),this.history.pop(),this.history.unshift([])}remove(e){let t=this.msgs.get(e);return t==null?null:(this.msgs.delete(e),t)}};var oc;(function(s){s.StrictSign="StrictSign",s.StrictNoSign="StrictNoSign"})(oc||(oc={}));var yt;(function(s){s[s.Signing=0]="Signing",s[s.Anonymous=1]="Anonymous"})(yt||(yt={}));var Ee;(function(s){s.Error="error",s.Ignore="ignore",s.Reject="reject",s.Blacklisted="blacklisted"})(Ee||(Ee={}));var le;(function(s){s.InvalidSignature="invalid_signature",s.InvalidSeqno="invalid_seqno",s.InvalidPeerId="invalid_peerid",s.SignaturePresent="signature_present",s.SeqnoPresent="seqno_present",s.FromPresent="from_present",s.TransformFailed="transform_failed"})(le||(le={}));var pe;(function(s){s.duplicate="duplicate",s.invalid="invalid",s.valid="valid"})(pe||(pe={}));function Ki(s){switch(s){case me.Ignore:return Ee.Ignore;case me.Reject:return Ee.Reject;default:throw new Error("Unreachable")}}var ac;(function(s){s.forward="forward",s.publish="publish"})(ac||(ac={}));var ge;(function(s){s.Fanout="fanout",s.Random="random",s.Subscribed="subscribed",s.Outbound="outbound",s.NotEnough="not_enough",s.Opportunistic="opportunistic"})(ge||(ge={}));var Ke;(function(s){s.Dc="disconnected",s.BadScore="bad_score",s.Prune="prune",s.Excess="excess"})(Ke||(Ke={}));var cs;(function(s){s.GraftBackoff="graft_backoff",s.BrokenPromise="broken_promise",s.MessageDeficit="message_deficit",s.IPColocation="IP_colocation"})(cs||(cs={}));var ls;(function(s){s.LowScore="low_score",s.MaxIhave="max_ihave",s.MaxIasked="max_iasked"})(ls||(ls={}));var as;(function(s){s.graylist="graylist",s.publish="publish",s.gossip="gossip",s.mesh="mesh"})(as||(as={}));function cc(s,e,t){return{protocolsEnabled:s.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:s.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:s.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:s.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEventsFanout:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_fanout_total",help:"Number of times we include peers in a topic mesh for fanout reasons",labelNames:["topic"]}),meshPeerInclusionEventsRandom:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_random_total",help:"Number of times we include peers in a topic mesh for random reasons",labelNames:["topic"]}),meshPeerInclusionEventsSubscribed:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_subscribed_total",help:"Number of times we include peers in a topic mesh for subscribed reasons",labelNames:["topic"]}),meshPeerInclusionEventsOutbound:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_outbound_total",help:"Number of times we include peers in a topic mesh for outbound reasons",labelNames:["topic"]}),meshPeerInclusionEventsNotEnough:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_not_enough_total",help:"Number of times we include peers in a topic mesh for not_enough reasons",labelNames:["topic"]}),meshPeerInclusionEventsOpportunistic:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_opportunistic_total",help:"Number of times we include peers in a topic mesh for opportunistic reasons",labelNames:["topic"]}),meshPeerInclusionEventsUnknown:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_unknown_total",help:"Number of times we include peers in a topic mesh for unknown reasons",labelNames:["topic"]}),meshPeerChurnEventsDisconnected:s.gauge({name:"gossipsub_peer_churn_events_disconnected_total",help:"Number of times we remove peers in a topic mesh for disconnected reasons",labelNames:["topic"]}),meshPeerChurnEventsBadScore:s.gauge({name:"gossipsub_peer_churn_events_bad_score_total",help:"Number of times we remove peers in a topic mesh for bad_score reasons",labelNames:["topic"]}),meshPeerChurnEventsPrune:s.gauge({name:"gossipsub_peer_churn_events_prune_total",help:"Number of times we remove peers in a topic mesh for prune reasons",labelNames:["topic"]}),meshPeerChurnEventsExcess:s.gauge({name:"gossipsub_peer_churn_events_excess_total",help:"Number of times we remove peers in a topic mesh for excess reasons",labelNames:["topic"]}),meshPeerChurnEventsUnknown:s.gauge({name:"gossipsub_peer_churn_events_unknown_total",help:"Number of times we remove peers in a topic mesh for unknown reasons",labelNames:["topic"]}),peersPerProtocol:s.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:s.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:s.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),acceptedMessagesTotal:s.gauge({name:"gossipsub_accepted_messages_total",help:"Total accepted messages for each topic",labelNames:["topic"]}),ignoredMessagesTotal:s.gauge({name:"gossipsub_ignored_messages_total",help:"Total ignored messages for each topic",labelNames:["topic"]}),rejectedMessagesTotal:s.gauge({name:"gossipsub_rejected_messages_total",help:"Total rejected messages for each topic",labelNames:["topic"]}),unknownValidationResultsTotal:s.gauge({name:"gossipsub_unknown_validation_results_total",help:"Total unknown validation results for each topic",labelNames:["topic"]}),asyncValidationMcacheHit:s.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),asyncValidationDelayFromFirstSeenSec:s.histogram({name:"gossipsub_async_validation_delay_from_first_seen",help:"Async validation report delay from first seen in second",buckets:[.01,.03,.1,.3,1,3,10]}),asyncValidationUnknownFirstSeen:s.gauge({name:"gossipsub_async_validation_unknown_first_seen_count_total",help:"Async validation report unknown first seen value for message"}),peerReadStreamError:s.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:s.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:s.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:s.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:s.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:s.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:s.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:s.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:s.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:s.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:s.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:s.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:s.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:s.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:s.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:s.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:s.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:s.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:s.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:s.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:s.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:s.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),rpcSentIDontWant:s.gauge({name:"gossipsub_rpc_sent_idontwant_total",help:"RPC sent"}),msgPublishCount:s.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeersByTopic:s.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),directPeersPublishedTotal:s.gauge({name:"gossipsub_direct_peers_published_total",help:"Total direct peers that we publish a msg to",labelNames:["topic"]}),floodsubPeersPublishedTotal:s.gauge({name:"gossipsub_floodsub_peers_published_total",help:"Total floodsub peers that we publish a msg to",labelNames:["topic"]}),meshPeersPublishedTotal:s.gauge({name:"gossipsub_mesh_peers_published_total",help:"Total mesh peers that we publish a msg to",labelNames:["topic"]}),fanoutPeersPublishedTotal:s.gauge({name:"gossipsub_fanout_peers_published_total",help:"Total fanout peers that we publish a msg to",labelNames:["topic"]}),msgPublishBytes:s.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgPublishTime:s.histogram({name:"gossipsub_msg_publish_seconds",help:"Total time in seconds to publish a message",buckets:[.001,.002,.005,.01,.1,.5,1],labelNames:["topic"]}),msgForwardCount:s.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:s.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:s.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:s.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),prevalidationInvalidTotal:s.gauge({name:"gossipsub_pre_validation_invalid_total",help:"Total count of invalid messages received",labelNames:["topic"]}),prevalidationValidTotal:s.gauge({name:"gossipsub_pre_validation_valid_total",help:"Total count of valid messages received",labelNames:["topic"]}),prevalidationDuplicateTotal:s.gauge({name:"gossipsub_pre_validation_duplicate_total",help:"Total count of duplicate messages received",labelNames:["topic"]}),prevalidationUnknownTotal:s.gauge({name:"gossipsub_pre_validation_unknown_status_total",help:"Total count of unknown_status messages received",labelNames:["topic"]}),msgReceivedInvalid:s.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["error"]}),msgReceivedInvalidByTopic:s.gauge({name:"gossipsub_msg_received_invalid_by_topic_total",help:"Tracks specific invalid message by topic",labelNames:["topic"]}),duplicateMsgDeliveryDelay:s.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*t.maxMeshMessageDeliveriesWindowSec,.5*t.maxMeshMessageDeliveriesWindowSec,Number(t.maxMeshMessageDeliveriesWindowSec),2*t.maxMeshMessageDeliveriesWindowSec,4*t.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:s.gauge({name:"gossisub_duplicate_msg_late_delivery_total",help:"Total count of late duplicate message delivery by topic, which triggers P3 penalty",labelNames:["topic"]}),duplicateMsgIgnored:s.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:s.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:s.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:s.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:s.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:s.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores"}),scoreWeights:s.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:s.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:s.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:s.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*t.behaviourPenaltyThreshold,.5*t.behaviourPenaltyThreshold,Number(t.behaviourPenaltyThreshold),2*t.behaviourPenaltyThreshold,4*t.behaviourPenaltyThreshold]}),ihaveRcvIgnored:s.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:s.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:s.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:s.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:s.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),idontwantRcvMsgids:s.gauge({name:"gossipsub_idontwant_rcv_msgids_total",help:"Total received IDONTWANT messages"}),idontwantRcvDonthaveMsgids:s.gauge({name:"gossipsub_idontwant_rcv_dont_have_msgids_total",help:"Total received IDONTWANT messageIDs that we do not have in mcache"}),iwantPromiseStarted:s.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:s.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:s.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:s.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:s.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:s.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:s.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*t.gossipPromiseExpireSec,Number(t.gossipPromiseExpireSec),2*t.gossipPromiseExpireSec,4*t.gossipPromiseExpireSec]}),iwantPromiseUntracked:s.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),connectedPeersBackoffSec:s.histogram({name:"gossipsub_connected_peers_backoff_seconds",help:"Backoff time in seconds",buckets:[1,2,4,10,20,60,120]}),cacheSize:s.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:s.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:s.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:s.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:s.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:e,toTopic(r){return this.topicStrToLabel.get(r)??r},onJoin(r){this.topicSubscriptionStatus.set({topicStr:r},1),this.meshPeerCounts.set({topicStr:r},0)},onLeave(r){this.topicSubscriptionStatus.set({topicStr:r},0),this.meshPeerCounts.set({topicStr:r},0)},onAddToMesh(r,n,i){let o=this.toTopic(r);switch(n){case ge.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:o},i);break;case ge.Random:this.meshPeerInclusionEventsRandom.inc({topic:o},i);break;case ge.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:o},i);break;case ge.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:o},i);break;case ge.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:o},i);break;case ge.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:o},i);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:o},i);break}},onRemoveFromMesh(r,n,i){let o=this.toTopic(r);switch(n){case Ke.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:o},i);break;case Ke.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:o},i);break;case Ke.Prune:this.meshPeerChurnEventsPrune.inc({topic:o},i);break;case Ke.Excess:this.meshPeerChurnEventsExcess.inc({topic:o},i);break;default:this.meshPeerChurnEventsUnknown.inc({topic:o},i);break}},onReportValidation(r,n,i){if(this.asyncValidationMcacheHit.inc({hit:r!=null?"hit":"miss"}),r!=null){let o=this.toTopic(r.message.topic);switch(n){case me.Accept:this.acceptedMessagesTotal.inc({topic:o});break;case me.Ignore:this.ignoredMessagesTotal.inc({topic:o});break;case me.Reject:this.rejectedMessagesTotal.inc({topic:o});break;default:this.unknownValidationResultsTotal.inc({topic:o});break}}i!=null?this.asyncValidationDelayFromFirstSeenSec.observe((Date.now()-i)/1e3):this.asyncValidationUnknownFirstSeen.inc()},onScorePenalty(r){this.scoringPenalties.inc({penalty:r},1)},onIhaveRcv(r,n,i){let o=this.toTopic(r);this.ihaveRcvMsgids.inc({topic:o},n),this.ihaveRcvNotSeenMsgids.inc({topic:o},i)},onIwantRcv(r,n){for(let[i,o]of r){let a=this.toTopic(i);this.iwantRcvMsgids.inc({topic:a},o)}this.iwantRcvDonthaveMsgids.inc(n)},onIdontwantRcv(r,n){this.idontwantRcvMsgids.inc(r),this.idontwantRcvDonthaveMsgids.inc(n)},onForwardMsg(r,n){let i=this.toTopic(r);this.msgForwardCount.inc({topic:i},1),this.msgForwardPeers.inc({topic:i},n)},onPublishMsg(r,n,i,o,a){let l=this.toTopic(r);this.msgPublishCount.inc({topic:l},1),this.msgPublishBytes.inc({topic:l},i*o),this.msgPublishPeersByTopic.inc({topic:l},i),this.directPeersPublishedTotal.inc({topic:l},n.direct),this.floodsubPeersPublishedTotal.inc({topic:l},n.floodsub),this.meshPeersPublishedTotal.inc({topic:l},n.mesh),this.fanoutPeersPublishedTotal.inc({topic:l},n.fanout),this.msgPublishTime.observe({topic:l},a/1e3)},onMsgRecvPreValidation(r){let n=this.toTopic(r);this.msgReceivedPreValidation.inc({topic:n},1)},onMsgRecvError(r){let n=this.toTopic(r);this.msgReceivedError.inc({topic:n},1)},onPrevalidationResult(r,n){let i=this.toTopic(r);switch(n){case pe.duplicate:this.prevalidationDuplicateTotal.inc({topic:i});break;case pe.invalid:this.prevalidationInvalidTotal.inc({topic:i});break;case pe.valid:this.prevalidationValidTotal.inc({topic:i});break;default:this.prevalidationUnknownTotal.inc({topic:i});break}},onMsgRecvInvalid(r,n){let i=this.toTopic(r),o=n.reason===Ee.Error?n.error:n.reason;this.msgReceivedInvalid.inc({error:o},1),this.msgReceivedInvalidByTopic.inc({topic:i},1)},onDuplicateMsgDelivery(r,n,i){let o=this.toTopic(r);this.duplicateMsgDeliveryDelay.observe({topic:o},n/1e3),i&&this.duplicateMsgLateDelivery.inc({topic:o},1)},onPublishDuplicateMsg(r){let n=this.toTopic(r);this.duplicateMsgIgnored.inc({topic:n},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(r,n){this.rpcRecvBytes.inc(n),this.rpcRecvCount.inc(1),r.subscriptions!=null&&this.rpcRecvSubscription.inc(r.subscriptions.length),r.messages!=null&&this.rpcRecvMessage.inc(r.messages.length),r.control!=null&&(this.rpcRecvControl.inc(1),r.control.ihave!=null&&this.rpcRecvIHave.inc(r.control.ihave.length),r.control.iwant!=null&&this.rpcRecvIWant.inc(r.control.iwant.length),r.control.graft!=null&&this.rpcRecvGraft.inc(r.control.graft.length),r.control.prune!=null&&this.rpcRecvPrune.inc(r.control.prune.length))},onRpcSent(r,n){if(this.rpcSentBytes.inc(n),this.rpcSentCount.inc(1),r.subscriptions!=null&&this.rpcSentSubscription.inc(r.subscriptions.length),r.messages!=null&&this.rpcSentMessage.inc(r.messages.length),r.control!=null){let i=r.control.ihave?.length??0,o=r.control.iwant?.length??0,a=r.control.graft?.length??0,l=r.control.prune?.length??0,u=r.control.idontwant?.length??0;i>0&&this.rpcSentIHave.inc(i),o>0&&this.rpcSentIWant.inc(o),a>0&&this.rpcSentGraft.inc(a),l>0&&this.rpcSentPrune.inc(l),u>0&&this.rpcSentIDontWant.inc(u),(i>0||o>0||a>0||l>0||u>0)&&this.rpcSentControl.inc(1)}},registerScores(r,n){let i=0,o=0,a=0,l=0;for(let u of r)u>=n.graylistThreshold&&i++,u>=n.publishThreshold&&o++,u>=n.gossipThreshold&&a++,u>=0&&l++;this.peersByScoreThreshold.set({threshold:as.graylist},i),this.peersByScoreThreshold.set({threshold:as.publish},o),this.peersByScoreThreshold.set({threshold:as.gossip},a),this.peersByScoreThreshold.set({threshold:as.mesh},l),this.score.set(r)},registerScoreWeights(r){for(let[n,i]of r.byTopic)this.scoreWeights.set({topic:n,p:"p1"},i.p1w),this.scoreWeights.set({topic:n,p:"p2"},i.p2w),this.scoreWeights.set({topic:n,p:"p3"},i.p3w),this.scoreWeights.set({topic:n,p:"p3b"},i.p3bw),this.scoreWeights.set({topic:n,p:"p4"},i.p4w);this.scoreWeights.set({p:"p5"},r.p5w),this.scoreWeights.set({p:"p6"},r.p6w),this.scoreWeights.set({p:"p7"},r.p7w)},registerScorePerMesh(r,n){let i=new Map;r.forEach((o,a)=>{let l=this.topicStrToLabel.get(a)??"unknown",u=i.get(l);u==null&&(u=new Set,i.set(l,u)),o.forEach(p=>u?.add(p))});for(let[o,a]of i){let l=[];a.forEach(u=>{l.push(n.get(u)??0)}),this.scorePerMesh.set({topic:o},l)}}}}var V=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var Vh={topics:{},topicScoreCap:10,appSpecificScore:()=>0,appSpecificWeight:10,IPColocationFactorWeight:-5,IPColocationFactorThreshold:10,IPColocationFactorWhitelist:new Set,behaviourPenaltyWeight:-10,behaviourPenaltyThreshold:0,behaviourPenaltyDecay:.2,decayInterval:1e3,decayToZero:.1,retainScore:3600*1e3},$h={topicWeight:.5,timeInMeshWeight:1,timeInMeshQuantum:1,timeInMeshCap:3600,firstMessageDeliveriesWeight:1,firstMessageDeliveriesDecay:.5,firstMessageDeliveriesCap:2e3,meshMessageDeliveriesWeight:-1,meshMessageDeliveriesDecay:.5,meshMessageDeliveriesCap:100,meshMessageDeliveriesThreshold:20,meshMessageDeliveriesWindow:10,meshMessageDeliveriesActivation:5e3,meshFailurePenaltyWeight:-1,meshFailurePenaltyDecay:.5,invalidMessageDeliveriesWeight:-1,invalidMessageDeliveriesDecay:.3};function lc(s={}){return{...Vh,...s,topics:s.topics!=null?Object.entries(s.topics).reduce((e,[t,r])=>(e[t]=jh(r),e),{}):{}}}function jh(s={}){return{...$h,...s}}function uc(s){for(let[e,t]of Object.entries(s.topics))try{Zh(t)}catch(r){throw new V(`invalid score parameters for topic ${e}: ${r.message}`)}if(s.topicScoreCap<0)throw new V("invalid topic score cap; must be positive (or 0 for no cap)");if(s.appSpecificScore===null||s.appSpecificScore===void 0)throw new V("missing application specific score function");if(s.IPColocationFactorWeight>0)throw new V("invalid IPColocationFactorWeight; must be negative (or 0 to disable)");if(s.IPColocationFactorWeight!==0&&s.IPColocationFactorThreshold<1)throw new V("invalid IPColocationFactorThreshold; must be at least 1");if(s.behaviourPenaltyWeight>0)throw new V("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)");if(s.behaviourPenaltyWeight!==0&&(s.behaviourPenaltyDecay<=0||s.behaviourPenaltyDecay>=1))throw new V("invalid BehaviourPenaltyDecay; must be between 0 and 1");if(s.decayInterval<1e3)throw new V("invalid DecayInterval; must be at least 1s");if(s.decayToZero<=0||s.decayToZero>=1)throw new V("invalid DecayToZero; must be between 0 and 1")}function Zh(s){if(s.topicWeight<0)throw new V("invalid topic weight; must be >= 0");if(s.timeInMeshQuantum===0)throw new V("invalid TimeInMeshQuantum; must be non zero");if(s.timeInMeshWeight<0)throw new V("invalid TimeInMeshWeight; must be positive (or 0 to disable)");if(s.timeInMeshWeight!==0&&s.timeInMeshQuantum<=0)throw new V("invalid TimeInMeshQuantum; must be positive");if(s.timeInMeshWeight!==0&&s.timeInMeshCap<=0)throw new V("invalid TimeInMeshCap; must be positive");if(s.firstMessageDeliveriesWeight<0)throw new V("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)");if(s.firstMessageDeliveriesWeight!==0&&(s.firstMessageDeliveriesDecay<=0||s.firstMessageDeliveriesDecay>=1))throw new V("invalid FirstMessageDeliveriesDecay; must be between 0 and 1");if(s.firstMessageDeliveriesWeight!==0&&s.firstMessageDeliveriesCap<=0)throw new V("invalid FirstMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight>0)throw new V("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.meshMessageDeliveriesWeight!==0&&(s.meshMessageDeliveriesDecay<=0||s.meshMessageDeliveriesDecay>=1))throw new V("invalid MeshMessageDeliveriesDecay; must be between 0 and 1");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesCap<=0)throw new V("invalid MeshMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesThreshold<=0)throw new V("invalid MeshMessageDeliveriesThreshold; must be positive");if(s.meshMessageDeliveriesWindow<0)throw new V("invalid MeshMessageDeliveriesWindow; must be non-negative");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesActivation<1e3)throw new V("invalid MeshMessageDeliveriesActivation; must be at least 1s");if(s.meshFailurePenaltyWeight>0)throw new V("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)");if(s.meshFailurePenaltyWeight!==0&&(s.meshFailurePenaltyDecay<=0||s.meshFailurePenaltyDecay>=1))throw new V("invalid MeshFailurePenaltyDecay; must be between 0 and 1");if(s.invalidMessageDeliveriesWeight>0)throw new V("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.invalidMessageDeliveriesDecay<=0||s.invalidMessageDeliveriesDecay>=1)throw new V("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1")}var Yh={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function hc(s={}){return{...Yh,...s}}function Fr(s,e,t=()=>!0){let r=new Set;if(e<=0)return r;for(let n of s){if(r.size>=e)break;t(n)&&(r.add(n),s.delete(n))}return r}function fc(s,e){return Fr(s,e,()=>!0)}var Cr=class extends Map{getDefault;constructor(e){super(),this.getDefault=e}getOrDefault(e){let t=super.get(e);return t===void 0&&(t=this.getDefault(),this.set(e,t)),t}};function dc(s,e,t,r){let n=0;Object.entries(e.topics).forEach(([o,a])=>{let l=t.topics[o];if(l===void 0)return;let u=0;if(a.inMesh){let y=a.meshTime/l.timeInMeshQuantum;y>l.timeInMeshCap&&(y=l.timeInMeshCap),u+=y*l.timeInMeshWeight}let p=a.firstMessageDeliveries;if(p>l.firstMessageDeliveriesCap&&(p=l.firstMessageDeliveriesCap),u+=p*l.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries<l.meshMessageDeliveriesThreshold){let y=l.meshMessageDeliveriesThreshold-a.meshMessageDeliveries,f=y*y;u+=f*l.meshMessageDeliveriesWeight}let m=a.meshFailurePenalty;u+=m*l.meshFailurePenaltyWeight;let x=a.invalidMessageDeliveries*a.invalidMessageDeliveries;u+=x*l.invalidMessageDeliveriesWeight,n+=u*l.topicWeight}),t.topicScoreCap>0&&n>t.topicScoreCap&&(n=t.topicScoreCap);let i=t.appSpecificScore(s);if(n+=i*t.appSpecificWeight,e.knownIPs.forEach(o=>{if(t.IPColocationFactorWhitelist.has(o))return;let a=r.get(o),l=a!=null?a.size:0;if(l>t.IPColocationFactorThreshold){let u=l-t.IPColocationFactorThreshold,p=u*u;n+=p*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let o=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=o*o;n+=a*t.behaviourPenaltyWeight}return n}var gc=zc(mc(),1);var Se;(function(s){s[s.unknown=0]="unknown",s[s.valid=1]="valid",s[s.invalid=2]="invalid",s[s.ignored=3]="ignored"})(Se||(Se={}));var Nr=class{records;queue;constructor(){this.records=new Map,this.queue=new gc.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:Se.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let r={msgId:e,expire:Date.now()+12e4};return this.queue.push(r),t}gc(){let e=Date.now(),t=this.queue.peekFront();for(;t!=null&&t.expire<e;)this.records.delete(t.msgId),this.queue.shift(),t=this.queue.peekFront()}clear(){this.records.clear(),this.queue.clear()}};var Or=class{params;metrics;peerStats=new Map;peerIPs=new Cr(()=>new Set);scoreCache=new Map;deliveryRecords=new Nr;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,r,n){this.params=e,this.metrics=t,uc(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??dc,this.log=r.forComponent("libp2p:gossipsub:score")}get size(){return this.peerStats.size}start(){if(this._backgroundInterval!=null){this.log("Peer score already running");return}this._backgroundInterval=setInterval(()=>{this.background()},this.params.decayInterval),this.log("started")}stop(){if(this._backgroundInterval==null){this.log("Peer score already stopped");return}clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),this.log("stopped")}background(){this.refreshScores(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map(([e,t])=>[e,t]))}messageFirstSeenTimestampMs(e){let t=this.deliveryRecords.getRecord(e);return t!=null?t.firstSeenTsMs:null}refreshScores(){let e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach((r,n)=>{if(!r.connected){e>r.expire&&(this.removeIPsForPeer(n,r.knownIPs),this.peerStats.delete(n),this.scoreCache.delete(n));return}Object.entries(r.topics).forEach(([i,o])=>{let a=this.params.topics[i];a!==void 0&&(o.firstMessageDeliveries*=a.firstMessageDeliveriesDecay,o.firstMessageDeliveries<t&&(o.firstMessageDeliveries=0),o.meshMessageDeliveries*=a.meshMessageDeliveriesDecay,o.meshMessageDeliveries<t&&(o.meshMessageDeliveries=0),o.meshFailurePenalty*=a.meshFailurePenaltyDecay,o.meshFailurePenalty<t&&(o.meshFailurePenalty=0),o.invalidMessageDeliveries*=a.invalidMessageDeliveriesDecay,o.invalidMessageDeliveries<t&&(o.invalidMessageDeliveries=0),o.inMesh&&(o.meshTime=e-o.graftTime,o.meshTime>a.meshMessageDeliveriesActivation&&(o.meshMessageDeliveriesActive=!0)))}),r.behaviourPenalty*=this.params.behaviourPenaltyDecay,r.behaviourPenalty<t&&(r.behaviourPenalty=0)})}score(e){this.metrics?.scoreFnCalls.inc();let t=this.peerStats.get(e);if(t==null)return 0;let r=Date.now(),n=this.scoreCache.get(e);if(n!=null&&n.cacheUntil>r)return n.score;this.metrics?.scoreFnRuns.inc();let i=this.computeScore(e,t,this.params,this.peerIPs),o=r+this.scoreCacheValidityMs;return n!=null?(this.metrics?.scoreCachedDelta.observe(Math.abs(i-n.score)),n.score=i,n.cacheUntil=o):this.scoreCache.set(e,{score:i,cacheUntil:o}),i}addPenalty(e,t,r){let n=this.peerStats.get(e);n!=null&&(n.behaviourPenalty+=t,this.metrics?.onScorePenalty(r))}addPeer(e){let t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){let r=this.peerStats.get(e);r?.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){let r=this.peerStats.get(e);r?.knownIPs.delete(t);let n=this.peerIPs.get(t);n!=null&&(n.delete(e),n.size===0&&this.peerIPs.delete(t))}removePeer(e){let t=this.peerStats.get(e);if(t!=null){if(this.score(e)>0){this.removeIPsForPeer(e,t.knownIPs),this.peerStats.delete(e);return}Object.entries(t.topics).forEach(([r,n])=>{n.firstMessageDeliveries=0;let i=this.params.topics[r].meshMessageDeliveriesThreshold;if(n.inMesh&&n.meshMessageDeliveriesActive&&n.meshMessageDeliveries<i){let o=i-n.meshMessageDeliveries;n.meshFailurePenalty+=o*o}n.inMesh=!1,n.meshMessageDeliveriesActive=!1}),t.connected=!1,t.expire=Date.now()+this.params.retainScore}}graft(e,t){let r=this.peerStats.get(e);if(r!=null){let n=this.getPtopicStats(r,t);n!=null&&(n.inMesh=!0,n.graftTime=Date.now(),n.meshTime=0,n.meshMessageDeliveriesActive=!1)}}prune(e,t){let r=this.peerStats.get(e);if(r!=null){let n=this.getPtopicStats(r,t);if(n!=null){let i=this.params.topics[t].meshMessageDeliveriesThreshold;if(n.meshMessageDeliveriesActive&&n.meshMessageDeliveries<i){let o=i-n.meshMessageDeliveries;n.meshFailurePenalty+=o*o}n.meshMessageDeliveriesActive=!1,n.inMesh=!1}}}validateMessage(e){this.deliveryRecords.ensureRecord(e)}deliverMessage(e,t,r){this.markFirstMessageDelivery(e,r);let n=this.deliveryRecords.ensureRecord(t),i=Date.now();if(n.status!==Se.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,i-n.firstSeenTsMs,Se[n.status]);return}n.status=Se.valid,n.validated=i,n.peers.forEach(o=>{o!==e.toString()&&this.markDuplicateMessageDelivery(o,r)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,r,n){switch(n){case Ee.Error:this.markInvalidMessageDelivery(e,r);return;case Ee.Blacklisted:return}let i=this.deliveryRecords.ensureRecord(t);if(i.status!==Se.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-i.firstSeenTsMs,Se[i.status]);return}if(n===Ee.Ignore){i.status=Se.ignored,i.peers.clear();return}i.status=Se.invalid,this.markInvalidMessageDelivery(e,r),i.peers.forEach(o=>{this.markInvalidMessageDelivery(o,r)}),i.peers.clear()}duplicateMessage(e,t,r){let n=this.deliveryRecords.ensureRecord(t);if(!n.peers.has(e))switch(n.status){case Se.unknown:n.peers.add(e);break;case Se.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,r,n.validated);break;case Se.invalid:this.markInvalidMessageDelivery(e,r);break;case Se.ignored:break}}markInvalidMessageDelivery(e,t){let r=this.peerStats.get(e);if(r!=null){let n=this.getPtopicStats(r,t);n!=null&&(n.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){let r=this.peerStats.get(e);if(r!=null){let n=this.getPtopicStats(r,t);if(n!=null){let i=this.params.topics[t].firstMessageDeliveriesCap;n.firstMessageDeliveries=Math.min(i,n.firstMessageDeliveries+1),n.inMesh&&(i=this.params.topics[t].meshMessageDeliveriesCap,n.meshMessageDeliveries=Math.min(i,n.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,r){let n=this.peerStats.get(e);if(n!=null){let i=r!==void 0?Date.now():0,o=this.getPtopicStats(n,t);if(o!=null&&o.inMesh){let a=this.params.topics[t];if(r!==void 0){let u=i-r,p=u>a.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,u,p),p)return}let l=a.meshMessageDeliveriesCap;o.meshMessageDeliveries=Math.min(l,o.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(let r of t){let n=this.peerIPs.get(r);n!=null&&(n.delete(e),n.size===0&&this.peerIPs.delete(r))}}getPtopicStats(e,t){let r=e.topics[t];return r!==void 0?r:this.params.topics[t]!==void 0?(r={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=r,r):null}};function Xh(s,e,t,r,n){let i=0,o=new Map;if(Object.entries(e.topics).forEach(([x,y])=>{let f=n.get(x)??"unknown",g=t.topics[x];if(g===void 0)return;let w=o.get(f);w==null&&(w={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},o.set(f,w));let E=0,S=0,c=0,h=0,d=0;if(y.inMesh){let D=Math.max(y.meshTime/g.timeInMeshQuantum,g.timeInMeshCap);E+=D*g.timeInMeshWeight}let b=y.firstMessageDeliveries;if(b>g.firstMessageDeliveriesCap&&(b=g.firstMessageDeliveriesCap),S+=b*g.firstMessageDeliveriesWeight,y.meshMessageDeliveriesActive&&y.meshMessageDeliveries<g.meshMessageDeliveriesThreshold){let D=g.meshMessageDeliveriesThreshold-y.meshMessageDeliveries,P=D*D;c+=P*g.meshMessageDeliveriesWeight}let v=y.meshFailurePenalty;h+=v*g.meshFailurePenaltyWeight;let _=y.invalidMessageDeliveries*y.invalidMessageDeliveries;d+=_*g.invalidMessageDeliveriesWeight,i+=(E+S+c+h+d)*g.topicWeight,w.p1w+=E,w.p2w+=S,w.p3w+=c,w.p3bw+=h,w.p4w+=d}),t.topicScoreCap>0&&i>t.topicScoreCap){i=t.topicScoreCap;let x=t.topicScoreCap/i;for(let y of o.values())y.p1w*=x,y.p2w*=x,y.p3w*=x,y.p3bw*=x,y.p4w*=x}let a=0,l=0,u=0,p=t.appSpecificScore(s);a+=p*t.appSpecificWeight,e.knownIPs.forEach(x=>{if(t.IPColocationFactorWhitelist.has(x))return;let y=r.get(x),f=y!=null?y.size:0;if(f>t.IPColocationFactorThreshold){let g=f-t.IPColocationFactorThreshold,w=g*g;l+=w*t.IPColocationFactorWeight}});let m=e.behaviourPenalty*e.behaviourPenalty;return u+=m*t.behaviourPenaltyWeight,i+=a+l+u,{byTopic:o,p5w:a,p6w:l,p7w:u,score:i}}function bc(s,e,t,r,n){let i={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let o of s){let a=e.get(o);if(a!=null){let l=Xh(o,a,t,r,n);for(let[u,p]of l.byTopic){let m=i.byTopic.get(u);m==null&&(m={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},i.byTopic.set(u,m)),m.p1w.push(p.p1w),m.p2w.push(p.p2w),m.p3w.push(p.p3w),m.p3bw.push(p.p3bw),m.p4w.push(p.p4w)}i.p5w.push(l.p5w),i.p6w.push(l.p6w),i.p7w.push(l.p7w),i.score.push(l.score)}else i.p5w.push(0),i.p6w.push(0),i.p7w.push(0),i.score.push(0)}return i}function zi(s){let e=s.getComponents(),t={},r=0;return e[r]?.name==="ip6zone"&&(t.zone=`${e[r].value}`,r++),e[r]?.name==="ip4"||e[r]?.name==="ip6"||e[r]?.name==="dns"||e[r]?.name==="dns4"||e[r]?.name==="dns6"?(t.type=e[r].name,t.host=e[r].value,r++):e[r]?.name==="dnsaddr"&&(t.type=e[r].name,t.host=`_dnsaddr.${e[r].value}`,r++),(e[r]?.name==="tcp"||e[r]?.name==="udp")&&(t.protocol=e[r].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[r].value}`),r++),e[r]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[r].value}`):t.type==="ip6"&&(t.cidr=`${e[r].value}`),r++),t.type==null||t.host==null?null:(e[r]?.name==="tls"&&e[r+1]?.name==="sni"&&(t.sni=e[r+1].value,r+=2),t)}function yc(s){let e=zi(s);if(e==null)throw new re(`Multiaddr ${s} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function wc(s){return zi(s)!==null}var qi=class s extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,s)}},xc=s=>s.reason??new DOMException("This operation was aborted.","AbortError");function Gi(s,e){let{milliseconds:t,fallback:r,message:n,customTimers:i={setTimeout,clearTimeout},signal:o}=e,a,l,p=new Promise((m,x)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(o?.aborted){x(xc(o));return}if(o&&(l=()=>{x(xc(o))},o.addEventListener("abort",l,{once:!0})),s.then(m,x),t===Number.POSITIVE_INFINITY)return;let y=new qi;a=i.setTimeout.call(void 0,()=>{if(r){try{m(r())}catch(f){x(f)}return}typeof s.cancel=="function"&&s.cancel(),n===!1?m():n instanceof Error?x(n):(y.message=n??`Promise timed out after ${t} milliseconds`,x(y))},t)}).finally(()=>{p.clear(),l&&o&&o.removeEventListener("abort",l)});return p.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},p}var Jh=s=>{let e=s.addEventListener||s.on||s.addListener,t=s.removeEventListener||s.off||s.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(s),removeListener:t.bind(s)}};function Qh(s,e,t){let r,n=new Promise((i,o)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),l=[],{addListener:u,removeListener:p}=Jh(s),m=async(...y)=>{let f=t.multiArgs?y:y[0];if(t.filter)try{if(!await t.filter(f))return}catch(g){r(),o(g);return}l.push(f),t.count===l.length&&(r(),i(l))},x=(...y)=>{r(),o(t.rejectionMultiArgs?y:y[0])};r=()=>{for(let y of a)p(y,m);for(let y of t.rejectionEvents)a.includes(y)||p(y,x)};for(let y of a)u(y,m);for(let y of t.rejectionEvents)a.includes(y)||u(y,x);t.signal&&t.signal.addEventListener("abort",()=>{x(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(l)});if(n.cancel=r,typeof t.timeout=="number"){let i=Gi(n,{milliseconds:t.timeout});return i.cancel=()=>{r(),i.clear()},i}return n}function vc(s,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let r=Qh(s,e,t),n=r.then(i=>i[0]);return n.cancel=r.cancel,n}function ef(s){return s?.addEventListener!=null}function tf(s){let e=Ct(),t,r=o=>{e.push(o.data)},n=()=>{e.end(),s.removeEventListener("message",r),s.removeEventListener("close",i),s.removeEventListener("remoteCloseWrite",n)},i=o=>{e.end(o.error),o.error!=null&&t?.reject(o.error),s.removeEventListener("message",r),s.removeEventListener("close",i),s.removeEventListener("remoteCloseWrite",n)};return s.addEventListener("message",r),s.addEventListener("close",i,{once:!0}),s.addEventListener("remoteCloseWrite",n,{once:!0}),{source:e,async sink(o){async function*a(){yield*o}let l=a();for(;;){t=Promise.withResolvers();let{done:u,value:p}=await Promise.race([l.next(),t.promise]);if(s.writeStatus==="closing"||s.writeStatus==="closed"||(p!=null&&(s.send(p)||await Promise.race([vc(s,"drain",{rejectionEvents:["close"]})])),u===!0))break}await s.close()}}}function Ec(...s){let e=s.map(t=>ef(t)?tf(t):t);return Ns(...e)}var Ur=class{rawStream;constructor(e,t,r){this.rawStream=e,r.maxBufferSize!=null&&(e.maxWriteBufferLength=r.maxBufferSize),e.addEventListener("close",n=>{n.error!=null&&t(n.error)})}get protocol(){return this.rawStream.protocol}push(e){this.pushPrefixed(is.single(e))}pushPrefixed(e){this.rawStream.send(e)}async close(e){await this.rawStream.close(e).catch(t=>{this.rawStream.abort(t)})}},Kr=class{source;rawStream;closeController;constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(r=>{e.abort(r)})}),this.source=Ec(this.rawStream,r=>Fs(r,t))}async close(){this.closeController.abort()}};var zr=class{gossipsubIWantFollowupMs;msgIdToStrFn;metrics;promises=new Map;requestMsByMsg=new Map;requestMsByMsgExpire;constructor(e,t,r){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=r,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){let r=Math.floor(Math.random()*t.length),n=t[r],i=this.msgIdToStrFn(n),o=this.promises.get(i);o==null&&(o=new Map,this.promises.set(i,o));let a=Date.now();o.has(e)||(o.set(e,a+this.gossipsubIWantFollowupMs),this.metrics!=null&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(i)||this.requestMsByMsg.set(i,a)))}getBrokenPromises(){let e=Date.now(),t=new Map,r=0;return this.promises.forEach((n,i)=>{n.forEach((o,a)=>{o<e&&(t.set(a,(t.get(a)??0)+1),n.delete(a),r++)}),n.size===0&&this.promises.delete(i)}),this.metrics?.iwantPromiseBroken.inc(r),t}deliverMessage(e,t=!1){this.trackMessage(e);let r=this.promises.get(e);r!=null&&(this.promises.delete(e),this.metrics!=null&&(this.metrics.iwantPromiseResolved.inc(1),t&&this.metrics.iwantPromiseResolvedFromDuplicate.inc(1),this.metrics.iwantPromiseResolvedPeers.inc(r.size)))}rejectMessage(e,t){this.trackMessage(e),t!==Ee.Error&&this.promises.delete(e)}clear(){this.promises.clear()}prune(){let e=Date.now()-this.requestMsByMsgExpire,t=0;for(let[r,n]of this.requestMsByMsg.entries())if(n<e)this.requestMsByMsg.delete(r),t++;else break;this.metrics?.iwantMessagePruned.inc(t)}trackMessage(e){if(this.metrics!=null){let t=this.requestMsByMsg.get(e);t!==void 0&&(this.metrics.iwantPromiseDeliveryTime.observe((Date.now()-t)/1e3),this.requestMsByMsg.delete(e))}}};var Sc=j("libp2p-pubsub:"),sf=BigInt(Date.now())*1000000n;function rf(){let s=++sf,e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,s,!1),e}async function _c(s,e,t,r){switch(s.type){case yt.Signing:{let n={from:s.author.toMultihash().bytes,data:r,seqno:rf(),topic:e,signature:void 0,key:void 0},i=Et([Sc,rt.Message.encode(n)]);n.signature=await s.privateKey.sign(i),n.key=s.key;let o={type:"signed",from:s.author,data:t,sequenceNumber:BigInt(`0x${$(n.seqno??new Uint8Array(0),"base16")}`),topic:e,signature:n.signature,key:Li(n.key)};return{raw:n,msg:o}}case yt.Anonymous:return{raw:{from:void 0,data:r,seqno:void 0,topic:e,signature:void 0,key:void 0},msg:{type:"unsigned",data:t,topic:e}};default:throw new Error("Unreachable")}}async function Ic(s,e){switch(s){case Ft:return e.signature!=null?{valid:!1,error:le.SignaturePresent}:e.seqno!=null?{valid:!1,error:le.SeqnoPresent}:e.key!=null?{valid:!1,error:le.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case wt:{if(e.seqno==null)return{valid:!1,error:le.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:le.InvalidSeqno};if(e.signature==null)return{valid:!1,error:le.InvalidSignature};if(e.from==null)return{valid:!1,error:le.InvalidPeerId};let t;try{t=rs(Ye(e.from))}catch{return{valid:!1,error:le.InvalidPeerId}}let r;if(e.key!=null){try{r=Li(e.key)}catch{return{valid:!1,error:le.InvalidPeerId}}if(!t.equals(r.toMultihash().bytes))return{valid:!1,error:le.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:le.InvalidPeerId};r=t.publicKey}let n={from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0},i=Et([Sc,rt.Message.encode(n)]),o;try{o=await r.verify(i,e.signature)}catch{o=!1}return o?{valid:!0,message:{type:"signed",from:t,data:e.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${$(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:r}}:{valid:!1,error:le.InvalidSignature}}default:throw new Error("Unreachable")}}function ze(s=[],e){return{subscriptions:[],messages:s,control:e!==void 0?{graft:e.graft??[],prune:e.prune??[],ihave:e.ihave??[],iwant:e.iwant??[],idontwant:e.idontwant??[]}:void 0}}function Hi(s){return s.control===void 0&&(s.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),s}function Ze(s){if(s.length<=1)return s;let e=()=>Math.floor(Math.random()*Math.floor(s.length));for(let t=0;t<s.length;t++){let r=e(),n=s[t];s[t]=s[r],s[r]=n}return s}function Tc(s){return $(s,"base64")}function Dc(s,e,t){switch(s){case wt:return{type:yt.Signing,author:e,key:We(t.publicKey),privateKey:t};case Ft:return{type:yt.Anonymous};default:throw new Error(`Unknown signature policy "${s}"`)}}var nf=(s,e)=>{let t=j(e.toString(16).padStart(16,"0"),"base16"),r=We(s),n=new Uint8Array(r.byteLength+t.length);return n.set(r,0),n.set(t,r.byteLength),n};function Ac(s){if(s.type!=="signed")throw new Error("expected signed message type");if(s.sequenceNumber==null)throw Error("missing seqno field");return nf(s.from.publicKey??s.key,s.sequenceNumber)}async function Mc(s){return St.encode(s.data)}function Pc(s){if(wc(s)){let e=yc(s);switch(e.type){case"ip4":case"ip6":return e.host;default:break}}return null}var us=class{entries=new Map;validityMs;constructor(e){this.validityMs=e.validityMs}get size(){return this.entries.size}put(e,t){return this.entries.has(e)?!0:(this.entries.set(e,{value:t,validUntilMs:Date.now()+this.validityMs}),!1)}prune(){let e=Date.now();for(let[t,r]of this.entries.entries())if(r.validUntilMs<e)this.entries.delete(t);else break}has(e){return this.entries.has(e)}get(e){let t=this.entries.get(e);return t!=null&&t.validUntilMs>=Date.now()?t.value:void 0}clear(){this.entries.clear()}};var Pe;(function(s){s[s.started=0]="started",s[s.stopped=1]="stopped"})(Pe||(Pe={}));var qr=class extends zs{globalSignaturePolicy;protocols=[Ot,$i,Wr];publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=Ct({objectMode:!0});direct=new Set;floodsubPeers=new Set;seenCache;acceptFromWhitelist=new Map;topics=new Map;subscriptions=new Set;mesh=new Map;fanout=new Map;fanoutLastpub=new Map;gossip=new Map;control=new Map;peerhave=new Map;iasked=new Map;iwantCounts=new Map;backoff=new Map;outbound=new Map;msgIdFn;fastMsgIdFn;msgIdToStrFn;fastMsgIdCache;publishedMessageIds;mcache;score;topicValidators=new Map;log;heartbeatTicks=0;gossipTracer;idontwantCounts=new Map;idontwants=new Map;components;directPeerInitial=null;static multicodec=Ot;opts;decodeRpcLimits;metrics;status={code:Pe.stopped};maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;allowedTopics;heartbeatTimer=null;constructor(e,t={}){super();let r={fallbackToFloodsub:!0,floodPublish:!0,batchPublish:!1,tagMeshPeers:!0,doPX:!1,directPeers:[],D:6,Dlo:4,Dhi:12,Dscore:4,Dout:2,Dlazy:6,heartbeatInterval:1e3,fanoutTTL:6e4,mcacheLength:5,mcacheGossip:3,seenTTL:12e4,gossipsubIWantFollowupMs:3e3,prunePeers:16,pruneBackoff:6e4,unsubcribeBackoff:1e4,graftFloodThreshold:1e4,opportunisticGraftPeers:2,opportunisticGraftTicks:60,directConnectTicks:300,gossipFactor:.25,idontwantMinDataSize:512,idontwantMaxMessages:512,...t,scoreParams:lc(t.scoreParams),scoreThresholds:hc(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=r.decodeRpcLimits??ic,this.globalSignaturePolicy=r.globalSignaturePolicy??wt,r.fallbackToFloodsub&&this.protocols.push(Hr),this.log=e.logger.forComponent(r.debugName??"libp2p:gossipsub"),this.opts=r,this.direct=new Set(r.directPeers.map(n=>n.id.toString())),this.seenCache=new us({validityMs:r.seenTTL}),this.publishedMessageIds=new us({validityMs:r.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case wt:this.msgIdFn=Ac;break;case Ft:this.msgIdFn=Mc;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new us({validityMs:r.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??Tc,this.mcache=t.messageCache??new Lr(r.mcacheGossip,r.mcacheLength,this.msgIdToStrFn),t.dataTransform!=null&&(this.dataTransform=t.dataTransform),t.metricsRegister!=null){if(t.metricsTopicStrToLabel==null)throw Error("Must set metricsTopicStrToLabel with metrics");let n=Math.max(...Object.values(r.scoreParams.topics).map(o=>o.meshMessageDeliveriesWindow),1e3),i=cc(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:r.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:n/1e3});i.mcacheSize.addCollect(()=>{this.onScrapeMetrics(i)});for(let o of this.protocols)i.protocolsEnabled.set({protocol:o},1);this.metrics=i}else this.metrics=null;this.gossipTracer=new zr(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new Or(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:r.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnLimitedConnection=t.runOnLimitedConnection,this.allowedTopics=r.allowedTopics!=null?new Set(r.allowedTopics):null}[Symbol.toStringTag]="@libp2p/gossipsub";[Xi]=["@libp2p/pubsub"];[Ji]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===Pe.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=Dc(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=Ct({objectMode:!0}),Ns(this.outboundInflightQueue,async i=>{for await(let{peerId:o,connection:a}of i)await this.createOutboundStream(o,a)}).catch(i=>{this.log.error("outbound inflight queue error",i)}),await Promise.all(this.opts.directPeers.map(async i=>{await this.components.peerStore.merge(i.id,{multiaddrs:i.addrs})}));let e=this.components.registrar;await Promise.all(this.protocols.map(async i=>e.handle(i,this.onIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection})));let t={onConnect:this.onPeerConnected.bind(this),onDisconnect:this.onPeerDisconnected.bind(this),notifyOnLimitedConnection:this.runOnLimitedConnection},r=await Promise.all(this.protocols.map(async i=>e.register(i,t))),n=setTimeout(this.runHeartbeat,100);this.status={code:Pe.started,registrarTopologyIds:r,heartbeatTimeout:n,hearbeatStartMs:Date.now()+100},this.score.start(),this.directPeerInitial=setTimeout(()=>{Promise.resolve().then(async()=>{await Promise.all(Array.from(this.direct).map(async i=>this.connect(i)))}).catch(i=>{this.log(i)})},1e3),this.opts.tagMeshPeers&&(this.addEventListener("gossipsub:graft",this.tagMeshPeer),this.addEventListener("gossipsub:prune",this.untagMeshPeer)),this.log("started")}async stop(){if(this.log("stopping"),this.status.code!==Pe.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:Pe.stopped},this.opts.tagMeshPeers&&(this.removeEventListener("gossipsub:graft",this.tagMeshPeer),this.removeEventListener("gossipsub:prune",this.untagMeshPeer));let t=this.components.registrar;await Promise.all(this.protocols.map(async n=>t.unhandle(n))),e.forEach(n=>{t.unregister(n)}),this.outboundInflightQueue.end();let r=[];for(let n of this.streamsOutbound.values())r.push(n.close());this.streamsOutbound.clear();for(let n of this.streamsInbound.values())r.push(n.close());this.streamsInbound.clear(),await Promise.all(r),this.peers.clear(),this.subscriptions.clear(),this.topics.clear(),this.heartbeatTimer!=null&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.iwantCounts.clear(),this.backoff.clear(),this.outbound.clear(),this.gossipTracer.clear(),this.seenCache.clear(),this.fastMsgIdCache!=null&&this.fastMsgIdCache.clear(),this.directPeerInitial!=null&&clearTimeout(this.directPeerInitial),this.idontwantCounts.clear(),this.idontwants.clear(),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream(e,t){if(!this.isStarted())return;let r=t.remotePeer;this.addPeer(r,t.direction,t.remoteAddr),this.createInboundStream(r,e),this.outboundInflightQueue.push({peerId:r,connection:t})}onPeerConnected(e,t){this.metrics?.newConnectionCount.inc({status:t.status}),!(!this.isStarted()||t.status!=="open")&&(this.addPeer(e,t.direction,t.remoteAddr),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}async createOutboundStream(e,t){if(!this.isStarted())return;let r=e.toString();if(this.peers.has(r)&&!this.streamsOutbound.has(r))try{let n=await t.newStream(this.protocols,{runOnLimitedConnection:this.runOnLimitedConnection}),i=new Ur(n,a=>{this.log.error("outbound pipe error",a)},{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(r,i);let o=i.protocol;o===Hr&&this.floodsubPeers.add(r),this.metrics?.peersPerProtocol.inc({protocol:o},1),n.addEventListener("close",()=>{this.streamsOutbound.get(r)===i&&(this.streamsOutbound.delete(r),this.floodsubPeers.delete(r),this.metrics?.peersPerProtocol.inc({protocol:o},-1))},{once:!0}),this.subscriptions.size>0&&(this.log("send subscriptions to",r),this.sendSubscriptions(r,Array.from(this.subscriptions),!0))}catch(n){this.log.error("createOutboundStream error",n)}}createInboundStream(e,t){if(!this.isStarted())return;let r=e.toString();if(!this.peers.has(r))return;let n=this.streamsInbound.get(r);n!==void 0&&(this.log("replacing existing inbound steam %s",r),n.close().catch(o=>{this.log.error(o)})),this.log("create inbound stream %s",r);let i=new Kr(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(r,i),this.pipePeerReadStream(e,i.source).catch(o=>{this.log(o)})}addPeer(e,t,r){let n=e.toString();if(!this.peers.has(n)){this.peers.set(n,e),this.score.addPeer(n);let i=Pc(r);i!==null?this.score.addIP(n,i):this.log("Added peer has no IP in current address %s %s",n,r.toString()),this.outbound.has(n)||this.outbound.set(n,t==="outbound")}}removePeer(e){let t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);let r=this.streamsOutbound.get(t),n=this.streamsInbound.get(t);r!=null&&this.metrics?.peersPerProtocol.inc({protocol:r.protocol},-1),r?.close().catch(i=>{this.log.error(i)}),n?.close().catch(i=>{this.log.error(i)}),this.streamsOutbound.delete(t),this.streamsInbound.delete(t);for(let[i,o]of this.topics)o.delete(t),o.size===0&&this.topics.delete(i);for(let[i,o]of this.mesh)o.delete(t)&&this.metrics?.onRemoveFromMesh(i,Ke.Dc,1);for(let i of this.fanout.values())i.delete(t);this.floodsubPeers.delete(t),this.gossip.delete(t),this.control.delete(t),this.outbound.delete(t),this.idontwantCounts.delete(t),this.idontwants.delete(t),this.score.removePeer(t),this.acceptFromWhitelist.delete(t)}get started(){return this.status.code===Pe.started}getMeshPeers(e){let t=this.mesh.get(e);return t!=null?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(t!=null?Array.from(t):[]).map(r=>this.peers.get(r)??Rt(r))}getTopics(){return Array.from(this.subscriptions)}decodeRpc(e){return rt.decode(e,{limits:{subscriptions:this.decodeRpcLimits.maxSubscriptions,messages:this.decodeRpcLimits.maxMessages,control:{ihave:this.decodeRpcLimits.maxControlMessages,ihave$:{messageIDs:this.decodeRpcLimits.maxIhaveMessageIDs},iwant:this.decodeRpcLimits.maxControlMessages,iwant$:{messageIDs:this.decodeRpcLimits.maxIwantMessageIDs},graft:this.decodeRpcLimits.maxControlMessages,prune:this.decodeRpcLimits.maxControlMessages,prune$:{peers:this.decodeRpcLimits.maxPeerInfos},idontwant:this.decodeRpcLimits.maxControlMessages,idontwant$:{messageIDs:this.decodeRpcLimits.maxIdontwantMessageIDs}}}})}async pipePeerReadStream(e,t){try{await Ns(t,async r=>{for await(let n of r)try{let i=n.subarray(),o=this.decodeRpc(i);if(this.metrics?.onRpcRecv(o,i.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,o)}catch(a){this.metrics?.onRpcRecvError(),this.log(a)}else this.handleReceivedRpc(e,o).catch(a=>{this.metrics?.onRpcRecvError(),this.log(a)})}catch(i){this.metrics?.onRpcDataError(),this.log(i)}})}catch(r){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(r,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){if(!this.acceptFrom(e.toString())){this.log("received message from unacceptable peer %p",e),this.metrics?.rpcRecvNotAccepted.inc();return}let r=t.subscriptions!=null?t.subscriptions.length:0,n=t.messages!=null?t.messages.length:0,i=0,o=0,a=0,l=0;if(t.control!=null&&(t.control.ihave!=null&&(i=t.control.ihave.length),t.control.iwant!=null&&(o=t.control.iwant.length),t.control.graft!=null&&(a=t.control.graft.length),t.control.prune!=null&&(l=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${r} messages ${n} ihave ${i} iwant ${o} graft ${a} prune ${l}`),t.subscriptions!=null&&t.subscriptions.length>0){let u=[],p=e.toString(),m=[];t.subscriptions.forEach(x=>{let y=x.topic,f=x.subscribe===!0;if(y!=null){if(this.allowedTopics!=null&&!this.allowedTopics.has(y))return;this.handleReceivedSubscription(e,y,f),f&&this.graftOnSubscribe(p,y)&&m.push(y),u.push({topic:y,subscribe:f})}}),m.length>0&&this.sendGraft(p,m),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:u}})}for(let u of t.messages){if(this.allowedTopics!=null&&!this.allowedTopics.has(u.topic))continue;let p=this.handleReceivedMessage(e,u).catch(m=>{this.metrics?.onMsgRecvError(u.topic),this.log(m)});this.opts.awaitRpcMessageHandler&&await p}t.control!=null&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,r){this.log("subscription update from %p topic %s",e,t);let n=this.topics.get(t);r?(n==null&&(n=new Set,this.topics.set(t,n)),n.add(e.toString())):n!=null&&(n.delete(e.toString()),n.size===0&&this.topics.delete(t))}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);let r=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,r.code);let n=r.code;switch(n){case pe.duplicate:this.score.duplicateMessage(e.toString(),r.msgIdStr,t.topic),this.gossipTracer.deliverMessage(r.msgIdStr,!0),this.mcache.observeDuplicate(r.msgIdStr,e.toString());return;case pe.invalid:if(r.msgIdStr!=null){let i=r.msgIdStr;this.score.rejectMessage(e.toString(),i,t.topic,r.reason),this.gossipTracer.rejectMessage(i,r.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);this.metrics?.onMsgRecvInvalid(t.topic,r);return;case pe.valid:this.score.validateMessage(r.messageId.msgIdStr),this.gossipTracer.deliverMessage(r.messageId.msgIdStr),this.mcache.put(r.messageId,t,!this.opts.asyncValidation),this.subscriptions.has(t.topic)&&(!this.components.peerId.equals(e)||this.opts.emitSelf)&&(super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:e,msgId:r.messageId.msgIdStr,msg:r.msg}})),super.dispatchEvent(new CustomEvent("message",{detail:r.msg}))),this.opts.asyncValidation||this.forwardMessage(r.messageId.msgIdStr,t,e.toString());break;default:throw new Error(`Invalid validation result: ${n}`)}}async validateReceivedMessage(e,t){let r=this.fastMsgIdFn?.(t),n=r!==void 0?this.fastMsgIdCache?.get(r):void 0;if(n!=null)return{code:pe.duplicate,msgIdStr:n};let i=await Ic(this.globalSignaturePolicy,t);if(!i.valid)return{code:pe.invalid,reason:Ee.Error,error:i.error};let o=i.message;try{this.dataTransform!=null&&(o.data=this.dataTransform.inboundTransform(t.topic,o.data))}catch(m){return this.log("Invalid message, transform failed",m),{code:pe.invalid,reason:Ee.Error,error:le.TransformFailed}}let a=await this.msgIdFn(o),l=this.msgIdToStrFn(a),u={msgId:a,msgIdStr:l};if(r!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(r,l)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(l))return{code:pe.duplicate,msgIdStr:l};this.seenCache.put(l),(t.data?.length??0)>=this.opts.idontwantMinDataSize&&this.sendIDontWants(a,t.topic,e.toString());let p=this.topicValidators.get(t.topic);if(p!=null){let m;try{m=await p(e,o)}catch(x){let y=x.code;y===Zi&&(m=me.Ignore),y===ji?m=me.Reject:m=me.Ignore}if(m!==me.Accept)return{code:pe.invalid,reason:Ki(m),msgIdStr:l}}return{code:pe.valid,messageId:u,msg:o}}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,r){this.sendRpc(e,{subscriptions:t.map(n=>({topic:n,subscribe:r})),messages:[]})}async handleControlMessage(e,t){if(t===void 0)return;let r=t.ihave?.length>0?this.handleIHave(e,t.ihave):[],n=t.iwant?.length>0?this.handleIWant(e,t.iwant):[],i=t.graft?.length>0?await this.handleGraft(e,t.graft):[];if(t.prune?.length>0&&await this.handlePrune(e,t.prune),t.idontwant?.length>0&&this.handleIdontwant(e,t.idontwant),r.length===0&&n.length===0&&i.length===0)return;let o=this.sendRpc(e,ze(n,{iwant:r,prune:i})),a=r[0]?.messageIDs;a!=null&&(o?this.gossipTracer.addPromise(e,a):this.metrics?.iwantPromiseUntracked.inc(1))}acceptFrom(e){if(this.direct.has(e))return!0;let t=Date.now(),r=this.acceptFromWhitelist.get(e);if(r!=null&&r.messagesAccepted<128&&r.acceptUntil>=t)return r.messagesAccepted+=1,!0;let n=this.score.score(e);return n>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),n>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){if(t.length===0)return[];let r=this.score.score(e);if(r<this.opts.scoreThresholds.gossipThreshold)return this.log("IHAVE: ignoring peer %s with score below threshold [ score = %d ]",e,r),this.metrics?.ihaveRcvIgnored.inc({reason:ls.LowScore}),[];let n=(this.peerhave.get(e)??0)+1;if(this.peerhave.set(e,n),n>10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:ls.MaxIhave}),[];let i=this.iasked.get(e)??0;if(i>=5e3)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,i),this.metrics?.ihaveRcvIgnored.inc({reason:ls.MaxIasked}),[];let o=new Map,a=0;e:for(let{topicID:p,messageIDs:m}of t){if(p==null||m==null||!this.mesh.has(p))continue;let x=0;for(let y of m){if(a>=5e3)break e;a++;let f=this.msgIdToStrFn(y);this.seenCache.has(f)||(o.set(f,y),x++)}this.metrics?.onIhaveRcv(p,m.length,x)}if(o.size===0)return[];let l=o.size;l+i>5e3&&(l=5e3-i),this.log("IHAVE: Asking for %d out of %d messages from %s",l,o.size,e);let u=Array.from(o.values());return Ze(u),u=u.slice(0,l),this.iasked.set(e,i+l),[{messageIDs:u}]}handleIWant(e,t){if(t.length===0)return[];let r=this.score.score(e);if(r<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,r),[];let n=(this.iwantCounts.get(e)??0)+1;if(this.iwantCounts.set(e,n),n>10)return this.log("IWANT: peer %s has requested too many times within this heartbeat interval; ignoring",e),[];let i=new Map,o=new Map,a=0,l=0;e:for(let{messageIDs:u}of t)if(u!=null)for(let p of u){if(l>=5e3)break e;l++;let m=this.msgIdToStrFn(p),x=this.mcache.getWithIWantCount(m,e);if(x==null){a++;continue}if(o.set(x.msg.topic,1+(o.get(x.msg.topic)??0)),x.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,p);continue}i.set(m,x.msg)}return this.metrics?.onIwantRcv(o,a),i.size===0?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",i.size,e),Array.from(i.values()))}async handleGraft(e,t){let r=[],n=this.score.score(e),i=Date.now(),o=this.opts.doPX;if(t.forEach(({topicID:l})=>{if(l==null)return;let u=this.mesh.get(l);if(u==null){o=!1;return}if(u.has(e))return;let p=this.backoff.get(l)?.get(e);if(this.direct.has(e))this.log("GRAFT: ignoring request from direct peer %s",e),r.push(l),o=!1;else if(typeof p=="number"&&i<p){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,cs.GraftBackoff),o=!1;let m=p+this.opts.graftFloodThreshold-this.opts.pruneBackoff;i<m&&this.score.addPenalty(e,1,cs.GraftBackoff),this.addBackoff(e,l),r.push(l)}else n<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,n,l),r.push(l),o=!1,this.addBackoff(e,l)):u.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(r.push(l),this.addBackoff(e,l)):(this.log("GRAFT: Add mesh link from %s in %s",e,l),this.addToMesh(e,l,ge.Subscribed));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:l,direction:"inbound"}})}),r.length===0)return[];let a=!1;return Promise.all(r.map(async l=>this.makePrune(e,l,o,a)))}async handlePrune(e,t){let r=this.score.score(e);for(let{topicID:n,backoff:i,peers:o}of t){if(n==null)continue;let a=this.mesh.get(n);if(a==null)return;this.log("PRUNE: Remove mesh link to %s in %s",e,n),this.score.prune(e,n),a.has(e)&&(a.delete(e),this.metrics?.onRemoveFromMesh(n,Ke.Prune,1)),typeof i=="number"&&i>0?this.doAddBackoff(e,n,i*1e3):this.addBackoff(e,n),o!=null&&o.length>0&&(r<this.opts.scoreThresholds.acceptPXThreshold?this.log("PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]",e,r,n):await this.pxConnect(o)),this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:n,direction:"inbound"}})}}handleIdontwant(e,t){let r=this.idontwantCounts.get(e)??0;if(r>=this.opts.idontwantMaxMessages)return;let n=r,i=this.idontwants.get(e);i==null&&(i=new Map,this.idontwants.set(e,i));let o=0;e:for(let{messageIDs:l}of t)for(let u of l){if(r>=this.opts.idontwantMaxMessages)break e;r++;let p=this.msgIdToStrFn(u);i.set(p,this.heartbeatTicks),this.mcache.msgs.has(p)||o++}this.idontwantCounts.set(e,r);let a=r-n;this.metrics?.onIdontwantRcv(a,o)}addBackoff(e,t){this.doAddBackoff(e,t,this.opts.pruneBackoff)}doAddBackoff(e,t,r){let n=this.backoff.get(t);n==null&&(n=new Map,this.backoff.set(t,n));let i=Date.now()+r;(n.get(e)??0)<i&&n.set(e,i)}applyIwantPenalties(){this.gossipTracer.getBrokenPromises().forEach((e,t)=>{this.log("peer %s didn't follow up in %d IWANT requests; adding penalty",t,e),this.score.addPenalty(t,e,cs.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!==0)return;let e=Date.now();this.backoff.forEach((t,r)=>{t.forEach((n,i)=>{n+1*this.opts.heartbeatInterval<e&&t.delete(i)}),t.size===0&&this.backoff.delete(r)})}async directConnect(){let e=[];this.direct.forEach(t=>{this.streamsOutbound.has(t)||e.push(t)}),await Promise.all(e.map(async t=>this.connect(t)))}async pxConnect(e){e.length>this.opts.prunePeers&&(Ze(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async r=>{if(r.peerID==null)return;let n=rs(Ye(r.peerID)),i=n.toString();if(!this.peers.has(i)){if(r.signedPeerRecord==null){t.push(i);return}try{if(!await this.components.peerStore.consumePeerRecord(r.signedPeerRecord,{expectedPeer:n})){this.log("bogus peer record obtained through px: could not add peer record to address book");return}t.push(i)}catch{this.log("bogus peer record obtained through px: invalid signature or not a peer record")}}})),t.length!==0&&await Promise.all(t.map(async r=>this.connect(r)))}async connect(e){this.log("Initiating connection with %s",e);let t=Rt(e),r=await this.components.connectionManager.openConnection(t);for(let n of this.protocols)for(let i of this.components.registrar.getTopologies(n))i.onConnect?.(t,r)}subscribe(e){if(this.status.code!==Pe.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(let t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==Pe.started)throw new Error("Pubsub is not started");let t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(let r of this.peers.keys())this.sendSubscriptions(r,[e],!1);this.leave(e)}join(e){if(this.status.code!==Pe.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);let t=new Set,r=this.backoff.get(e),n=this.fanout.get(e);if(n!=null&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),n.forEach(i=>{!this.direct.has(i)&&this.score.score(i)>=0&&r?.has(i)!==!0&&t.add(i)}),this.metrics?.onAddToMesh(e,ge.Fanout,t.size)),t.size<this.opts.D){let i=t.size;this.getRandomGossipPeers(e,this.opts.D,a=>!t.has(a)&&!this.direct.has(a)&&this.score.score(a)>=0&&r?.has(a)!==!0).forEach(a=>{t.add(a)}),this.metrics?.onAddToMesh(e,ge.Random,t.size-i)}this.mesh.set(e,t),t.forEach(i=>{this.log("JOIN: Add mesh link to %s in %s",i,e),this.sendGraft(i,[e])})}leave(e){if(this.status.code!==Pe.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);let t=this.mesh.get(e);t!=null&&(Promise.all(Array.from(t).map(async r=>{this.log("LEAVE: Remove mesh link to %s in %s",r,e),await this.sendPrune(r,e)})).catch(r=>{this.log("Error sending prunes to mesh peers",r)}),this.mesh.delete(e))}selectPeersToForward(e,t,r){let n=new Set,i=this.topics.get(e);i!=null&&(this.direct.forEach(a=>{i.has(a)&&t!==a&&!(r?.has(a)??!1)&&n.add(a)}),this.floodsubPeers.forEach(a=>{i.has(a)&&t!==a&&!(r?.has(a)??!1)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&n.add(a)}));let o=this.mesh.get(e);return o!=null&&o.size>0&&o.forEach(a=>{t!==a&&!(r?.has(a)??!1)&&n.add(a)}),n}selectPeersToPublish(e){let t=new Set,r={direct:0,floodsub:0,mesh:0,fanout:0},n=this.topics.get(e);if(n!=null)if(this.opts.floodPublish)n.forEach(i=>{this.direct.has(i)?(t.add(i),r.direct++):this.score.score(i)>=this.opts.scoreThresholds.publishThreshold&&(t.add(i),r.floodsub++)});else{this.direct.forEach(o=>{n.has(o)&&(t.add(o),r.direct++)}),this.floodsubPeers.forEach(o=>{n.has(o)&&this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),r.floodsub++)});let i=this.mesh.get(e);if(i!=null&&i.size>0)i.forEach(o=>{t.add(o),r.mesh++}),i.size<this.opts.D&&this.getRandomGossipPeers(e,this.opts.D-i.size,a=>!i.has(a)&&!this.direct.has(a)&&!this.floodsubPeers.has(a)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold).forEach(a=>{t.add(a),r.mesh++});else{let o=this.fanout.get(e);if(o!=null&&o.size>0)o.forEach(a=>{t.add(a),r.fanout++});else{let a=this.getRandomGossipPeers(e,this.opts.D,l=>this.score.score(l)>=this.opts.scoreThresholds.publishThreshold);a.size>0&&(this.fanout.set(e,a),a.forEach(l=>{t.add(l),r.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:r}}forwardMessage(e,t,r,n){r!=null&&this.score.deliverMessage(r,e,t.topic);let i=this.selectPeersToForward(t.topic,r,n);i.forEach(o=>{this.sendRpc(o,ze([t]))}),this.metrics?.onForwardMsg(t.topic,i.size)}async publish(e,t,r){let n=Date.now(),i=this.dataTransform!=null?this.dataTransform.outboundTransform(e,t):t;if(this.publishConfig==null)throw Error("PublishError.Uninitialized");let{raw:o,msg:a}=await _c(this.publishConfig,e,t,i),l=await this.msgIdFn(a),u=this.msgIdToStrFn(l),p=r?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(u)){if(p)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:m,tosendCount:x}=this.selectPeersToPublish(e),y=this.opts.emitSelf&&this.subscriptions.has(e),f=r?.allowPublishToZeroTopicPeers??this.opts.allowPublishToZeroTopicPeers;if(m.size===0&&!f&&!y)throw Error("PublishError.NoPeersSubscribedToTopic");this.seenCache.put(u),this.mcache.put({msgId:l,msgIdStr:u},o,!0),this.gossipTracer.deliverMessage(u),this.publishedMessageIds.put(u);let g=r?.batchPublish??this.opts.batchPublish,w=ze([o]);if(g)this.sendRpcInBatch(m,w);else for(let S of m)this.sendRpc(S,w)||m.delete(S);let E=Date.now()-n;return this.metrics?.onPublishMsg(e,x,m.size,o.data!=null?o.data.length:0,E),y&&(m.add(this.components.peerId.toString()),super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:u,msg:a}})),super.dispatchEvent(new CustomEvent("message",{detail:a}))),{recipients:Array.from(m.values()).map(S=>this.peers.get(S)??Rt(S))}}sendRpcInBatch(e,t){let r=rt.encode(t),n=is.single(r);for(let i of e){let o=this.streamsOutbound.get(i);if(o==null){this.log(`Cannot send RPC to ${i} as there is no open stream to it available`),e.delete(i);continue}try{o.pushPrefixed(n)}catch(a){e.delete(i),this.log.error(`Cannot send rpc to ${i}`,a)}this.metrics?.onRpcSent(t,r.length)}}reportMessageValidationResult(e,t,r){let n;if(r===me.Accept){if(n=this.mcache.validate(e),n!=null){let{message:o,originatingPeers:a}=n;this.score.deliverMessage(t,e,o.topic),this.forwardMessage(e,n.message,t,a)}}else if(n=this.mcache.remove(e),n!=null){let o=Ki(r),{message:a,originatingPeers:l}=n;this.score.rejectMessage(t,e,a.topic,o);for(let u of l)this.score.rejectMessage(u,e,a.topic,o)}let i=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(n,r,i)}sendGraft(e,t){let r=t.map(i=>({topicID:i})),n=ze([],{graft:r});this.sendRpc(e,n)}addToMesh(e,t,r){this.score.graft(e,t),this.mesh.get(t)?.add(e),this.metrics?.onAddToMesh(t,r,1)}graftOnSubscribe(e,t){let r=this.mesh.get(t);if(r==null||r.has(e)||r.size>=this.opts.Dlo)return!1;let n=this.streamsOutbound.get(e);return n==null||!this.protocols.includes(n.protocol)||this.direct.has(e)||this.score.score(e)<0||(this.backoff.get(t)?.has(e)??!1)?!1:(this.addToMesh(e,t,ge.Subscribed),!0)}async sendPrune(e,t){let n=[await this.makePrune(e,t,this.opts.doPX,!0)],i=ze([],{prune:n});this.sendRpc(e,i)}sendIDontWants(e,t,r){let n=this.mesh.get(t);if(n==null)return;let i=new Set(n);i.delete(r);for(let a of i)this.streamsOutbound.get(a)?.protocol!==Ot&&i.delete(a);let o=ze([],{idontwant:[{messageIDs:[e]}]});this.sendRpcInBatch(i,o)}sendRpc(e,t){let r=this.streamsOutbound.get(e);if(r==null)return this.log(`Cannot send RPC to ${e} as there is no open stream to it available`),!1;let n=this.control.get(e);n!=null&&(this.piggybackControl(e,t,n),this.control.delete(e));let i=this.gossip.get(e);i!=null&&(this.piggybackGossip(e,t,i),this.gossip.delete(e));let o=rt.encode(t);try{r.push(o)}catch(a){return this.log.error(`Cannot send rpc to ${e}`,a),n!=null&&this.control.set(e,n),i!=null&&this.gossip.set(e,i),!1}if(this.metrics?.onRpcSent(t,o.length),t.control?.graft!=null)for(let a of t.control?.graft)a.topicID!=null&&this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:a.topicID,direction:"outbound"}});if(t.control?.prune!=null)for(let a of t.control?.prune)a.topicID!=null&&this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:a.topicID,direction:"outbound"}});return!0}piggybackControl(e,t,r){let n=Hi(t);for(let i of r.graft)i.topicID!=null&&(this.mesh.get(i.topicID)?.has(e)??!1)&&n.control.graft.push(i);for(let i of r.prune)i.topicID!=null&&!(this.mesh.get(i.topicID)?.has(e)??!1)&&n.control.prune.push(i)}piggybackGossip(e,t,r){let n=Hi(t);n.control.ihave=r}async sendGraftPrune(e,t,r){let n=this.opts.doPX,i=!1;for(let[o,a]of e){let l=a.map(m=>({topicID:m})),u=[],p=t.get(o);p!=null&&(u=await Promise.all(p.map(async m=>this.makePrune(o,m,n&&!(r.get(o)??!1),i))),t.delete(o)),this.sendRpc(o,ze([],{graft:l,prune:u}))}for(let[o,a]of t){let l=await Promise.all(a.map(async u=>this.makePrune(o,u,n&&!(r.get(o)??!1),i)));this.sendRpc(o,ze([],{prune:l}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[r,n]of e)this.doEmitGossip(r,n,t.get(r)??[])}doEmitGossip(e,t,r){if(r.length===0||(Ze(r),r.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",r.length),t.size===0))return;let n=this.opts.Dlazy,o=this.opts.gossipFactor*t.size,a=t;o>n&&(n=o),n>a.size?n=a.size:a=Ze(Array.from(a)).slice(0,n),a.forEach(l=>{let u=r;r.length>5e3&&(u=Ze(u.slice()).slice(0,5e3)),this.pushGossip(l,{topicID:e,messageIDs:u})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,ze([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let r=ze([],{graft:t.graft,prune:t.prune});this.sendRpc(e,r)}}pushGossip(e,t){this.log("Add gossip to %s",e);let r=this.gossip.get(e)??[];this.gossip.set(e,r.concat(t))}async makePrune(e,t,r,n){if(this.score.prune(e,t),this.streamsOutbound.get(e)?.protocol===Wr)return{topicID:t,peers:[]};let i=n?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,o=i/1e3;if(this.doAddBackoff(e,t,i),!r)return{topicID:t,peers:[],backoff:o};let a=this.getRandomGossipPeers(t,this.opts.prunePeers,u=>u!==e&&this.score.score(u)>=0),l=await Promise.all(Array.from(a).map(async u=>{let p=this.peers.get(u)??Rt(u),m;try{m=await this.components.peerStore.get(p)}catch(x){if(x.name!=="NotFoundError")throw x}return{peerID:p.toMultihash().bytes,signedPeerRecord:m?.peerRecordEnvelope}}));return{topicID:t,peers:l,backoff:o}}runHeartbeat=()=>{let e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch(t=>{this.log("Error running heartbeat",t)}).finally(()=>{if(e?.(),this.status.code===Pe.started){clearTimeout(this.status.heartbeatTimeout);let t=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;t<this.opts.heartbeatInterval*.25&&(t+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,t)}})};async heartbeat(){let{D:e,Dlo:t,Dhi:r,Dscore:n,Dout:i,fanoutTTL:o}=this.opts;this.heartbeatTicks++;let a=new Map,l=f=>{let g=a.get(f);return g===void 0&&(g=this.score.score(f),a.set(f,g)),g},u=new Map,p=new Map,m=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.iwantCounts.clear(),this.applyIwantPenalties(),this.idontwantCounts.clear();for(let f of this.idontwants.values())for(let[g,w]of f)this.heartbeatTicks-w>=this.opts.mcacheLength&&f.delete(g);this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let x=new Map;this.mesh.forEach((f,g)=>{let w=this.topics.get(g),E=new Set,S=new Set;if(x.set(g,S),w!=null){let d=Ze(Array.from(w)),b=this.backoff.get(g);for(let v of d){let _=this.streamsOutbound.get(v);if(_!=null&&this.protocols.includes(_.protocol)&&!f.has(v)&&!this.direct.has(v)){let D=l(v);b?.has(v)!==!0&&D>=0&&E.add(v),D>=this.opts.scoreThresholds.gossipThreshold&&S.add(v)}}}let c=(d,b)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",d,g),this.addBackoff(d,g),f.delete(d),l(d)>=this.opts.scoreThresholds.gossipThreshold&&S.add(d),this.metrics?.onRemoveFromMesh(g,b,1);let v=p.get(d);v==null?p.set(d,[g]):v.push(g)},h=(d,b)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",d,g),this.addToMesh(d,g,b),S.delete(d);let v=u.get(d);v==null?u.set(d,[g]):v.push(g)};if(f.forEach(d=>{let b=l(d);b<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",d,b,g),c(d,Ke.BadScore),m.set(d,!0))}),f.size<t){let d=e-f.size;fc(E,d).forEach(v=>{h(v,ge.NotEnough)})}if(f.size>r){let d=Array.from(f);d.sort((v,_)=>l(_)-l(v)),d=d.slice(0,n).concat(Ze(d.slice(n)));let b=0;if(d.slice(0,e).forEach(v=>{(this.outbound.get(v)??!1)&&b++}),b<i){let v=D=>{let P=d[D];for(let K=D;K>0;K--)d[K]=d[K-1];d[0]=P};if(b>0){let D=b;for(let P=1;P<e&&D>0;P++)(this.outbound.get(d[P])??!1)&&(v(P),D--)}let _=e-b;for(let D=e;D<d.length&&_>0;D++)(this.outbound.get(d[D])??!1)&&(v(D),_--)}d.slice(e).forEach(v=>{c(v,Ke.Excess)})}if(f.size>=t){let d=0;if(f.forEach(b=>{(this.outbound.get(b)??!1)&&d++}),d<i){let b=i-d;Fr(E,b,_=>this.outbound.get(_)===!0).forEach(_=>{h(_,ge.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&f.size>1){let d=Array.from(f).sort((_,D)=>l(_)-l(D)),b=Math.floor(f.size/2),v=l(d[b]);if(v<this.opts.scoreThresholds.opportunisticGraftThreshold){let _=this.opts.opportunisticGraftPeers,D=Fr(E,_,P=>l(P)>v);for(let P of D)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",P,g),h(P,ge.Opportunistic)}}});let y=Date.now();this.fanoutLastpub.forEach((f,g)=>{f+o<y&&(this.fanout.delete(g),this.fanoutLastpub.delete(g))}),this.fanout.forEach((f,g)=>{let w=this.topics.get(g);f.forEach(h=>{(!(w?.has(h)??!1)||l(h)<this.opts.scoreThresholds.publishThreshold)&&f.delete(h)});let E=this.topics.get(g),S=[],c=new Set;if(x.set(g,c),E!=null){let h=Ze(Array.from(E));for(let d of h){let b=this.streamsOutbound.get(d);if(b!=null&&this.protocols.includes(b.protocol)&&!f.has(d)&&!this.direct.has(d)){let v=l(d);v>=this.opts.scoreThresholds.publishThreshold&&S.push(d),v>=this.opts.scoreThresholds.gossipThreshold&&c.add(d)}}}if(f.size<e){let h=e-f.size;S.slice(0,h).forEach(d=>{f.add(d),c?.delete(d)})}}),this.emitGossip(x),await this.sendGraftPrune(u,p,m),this.flush(),this.mcache.shift(),this.dispatchEvent(new CustomEvent("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,r=()=>!0){let n=this.topics.get(e);if(n==null)return new Set;let i=[];return n.forEach(o=>{let a=this.streamsOutbound.get(o);a!=null&&this.protocols.includes(a.protocol)&&r(o)&&i.push(o)}),i=Ze(i),t>0&&i.length>t&&(i=i.slice(0,t)),new Set(i)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0,r=Date.now();e.connectedPeersBackoffSec.reset();for(let l of this.backoff.values()){t+=l.size;for(let[u,p]of l.entries())this.peers.has(u)&&e.connectedPeersBackoffSec.observe(Math.max(0,p-r)/1e3)}e.cacheSize.set({cache:"backoff"},t);let n=0;for(let l of this.idontwants.values())n+=l.size;e.cacheSize.set({cache:"idontwants"},n);for(let[l,u]of this.topics)e.topicPeersCount.set({topicStr:l},u.size);for(let[l,u]of this.mesh)e.meshPeerCounts.set({topicStr:l},u.size);let i=[],o=new Map;e.behaviourPenalty.reset();for(let l of this.peers.keys()){let u=this.score.score(l);i.push(u),o.set(l,u),e.behaviourPenalty.observe(this.score.peerStats.get(l)?.behaviourPenalty??0)}e.registerScores(i,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,o);let a=bc(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(a)}tagMeshPeer=e=>{let{peerId:t,topic:r}=e.detail;this.components.peerStore.merge(this.peers.get(t)??Rt(t),{tags:{[r]:{value:100}}}).catch(n=>{this.log.error("Error tagging peer %s with topic %s",t,r,n)})};untagMeshPeer=e=>{let{peerId:t,topic:r}=e.detail;this.components.peerStore.merge(this.peers.get(t)??Rt(t),{tags:{[r]:void 0}}).catch(n=>{this.log.error("Error untagging peer %s with topic %s",t,r,n)})}};var wt="StrictSign",Ft="StrictNoSign",me;(function(s){s.Accept="accept",s.Ignore="ignore",s.Reject="reject"})(me||(me={}));var Lf=Ot;function Cf(s={}){return e=>new qr(e,s)}return qc(Ff);})();
2
+ "use strict";var Libp2PGossipsub=(()=>{var Nc=Object.create;var Os=Object.defineProperty;var Oc=Object.getOwnPropertyDescriptor;var Uc=Object.getOwnPropertyNames;var Kc=Object.getPrototypeOf,zc=Object.prototype.hasOwnProperty;var qc=(s,e)=>()=>{try{return e||s((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},_e=(s,e)=>{for(var t in e)Os(s,t,{get:e[t],enumerable:!0})},$i=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Uc(e))!zc.call(s,n)&&n!==t&&Os(s,n,{get:()=>e[n],enumerable:!(r=Oc(e,n))||r.enumerable});return s};var Gc=(s,e,t)=>(t=s!=null?Nc(Kc(s)):{},$i(e||!s||!s.__esModule?Os(t,"default",{value:s,enumerable:!0}):t,s)),Hc=s=>$i(Os({},"__esModule",{value:!0}),s);var bc=qc((J0,gc)=>{"use strict";function ee(s,t){var t=t||{};this._capacity=t.capacity,this._head=0,this._tail=0,Array.isArray(s)?this._fromArray(s):(this._capacityMask=3,this._list=new Array(4))}ee.prototype.peekAt=function(e){var t=e;if(t===(t|0)){var r=this.size();if(!(t>=r||t<-r))return t<0&&(t+=r),t=this._head+t&this._capacityMask,this._list[t]}};ee.prototype.get=function(e){return this.peekAt(e)};ee.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};ee.prototype.peekFront=function(){return this.peek()};ee.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(ee.prototype,"length",{get:function(){return this.size()}});ee.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ee.prototype.unshift=function(e){if(arguments.length===0)return this.size();var t=this._list.length;return this._head=this._head-1+t&this._capacityMask,this._list[this._head]=e,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.pop(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ee.prototype.shift=function(){var e=this._head;if(e!==this._tail){var t=this._list[e];return this._list[e]=void 0,this._head=e+1&this._capacityMask,e<2&&this._tail>1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}};ee.prototype.push=function(e){if(arguments.length===0)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ee.prototype.pop=function(){var e=this._tail;if(e!==this._head){var t=this._list.length;this._tail=e-1+t&this._capacityMask;var r=this._list[this._tail];return this._list[this._tail]=void 0,this._head<2&&e>1e4&&e<=t>>>2&&this._shrinkArray(),r}};ee.prototype.removeOne=function(e){var t=e;if(t===(t|0)&&this._head!==this._tail){var r=this.size(),n=this._list.length;if(!(t>=r||t<-r)){t<0&&(t+=r),t=this._head+t&this._capacityMask;var i=this._list[t],o;if(e<r/2){for(o=e;o>0;o--)this._list[t]=this._list[t=t-1+n&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+n&this._capacityMask}else{for(o=r-1-e;o>0;o--)this._list[t]=this._list[t=t+1+n&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+n&this._capacityMask}return i}}};ee.prototype.remove=function(e,t){var r=e,n,i=t;if(r===(r|0)&&this._head!==this._tail){var o=this.size(),a=this._list.length;if(!(r>=o||r<-o||t<1)){if(r<0&&(r+=o),t===1||!t)return n=new Array(1),n[0]=this.removeOne(r),n;if(r===0&&r+t>=o)return n=this.toArray(),this.clear(),n;r+t>o&&(t=o-r);var l;for(n=new Array(t),l=0;l<t;l++)n[l]=this._list[this._head+r+l&this._capacityMask];if(r=this._head+r&this._capacityMask,e+t===o){for(this._tail=this._tail-t+a&this._capacityMask,l=t;l>0;l--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(e===0){for(this._head=this._head+t+a&this._capacityMask,l=t-1;l>0;l--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(r<o/2){for(this._head=this._head+e+t+a&this._capacityMask,l=e;l>0;l--)this.unshift(this._list[r=r-1+a&this._capacityMask]);for(r=this._head-1+a&this._capacityMask;i>0;)this._list[r=r-1+a&this._capacityMask]=void 0,i--;e<0&&(this._tail=r)}else{for(this._tail=r,r=r+t+a&this._capacityMask,l=o-(t+e);l>0;l--)this.push(this._list[r++]);for(r=this._tail;i>0;)this._list[r=r+1+a&this._capacityMask]=void 0,i--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),n}}};ee.prototype.splice=function(e,t){var r=e;if(r===(r|0)){var n=this.size();if(r<0&&(r+=n),!(r>n))if(arguments.length>2){var i,o,a,l=arguments.length,u=this._list.length,p=2;if(!n||r<n/2){for(o=new Array(r),i=0;i<r;i++)o[i]=this._list[this._head+i&this._capacityMask];for(t===0?(a=[],r>0&&(this._head=this._head+r+u&this._capacityMask)):(a=this.remove(r,t),this._head=this._head+r+u&this._capacityMask);l>p;)this.unshift(arguments[--l]);for(i=r;i>0;i--)this.unshift(o[i-1])}else{o=new Array(n-(r+t));var m=o.length;for(i=0;i<m;i++)o[i]=this._list[this._head+r+t+i&this._capacityMask];for(t===0?(a=[],r!=n&&(this._tail=this._head+r+u&this._capacityMask)):(a=this.remove(r,t),this._tail=this._tail-m+u&this._capacityMask);p<l;)this.push(arguments[p++]);for(i=0;i<m;i++)this.push(o[i])}return a}else return this.remove(r,t)}};ee.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0};ee.prototype.isEmpty=function(){return this._head===this._tail};ee.prototype.toArray=function(){return this._copyArray(!1)};ee.prototype._fromArray=function(e){var t=e.length,r=this._nextPowerOf2(t);this._list=new Array(r),this._capacityMask=r-1,this._tail=t;for(var n=0;n<t;n++)this._list[n]=e[n]};ee.prototype._copyArray=function(e,t){var r=this._list,n=r.length,i=this.length;if(t=t|i,t==i&&this._head<this._tail)return this._list.slice(this._head,this._tail);var o=new Array(t),a=0,l;if(e||this._head>this._tail){for(l=this._head;l<n;l++)o[a++]=r[l];for(l=0;l<this._tail;l++)o[a++]=r[l]}else for(l=this._head;l<this._tail;l++)o[a++]=r[l];return o};ee.prototype._growArray=function(){if(this._head!=0){var e=this._copyArray(!0,this._list.length<<1);this._tail=this._list.length,this._head=0,this._list=e}else this._tail=this._list.length,this._list.length<<=1;this._capacityMask=this._capacityMask<<1|1};ee.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1};ee.prototype._nextPowerOf2=function(e){var t=Math.log(e)/Math.log(2),r=1<<t+1;return Math.max(r,4)};gc.exports=ee});var zf={};_e(zf,{StrictNoSign:()=>Ft,StrictSign:()=>wt,TopicValidatorResult:()=>me,gossipsub:()=>Kf,multicodec:()=>Uf});var Hr="/floodsub/1.0.0",Wr="/meshsub/1.0.0",ji="/meshsub/1.1.0",Ot="/meshsub/1.2.0";var Zi="ERR_TOPIC_VALIDATOR_REJECT",Yi="ERR_TOPIC_VALIDATOR_IGNORE";var re=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Ut=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Us=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Ks=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Kt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Vr=Symbol.for("@libp2p/peer-id");function Wc(s){return typeof s?.handleEvent=="function"}function Vc(s){return s===!0||s===!1}function $c(s){return Vc(s)?s:s?.capture??!1}function $r(s){let e={capture:$c(s),once:!!s?.once};return s?.passive!=null&&(e.passive=s?.passive),s?.signal!=null&&(e.signal=s?.signal),e}function Ji(s,e){return $r(s).capture===$r(e).capture}var zs=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,r){let n=$r(r);if(n?.signal?.aborted===!0)return;let i=u=>{n.once&&this.removeEventListener(e,t,n),Wc(t)?t.handleEvent(u):t(u)},o=this.#e.get(e);if(o==null&&(o=[],this.#e.set(e,o)),o.some(u=>u.callback!==t?!1:Ji(u.options,n)))return;super.addEventListener(e,i,n);let l=()=>{this.removeEventListener(e,t,n)};n.signal?.addEventListener("abort",l),o.push({callback:t,wrapper:i,options:n,onAbort:l})}removeEventListener(e,t,r){let n=this.#e.get(e);if(n==null){super.removeEventListener(e,t??null,r);return}this.#e.set(e,n.filter(i=>i.callback===t&&Ji(i.options,r)?(super.removeEventListener(e,i.wrapper,r),i.options?.signal?.removeEventListener("abort",i.onAbort),!1):!0))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Qi=Symbol.for("@libp2p/service-capabilities"),eo=Symbol.for("@libp2p/service-dependencies");var Jr={};_e(Jr,{base58btc:()=>ie,base58flickr:()=>tl});var bd=new Uint8Array(0);function so(s,e){if(s===e)return!0;if(s.byteLength!==e.byteLength)return!1;for(let t=0;t<s.byteLength;t++)if(s[t]!==e[t])return!1;return!0}function Be(s){if(s instanceof Uint8Array&&s.constructor.name==="Uint8Array")return vt(s);if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return vt(new Uint8Array(s.buffer,s.byteOffset,s.byteLength));throw new Error("Unknown type, must be binary type")}function ro(s){let e=new Uint8Array(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}var to=4096;function no(s){let e=s.length;if(e<=to)return String.fromCharCode.apply(String,s);let t="",r=0;for(;r<e;)t+=String.fromCharCode.apply(String,s.subarray(r,r+=to));return t}function jc(s){return s?.buffer instanceof ArrayBuffer}function vt(s){return jc(s)?s:s.slice()}function Zc(s,e,t){if(s.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 i=0;i<s.length;i++){var o=s.charAt(i),a=o.charCodeAt(0);if(r[a]!==255)throw new TypeError(o+" is ambiguous");if(r[a]=i,t){var l=o.toLowerCase().charCodeAt(0),u=o.toUpperCase().charCodeAt(0);l!==a&&(r[l]=i),u!==a&&(r[u]=i)}}var p=s.length,m=s.charAt(0),x=Math.log(p)/Math.log(256),y=Math.log(256)/Math.log(p);function f(E){if(E instanceof Uint8Array||(ArrayBuffer.isView(E)?E=new Uint8Array(E.buffer,E.byteOffset,E.byteLength):Array.isArray(E)&&(E=Uint8Array.from(E))),!(E instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(E.length===0)return"";for(var S=0,c=0,h=0,d=E.length;h!==d&&E[h]===0;)h++,S++;for(var b=(d-h)*y+1>>>0,v=new Uint8Array(b);h!==d;){for(var _=E[h],D=0,P=b-1;(_!==0||D<c)&&P!==-1;P--,D++)_+=256*v[P]>>>0,v[P]=_%p>>>0,_=_/p>>>0;if(_!==0)throw new Error("Non-zero carry");c=D,h++}for(var K=b-c;K!==b&&v[K]===0;)K++;for(var F=m.repeat(S);K<b;++K)F+=s.charAt(v[K]);return F}function g(E){if(typeof E!="string")throw new TypeError("Expected String");if(E.length===0)return new Uint8Array;var S=0;if(E[S]!==" "){for(var c=0,h=0;E[S]===m;)c++,S++;for(var d=(E.length-S)*x+1>>>0,b=new Uint8Array(d);E[S];){var v=r[E.charCodeAt(S)];if(v===255)return;for(var _=0,D=d-1;(v!==0||_<h)&&D!==-1;D--,_++)v+=p*b[D]>>>0,b[D]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");h=_,S++}if(E[S]!==" "){for(var P=d-h;P!==d&&b[P]===0;)P++;for(var K=new Uint8Array(c+(d-P)),F=c;P!==d;)K[F++]=b[P++];return K}}}function w(E){var S=g(E);if(S)return S;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:g,decode:w}}var Yc=Zc,Xc=Yc,oo=Xc;var jr=class{name;prefix;baseEncode;constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Zr=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,r){this.name=e,this.prefix=t;let n=t.codePointAt(0);if(n===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=r}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 ao(this,e)}},Yr=class{decoders;constructor(e){this.decoders=e}or(e){return ao(this,e)}decode(e){let t=e[0],r=this.decoders[t];if(r!=null)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ao(s,e){return new Yr({...s.decoders??{[s.prefix]:s},...e.decoders??{[e.prefix]:e}})}var Xr=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,r,n){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new jr(e,t,r),this.decoder=new Zr(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function zt({name:s,prefix:e,encode:t,decode:r}){return new Xr(s,e,t,r)}function it({name:s,prefix:e,alphabet:t,caseInsensitive:r=!1}){let{encode:n,decode:i}=oo(t,s,r);return zt({prefix:e,name:s,encode:n,decode:o=>Be(i(o))})}function Jc(s,e,t,r){let n=s.length;for(;s[n-1]==="=";)--n;let i=new Uint8Array(n*t/8|0),o=0,a=0,l=0;for(let u=0;u<n;++u){let p=e[s[u]];if(p===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<t|p,o+=t,o>=8&&(o-=8,i[l++]=255&a>>o)}if(o>=t||(255&a<<8-o)!==0)throw new SyntaxError("Unexpected end of data");return i}function Qc(s,e,t){let r=e[e.length-1]==="=",n=(1<<t)-1,i="",o=0,a=0;for(let l=0;l<s.length;++l)for(a=a<<8|s[l],o+=8;o>t;)o-=t,i+=e[n&a>>o];if(o!==0&&(i+=e[n&a<<t-o]),r)for(;(i.length*t&7)!==0;)i+="=";return i}function el(s,e){let t={};for(let r=0;r<s.length;++r)if(t[s[r]]=r,e){let n=s[r].toLowerCase(),i=s[r].toUpperCase();n!==s[r]&&(t[n]=r),i!==s[r]&&(t[i]=r)}return t}function ne({name:s,prefix:e,bitsPerChar:t,alphabet:r,caseInsensitive:n=!1}){let i=el(r,n);return zt({prefix:e,name:s,encode(o){return Qc(o,r,t)},decode(o){return Jc(o,i,t,s)}})}var ie=it({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),tl=it({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Qr={};_e(Qr,{base32:()=>qt,base32hex:()=>il,base32hexpad:()=>al,base32hexpadupper:()=>cl,base32hexupper:()=>ol,base32pad:()=>rl,base32padupper:()=>nl,base32upper:()=>sl,base32z:()=>ll});var qt=ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),sl=ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),rl=ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),nl=ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),il=ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),ol=ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),al=ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),cl=ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),ll=ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var en={};_e(en,{base36:()=>ds,base36upper:()=>ul});var ds=it({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),ul=it({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var hl=uo,co=128,fl=127,dl=~fl,pl=Math.pow(2,31);function uo(s,e,t){e=e||[],t=t||0;for(var r=t;s>=pl;)e[t++]=s&255|co,s/=128;for(;s&dl;)e[t++]=s&255|co,s>>>=7;return e[t]=s|0,uo.bytes=t-r+1,e}var ml=tn,gl=128,lo=127;function tn(s,r){var t=0,r=r||0,n=0,i=r,o,a=s.length;do{if(i>=a)throw tn.bytes=0,new RangeError("Could not decode varint");o=s[i++],t+=n<28?(o&lo)<<n:(o&lo)*Math.pow(2,n),n+=7}while(o>=gl);return tn.bytes=i-r,t}var bl=Math.pow(2,7),yl=Math.pow(2,14),wl=Math.pow(2,21),xl=Math.pow(2,28),vl=Math.pow(2,35),El=Math.pow(2,42),Sl=Math.pow(2,49),_l=Math.pow(2,56),Il=Math.pow(2,63),Tl=function(s){return s<bl?1:s<yl?2:s<wl?3:s<xl?4:s<vl?5:s<El?6:s<Sl?7:s<_l?8:s<Il?9:10},Dl={encode:hl,decode:ml,encodingLength:Tl},Al=Dl,ps=Al;function ms(s,e=0){let t=ps.decode(s,e),r=ps.decode.bytes;if(r>9)throw new RangeError("Invalid varint: too long");if(r>1&&s[e+r-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[t,r]}function Gt(s,e,t=0){return ps.encode(s,e,t),e}function Ht(s){return ps.encodingLength(s)}function He(s,e){let t=e.byteLength,r=Ht(s),n=r+Ht(t),i=new Uint8Array(n+t);return Gt(s,i,0),Gt(t,i,r),i.set(e,n),new Wt(s,t,e,i)}function Ye(s){let e=Be(s),[t,r]=ms(e),[n,i]=ms(e.subarray(r)),o=e.subarray(r+i);if(o.byteLength!==n)throw new Error("Incorrect length");return new Wt(t,n,o,e)}function ho(s,e){if(s===e)return!0;{let t=e;return s.code===t.code&&s.size===t.size&&t.bytes instanceof Uint8Array&&so(s.bytes,t.bytes)}}var Wt=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=vt(r),this.bytes=vt(n)}};function fo(s,e){let{bytes:t,version:r}=s;return r===0?Pl(t,sn(s),e??ie.encoder):Bl(t,sn(s),e??qt.encoder)}var po=new WeakMap;function sn(s){let e=po.get(s);if(e==null){let t=new Map;return po.set(s,t),t}return e}var ce=class s{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=vt(n),this["/"]=this.bytes}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:t}=this;if(e!==gs)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==kl)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return s.createV0(t)}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:t}=this.multihash,r=He(e,t);return s.createV1(this.code,r)}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 s.equals(this,e)}static equals(e,t){let r=t;return r!=null&&e.code===r.code&&e.version===r.version&&ho(e.multihash,r.multihash)}toString(e){return fo(this,e)}toJSON(){return{"/":fo(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 t=e;if(t instanceof s)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:r,code:n,multihash:i,bytes:o}=t;return new s(r,n,i,o??mo(r,n,i.bytes))}else if(t[Rl]===!0){let{version:r,multihash:n,code:i}=t,o=Ye(n);return s.create(r,i,o)}else return null}static create(e,t,r){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==gs)throw new Error(`Version 0 CID must use dag-pb (code: ${gs}) block encoding`);return new s(e,t,r,r.bytes)}case 1:{let n=mo(e,t,r.bytes);return new s(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return s.create(0,gs,e)}static createV1(e,t){return s.create(1,e,t)}static decode(e){let[t,r]=s.decodeFirst(e);if(r.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=s.inspectBytes(e),r=t.size-t.multihashSize,n=Be(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=n.subarray(t.multihashSize-t.digestSize),o=new Wt(t.multihashCode,t.digestSize,i,n);return[t.version===0?s.createV0(o):s.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,r=()=>{let[m,x]=ms(e.subarray(t));return t+=x,m},n=r(),i=gs;if(n===18?(n=0,t=0):i=r(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let o=t,a=r(),l=r(),u=t+l,p=u-o;return{version:n,codec:i,multihashCode:a,digestSize:l,multihashSize:p,size:u}}static parse(e,t){let[r,n]=Ml(e,t),i=s.decode(n);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return sn(i).set(r,e),i}};function Ml(s,e){switch(s[0]){case"Q":{let t=e??ie;return[ie.prefix,t.decode(`${ie.prefix}${s}`)]}case ie.prefix:{let t=e??ie;return[ie.prefix,t.decode(s)]}case qt.prefix:{let t=e??qt;return[qt.prefix,t.decode(s)]}case ds.prefix:{let t=e??ds;return[ds.prefix,t.decode(s)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[s[0],e.decode(s)]}}}function Pl(s,e,t){let{prefix:r}=t;if(r!==ie.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let n=e.get(r);if(n==null){let i=t.encode(s).slice(1);return e.set(r,i),i}else return n}function Bl(s,e,t){let{prefix:r}=t,n=e.get(r);if(n==null){let i=t.encode(s);return e.set(r,i),i}else return n}var gs=112,kl=18;function mo(s,e,t){let r=Ht(s),n=r+Ht(e),i=new Uint8Array(n+t.byteLength);return Gt(s,i,0),Gt(e,i,r),i.set(t,n),i}var Rl=Symbol.for("@ipld/js-cid/CID");var rn={};_e(rn,{identity:()=>Ne});var go=0,Ll="identity",bo=Be;function Cl(s,e){if(e?.truncate!=null&&e.truncate!==s.byteLength){if(e.truncate<0||e.truncate>s.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${s.byteLength}`);s=s.subarray(0,e.truncate)}return He(go,bo(s))}var Ne={code:go,name:Ll,encode:bo,digest:Cl};function Ie(s,e){if(s===e)return!0;if(s.byteLength!==e.byteLength)return!1;for(let t=0;t<s.byteLength;t++)if(s[t]!==e[t])return!1;return!0}function Fl(s){return s.buffer instanceof ArrayBuffer}function ke(s){return Fl(s)?s:s.slice()}async function yo(s,e,t,r){let n=await crypto.subtle.importKey("jwk",s,{name:"ECDSA",namedCurve:s.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();let i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,ke(e),ke(t.subarray()));return r?.signal?.throwIfAborted(),i}function Xe(s=0){return new Uint8Array(s)}function he(s=0){return new Uint8Array(s)}function Nl(s){return s?.buffer instanceof ArrayBuffer}function wo(s){if(Nl(s))return s;let e=s.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Et(s,e){e==null&&(e=s.reduce((n,i)=>n+i.length,0));let t=he(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return wo(t)}var vo=Symbol.for("@achingbrain/uint8arraylist");function xo(s,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let r of s){let n=t+r.byteLength;if(e<n)return{buf:r,index:e-t};t=n}throw new RangeError("index is out of bounds")}function Gs(s){return!!s?.[vo]}var ae=class s{bufs;length;[vo]=!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 t=0;for(let r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else if(Gs(r)){t+=r.byteLength;for(let n of r.bufs)this.bufs.push(n)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else if(Gs(r))t+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=xo(this.bufs,e);return t.buf[t.index]}set(e,t){let r=xo(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(t+r,e[r]);else if(Gs(e))for(let r=0;r<e.length;r++)this.set(t+r,e.get(r));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,t){let{bufs:r,length:n}=this._subList(e,t);return Et(r,n)}subarray(e,t){let{bufs:r,length:n}=this._subList(e,t);return r.length===1?r[0]:Et(r,n)}sublist(e,t){let{bufs:r,length:n}=this._subList(e,t),i=new s;return i.length=n,i.bufs=r,i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let r=[],n=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],a=n,l=a+o.byteLength;if(n=l,e>=l)continue;let u=e>=a&&e<l,p=t>a&&t<=l;if(u&&p){if(e===a&&t===l){r.push(o);break}let m=e-a;r.push(o.subarray(m,m+(t-e)));break}if(u){if(e===0){r.push(o);continue}r.push(o.subarray(e-a));continue}if(p){if(t===l){r.push(o);break}r.push(o.subarray(0,t-a));break}r.push(o)}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!Gs(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let r=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let n=r.byteLength;if(n===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let m=0;m<i;m++)o[m]=-1;for(let m=0;m<n;m++)o[r[m]]=m;let a=o,l=this.byteLength-r.byteLength,u=r.byteLength-1,p;for(let m=t;m<=l;m+=p){p=0;for(let x=u;x>=0;x--){let y=this.get(m+x);if(r[x]!==y){p=Math.max(1,x-a[y]);break}}if(p===0)return m}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let r=he(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){let n=Xe(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){let n=Xe(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){let n=Xe(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let r=he(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){let n=Xe(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){let n=Xe(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){let n=Xe(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){let n=Xe(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){let n=Xe(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(e==null||!(e instanceof s)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Ie(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let r=new s;return r.bufs=e,t==null&&(t=e.reduce((n,i)=>n+i.byteLength,0)),r.length=t,r}};var nn={};_e(nn,{base10:()=>Ol});var Ol=it({prefix:"9",name:"base10",alphabet:"0123456789"});var on={};_e(on,{base16:()=>Ul,base16upper:()=>Kl});var Ul=ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),Kl=ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var an={};_e(an,{base2:()=>zl});var zl=ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var cn={};_e(cn,{base256emoji:()=>Vl});var Eo=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}"),ql=Eo.reduce((s,e,t)=>(s[t]=e,s),[]),Gl=Eo.reduce((s,e,t)=>{let r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return s[r]=t,s},[]);function Hl(s){return s.reduce((e,t)=>(e+=ql[t],e),"")}function Wl(s){let e=[];for(let t of s){let r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);let n=Gl[r];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Vl=zt({prefix:"\u{1F680}",name:"base256emoji",encode:Hl,decode:Wl});var ln={};_e(ln,{base64:()=>$l,base64pad:()=>jl,base64url:()=>Zl,base64urlpad:()=>Yl});var $l=ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),jl=ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Zl=ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Yl=ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var un={};_e(un,{base8:()=>Xl});var Xl=ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var hn={};_e(hn,{identity:()=>Jl});var Jl=zt({prefix:"\0",name:"identity",encode:s=>no(Be(s)),decode:s=>Be(ro(s))});var sp=new TextEncoder,rp=new TextDecoder;var pn={};_e(pn,{sha256:()=>St,sha512:()=>su});var tu=20;function dn({name:s,code:e,encode:t,minDigestLength:r,maxDigestLength:n}){return new fn(s,e,t,r,n)}var fn=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,r,n,i){this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??tu,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?So(r,this.code,t?.truncate):r.then(n=>So(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function So(s,e,t){if(t!=null&&t!==s.byteLength){if(t>s.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${s.byteLength}`);s=s.subarray(0,t)}return He(e,s)}function Io(s){return async e=>new Uint8Array(await crypto.subtle.digest(s,e))}var St=dn({name:"sha2-256",code:18,encode:Io("SHA-256")}),su=dn({name:"sha2-512",code:19,encode:Io("SHA-512")});var mn={...hn,...an,...un,...nn,...on,...Qr,...en,...Jr,...ln,...cn},mp={...pn,...rn};function Do(s,e,t,r){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:r}}}var To=Do("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),gn=Do("ascii","a",s=>{let e="a";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return e},s=>{s=s.substring(1);let e=he(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),ru={utf8:To,"utf-8":To,hex:mn.base16,latin1:gn,ascii:gn,binary:gn,...mn},Hs=ru;function j(s,e="utf8"){let t=Hs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${s}`)}function $(s,e="utf8"){let t=Hs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(s).substring(1)}var nu=parseInt("11111",2),bn=parseInt("10000000",2),iu=parseInt("01111111",2),Ao={0:bs,1:bs,2:ou,3:lu,4:uu,5:cu,6:au,16:bs,22:bs,48:bs};function Je(s,e={offset:0}){let t=s[e.offset]&nu;if(e.offset++,Ao[t]!=null)return Ao[t](s,e);throw new Error("No decoder for tag "+t)}function ys(s,e){let t=0;if((s[e.offset]&bn)===bn){let r=s[e.offset]&iu,n="0x";e.offset++;for(let i=0;i<r;i++,e.offset++){if(e.offset>=s.byteLength)throw new Error("invalid DER element length");n+=s[e.offset].toString(16).padStart(2,"0")}t=parseInt(n,16)}else t=s[e.offset],e.offset++;if(!Number.isInteger(t)||t<0||t>s.byteLength-e.offset)throw new Error("invalid DER element length");return t}function bs(s,e){ys(s,e);let t=[];for(;!(e.offset>=s.byteLength);){let r=Je(s,e);if(r===null)break;t.push(r)}return t}function ou(s,e){let t=ys(s,e),r=e.offset,n=e.offset+t,i=[];for(let o=r;o<n;o++)o===r&&s[o]===0||i.push(s[o]);return e.offset+=t,Uint8Array.from(i)}function au(s,e){let t=ys(s,e),r=e.offset+t,n=s[e.offset];e.offset++;let i=0,o=0;n<40?(i=0,o=n):n<80?(i=1,o=n-40):(i=2,o=n-80);let a=`${i}.${o}`,l=[];for(;e.offset<r;){let u=s[e.offset];if(e.offset++,l.push(u&127),u<128){l.reverse();let p=0;for(let m=0;m<l.length;m++)p+=l[m]<<m*7;a+=`.${p}`,l=[]}}return a}function cu(s,e){return e.offset++,null}function lu(s,e){let t=ys(s,e),r=s[e.offset];e.offset++;let n=s.subarray(e.offset,e.offset+t-1);if(e.offset+=t,r!==0)throw new Error("Unused bits in bit string is unimplemented");return n}function uu(s,e){let t=ys(s,e),r=s.subarray(e.offset,e.offset+t);return e.offset+=t,r}function hu(s){let e=s.toString(16);e.length%2===1&&(e="0"+e);let t=new ae;for(let r=0;r<e.length;r+=2)t.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return t}function yn(s){if(s.byteLength<128)return Uint8Array.from([s.byteLength]);let e=hu(s.byteLength);return new ae(Uint8Array.from([e.byteLength|bn]),e)}function Te(s){let e=new ae,t=128;return(s.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(s),new ae(Uint8Array.from([2]),yn(e),e)}function Ws(s){let e=Uint8Array.from([0]),t=new ae(e,s);return new ae(Uint8Array.from([3]),yn(t),t)}function at(s,e=48){let t=new ae;for(let r of s)t.append(r);return new ae(Uint8Array.from([e]),yn(t),t)}var fu=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),du=Uint8Array.from([6,5,43,129,4,0,34]),pu=Uint8Array.from([6,5,43,129,4,0,35]),mu={ext:!0,kty:"EC",crv:"P-256"},gu={ext:!0,kty:"EC",crv:"P-384"},bu={ext:!0,kty:"EC",crv:"P-521"},wn=32,xn=48,vn=66;function En(s){let e=Je(s);return Mo(e)}function Mo(s){let e=s[1][1][0],t=1,r,n;if(e.byteLength===wn*2+1)return r=$(e.subarray(t,t+wn),"base64url"),n=$(e.subarray(t+wn),"base64url"),new Vt({...mu,key_ops:["verify"],x:r,y:n});if(e.byteLength===xn*2+1)return r=$(e.subarray(t,t+xn),"base64url"),n=$(e.subarray(t+xn),"base64url"),new Vt({...gu,key_ops:["verify"],x:r,y:n});if(e.byteLength===vn*2+1)return r=$(e.subarray(t,t+vn),"base64url"),n=$(e.subarray(t+vn),"base64url"),new Vt({...bu,key_ops:["verify"],x:r,y:n});throw new re(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Po(s){return at([Te(Uint8Array.from([1])),at([yu(s.crv)],160),at([Ws(new ae(Uint8Array.from([4]),j(s.x??"","base64url"),j(s.y??"","base64url")))],161)]).subarray()}function yu(s){if(s==="P-256")return fu;if(s==="P-384")return du;if(s==="P-521")return pu;throw new re(`Invalid curve ${s}`)}var Vt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Po(this.jwk)),this._raw}toMultihash(){return Ne.digest(We(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}async verify(e,t,r){return yo(this.jwk,t,e,r)}};var Vs=BigInt(4294967295),Bo=BigInt(32);function wu(s,e=!1){return e?{h:Number(s&Vs),l:Number(s>>Bo&Vs)}:{h:Number(s>>Bo&Vs)|0,l:Number(s&Vs)|0}}function ko(s,e=!1){let t=s.length,r=new Uint32Array(t),n=new Uint32Array(t);for(let i=0;i<t;i++){let{h:o,l:a}=wu(s[i],e);[r[i],n[i]]=[o,a]}return[r,n]}var xu=s=>s/2**32|0,vu=s=>s>>>0;function Ro(s,e,t,r){let n=xu(t),i=vu(t);s.setUint32(e,r?i:n,r),s.setUint32(e+4,r?n:i,r)}var Sn=(s,e,t)=>s>>>t,_n=(s,e,t)=>s<<32-t|e>>>t,_t=(s,e,t)=>s>>>t|e<<32-t,It=(s,e,t)=>s<<32-t|e>>>t,ws=(s,e,t)=>s<<64-t|e>>>t-32,xs=(s,e,t)=>s>>>t-32|e<<64-t;function Ve(s,e,t,r){let n=(e>>>0)+(r>>>0);return{h:s+t+(n/2**32|0)|0,l:n|0}}var Lo=(s,e,t)=>(s>>>0)+(e>>>0)+(t>>>0),Co=(s,e,t,r)=>e+t+r+(s/2**32|0)|0,Fo=(s,e,t,r)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0),No=(s,e,t,r,n)=>e+t+r+n+(s/2**32|0)|0,Oo=(s,e,t,r,n)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Uo=(s,e,t,r,n,i)=>e+t+r+n+i+(s/2**32|0)|0;function $s(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in s&&s.BYTES_PER_ELEMENT===1}var In=s=>s?`"${s}" `:"";function Qe(s,e=""){if(typeof s!="number")throw new TypeError(In(e)+"expected number, got "+typeof s);if(!Number.isSafeInteger(s)||s<0)throw new RangeError(In(e)+"expected integer >= 0, got "+s);return s}function Re(s,e,t=""){if($s(s)&&(e===void 0||s.length===e))return s;e!==void 0&&Qe(e,"length");let r=$s(s),n=e!==void 0?` of length ${e}`:"",i=r?`length=${s.length}`:`type=${typeof s}`,o=In(t)+"expected Uint8Array"+n+", got "+i;throw r?new RangeError(o):new TypeError(o)}function js(s){if(typeof s!="function"||typeof s.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Qe(s.outputLen),Qe(s.blockLen),s.outputLen<1||s.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var Ko=(s,e)=>{if(s===null||typeof s!="object"||Array.isArray(s))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof s)};function $t(s,e=!0){if(s.destroyed)throw new Error("hash was destroyed");if(e&&s.finished)throw new Error("digest() was already called")}function Zs(s,e){Re(s,void 0,"output");let t=e.outputLen;if(!(s.length>=t))throw new RangeError('"output" expected length >= '+t)}function Tt(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Ys(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Oe(s,e){return s<<32-e|s>>>e}var qo=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Su=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Xs(s){if(Re(s),qo)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=Su[s[t]];return e}function zo(s){return s>=48&&s<=57?s-48:s>=65&&s<=70?s-55:s>=97&&s<=102?s-87:void 0}function Js(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);if(qo)try{return Uint8Array.fromHex(s)}catch(n){throw n instanceof SyntaxError?new RangeError(n.message):n}let e=s.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let n=0,i=0;n<t;n++,i+=2){let o=zo(s.charCodeAt(i)),a=zo(s.charCodeAt(i+1));if(o===void 0||a===void 0){let l=s[i]+s[i+1];throw new RangeError('hex string expected, got non-hex character "'+l+'" at index '+i)}r[n]=o*16+a}return r}function Tn(...s){let e=0;for(let r=0;r<s.length;r++){let n=s[r];Re(n),e+=n.length}let t=new Uint8Array(e);for(let r=0,n=0;r<s.length;r++){let i=s[r];t.set(i,n),n+=i.length}return t}function _u(s,e,t="opts"){return Ko(s,"defaults"),e!==void 0&&Ko(e,t),Object.assign(s,e)}function Dn(s,e={}){if(typeof s!="function")throw new TypeError('"hashCons" expected function, got type='+typeof s);e=_u({},e,"info");let t=(n,i)=>s(i).update(n).digest(),r=s(void 0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.canXOF=r.canXOF,t.create=n=>s(n),Object.assign(t,e),Object.freeze(t)}function Go(s=32){Qe(s,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(s>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${s}`);return e.getRandomValues(new Uint8Array(s))}var An=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function Ho(s,e,t){return s&e^~s&t}function Wo(s,e,t){return s&e^s&t^e&t}var vs=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Ys(this.buffer)}update(e){$t(this),Re(e);let{view:t,buffer:r,blockLen:n}=this,i=e.length,o=!1;for(let a=0;a<i;){let l=Math.min(n-this.pos,i-a);if(l===n){let u=Ys(e);for(;n<=i-a;a+=n)this.process(u,a);o=!0;continue}r.set(a===0&&l===i?e:e.subarray(a,a+l),this.pos),this.pos+=l,a+=l,this.pos===n&&(this.process(t,0),this.pos=0,o=!0)}return this.length+=e.length,o&&this.roundClean(),this}digestInto(e){$t(this),Zs(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,t.fill(0,o),this.padOffset>n-o&&(this.process(r,0),t.fill(0)),Ro(r,n-8,this.length*8,i),this.process(r,0),this.roundClean();let a=e===t?r:Ys(e),l=this.outputLen,u=l/4,p=this.get();if(l%4||u>p.length)throw new Error("invalid outputLen");for(let m=0;m<u;m++)a.setUint32(4*m,p[m],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:i,pos:o}=this;return e.destroyed=i,e.finished=n,e.length=r,e.pos=o,o&&e.buffer.set(t),e}clone(){return this._cloneInto()}},Vo=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var $o=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Iu=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]),ct=new Uint32Array(64),Mn=class extends vs{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:i,F:o,G:a,H:l}=this;return[e,t,r,n,i,o,a,l]}set(e,t,r,n,i,o,a,l){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=l|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let m=0;m<16;m++,t+=4)ct[m]=e.getUint32(t,!1);for(let m=16;m<64;m++){let x=ct[m-15],y=ct[m-2],f=Oe(x,7)^Oe(x,18)^x>>>3,g=Oe(y,17)^Oe(y,19)^y>>>10;ct[m]=g+ct[m-7]+f+ct[m-16]|0}let{A:r,B:n,C:i,D:o,E:a,F:l,G:u,H:p}=this;for(let m=0;m<64;m++){let x=Oe(a,6)^Oe(a,11)^Oe(a,25),y=p+x+Ho(a,l,u)+Iu[m]+ct[m]|0,g=(Oe(r,2)^Oe(r,13)^Oe(r,22))+Wo(r,n,i)|0;p=u,u=l,l=a,a=o+y|0,o=i,i=n,n=r,r=y+g|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,l=l+this.F|0,u=u+this.G|0,p=p+this.H|0,this.set(r,n,i,o,a,l,u,p)}roundClean(){Tt(ct)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Tt(this.buffer)}},Pn=class extends Mn{constructor(){super(32,Vo)}};var jo=ko(["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(s=>BigInt(s))),Tu=jo[0],Du=jo[1],lt=new Uint32Array(80),ut=new Uint32Array(80),Bn=class extends vs{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:o,Dh:a,Dl:l,Eh:u,El:p,Fh:m,Fl:x,Gh:y,Gl:f,Hh:g,Hl:w}=this;return[e,t,r,n,i,o,a,l,u,p,m,x,y,f,g,w]}set(e,t,r,n,i,o,a,l,u,p,m,x,y,f,g,w){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=n|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=l|0,this.Eh=u|0,this.El=p|0,this.Fh=m|0,this.Fl=x|0,this.Gh=y|0,this.Gl=f|0,this.Hh=g|0,this.Hl=w|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let c=0;c<16;c++,t+=4)lt[c]=e.getUint32(t),ut[c]=e.getUint32(t+=4);for(let c=16;c<80;c++){let h=lt[c-15]|0,d=ut[c-15]|0,b=_t(h,d,1)^_t(h,d,8)^Sn(h,d,7),v=It(h,d,1)^It(h,d,8)^_n(h,d,7),_=lt[c-2]|0,D=ut[c-2]|0,P=_t(_,D,19)^ws(_,D,61)^Sn(_,D,6),K=It(_,D,19)^xs(_,D,61)^_n(_,D,6),F=Fo(v,K,ut[c-7],ut[c-16]),Y=No(F,b,P,lt[c-7],lt[c-16]);lt[c]=Y|0,ut[c]=F|0}let{Ah:r,Al:n,Bh:i,Bl:o,Ch:a,Cl:l,Dh:u,Dl:p,Eh:m,El:x,Fh:y,Fl:f,Gh:g,Gl:w,Hh:E,Hl:S}=this;for(let c=0;c<80;c++){let h=_t(m,x,14)^_t(m,x,18)^ws(m,x,41),d=It(m,x,14)^It(m,x,18)^xs(m,x,41),b=m&y^~m&g,v=x&f^~x&w,_=Oo(S,d,v,Du[c],ut[c]),D=Uo(_,E,h,b,Tu[c],lt[c]),P=_|0,K=_t(r,n,28)^ws(r,n,34)^ws(r,n,39),F=It(r,n,28)^xs(r,n,34)^xs(r,n,39),Y=r&i^r&a^i&a,C=n&o^n&l^o&l;E=g|0,S=w|0,g=y|0,w=f|0,y=m|0,f=x|0,{h:m,l:x}=Ve(u|0,p|0,D|0,P|0),u=a|0,p=l|0,a=i|0,l=o|0,i=r|0,o=n|0;let L=Lo(P,F,C);r=Co(L,D,K,Y),n=L|0}({h:r,l:n}=Ve(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=Ve(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l}=Ve(this.Ch|0,this.Cl|0,a|0,l|0),{h:u,l:p}=Ve(this.Dh|0,this.Dl|0,u|0,p|0),{h:m,l:x}=Ve(this.Eh|0,this.El|0,m|0,x|0),{h:y,l:f}=Ve(this.Fh|0,this.Fl|0,y|0,f|0),{h:g,l:w}=Ve(this.Gh|0,this.Gl|0,g|0,w|0),{h:E,l:S}=Ve(this.Hh|0,this.Hl|0,E|0,S|0),this.set(r,n,i,o,a,l,u,p,m,x,y,f,g,w,E,S)}roundClean(){Tt(lt,ut)}destroy(){this.destroyed=!0,Tt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},kn=class extends Bn{constructor(){super(64,$o)}};var jt=Dn(()=>new Pn,An(1));var Rn=Dn(()=>new kn,An(3));function er(s,e,t=()=>{}){if(!Array.isArray(s))throw new TypeError(`"${e}" expected array, got type=${typeof s}`);for(let r=0;r<s.length;r++)t(s[r],`${e}[${r}]`);return s}var G=(s,e,t)=>Re(s,e,t),Ln=Qe;function Yo(s,e=""){if(typeof s!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof s)}return s}function ht(s,e="object"){if(s===null||typeof s!="object"||Array.isArray(s))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof s}`);return s}function Dt(s,e){if(typeof s!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof s}`);return s}var Es=Xs,Le=(...s)=>Tn(...s),Zt=s=>Js(s),dt=$s,At=s=>Go(s),Qs=BigInt(0),Zo=BigInt(1),Au=s=>s?`"${s}" `:"";function De(s,e=""){if(typeof s!="boolean")throw new TypeError(Au(e)+"expected boolean, got type="+typeof s);return s}function tr(s){if(typeof s=="bigint"){if(!ft(s))throw new RangeError("positive bigint expected, got "+s)}else Ln(s);return s}function pt(s,e=""){if(typeof s!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof s)}if(!Number.isSafeInteger(s)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+s)}}function Ss(s){let e=tr(s).toString(16);return e.length&1?"0"+e:e}function Xo(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);return s===""?Qs:BigInt("0x"+s)}function $e(s){return Xo(Xs(s))}function Mt(s){return Xo(Xs(rr(Re(s)).reverse()))}function sr(s,e){if(Qe(e),e===0)throw new Error("zero output length is invalid");s=tr(s);let t=e*2,r=s.toString(16);if(r.length>t)throw new RangeError("number is too large");return Js(r.padStart(t,"0"))}function Cn(s,e){return sr(s,e).reverse()}function rr(s){return Uint8Array.from(G(s))}function ft(s){return typeof s=="bigint"&&Qs<=s}function Fn(s,e,t){return ft(s)&&ft(e)&&ft(t)&&e<=s&&s<t}function Yt(s,e,t,r){if(!Fn(e,t,r))throw new RangeError("expected valid "+s+": "+t+" <= n < "+r+", got "+e)}function Xt(s){if(s<Qs)throw new Error("expected non-negative bigint, got "+s);return s===Qs?0:s.toString(2).length}var _s=s=>(pt(s,"n"),(Zo<<BigInt(s))-Zo);function Jo(s,e,t){if(Qe(s,"hashLen"),Qe(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let r=w=>new Uint8Array(w),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3,l=r(s),u=r(s),p=0,m=()=>{l.fill(1),u.fill(0),p=0},x=(...w)=>t(u,Le(l,...w)),y=(w=n)=>{u=x(i,w),l=x(),w.length!==0&&(u=x(o,w),l=x())},f=()=>{if(p++>=a)throw new Error("drbg: tried max amount of iterations");let w=0,E=[];for(;w<e;){l=x();let S=l.slice();E.push(S),w+=l.length}return Le(...E)};return(w,E)=>{m(),y(w);let S;for(;(S=E(f()))===void 0;)y();return m(),S}}function Ae(s,e={},t={},r="object"){ht(s,r),ht(e,"fields"),ht(t,"optFields");function n(o,a,l){let u=r==="object"?`param "${String(o)}"`:`"${r}.${String(o)}"`,p=s[o];if(!Object.hasOwn(s,o)&&(l?p!==void 0:a!=="function"))throw new TypeError(`${u} is invalid: expected own property`);if(l&&p===void 0)return;let m=typeof p;if(m!==a||p===null)throw new TypeError(`${u} is invalid: expected ${a}, got ${m}`)}let i=(o,a)=>Object.entries(o).forEach(([l,u])=>n(l,u,a));i(e,!1),i(t,!0)}var oe=BigInt(0),H=BigInt(1),mt=BigInt(2),ta=BigInt(3),Nn=BigInt(4),sa=BigInt(5),Mu=BigInt(7),ra=BigInt(8),Pu=BigInt(9),Bu=BigInt(15),na=BigInt(16),ku=BigInt("0x10000000000000000");function J(s,e){if(e<=oe)throw new Error("mod: expected positive modulus, got "+e);let t=s%e;return t>=oe?t:e+t}function ia(s,e,t){if(t<=H)throw new Error("pow: expected modulus > 1, got "+t);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<oe)throw new Error("invalid exponent, negatives unsupported");if(e===oe)return H;if(e===H)return s;let r=s%t;if(r<oe&&(r+=t),e<ku){let a=H;for(;e>oe;)e&H&&(a=a*r%t),r=r*r%t,e>>=H;return a}let n=[];for(;e>oe;)n.push(Number(e&Bu)),e>>=Nn;let i=new Array(16);i[0]=H,i[1]=r;for(let a=2;a<16;a++)i[a]=i[a-1]*r%t;let o=i[n[n.length-1]];for(let a=n.length-2;a>=0;a--){o=o*o%t,o=o*o%t,o=o*o%t,o=o*o%t;let l=n[a];l!==0&&(o=o*i[l]%t)}return o}function X(s,e,t){if(t<=H)throw new Error("pow2: expected modulus > 1, got "+t);if(e<oe)throw new Error("pow2: expected non-negative exponent, got "+e);let r=s;for(;e-- >oe;)r*=r,r%=t;return r}function Qo(s,e){if(s===oe)throw new Error("invert: expected non-zero number");if(e<=H)throw new Error("invert: expected modulus > 1, got "+e);let t=J(s,e),r=e,n=oe,i=H;for(;t!==oe;){let a=r/t,l=r-t*a,u=n-i*a;r=t,t=l,n=i,i=u}if(r!==H)throw new Error("invert: does not exist");return J(n,e)}function oa(s,e){if(e<=H)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=J(s,e);if(t===oe)throw new Error("invertCt: expected non-zero number");let r=ia(t,e-mt,e);if(J(t*r,e)!==H)throw new Error("invertCt: does not exist");return r}function On(s,e,t){let r=s;if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function Un(s,e){if((s&H)===oe)throw new Error(e+": expected odd modulus, got "+s)}function aa(s,e){let t=s,r=(t.ORDER+H)/Nn,n=t.pow(e,r);return On(t,n,e),n}function Ru(s,e){let t=s,r=(t.ORDER-sa)/ra,n=t.mul(e,mt),i=t.pow(n,r),o=t.mul(e,i),a=t.mul(t.mul(o,mt),i),l=t.mul(o,t.sub(a,t.ONE));return On(t,l,e),l}function Lu(s){let e=Qt(s),t=ca(s),r=t(e,e.neg(e.ONE)),n=t(e,r),i=t(e,e.neg(r)),o=(s+Mu)/na;return((a,l)=>{let u=a,p=u.pow(l,o),m=u.mul(p,r),x=u.mul(p,n),y=u.mul(p,i),f=u.eql(u.sqr(m),l),g=u.eql(u.sqr(x),l);p=u.cmov(p,m,f),m=u.cmov(y,x,g);let w=u.eql(u.sqr(m),l),E=u.cmov(p,m,w);return On(u,E,l),E})}function ca(s){if(s<ta)throw new Error("sqrt is not defined for small field");Un(s,"tonelliShanks");let e=s-H,t=0;for(;e%mt===oe;)e/=mt,t++;let r=mt,n=Qt(s);for(;Is(n,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return aa;let i=n.pow(r,e),o=(e+H)/mt;return function(l,u){let p=l;if(p.is0(u))return u;if(Is(p,u)!==1)throw new Error("Cannot find square root");let m=t,x=p.mul(p.ONE,i),y=p.pow(u,e),f=p.pow(u,o);for(;!p.eql(y,p.ONE);){if(p.is0(y))throw new Error("Cannot find square root: probably non-prime P");let g=1,w=p.sqr(y);for(;!p.eql(w,p.ONE);)if(g++,w=p.sqr(w),g===m)throw new Error("Cannot find square root");let E=H<<BigInt(m-g-1),S=p.pow(x,E);m=g,x=p.sqr(S),y=p.mul(y,x),f=p.mul(f,S)}return f}}function Cu(s){return Un(s,"Fp.sqrt"),s%Nn===ta?aa:s%ra===sa?Ru:s%na===Pu?Lu(s):ca(s)}var la=(s,e)=>(J(s,e)&H)===H,Fu=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Jt(s){if(ht(s,"field"),typeof s.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof s.ORDER);pt(s.BYTES,"BYTES"),pt(s.BITS,"BITS");for(let e of Fu)Dt(s[e],"field."+e);if(s.BYTES<1||s.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(s.ORDER<=H)throw new Error("invalid field: expected ORDER > 1, got "+s.ORDER);return s}function ir(s,e,t=!1){Jt(s),er(e,"nums"),De(t,"passZero");let r=s,n=new Array(e.length).fill(t?r.ZERO:void 0),i=e.reduce((a,l,u)=>r.is0(l)?a:(n[u]=a,r.mul(a,l)),r.ONE),o=r.inv(i);return e.reduceRight((a,l,u)=>r.is0(l)?a:(n[u]=r.mul(a,n[u]),r.mul(a,l)),o),n}function Is(s,e){Jt(s);let t=s;Un(t.ORDER,"FpLegendre");let r=(t.ORDER-H)/mt,n=t.pow(e,r),i=t.eql(n,t.ONE),o=t.eql(n,t.ZERO),a=t.eql(n,t.neg(t.ONE));if(!i&&!o&&!a)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function Nu(s,e){if(e!==void 0&&Ln(e),s<=oe)throw new Error("invalid n length: expected positive n, got "+s);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Xt(s);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let r=e!==void 0?e:t,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var ea=new WeakMap,nr=class{ORDER;BITS;BYTES;isLE;ZERO=oe;ONE=H;_lengths;_mod;constructor(e,t={}){if(e<=H)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:n,nByteLength:i}=Nu(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,Object.freeze(this)}create(e){return J(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return oe<=e&&e<this.ORDER}is0(e){return e===oe}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&H)===H}neg(e){return J(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return J(e*e,this.ORDER)}add(e,t){return J(e+t,this.ORDER)}sub(e,t){return J(e-t,this.ORDER)}mul(e,t){return J(e*t,this.ORDER)}pow(e,t){return ia(e,t,this.ORDER)}div(e,t){return J(e*Qo(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Qo(e,this.ORDER)}sqrt(e){let t=ea.get(this);return t||ea.set(this,t=Cu(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Cn(e,this.BYTES):sr(e,this.BYTES)}fromBytes(e,t=!1){G(e);let{_lengths:r,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let u=new Uint8Array(n);u.set(e,i?0:u.length-e.length),e=u}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=i?Mt(e):$e(e);if(a&&(l=J(l,o)),!t&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return ir(this,e,!0)}cmov(e,t,r){return De(r,"condition"),r?t:e}};function Qt(s,e={}){return Object.freeze(nr.prototype),new nr(s,e)}function ua(s){if(typeof s!="bigint")throw new Error("field order must be bigint");if(s<=H)throw new Error("field order must be greater than 1");let e=Xt(s-H);return Math.ceil(e/8)}function or(s){let e=ua(s);return e+Math.ceil(e/2)}function ar(s,e,t=!1){G(s);let r=s.length,n=ua(e),i=Math.max(or(e),16);if(r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let o=t?Mt(s):$e(s),a=J(o,e-H)+H;return t?Cn(a,n):sr(a,n)}var qn=BigInt(0),Ts=BigInt(1),Ou=BigInt(4),Kn=16,ha=128,Uu=5,fa=2**31;function gt(s){let e=s;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof s);Dt(e.fromAffine,"Point.fromAffine"),Dt(e.fromBytes,"Point.fromBytes"),Dt(e.fromHex,"Point.fromHex"),ht(e.BASE,"Point.BASE"),ht(e.ZERO,"Point.ZERO"),Jt(e.Fp),Jt(e.Fn)}function cr(s,e){gt(s),pa(e,s);let t=ir(s.Fp,e.map(r=>r.Z));return e.map((r,n)=>s.fromAffine(r.toAffine(t[n])))}function Ku(s,e,t=1){if(!Number.isSafeInteger(s)||s<t||s>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+s)}function zu(s,e){let t=s*(4*e+128);if(t>fa)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+fa/2**20+" MiB")}function Gn(s,e){if(s!==void 0){Dt(s,"randomBytes");try{let t=s(e);if(!dt(t)||t.length!==e)return}catch{return}return s}}function pa(s,e){er(s,"points"),s.forEach((t,r)=>{if(!(t instanceof e))throw new Error("invalid point at index "+r)})}function qu(s,e,t){if(!Array.isArray(s))throw new Error("array of scalars expected");s.forEach((r,n)=>{if(!(t===void 0?e.isValid(r):ft(r)&&r<t))throw new Error("invalid scalar at index "+n)})}var ma=new WeakMap;function zn(s){return ma.get(s)||1}function Gu(s,e){let t=s.double(),r=[s];for(let n=1;n<e;n++)r.push(r[n-1].add(t));return r}function Hu(s,e){let t=2**e,r=t/2,n=BigInt(t-1),i=[];for(;s>qn;){let o=0;s&Ts&&(o=Number(s&n),o>=r&&(o-=t),s-=BigInt(o)),i.push(o),s>>=Ts}return i}function Wu(s,e,t){let r=2**e,n=r/2,i=BigInt(r-1),o=BigInt(e),a=[];for(let l=0;l<t;l++){let u=Number(s&i);s>>=o,u>n&&(u-=r,s+=Ts),a.push(u)}if(s!==qn)throw new Error("invalid wnaf");return a}function Vu(s,e,t){let r=0;for(let i of t)r=Math.max(r,i.length);let n=s;for(let i=r-1;i>=0;i--){i!==r-1&&(n=n.double());for(let o=0;o<t.length;o++){let a=t[o][i];if(a){let l=e[o][Math.abs(a)-1>>1];n=n.add(a<0?l.negate():l)}}}return n}var es=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){gt(e),this.randomBytes=Gn(t,Kn),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,r){let n=Math.ceil(r/t)+1,i=2**(t-1),o=[],a=e;for(let l=0;l<n;l++){let u=a;for(let p=0;p<i;p++)o.push(u),u=u.add(a);a=o[o.length-1].double()}return{W:t,bits:r,windows:n,comp:o}}wnafCachedCT(e,t){let{W:r,windows:n,comp:i}=e,o=2**(r-1),a=Wu(t,r,n),l=this.ZERO,u=this.BASE;for(let p=0;p<n;p++){let m=a[p],x=p*o,y=Math.abs(m)-1,f=i[x];for(let w=1;w<o;w++)f=w===y?i[x+w]:f;let g=f.negate();m===0?u=u.add(i[x]):l=l.add(m<0?g:f)}return{p:l,f:u}}getWnafPrecomputes(e,t,r,n){let i=this.wnafPrecomputes.get(t),o=i?.find(a=>a.W===e&&a.bits===r);return o||(o=this.buildWnafTable(t,e,r),typeof n=="function"&&(o={...o,comp:n(o.comp)}),i||(i=[],this.wnafPrecomputes.set(t,i)),i.push(o)),o}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!Fn(t,Ts,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,r,n){let i=zn(e);return i===1?this.fixedWindowCT(e,t,r):this.wnafCachedCT(this.getWnafPrecomputes(i,e,r,n),t)}mulCT(e,t,r){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,r)}mulCTBlinded(e,t,r){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let n=this.Point.Fn.BITS+ha,i=this.randomBytes(Kn);if(!dt(i)||i.length!==Kn)throw new Error("randomBytes returned invalid byte array");i[0]=i[0]&63|128;let o=t+$e(i)*this.Point.Fn.ORDER;return this.runCT(e,o,n,r)}fixedWindowCT(e,t,r){let n=Uu,i=1<<n,o=_s(n),a=new Array(i);a[0]=this.ZERO;for(let p=1;p<i;p++)a[p]=a[p-1].add(e);let l=Math.ceil(r/n),u=this.ZERO;for(let p=l-1;p>=0;p--){if(p!==l-1)for(let y=0;y<n;y++)u=u.double();let m=Number(t>>BigInt(p*n)&o),x=a[0];for(let y=1;y<i;y++)x=y===m?a[y]:x;u=u.add(x)}return{p:u,f:u}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===Ts?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,r,n){return this.shouldBlind(e,r)?this.mulCTBlinded(e,t,n):this.mulCT(e,t,n)}mulUnsafe(e,t,r){if(this.assertPoint(e),!ft(t))throw new Error("invalid scalar");let n=zn(e);if(n===1||t>=this.Point.Fn.ORDER)return lr(this.Point,[e],[t],!0);let i=this.getWnafPrecomputes(n,e,this.bits,r);return this.wnafCachedCT(i,t).p}setWindowSize(e,t){this.assertPoint(e),Ku(t,this.bits);let r=Math.ceil((this.bits+ha)/t)+1;zu(r*2**(t-1),this.Point.Fp.BYTES),ma.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return zn(e)!==1}};function lr(s,e,t,r=!1){if(gt(s),pa(e,s),De(r,"allowOversized"),qu(t,s.Fn,r?s.Fn.ORDER**Ou:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let n=e.map(o=>Gu(o,4)),i=t.map(o=>Hu(o,4));return Vu(s.ZERO,n,i)}function da(s,e,t){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Jt(e),e}else return Qt(s,{isLE:t})}function ur(s,e,t={},r){if(s!=="weierstrass"&&s!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(r===void 0&&(r=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);Ae(t);for(let l of["p","n","h"]){let u=e[l];if(!(ft(u)&&u!==qn))throw new Error(`CURVE.${l} must be positive bigint`)}let n=da(e.p,t.Fp,r),i=da(e.n,t.Fn,r),a=["Gx","Gy","a",s==="weierstrass"?"b":"d"];for(let l of a)if(!n.isValid(e[l]))throw new Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function hr(s,e){return function(r){let n=s(r);return{secretKey:n,publicKey:e(n)}}}var fr=BigInt(0),dr=BigInt(1),pr=BigInt(2),$u=BigInt(4),ga=BigInt(8);function ju(s,e,t,r){let n=s.sqr(t),i=s.sqr(r),o=s.add(s.mul(e.a,n),i),a=s.add(s.ONE,s.mul(e.d,s.mul(n,i)));return s.eql(o,a)}function ba(s,e={}){Ae(e,{},{},"extraOpts");let t=e,r=ur("edwards",s,t,t.FpFnLE),{Fp:n,Fn:i}=r,o=r.CURVE,{h:a}=o;if(Is(n,o.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Is(n,o.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Ae(t,{},{uvRatio:"function",randomBytes:"function"});let l=t.randomBytes===void 0?At:t.randomBytes,u=pr<<BigInt(n.BYTES*8)-dr;function p(S){if(!n.isOdd)throw new Error("Field does not have .isOdd()");return n.isOdd(S)}let m=t.uvRatio===void 0?(S,c)=>{try{return{isValid:!0,value:n.sqrt(n.div(S,c))}}catch{return{isValid:!1,value:fr}}}:t.uvRatio;if(!ju(n,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");let x=n.eql(o.a,n.neg(n.ONE))?S=>n.neg(S):n.eql(o.a,n.ONE)?S=>S:S=>n.mul(o.a,S);function y(S,c,h=!1){let d=h?dr:fr;return Yt("coordinate "+S,c,d,u),c}function f(S){if(!(S instanceof g))throw new Error("EdwardsPoint expected")}class g{static BASE=new g(o.Gx,o.Gy,n.ONE,n.mul(o.Gx,o.Gy));static ZERO=new g(n.ZERO,n.ONE,n.ONE,n.ZERO);static Fp=n;static Fn=i;X;Y;Z;T;constructor(c,h,d,b){this.X=y("x",c),this.Y=y("y",h),this.Z=y("z",d,!0),this.T=y("t",b),Object.freeze(this)}static CURVE(){return o}static fromAffine(c){if(c instanceof g)throw new Error("extended point not allowed");let{x:h,y:d}=c||{};return y("x",h),y("y",d),new g(h,d,n.ONE,n.mul(h,d))}static fromBytes(c,h=!1){let d=n.BYTES,{a:b,d:v}=o;c=rr(G(c,d,"point")),De(h,"zip215");let _=rr(c),D=c[d-1];_[d-1]=D&-129;let P=Mt(_),K=h?u:n.ORDER;Yt("point.y",P,fr,K);let F=n.sqr(P),Y=n.sub(F,n.ONE),C=n.sub(n.mulN(v,F),b),{isValid:L,value:I}=m(Y,C);if(!L)throw new Error("bad point: invalid y coordinate");let A=p(I),B=(D&128)!==0;if(!h&&n.is0(I)&&B)throw new Error("bad point: x=0 and x_0=1");return B!==A&&(I=n.neg(I)),g.fromAffine({x:I,y:P})}static fromHex(c,h=!1){return g.fromBytes(Zt(c),h)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(c=6,h=!0){return E.setWindowSize(this,c),h||this.multiply(pr),this}assertValidity(){let c=this,{a:h,d}=o;if(c.is0())throw new Error("bad point: ZERO");let{X:b,Y:v,Z:_,T:D}=c,P=n.sqr(b),K=n.sqr(v),F=n.sqr(_),Y=n.sqr(F),C=n.mul(P,h),L=n.mul(n.add(C,K),F),I=n.add(Y,n.mul(d,n.mul(P,K)));if(!n.eql(L,I))throw new Error("bad point: equation left != right (1)");let A=n.mul(b,v),B=n.mul(_,D);if(!n.eql(A,B))throw new Error("bad point: equation left != right (2)")}equals(c){f(c);let{X:h,Y:d,Z:b}=this,{X:v,Y:_,Z:D}=c,P=n.mul(h,D),K=n.mul(v,b),F=n.mul(d,D),Y=n.mul(_,b);return n.eql(P,K)&&n.eql(F,Y)}is0(){return this.equals(g.ZERO)}negate(){return new g(n.neg(this.X),this.Y,this.Z,n.neg(this.T))}double(){let{X:c,Y:h,Z:d}=this,b=n.sqr(c),v=n.sqr(h),_=n.mul(n.sqr(d),pr),D=x(b),P=n.addN(c,h),K=n.sub(n.subN(n.sqr(P),b),v),F=n.addN(D,v),Y=n.subN(F,_),C=n.subN(D,v),L=n.mul(K,Y),I=n.mul(F,C),A=n.mul(K,C),B=n.mul(Y,F);return new g(L,I,B,A)}add(c){f(c);let{d:h}=o,{X:d,Y:b,Z:v,T:_}=this,{X:D,Y:P,Z:K,T:F}=c,Y=n.mul(d,D),C=n.mul(b,P),L=n.mul(n.mulN(_,h),F),I=n.mul(v,K),A=n.sub(n.subN(n.mulN(n.addN(d,b),n.addN(D,P)),Y),C),B=n.subN(I,L),N=n.addN(I,L),M=n.sub(C,x(Y)),T=n.mul(A,B),k=n.mul(N,M),R=n.mul(A,M),O=n.mul(B,N);return new g(T,k,O,R)}subtract(c){return f(c),this.add(c.negate())}multiply(c){if(!i.isValidNot0(c))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:h,f:d}=E.mulSecret(this,c,a,w);return w([h,d])[0]}multiplyUnsafe(c){if(!i.isValid(c))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return c===fr?g.ZERO:this.is0()||c===dr?this:E.mulUnsafe(this,c,w)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return E.mulUnsafe(this,o.n).is0()}toAffine(c){let h=this,d=c;if(d!=null&&typeof d!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof d);let{X:b,Y:v,Z:_}=h,D=h.is0();d==null&&(d=D?n.create(ga):n.inv(_));let P=n.mul(b,d),K=n.mul(v,d),F=n.mul(_,d);if(D)return{x:n.ZERO,y:n.ONE};if(!n.eql(F,n.ONE))throw new Error("invZ was invalid");return{x:P,y:K}}clearCofactor(){return a===dr?this:a===pr?this.double():a===$u?this.double().double():a===ga?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:c,y:h}=this.toAffine(),d=n.toBytes(h);return d[d.length-1]|=p(c)?128:0,d}toHex(){return Es(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let w=S=>cr(g,S),E=new es(g,l);return E.bits>=6&&g.BASE.precompute(6),Object.freeze(g.prototype),Object.freeze(g),g}function ya(s,e,t={}){if(gt(s),typeof e!="function")throw new Error('"hash" function param is required');let r=e,n=t;Ae(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:i}=n,{BASE:o,Fp:a,Fn:l}=s,u=r.outputLen,p=2*a.BYTES;if(u!==void 0&&(pt(u,"hash.outputLen"),u!==p))throw new Error(`hash.outputLen must be ${p}, got ${u}`);let m=n.randomBytes===void 0?At:n.randomBytes,x=n.toMontgomery,y=n.toMontgomerySecret,f=n.adjustScalarBytes===void 0?C=>C:n.adjustScalarBytes,g=n.domain===void 0?(C,L,I)=>{if(De(I,"phflag"),L.length||I)throw new Error("Contexts/pre-hash are not supported");return C}:n.domain;function w(C){return l.create(Mt(C))}function E(C){let L=D.secretKey;G(C,D.secretKey,"secretKey");let I=G(r(C),2*L,"hashedSecretKey"),A=f(I.slice(0,L)),B=I.slice(L,2*L),N=w(A);return{head:A,prefix:B,scalar:N}}function S(C){let{head:L,prefix:I,scalar:A}=E(C),B=o.multiply(A),N=B.toBytes();return{head:L,prefix:I,scalar:A,point:B,pointBytes:N}}function c(C){return S(C).pointBytes}function h(C=Uint8Array.of(),...L){let I=Le(...L);return w(r(g(I,G(C,void 0,"context"),!!i)))}function d(C,L,I={}){Ae(I,{},{},"options"),C=G(C,void 0,"message"),i&&(C=i(C));let{prefix:A,scalar:B,pointBytes:N}=S(L),M=h(I.context,A,C),T=o.multiply(M).toBytes(),k=h(I.context,T,N,C),R=l.create(M+k*B);if(!l.isValid(R))throw new Error("sign failed: invalid s");let O=Le(T,l.toBytes(R));return G(O,D.signature,"result")}let b={zip215:n.zip215};function v(C,L,I,A=b){Ae(A);let{context:B}=A,N=A.zip215===void 0?!!b.zip215:A.zip215,M=D.signature;C=G(C,M,"signature"),L=G(L,void 0,"message"),I=G(I,D.publicKey,"publicKey"),N!==void 0&&De(N,"zip215"),i&&(L=i(L));let T=M/2,k=C.subarray(0,T),R=Mt(C.subarray(T,M)),O,U,q;try{O=s.fromBytes(I,N),U=s.fromBytes(k,N),q=o.multiplyUnsafe(R)}catch{return!1}if(!N&&O.isSmallOrder())return!1;let z=h(B,k,I,L);return U.add(O.multiplyUnsafe(z)).subtract(q).clearCofactor().is0()}let _=a.BYTES,D={secretKey:_,publicKey:_,signature:2*_,seed:_};function P(C){return C=C===void 0?m(D.seed):C,G(C,D.seed,"seed")}function K(C){return dt(C)&&C.length===D.secretKey}function F(C,L){try{return!!s.fromBytes(C,L===void 0?b.zip215:L)}catch{return!1}}let Y={getExtendedPublicKey:S,randomSecretKey:P,isValidSecretKey:K,isValidPublicKey:F,toMontgomery(C){if(x===void 0)throw new Error("Montgomery conversion is not supported for this curve");return x(s.fromBytes(C))},toMontgomerySecret(C){if(y===void 0)throw new Error("Montgomery conversion is not supported for this curve");return y(C)}};return Object.freeze(D),Object.freeze(Y),Object.freeze({keygen:hr(P,c),getPublicKey:c,sign:d,verify:v,utils:Y,Point:s,lengths:D})}var Hn=BigInt(1),wa=BigInt(2);var Zu=BigInt(5),Yu=BigInt(8),Wn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Xu={p:Wn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Yu,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ju(s){let e=BigInt(10),t=BigInt(20),r=BigInt(40),n=BigInt(80),i=Wn,a=s*s%i*s%i,l=X(a,wa,i)*a%i,u=X(l,Hn,i)*s%i,p=X(u,Zu,i)*u%i,m=X(p,e,i)*p%i,x=X(m,t,i)*m%i,y=X(x,r,i)*x%i,f=X(y,n,i)*y%i,g=X(f,n,i)*y%i,w=X(g,e,i)*p%i;return{pow_p_5_8:X(w,wa,i)*s%i,b2:a}}function Ea(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}var xa=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Qu(s,e){let t=Wn,r=J(e*e*e,t),n=J(r*r*e,t),i=Ju(s*n).pow_p_5_8,o=J(s*r*i,t),a=J(e*o*o,t),l=o,u=J(o*xa,t),p=a===s,m=a===J(-s,t),x=a===J(-s*xa,t);return p&&(o=l),(m||x)&&(o=u),la(o,t)&&(o=J(-o,t)),{isValid:p||m,value:o}}var Vn=ba(Xu,{uvRatio:Qu}),va=Vn.Fp;function eh(s){let{y:e}=s;return va.toBytes(va.div(Hn+e,Hn-e))}function th(s){let e=Vn.Fp.BYTES;return Re(s,e),Ea(Rn(s.subarray(0,e))).subarray(0,e)}function sh(s){return ya(Vn,Rn,Object.assign({adjustScalarBytes:Ea,toMontgomery:eh,toMontgomerySecret:th,zip215:!0},s))}var Sa=sh({});var Ds=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},mr=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ce={get(s=globalThis){let e=s.crypto;if(e?.subtle==null)throw new mr("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 gr=32;var $n,rh=(async()=>{try{return await Ce.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function nh(s,e,t){if(s.buffer instanceof ArrayBuffer){let r=await Ce.get().subtle.importKey("raw",s.buffer,{name:"Ed25519"},!1,["verify"]);return await Ce.get().subtle.verify({name:"Ed25519"},r,ke(e),ke(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function ih(s,e,t){return Sa.verify(e,t instanceof Uint8Array?t:t.subarray(),s)}async function _a(s,e,t){return $n==null&&($n=await rh),$n?nh(s,e,t):ih(s,e,t)}function br(s){return s==null?!1:typeof s.then=="function"&&typeof s.catch=="function"&&typeof s.finally=="function"}var yr=class{type="Ed25519";raw;constructor(e){this.raw=jn(e,gr)}toMultihash(){return Ne.digest(We(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();let n=_a(this.raw,t,e);return br(n)?n.then(i=>(r?.signal?.throwIfAborted(),i)):n}};function Zn(s){return s=jn(s,gr),new yr(s)}function jn(s,e){if(s=Uint8Array.from(s??[]),s.length!==e)throw new re(`Key must be a Uint8Array of length ${e}, got ${s.length}`);return s}var ah=Math.pow(2,7),ch=Math.pow(2,14),lh=Math.pow(2,21),Yn=Math.pow(2,28),Xn=Math.pow(2,35),Jn=Math.pow(2,42),Qn=Math.pow(2,49),W=128,fe=127;function Fe(s){if(s<ah)return 1;if(s<ch)return 2;if(s<lh)return 3;if(s<Yn)return 4;if(s<Xn)return 5;if(s<Jn)return 6;if(s<Qn)return 7;if(Number.MAX_SAFE_INTEGER!=null&&s>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ei(s,e,t=0){switch(Fe(s)){case 8:e[t++]=s&255|W,s/=128;case 7:e[t++]=s&255|W,s/=128;case 6:e[t++]=s&255|W,s/=128;case 5:e[t++]=s&255|W,s/=128;case 4:e[t++]=s&255|W,s>>>=7;case 3:e[t++]=s&255|W,s>>>=7;case 2:e[t++]=s&255|W,s>>>=7;case 1:{e[t++]=s&255,s>>>=7;break}default:throw new Error("unreachable")}return e}function uh(s,e,t=0){switch(Fe(s)){case 8:e.set(t++,s&255|W),s/=128;case 7:e.set(t++,s&255|W),s/=128;case 6:e.set(t++,s&255|W),s/=128;case 5:e.set(t++,s&255|W),s/=128;case 4:e.set(t++,s&255|W),s>>>=7;case 3:e.set(t++,s&255|W),s>>>=7;case 2:e.set(t++,s&255|W),s>>>=7;case 1:{e.set(t++,s&255),s>>>=7;break}default:throw new Error("unreachable")}return e}function ti(s,e){let t=s[e],r=0;if(r+=t&fe,t<W||(t=s[e+1],r+=(t&fe)<<7,t<W)||(t=s[e+2],r+=(t&fe)<<14,t<W)||(t=s[e+3],r+=(t&fe)<<21,t<W)||(t=s[e+4],r+=(t&fe)*Yn,t<W)||(t=s[e+5],r+=(t&fe)*Xn,t<W)||(t=s[e+6],r+=(t&fe)*Jn,t<W)||(t=s[e+7],r+=(t&fe)*Qn,t<W))return r;throw new RangeError("Could not decode varint")}function hh(s,e){let t=s.get(e),r=0;if(r+=t&fe,t<W||(t=s.get(e+1),r+=(t&fe)<<7,t<W)||(t=s.get(e+2),r+=(t&fe)<<14,t<W)||(t=s.get(e+3),r+=(t&fe)<<21,t<W)||(t=s.get(e+4),r+=(t&fe)*Yn,t<W)||(t=s.get(e+5),r+=(t&fe)*Xn,t<W)||(t=s.get(e+6),r+=(t&fe)*Jn,t<W)||(t=s.get(e+7),r+=(t&fe)*Qn,t<W))return r;throw new RangeError("Could not decode varint")}function si(s,e,t=0){return e==null&&(e=he(Fe(s))),e instanceof Uint8Array?ei(s,e,t):uh(s,e,t)}function ri(s,e=0){return s instanceof Uint8Array?ti(s,e):hh(s,e)}var ii=new Float32Array([-0]),bt=new Uint8Array(ii.buffer);function Ta(s,e,t){ii[0]=s,e[t]=bt[0],e[t+1]=bt[1],e[t+2]=bt[2],e[t+3]=bt[3]}function Da(s,e){return bt[0]=s[e],bt[1]=s[e+1],bt[2]=s[e+2],bt[3]=s[e+3],ii[0]}var oi=new Float64Array([-0]),de=new Uint8Array(oi.buffer);function Aa(s,e,t){oi[0]=s,e[t]=de[0],e[t+1]=de[1],e[t+2]=de[2],e[t+3]=de[3],e[t+4]=de[4],e[t+5]=de[5],e[t+6]=de[6],e[t+7]=de[7]}function Ma(s,e){return de[0]=s[e],de[1]=s[e+1],de[2]=s[e+2],de[3]=s[e+3],de[4]=s[e+4],de[5]=s[e+5],de[6]=s[e+6],de[7]=s[e+7],oi[0]}var fh=BigInt(Number.MAX_SAFE_INTEGER),dh=BigInt(Number.MIN_SAFE_INTEGER),Me=class s{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,r=~this.hi>>>0;return t===0&&(r=r+1>>>0),-(t+r*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 t=~this.lo+1>>>0,r=~this.hi>>>0;return t===0&&(r=r+1>>>0),-(BigInt(t)+(BigInt(r)<<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,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(e===0n)return Pt;if(e<fh&&e>dh)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let r=e>>32n,n=e-(r<<32n);return t&&(r=~r|0n,n=~n|0n,++n>Pa&&(n=0n,++r>Pa&&(r=0n))),new s(Number(n),Number(r))}static fromNumber(e){if(e===0)return Pt;let t=e<0;t&&(e=-e);let r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new s(r,n)}static from(e){return typeof e=="number"?s.fromNumber(e):typeof e=="bigint"?s.fromBigInt(e):typeof e=="string"?s.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new s(e.low>>>0,e.high>>>0):Pt}},Pt=new Me(0,0);Pt.toBigInt=function(){return 0n};Pt.zzEncode=Pt.zzDecode=function(){return this};Pt.length=function(){return 1};var Pa=4294967296n;function Ba(s){let e=0,t=0;for(let r=0;r<s.length;++r)t=s.charCodeAt(r),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(s.charCodeAt(r+1)&64512)===56320?(++r,e+=4):e+=3;return e}function ka(s,e,t){if(t-e<1)return"";let n,i=[],o=0,a;for(;e<t;)a=s[e++],a<128?i[o++]=a:a>191&&a<224?i[o++]=(a&31)<<6|s[e++]&63:a>239&&a<365?(a=((a&7)<<18|(s[e++]&63)<<12|(s[e++]&63)<<6|s[e++]&63)-65536,i[o++]=55296+(a>>10),i[o++]=56320+(a&1023)):i[o++]=(a&15)<<12|(s[e++]&63)<<6|s[e++]&63,o>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,i)),o=0);return n!=null?(o>0&&n.push(String.fromCharCode.apply(String,i.slice(0,o))),n.join("")):String.fromCharCode.apply(String,i.slice(0,o))}function ai(s,e,t){let r=t,n,i;for(let o=0;o<s.length;++o)n=s.charCodeAt(o),n<128?e[t++]=n:n<2048?(e[t++]=n>>6|192,e[t++]=n&63|128):(n&64512)===55296&&((i=s.charCodeAt(o+1))&64512)===56320?(n=65536+((n&1023)<<10)+(i&1023),++o,e[t++]=n>>18|240,e[t++]=n>>12&63|128,e[t++]=n>>6&63|128,e[t++]=n&63|128):(e[t++]=n>>12|224,e[t++]=n>>6&63|128,e[t++]=n&63|128);return t-r}function Ue(s,e){return RangeError(`index out of range: ${s.pos} + ${e??1} > ${s.len}`)}function wr(s,e){return(s[e-4]|s[e-3]<<8|s[e-2]<<16|s[e-1]<<24)>>>0}var ci=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=ke(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,Ue(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 Ue(this,4);return wr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ue(this,4);return wr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ue(this,4);let e=Da(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ue(this,4);let e=Ma(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw Ue(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){let e=this.bytes();return ka(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Ue(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Ue(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 Me(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*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;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Ue(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Ue(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Ue(this,8);let e=wr(this.buf,this.pos+=4),t=wr(this.buf,this.pos+=4);return new Me(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=ti(this.buf,this.pos);return this.pos+=Fe(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 As(s){return new ci(s instanceof Uint8Array?s:s.subarray())}function ye(s,e,t){let r=As(s);return e.decode(r,void 0,t)}function li(s){let e=s??8192,t=e>>>1,r,n=e;return function(o){if(o<1||o>t)return he(o);n+o>e&&(r=he(e),n=0);let a=r.subarray(n,n+=o);return(n&7)!==0&&(n=(n|7)+1),a}}var Bt=class{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}};function ui(){}var fi=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},ph=li();function mh(s){return globalThis.Buffer!=null?he(s):ph(s)}var Ps=class{len;head;tail;states;constructor(){this.len=0,this.head=new Bt(ui,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new Bt(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new di((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(xr,10,Me.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Me.fromBigInt(e);return this._push(xr,t.length(),t)}uint64Number(e){return this._push(ei,Fe(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 t=Me.fromBigInt(e).zzEncode();return this._push(xr,t.length(),t)}sint64Number(e){let t=Me.fromNumber(e).zzEncode();return this._push(xr,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(hi,1,e?1:0)}fixed32(e){return this._push(Ms,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Me.fromBigInt(e);return this._push(Ms,4,t.lo)._push(Ms,4,t.hi)}fixed64Number(e){let t=Me.fromNumber(e);return this._push(Ms,4,t.lo)._push(Ms,4,t.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(Ta,4,e)}double(e){return this._push(Aa,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(hi,1,0):this.uint32(t)._push(bh,t,e)}string(e){let t=Ba(e);return t!==0?this.uint32(t)._push(ai,t,e):this._push(hi,1,0)}fork(){return this.states=new fi(this),this.head=this.tail=new Bt(ui,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 Bt(ui,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r!==0&&(this.tail.next=e.next,this.tail=t,this.len+=r),this}finish(){let e=this.head.next,t=mh(this.len),r=0;for(;e!=null;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}};function hi(s,e,t){e[t]=s&255}function gh(s,e,t){for(;s>127;)e[t++]=s&127|128,s>>>=7;e[t]=s}var di=class extends Bt{next;constructor(e,t){super(gh,e,t),this.next=void 0}};function xr(s,e,t){for(;s.hi!==0;)e[t++]=s.lo&127|128,s.lo=(s.lo>>>7|s.hi<<25)>>>0,s.hi>>>=7;for(;s.lo>127;)e[t++]=s.lo&127|128,s.lo=s.lo>>>7;e[t++]=s.lo}function Ms(s,e,t){e[t]=s&255,e[t+1]=s>>>8&255,e[t+2]=s>>>16&255,e[t+3]=s>>>24}function bh(s,e,t){e.set(s,t)}globalThis.Buffer!=null&&(Ps.prototype.bytes=function(s){let e=s.length>>>0;return this.uint32(e),e>0&&this._push(yh,e,s),this},Ps.prototype.string=function(s){let e=globalThis.Buffer.byteLength(s);return this.uint32(e),e>0&&this._push(wh,e,s),this});function yh(s,e,t){e.set(s,t)}function wh(s,e,t){s.length<40?ai(s,e,t):e.utf8Write!=null?e.utf8Write(s,t):e.set(j(s),t)}function pi(){return new Ps}function we(s,e){let t=pi();return e.encode(s,t,{lengthDelimited:!1}),t.finish()}function*xe(s,e,t){let r=As(s);yield*e.stream(r,void 0,"$",t)}var vr={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Er(s,e,t,r,n){return{name:s,type:e,encode:t,decode:r,stream:n}}function mi(s){function e(i){if(s[i.toString()]==null)throw new Error("Invalid enum value");return s[i]}let t=function(o,a){let l=e(o);a.int32(l)},r=function(o){let a=o.int32();return e(a)},n=function*(o){let a=o.int32();yield e(a)};return Er("enum",vr.VARINT,t,r,n)}function ve(s,e,t){return Er("message",vr.LENGTH_DELIMITED,s,e,t)}var Z=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var Q;(function(s){s.RSA="RSA",s.Ed25519="Ed25519",s.secp256k1="secp256k1",s.ECDSA="ECDSA"})(Q||(Q={}));var gi;(function(s){s[s.RSA=0]="RSA",s[s.Ed25519=1]="Ed25519",s[s.secp256k1=2]="secp256k1",s[s.ECDSA=3]="ECDSA"})(gi||(gi={}));(function(s){s.codec=()=>mi(gi)})(Q||(Q={}));var je;(function(s){let e;s.codec=()=>(e==null&&(e=ve((i,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),i.Type!=null&&(o.uint32(8),Q.codec().encode(i.Type,o)),i.Data!=null&&(o.uint32(18),o.bytes(i.Data)),a.lengthDelimited!==!1&&o.ldelim()},(i,o,a={})=>{let l={},u=o==null?i.len:i.pos+o;for(;i.pos<u;){let p=i.uint32();switch(p>>>3){case 1:{l.Type=Q.codec().decode(i);break}case 2:{l.Data=i.bytes();break}default:{i.skipType(p&7);break}}}return l},function*(i,o,a,l={}){let u=o==null?i.len:i.pos+o;for(;i.pos<u;){let p=i.uint32();switch(p>>>3){case 1:{yield{field:`${a}.Type`,value:Q.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(p&7);break}}}})),e);function t(i){return we(i,s.codec())}s.encode=t;function r(i,o){return ye(i,s.codec(),o)}s.decode=r;function n(i,o){return xe(i,s.codec(),o)}s.stream=n})(je||(je={}));var bi;(function(s){let e;s.codec=()=>(e==null&&(e=ve((i,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),i.Type!=null&&(o.uint32(8),Q.codec().encode(i.Type,o)),i.Data!=null&&(o.uint32(18),o.bytes(i.Data)),a.lengthDelimited!==!1&&o.ldelim()},(i,o,a={})=>{let l={},u=o==null?i.len:i.pos+o;for(;i.pos<u;){let p=i.uint32();switch(p>>>3){case 1:{l.Type=Q.codec().decode(i);break}case 2:{l.Data=i.bytes();break}default:{i.skipType(p&7);break}}}return l},function*(i,o,a,l={}){let u=o==null?i.len:i.pos+o;for(;i.pos<u;){let p=i.uint32();switch(p>>>3){case 1:{yield{field:`${a}.Type`,value:Q.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(p&7);break}}}})),e);function t(i){return we(i,s.codec())}s.encode=t;function r(i,o){return ye(i,s.codec(),o)}s.decode=r;function n(i,o){return xe(i,s.codec(),o)}s.stream=n})(bi||(bi={}));var ks={};_e(ks,{MAX_RSA_KEY_SIZE:()=>yi,generateRSAKeyPair:()=>Oa,jwkToJWKKeyPair:()=>Ua,jwkToPkcs1:()=>Sh,jwkToPkix:()=>Ei,jwkToRSAPrivateKey:()=>Ti,pkcs1MessageToJwk:()=>xi,pkcs1MessageToRSAPrivateKey:()=>Si,pkcs1ToJwk:()=>Eh,pkcs1ToRSAPrivateKey:()=>Na,pkixMessageToJwk:()=>vi,pkixMessageToRSAPublicKey:()=>Ii,pkixToJwk:()=>_h,pkixToRSAPublicKey:()=>_i});var ts=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=ks.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ce.createV1(114,this._multihash)}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}verify(e,t,r){return Fa(this.jwk,t,e,r)}},Bs=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=ks.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}sign(e,t){return Ca(this.jwk,e,t)}};var yi=8192,wi=18,xh=1062,vh=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Eh(s){let e=Je(s);return xi(e)}function xi(s){return{n:$(s[1],"base64url"),e:$(s[2],"base64url"),d:$(s[3],"base64url"),p:$(s[4],"base64url"),q:$(s[5],"base64url"),dp:$(s[6],"base64url"),dq:$(s[7],"base64url"),qi:$(s[8],"base64url"),kty:"RSA"}}function Sh(s){if(s.n==null||s.e==null||s.d==null||s.p==null||s.q==null||s.dp==null||s.dq==null||s.qi==null)throw new re("JWK was missing components");return at([Te(Uint8Array.from([0])),Te(j(s.n,"base64url")),Te(j(s.e,"base64url")),Te(j(s.d,"base64url")),Te(j(s.p,"base64url")),Te(j(s.q,"base64url")),Te(j(s.dp,"base64url")),Te(j(s.dq,"base64url")),Te(j(s.qi,"base64url"))]).subarray()}function _h(s){let e=Je(s,{offset:0});return vi(e)}function vi(s){let e=Je(s[1],{offset:0});return{kty:"RSA",n:$(e[0],"base64url"),e:$(e[1],"base64url")}}function Ei(s){if(s.n==null||s.e==null)throw new re("JWK was missing components");return at([vh,Ws(at([Te(j(s.n,"base64url")),Te(j(s.e,"base64url"))]))]).subarray()}function Na(s){let e=Je(s);return Si(e)}function Si(s){let e=xi(s);return Ti(e)}function _i(s,e){if(s.byteLength>=xh)throw new Ut("Key size is too large");let t=Je(s,{offset:0});return Ii(t,s,e)}function Ii(s,e,t){let r=vi(s);if(t==null){let n=jt(je.encode({Type:Q.RSA,Data:e}));t=He(wi,n)}return new ts(r,t)}function Ti(s){if(za(s)>yi)throw new re("Key size is too large");let e=Ua(s),t=jt(je.encode({Type:Q.RSA,Data:Ei(e.publicKey)})),r=He(wi,t);return new Bs(e.privateKey,new ts(e.publicKey,r))}async function Oa(s){if(s>yi)throw new re("Key size is too large");let e=await Ka(s),t=jt(je.encode({Type:Q.RSA,Data:Ei(e.publicKey)})),r=He(wi,t);return new Bs(e.privateKey,new ts(e.publicKey,r))}function Ua(s){if(s==null)throw new re("Missing key parameter");return{privateKey:s,publicKey:{kty:s.kty,n:s.n,e:s.e}}}async function Ka(s,e){let t=await Ce.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:s,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let r=await Ih(t,e);return{privateKey:r[0],publicKey:r[1]}}async function Ca(s,e,t){let r=await Ce.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let n=await Ce.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,ke(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(n,0,n.byteLength)}async function Fa(s,e,t,r){let n=await Ce.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();let i=await Ce.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,ke(e),ke(t instanceof Uint8Array?t:t.subarray()));return r?.signal?.throwIfAborted(),i}async function Ih(s,e){if(s.privateKey==null||s.publicKey==null)throw new re("Private and public key are required");let t=await Promise.all([Ce.get().subtle.exportKey("jwk",s.privateKey),Ce.get().subtle.exportKey("jwk",s.publicKey)]);return e?.signal?.throwIfAborted(),t}function za(s){if(s.kty!=="RSA")throw new re("invalid key type");if(s.n==null)throw new re("invalid key modulus");return j(s.n,"base64url").length*8}var Sr=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(js(e),Re(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,n=new Uint8Array(r);n.set(t.length>r?e.create().update(t).digest():t);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),Tt(n)}update(e){return $t(this),this.iHash.update(e),this}digestInto(e){$t(this),Zs(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),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:t,iHash:r,finished:n,destroyed:i,blockLen:o,outputLen:a,canXOF:l}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.canXOF=l,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},qa=(()=>{let s=((e,t,r)=>new Sr(e,t).update(r).digest());return s.create=(e,t)=>new Sr(e,t),s})();var Th=BigInt(0),Di=class extends Error{constructor(e=""){super(e)}},et={Err:Di,_tlv:{encode:(s,e)=>{let{Err:t}=et;if(pt(s,"tag"),s<0||s>255)throw new t("tlv.encode: wrong tag");if(Yo(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let r=e.length/2,n=Ss(r);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let i=r>127?Ss(n.length/2|128):"";return Ss(s)+i+n+e},decode(s,e){let{Err:t}=et;e=G(e,void 0,"DER data");let r=0;if(s<0||s>255)throw new t("tlv.decode: wrong tag");if(e.length<2||e[r++]!==s)throw new t("tlv.decode: wrong tlv");let n=e[r++],i=!!(n&128),o=0;if(!i)o=n;else{let l=n&127;if(!l)throw new t("tlv.decode(long): indefinite length not supported");if(l>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(r,r+l);if(u.length!==l)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let p of u)o=o<<8|p;if(r+=l,o<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(s){let{Err:e}=et;if(tr(s),s<Th)throw new e("integer: negative integers are not allowed");let t=Ss(s);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(s){let{Err:e}=et;if(s.length<1)throw new e("invalid signature integer: empty");if(s[0]&128)throw new e("invalid signature integer: negative");if(s.length>1&&s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return $e(s)}},toSig(s){let{Err:e,_int:t,_tlv:r}=et,n=G(s,void 0,"signature"),{v:i,l:o}=r.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l}=r.decode(2,i),{v:u,l:p}=r.decode(2,l);if(p.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(s){let{_tlv:e,_int:t}=et;Ae(s,{r:"bigint",s:"bigint"},{},"sig");let r=e.encode(2,t.encode(s.r)),n=e.encode(2,t.encode(s.s)),i=r+n;return e.encode(48,i)}},Ai=(Object.freeze(et._tlv),Object.freeze(et._int),Object.freeze(et));var Ga=(s,e)=>(s+(s>=0?e:-e)/Ha)/e;function Dh(s,e,t){Yt("scalar",s,tt,t);let[[r,n],[i,o]]=e,a=Ga(o*s,t),l=Ga(-n*s,t),u=s-a*r-l*i,p=-a*n-l*o,m=u<tt,x=p<tt;m&&(u=-u),x&&(p=-p);let y=_s(Math.ceil(Xt(t)/2))+kt;if(u<tt||u>=y||p<tt||p>=y)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:m,k1:u,k2neg:x,k2:p}}function Bi(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function Mi(s,e){Ae(s);let t={};for(let r of Object.keys(e))t[r]=s[r]===void 0?e[r]:s[r];return De(t.lowS,"lowS"),De(t.prehash,"prehash"),t.format!==void 0&&Bi(t.format),t}var tt=BigInt(0),kt=BigInt(1),Ha=BigInt(2),Pi=BigInt(3),Ah=BigInt(4);function Wa(s,e={}){let t=ur("weierstrass",s,e),r=t.Fp,n=t.Fn,i=t.CURVE,{h:o,n:a}=i;Ae(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:l,allowInfinityPoint:u}=e,p=e.randomBytes===void 0?At:e.randomBytes;if(l&&(!r.is0(i.a)||typeof l.beta!="bigint"||!Array.isArray(l.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let m=$a(r,n);function x(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function y(L,I,A){if(u&&I.is0())return Uint8Array.of(0);let{x:B,y:N}=I.toAffine(),M=r.toBytes(B);if(De(A,"isCompressed"),A){x();let T=!r.isOdd(N);return Le(Va(T),M)}else return Le(Uint8Array.of(4),M,r.toBytes(N))}function f(L){G(L,void 0,"Point");let{publicKey:I,publicKeyUncompressed:A}=m,B=L.length,N=L[0],M=L.subarray(1);if(u&&B===1&&N===0)return{x:r.ZERO,y:r.ZERO};if(B===I&&(N===2||N===3)){let T=r.fromBytes(M);if(!r.isValid(T))throw new Error("bad point: is not on curve, wrong x");let k=c(T),R;try{R=r.sqrt(k)}catch(q){let z=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}x();let O=r.isOdd(R);return(N&1)===1!==O&&(R=r.neg(R)),{x:T,y:R}}else if(B===A&&N===4){let T=r.BYTES,k=r.fromBytes(M.subarray(0,T)),R=r.fromBytes(M.subarray(T,T*2));if(!h(k,R))throw new Error("bad point: is not on curve");return{x:k,y:R}}else throw new Error(`bad point: got length ${B}, expected compressed=${I} or uncompressed=${A}`)}let g=e.toBytes===void 0?y:e.toBytes,w=e.fromBytes===void 0?f:e.fromBytes,E=r.mul(i.b,Pi),S=r.is0(i.a)?L=>r.ZERO:L=>r.mul(i.a,L);function c(L){let I=r.sqr(L),A=r.mul(I,L);return r.add(r.add(A,r.mul(L,i.a)),i.b)}function h(L,I){let A=r.sqr(I),B=c(L);return r.eql(A,B)}if(!h(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let d=r.mul(r.pow(i.a,Pi),Ah),b=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(d,b)))throw new Error("bad curve params: a or b");function v(L,I,A=!1){if(!r.isValid(I)||A&&r.is0(I))throw new Error(`bad point coordinate ${L}`);return I}function _(L){if(!(L instanceof F))throw new Error("Weierstrass Point expected")}function D(L){if(!l||!l.basises)throw new Error("no endo");return Dh(L,l.basises,n.ORDER)}function P(L,I,A,B){if(!n.isValid(B))throw new RangeError("invalid scalar: out of range");if(l){let{k1neg:N,k1:M,k2neg:T,k2:k}=D(B),R=new F(r.mul(A.X,l.beta),A.Y,A.Z);L.push(N?A.negate():A,T?R.negate():R),I.push(M,k)}else L.push(A),I.push(B)}let K=new WeakSet;class F{static BASE=new F(i.Gx,i.Gy,r.ONE);static ZERO=new F(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=n;X;Y;Z;constructor(I,A,B){this.X=v("x",I),this.Y=v("y",A,!0),this.Z=v("z",B),Object.freeze(this)}static CURVE(){return i}static fromAffine(I){let{x:A,y:B}=I||{};if(!I||!r.isValid(A)||!r.isValid(B))throw new Error("invalid affine point");if(I instanceof F)throw new Error("projective point not allowed");return r.is0(A)&&r.is0(B)?F.ZERO:new F(A,B,r.ONE)}static fromBytes(I){let A=F.fromAffine(w(G(I,void 0,"point")));return A.assertValidity(),A}static fromHex(I){return F.fromBytes(Zt(I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=6,A=!0){return C.setWindowSize(this,I),A||this.multiply(Pi),this}assertValidity(){let I=this;if(I.is0()){if(e.allowInfinityPoint&&r.is0(I.X)&&r.eql(I.Y,r.ONE)&&r.is0(I.Z))return;throw new Error("bad point: ZERO")}if(K.has(I))return;let{x:A,y:B}=I.toAffine();if(!r.isValid(A)||!r.isValid(B))throw new Error("bad point: x or y not field elements");if(!h(A,B))throw new Error("bad point: equation left != right");if(!I.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");K.add(I)}hasEvenY(){let{y:I}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(I)}equals(I){_(I);let{X:A,Y:B,Z:N}=this,{X:M,Y:T,Z:k}=I,R=r.eql(r.mul(A,k),r.mul(M,N)),O=r.eql(r.mul(B,k),r.mul(T,N));return R&&O}negate(){return new F(this.X,r.neg(this.Y),this.Z)}double(){let{X:I,Y:A,Z:B}=this,N=r.ZERO,M=r.ZERO,T=r.ZERO,k=r.mul(I,I),R=r.mul(A,A),O=r.mul(B,B),U=r.mul(I,A);return U=r.add(U,U),T=r.mul(I,B),T=r.add(T,T),N=S(T),M=r.mul(E,O),M=r.add(N,M),N=r.sub(R,M),M=r.add(R,M),M=r.mul(N,M),N=r.mul(U,N),T=r.mul(E,T),O=S(O),U=r.sub(k,O),U=S(U),U=r.add(U,T),T=r.add(k,k),k=r.add(T,k),k=r.add(k,O),k=r.mul(k,U),M=r.add(M,k),O=r.mul(A,B),O=r.add(O,O),k=r.mul(O,U),N=r.sub(N,k),T=r.mul(O,R),T=r.add(T,T),T=r.add(T,T),new F(N,M,T)}add(I){_(I);let{X:A,Y:B,Z:N}=this,{X:M,Y:T,Z:k}=I,R=r.ZERO,O=r.ZERO,U=r.ZERO,q=r.mul(A,M),z=r.mul(B,T),te=r.mul(N,k),be=r.add(A,B),se=r.add(M,T);be=r.mul(be,se),se=r.add(q,z),be=r.sub(be,se),se=r.add(A,N);let ue=r.add(M,k);return se=r.mul(se,ue),ue=r.add(q,te),se=r.sub(se,ue),ue=r.add(B,N),R=r.add(T,k),ue=r.mul(ue,R),R=r.add(z,te),ue=r.sub(ue,R),U=S(se),R=r.mul(E,te),U=r.add(R,U),R=r.sub(z,U),U=r.add(z,U),O=r.mul(R,U),z=r.add(q,q),z=r.add(z,q),te=S(te),se=r.mul(E,se),z=r.add(z,te),te=r.sub(q,te),te=S(te),se=r.add(se,te),q=r.mul(z,se),O=r.add(O,q),q=r.mul(ue,se),R=r.mul(be,R),R=r.sub(R,q),q=r.mul(be,z),U=r.mul(ue,U),U=r.add(U,q),new F(R,O,U)}subtract(I){return _(I),this.add(I.negate())}is0(){return this.equals(F.ZERO)}multiply(I){if(!n.isValidNot0(I))throw new RangeError("invalid scalar: out of range");let{p:A,f:B}=C.mulSecret(this,I,o,Y);return Y([A,B])[0]}multiplyUnsafe(I){let A=this,B=I;if(!n.isValid(B))throw new RangeError("invalid scalar: out of range");if(B===tt||A.is0())return F.ZERO;if(B===kt)return A;if(C.hasWindowSize(this))return C.mulUnsafe(A,B,Y);let N=[],M=[];return P(N,M,A,B),lr(F,N,M)}mulAddUnsafe(I,A,B){_(A);let N=[],M=[];return P(N,M,this,I),P(N,M,A,B),lr(F,N,M)}toAffine(I){let A=this,B=I;if(B!=null&&!r.isValid(B))throw new RangeError('"invertedZ" expected valid field element');let{X:N,Y:M,Z:T}=A;if(r.eql(T,r.ONE))return{x:N,y:M};let k=A.is0();B==null&&(B=k?r.ONE:r.inv(T));let R=r.mul(N,B),O=r.mul(M,B),U=r.mul(T,B);if(k)return{x:r.ZERO,y:r.ZERO};if(!r.eql(U,r.ONE))throw new Error("invZ was invalid");return{x:R,y:O}}isTorsionFree(){let{isTorsionFree:I}=e;return o===kt?!0:I?I(F,this):C.mulUnsafe(this,a).is0()}clearCofactor(){let{clearCofactor:I}=e;return o===kt?this:I?I(F,this):this.multiplyUnsafe(o)}isSmallOrder(){return o===kt?this.is0():this.clearCofactor().is0()}toBytes(I=!0){return De(I,"isCompressed"),this.assertValidity(),g(F,this,I)}toHex(I=!0){return Es(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let Y=L=>cr(F,L),C=new es(F,p);return C.bits>=6&&F.BASE.precompute(6),Object.freeze(F.prototype),Object.freeze(F),F}function Va(s){return Uint8Array.of(s?2:3)}function $a(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Mh(s,e={}){gt(s);let{Fn:t}=s,r=e.randomBytes===void 0?At:e.randomBytes,n=Object.assign($a(s.Fp,t),{seed:Math.max(or(t.ORDER),16)});function i(y){try{let f=t.fromBytes(y);return t.isValidNot0(f)}catch{return!1}}function o(y,f){let{publicKey:g,publicKeyUncompressed:w}=n;try{let E=y.length;return f===!0&&E!==g||f===!1&&E!==w?!1:!!s.fromBytes(y)}catch{return!1}}function a(y){return y=y===void 0?r(n.seed):y,ar(G(y,n.seed,"seed"),t.ORDER)}function l(y,f=!0){return s.BASE.multiply(t.fromBytes(y)).toBytes(f)}function u(y){let{secretKey:f,publicKey:g,publicKeyUncompressed:w}=n,E=t._lengths;if(!dt(y))return;let S=G(y,void 0,"key").length,c=S===g||S===w,h=S===f||!!E?.includes(S);if(!(c&&h))return c}function p(y,f,g=!0){if(u(y)===!0)throw new Error("first arg must be private key");if(u(f)===!1)throw new Error("second arg must be public key");let w=t.fromBytes(y);return s.fromBytes(f).multiply(w).toBytes(g)}let m={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},x=hr(a,l);return Object.freeze(m),Object.freeze(n),Object.freeze({getPublicKey:l,getSharedSecret:p,keygen:x,Point:s,utils:m,lengths:n})}function ja(s,e,t={}){gt(s);let r=e;js(r),Ae(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=Object.assign({},t),i=n.randomBytes===void 0?At:n.randomBytes,o=n.hmac===void 0?(M,T)=>qa(r,M,T):n.hmac,{Fp:a,Fn:l}=s,{ORDER:u,BITS:p}=l,m=or(u),x=Gn(i,m),{keygen:y,getPublicKey:f,getSharedSecret:g,utils:w,lengths:E}=Mh(s,n),S={prehash:!0,lowS:typeof n.lowS=="boolean"?n.lowS:!0,format:"compact",extraEntropy:!1},c=u*Ha+kt<a.ORDER;function h(M){let T=u>>kt;return M>T}function d(M,T){if(!l.isValidNot0(T))throw new Error(`invalid signature ${M}: out of range 1..Point.Fn.ORDER`);return T}function b(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function v(M,T,k){return b(),(M===k?0:2)|Number(a.isOdd(T))}function _(){if(c)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function D(M,T){Bi(T);let k=E.signature,R=T==="compact"?k:T==="recovered"?k+1:void 0;return G(M,R)}class P{r;s;recovery;constructor(T,k,R){if(this.r=d("r",T),this.s=d("s",k),R!=null){if(_(),![0,1,2,3].includes(R))throw new Error("invalid recovery id");this.recovery=R}Object.freeze(this)}static fromBytes(T,k=S.format){D(T,k);let R;if(k==="der"){let{r:z,s:te}=Ai.toSig(G(T));return new P(z,te)}k==="recovered"&&(R=T[0],k="compact",T=T.subarray(1));let O=E.signature/2,U=T.subarray(0,O),q=T.subarray(O,O*2);return new P(l.fromBytes(U),l.fromBytes(q),R)}static fromHex(T,k){return this.fromBytes(Zt(T),k)}assertRecovery(){let{recovery:T}=this;if(T==null)throw new Error("invalid recovery id: must be present");return T}addRecoveryBit(T){return new P(this.r,this.s,T)}recoverPublicKey(T){let{r:k,s:R}=this,O=this.assertRecovery(),U=O===2||O===3?k+u:k;if(!a.isValid(U))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let q=a.toBytes(U),z=s.fromBytes(Le(Va((O&1)===0),q)),te=l.inv(U),be=F(G(T,void 0,"msgHash")),se=l.create(-be*te),ue=l.create(R*te),qe=s.BASE.mulAddUnsafe(se,z,ue);if(qe.is0())throw new Error("invalid recovery: point at infinify");return qe.assertValidity(),qe}hasHighS(){return h(this.s)}toBytes(T=S.format){if(Bi(T),T==="der")return Zt(Ai.hexFromSig(this));let{r:k,s:R}=this,O=l.toBytes(k),U=l.toBytes(R);return T==="recovered"?(_(),Le(Uint8Array.of(this.assertRecovery()),O,U)):Le(O,U)}toHex(T){return Es(this.toBytes(T))}}Object.freeze(P.prototype),Object.freeze(P);let K=n.bits2int===void 0?function(T){if(T.length>8192)throw new Error("input is too large");let k=$e(T),R=T.length*8-p;return R>0?k>>BigInt(R):k}:n.bits2int,F=n.bits2int_modN===void 0?function(T){return l.create(K(T))}:n.bits2int_modN,Y=_s(p);function C(M){return Yt("num < 2^"+p,M,tt,Y),l.toBytes(M)}function L(M,T){return G(M,void 0,"message"),T?G(r(M),void 0,"prehashed message"):M}function I(M,T,k){let{lowS:R,prehash:O,extraEntropy:U}=Mi(k,S);M=L(M,O);let q=F(M),z=l.fromBytes(T);if(!l.isValidNot0(z))throw new Error("invalid private key");let te=[C(z),C(q)];if(U!=null&&U!==!1){let qe=U===!0?i(E.secretKey):U;te.push(G(qe,void 0,"extraEntropy"))}let be=Le(...te),se=q;function ue(qe){let Nt=K(qe);if(!l.isValidNot0(Nt))return;let hs=s.BASE.multiply(Nt).toAffine(),nt=l.create(hs.x);if(nt===tt)return;let Ge;if(x!==void 0){let fs=$e(ar(x(m),u)),Lc=l.inv(l.mul(fs,Nt)),Cc=l.mul(fs,se),Fc=l.mul(fs,z);Ge=l.create(Lc*l.create(Cc+Fc*nt))}else{let fs=oa(Nt,u);Ge=l.create(fs*l.create(se+nt*z))}if(Ge===tt)return;let Gr=v(hs.x,hs.y,nt),Vi=Ge;return R&&h(Ge)&&(Vi=l.neg(Ge),Gr^=1),new P(nt,Vi,c?void 0:Gr)}return{seed:be,k2sig:ue}}function A(M,T,k={}){let{seed:R,k2sig:O}=I(M,T,k);return Jo(r.outputLen,l.BYTES,o)(R,O).toBytes(k.format)}function B(M,T,k,R={}){let{lowS:O,prehash:U,format:q}=Mi(R,S);if(k=G(k,void 0,"publicKey"),T=L(T,U),!dt(M)){let z=M instanceof P?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+z)}D(M,q);try{let z=P.fromBytes(M,q),te=s.fromBytes(k);if(O&&z.hasHighS())return!1;let{r:be,s:se}=z,ue=F(T),qe=l.inv(se),Nt=l.create(ue*qe),hs=l.create(be*qe),nt=s.BASE.mulAddUnsafe(Nt,te,hs);if(nt.is0())return!1;let Ge=nt.toAffine();return!(l.create(Ge.x)!==be||q==="recovered"&&z.recovery!==v(Ge.x,Ge.y,be))}catch{return!1}}function N(M,T,k={}){let{prehash:R}=Mi(k,S);return T=L(T,R),P.fromBytes(M,"recovered").recoverPublicKey(T).toBytes()}return Object.freeze({keygen:y,getPublicKey:f,getSharedSecret:g,utils:w,lengths:E,Point:s,sign:A,verify:B,recoverPublicKey:N,Signature:P,hash:r})}var Ri={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Ph={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Za=BigInt(2);function Bh(s){let e=Ri.p,t=BigInt(3),r=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),l=BigInt(88),u=s*s*s%e,p=u*u*s%e,m=X(p,t,e)*p%e,x=X(m,t,e)*p%e,y=X(x,Za,e)*u%e,f=X(y,n,e)*y%e,g=X(f,i,e)*f%e,w=X(g,a,e)*g%e,E=X(w,l,e)*w%e,S=X(E,a,e)*g%e,c=X(S,t,e)*p%e,h=X(c,o,e)*f%e,d=X(h,r,e)*u%e,b=X(d,Za,e);if(!ki.eql(ki.sqr(b),s))throw new Error("Cannot find square root");return b}var ki=Qt(Ri.p,{sqrt:Bh}),kh=Wa(Ri,{Fp:ki,endo:Ph}),ss=ja(kh,jt);function Ya(s,e,t,r){let n=St.digest(t instanceof Uint8Array?t:t.subarray());if(br(n))return n.then(({digest:i})=>(r?.signal?.throwIfAborted(),ss.verify(e,i,s,{prehash:!1,format:"der"}))).catch(i=>{throw i.name==="AbortError"?i:new Ds(String(i))});try{return r?.signal?.throwIfAborted(),ss.verify(e,n.digest,s,{prehash:!1,format:"der"})}catch(i){throw new Ds(String(i))}}var _r=class{type="secp256k1";raw;_key;constructor(e){this._key=Ja(e),this.raw=Xa(this._key)}toMultihash(){return Ne.digest(We(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}verify(e,t,r){return Ya(this._key,t,e,r)}};function Li(s){return new _r(s)}function Xa(s){return ss.Point.fromBytes(s).toBytes()}function Ja(s){try{return ss.Point.fromBytes(s),s}catch(e){throw new Ut(String(e))}}function Ci(s,e){let{Type:t,Data:r}=je.decode(s),n=r??new Uint8Array;switch(t){case Q.RSA:return _i(n,e);case Q.Ed25519:return Zn(n);case Q.secp256k1:return Li(n);case Q.ECDSA:return En(n);default:throw new Kt}}function Qa(s){let{Type:e,Data:t}=je.decode(s.digest),r=t??new Uint8Array;switch(e){case Q.Ed25519:return Zn(r);case Q.secp256k1:return Li(r);case Q.ECDSA:return En(r);default:throw new Kt}}function We(s){return je.encode({Type:Q[s.type],Data:s.raw})}var ec=Symbol.for("nodejs.util.inspect.custom"),Rh=114,Rs=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()})`}[Vr]=!0;toString(){return this.string==null&&(this.string=ie.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ce.createV1(Rh,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Ie(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Ie(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[ec](){return`PeerId(${this.toString()})`}},Ir=class extends Rs{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Tr=class extends Rs{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Dr=class extends Rs{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Lh=2336,Ls=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ne.digest(j(this.url))}[ec](){return`PeerId(${this.url})`}[Vr]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ce.createV1(Lh,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=$(e)),e.toString()===this.toString())}};var Ch=114,tc=2336;function Rt(s,e){let t;if(s.charAt(0)==="1"||s.charAt(0)==="Q")t=Ye(ie.decode(`z${s}`));else{if(s.startsWith("k51qzi5uqu5")||s.startsWith("kzwfwjn5ji4")||s.startsWith("k2k4r8")||s.startsWith("bafz"))return Fh(ce.parse(s));if(e==null)throw new re('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ye(e.decode(s))}return rs(t)}function rs(s){if(Oh(s))return new Ir({multihash:s});if(Nh(s))try{let e=Qa(s);if(e.type==="Ed25519")return new Tr({multihash:s,publicKey:e});if(e.type==="secp256k1")return new Dr({multihash:s,publicKey:e})}catch{let t=$(s.digest);return new Ls(new URL(t))}throw new Ks("Supplied PeerID Multihash is invalid")}function Fh(s){if(s?.multihash==null||s.version==null||s.version===1&&s.code!==Ch&&s.code!==tc)throw new Us("Supplied PeerID CID is invalid");if(s.code===tc){let e=$(s.multihash.digest);return new Ls(new URL(e))}return rs(s.multihash)}function Nh(s){return s.code===Ne.code}function Oh(s){return s.code===St.code}var Ar=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ns=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Mr=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Cs=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Pr(s){return s[Symbol.asyncIterator]!=null}function sc(s,e){if(s.byteLength>e)throw new ns("Message length too long")}var kr=s=>{let e=Fe(s),t=he(e);return si(s,t),kr.bytes=e,t};kr.bytes=0;function is(s,e){e=e??{};let t=e.lengthEncoder??kr,r=e?.maxDataLength??4194304;function*n(i){sc(i,r);let o=t(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return Pr(s)?(async function*(){for await(let i of s)yield*n(i)})():(function*(){for(let i of s)yield*n(i)})()}is.single=(s,e)=>{e=e??{};let t=e.lengthEncoder??kr,r=e?.maxDataLength??4194304;return sc(s,r),new ae(t(s.byteLength),s)};var Lt;(function(s){s[s.LENGTH=0]="LENGTH",s[s.DATA=1]="DATA"})(Lt||(Lt={}));var Fi=s=>{let e=ri(s);return Fi.bytes=Fe(e),e};Fi.bytes=0;function Fs(s,e){let t=new ae,r=Lt.LENGTH,n=-1,i=e?.lengthDecoder??Fi,o=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*l(){for(;t.byteLength>0;){if(r===Lt.LENGTH)try{if(n=i(t),n<0)throw new Ar("Invalid message length");if(n>a)throw new ns("Message length too long");let u=i.bytes;t.consume(u),e?.onLength!=null&&e.onLength(n),r=Lt.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>o)throw new Mr("Message length length too long");break}throw u}if(r===Lt.DATA){if(t.byteLength<n)break;let u=t.sublist(0,n);t.consume(n),e?.onData!=null&&e.onData(u),yield u,r=Lt.LENGTH}}}return Pr(s)?(async function*(){for await(let u of s)t.append(u),yield*l();if(t.byteLength>0)throw new Cs("Unexpected end of input")})():(function*(){for(let u of s)t.append(u),yield*l();if(t.byteLength>0)throw new Cs("Unexpected end of input")})()}Fs.fromReader=(s,e)=>{let t=1,r=(async function*(){for(;;)try{let{done:i,value:o}=await s.next(t);if(i===!0)return;o!=null&&(yield o)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{t=1}})();return Fs(r,{...e??{},onLength:i=>{t=i}})};function st(){let s={};return s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),s}var Rr=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}},os=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Rr(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 t=this.head;this.head=t.next=new Rr(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Ni=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ct(s={}){return Kh(t=>{let r=t.shift();if(r==null)return{done:!0};if(r.error!=null)throw r.error;return{done:r.done===!0,value:r.value}},s)}function Kh(s,e){e=e??{};let t=e.onEnd,r=new os,n,i,o,a=st(),l=async()=>{try{return r.isEmpty()?o?{done:!0}:await new Promise((w,E)=>{i=S=>{i=null,r.push(S);try{w(s(r))}catch(c){E(c)}return n}}):s(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=st()})}},u=w=>i!=null?i(w):(r.push(w),n),p=w=>(r=new os,i!=null?i({error:w}):(r.push({error:w}),n)),m=w=>{if(o)return n;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:w})},x=w=>o?n:(o=!0,w!=null?p(w):u({done:!0})),y=()=>(r=new os,x(),{done:!0}),f=w=>(x(w),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:l,return:y,throw:f,push:m,end:x,get readableLength(){return r.size},onEmpty:async w=>{let E=w?.signal;if(E?.throwIfAborted(),r.isEmpty())return;let S,c;E!=null&&(S=new Promise((h,d)=>{c=()=>{d(new Ni)},E.addEventListener("abort",c)}));try{await Promise.race([a.promise,S])}finally{c!=null&&E!=null&&E?.removeEventListener("abort",c)}}},t==null)return n;let g=n;return n={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(w){return g.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:m,end(w){return g.end(w),t!=null&&(t(w),t=void 0),n},get readableLength(){return g.readableLength},onEmpty:w=>g.onEmpty(w)},n}function zh(s){return s.reason}async function Oi(s,e,t){if(e==null)return s;let r=t?.translateError??zh;if(e.aborted)return s.catch(()=>{}),Promise.reject(r(e));let n;try{return await Promise.race([s,new Promise((i,o)=>{n=()=>{o(r(e))},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Ui=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=st(),this.haveNext=st()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=st(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=st(),await Oi(this.readNext.promise,t?.signal,t)}};function rc(){return new Ui}function qh(s){return s[Symbol.asyncIterator]!=null}async function Gh(s,e,t){try{await Promise.all(s.map(async r=>{for await(let n of r)await e.push(n,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(r){await e.end(r,{signal:t}).catch(()=>{})}}async function*Hh(s){let e=new AbortController,t=rc();Gh(s,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Wh(s){for(let e of s)yield*e}function Vh(...s){let e=[];for(let t of s)qh(t)||e.push(t);return e.length===s.length?Wh(e):Hh(s)}var nc=Vh;function Ns(s,...e){if(s==null)throw new Error("Empty pipeline");if(Ki(s)){let r=s;s=()=>r.source}else if(oc(s)||ic(s)){let r=s;s=()=>r}let t=[s,...e];if(t.length>1&&Ki(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let r=1;r<t.length-1;r++)Ki(t[r])&&(t[r]=jh(t[r]));return $h(...t)}var $h=(...s)=>{let e;for(;s.length>0;)e=s.shift()(e);return e},ic=s=>s?.[Symbol.asyncIterator]!=null,oc=s=>s?.[Symbol.iterator]!=null,Ki=s=>s==null?!1:s.sink!=null&&s.source!=null,jh=s=>e=>{let t=s.sink(e);if(t?.then!=null){let r=Ct({objectMode:!0});t.then(()=>{r.end()},o=>{r.end(o)});let n,i=s.source;if(ic(i))n=async function*(){yield*i,r.end()};else if(oc(i))n=function*(){yield*i,r.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return nc(r,n())}return s.source};var ac={maxSubscriptions:5e3,maxMessages:5e3,maxIhaveMessageIDs:5e3,maxIwantMessageIDs:5e3,maxControlMessages:5e3,maxIdontwantMessageIDs:512,maxPeerInfos:16};var rt;(function(s){let e;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),c.subscribe!=null&&(h.uint32(8),h.bool(c.subscribe)),c.topic!=null&&(h.uint32(18),h.string(c.topic)),d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{b.subscribe=c.bool();break}case 2:{b.topic=c.string();break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{yield{field:`${d}.subscribe`,value:c.bool()};break}case 2:{yield{field:`${d}.topic`,value:c.string()};break}default:{c.skipType(_&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(e=s.SubOpts||(s.SubOpts={}));let t;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),c.from!=null&&(h.uint32(10),h.bytes(c.from)),c.data!=null&&(h.uint32(18),h.bytes(c.data)),c.seqno!=null&&(h.uint32(26),h.bytes(c.seqno)),c.topic!=null&&c.topic!==""&&(h.uint32(34),h.string(c.topic)),c.signature!=null&&(h.uint32(42),h.bytes(c.signature)),c.key!=null&&(h.uint32(50),h.bytes(c.key)),d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={topic:""},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{b.from=c.bytes();break}case 2:{b.data=c.bytes();break}case 3:{b.seqno=c.bytes();break}case 4:{b.topic=c.string();break}case 5:{b.signature=c.bytes();break}case 6:{b.key=c.bytes();break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{yield{field:`${d}.from`,value:c.bytes()};break}case 2:{yield{field:`${d}.data`,value:c.bytes()};break}case 3:{yield{field:`${d}.seqno`,value:c.bytes()};break}case 4:{yield{field:`${d}.topic`,value:c.string()};break}case 5:{yield{field:`${d}.signature`,value:c.bytes()};break}case 6:{yield{field:`${d}.key`,value:c.bytes()};break}default:{c.skipType(_&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(t=s.Message||(s.Message={}));let r;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),c.ihave!=null&&c.ihave.length>0)for(let b of c.ihave)h.uint32(10),s.ControlIHave.codec().encode(b,h);if(c.iwant!=null&&c.iwant.length>0)for(let b of c.iwant)h.uint32(18),s.ControlIWant.codec().encode(b,h);if(c.graft!=null&&c.graft.length>0)for(let b of c.graft)h.uint32(26),s.ControlGraft.codec().encode(b,h);if(c.prune!=null&&c.prune.length>0)for(let b of c.prune)h.uint32(34),s.ControlPrune.codec().encode(b,h);if(c.idontwant!=null&&c.idontwant.length>0)for(let b of c.idontwant)h.uint32(42),s.ControlIDontWant.codec().encode(b,h);d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={ihave:[],iwant:[],graft:[],prune:[],idontwant:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{if(d.limits?.ihave!=null&&b.ihave.length===d.limits.ihave)throw new Z('Decode error - repeated field "ihave" had too many elements');b.ihave.push(s.ControlIHave.codec().decode(c,c.uint32(),{limits:d.limits?.ihave$}));break}case 2:{if(d.limits?.iwant!=null&&b.iwant.length===d.limits.iwant)throw new Z('Decode error - repeated field "iwant" had too many elements');b.iwant.push(s.ControlIWant.codec().decode(c,c.uint32(),{limits:d.limits?.iwant$}));break}case 3:{if(d.limits?.graft!=null&&b.graft.length===d.limits.graft)throw new Z('Decode error - repeated field "graft" had too many elements');b.graft.push(s.ControlGraft.codec().decode(c,c.uint32(),{limits:d.limits?.graft$}));break}case 4:{if(d.limits?.prune!=null&&b.prune.length===d.limits.prune)throw new Z('Decode error - repeated field "prune" had too many elements');b.prune.push(s.ControlPrune.codec().decode(c,c.uint32(),{limits:d.limits?.prune$}));break}case 5:{if(d.limits?.idontwant!=null&&b.idontwant.length===d.limits.idontwant)throw new Z('Decode error - repeated field "idontwant" had too many elements');b.idontwant.push(s.ControlIDontWant.codec().decode(c,c.uint32(),{limits:d.limits?.idontwant$}));break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v={ihave:0,iwant:0,graft:0,prune:0,idontwant:0},_=h==null?c.len:c.pos+h;for(;c.pos<_;){let D=c.uint32();switch(D>>>3){case 1:{if(b.limits?.ihave!=null&&v.ihave===b.limits.ihave)throw new Z('Streaming decode error - repeated field "ihave" had too many elements');for(let P of s.ControlIHave.codec().stream(c,c.uint32(),`${d}.ihave[]`,{limits:b.limits?.ihave$}))yield{...P,index:v.ihave};v.ihave++;break}case 2:{if(b.limits?.iwant!=null&&v.iwant===b.limits.iwant)throw new Z('Streaming decode error - repeated field "iwant" had too many elements');for(let P of s.ControlIWant.codec().stream(c,c.uint32(),`${d}.iwant[]`,{limits:b.limits?.iwant$}))yield{...P,index:v.iwant};v.iwant++;break}case 3:{if(b.limits?.graft!=null&&v.graft===b.limits.graft)throw new Z('Streaming decode error - repeated field "graft" had too many elements');for(let P of s.ControlGraft.codec().stream(c,c.uint32(),`${d}.graft[]`,{limits:b.limits?.graft$}))yield{...P,index:v.graft};v.graft++;break}case 4:{if(b.limits?.prune!=null&&v.prune===b.limits.prune)throw new Z('Streaming decode error - repeated field "prune" had too many elements');for(let P of s.ControlPrune.codec().stream(c,c.uint32(),`${d}.prune[]`,{limits:b.limits?.prune$}))yield{...P,index:v.prune};v.prune++;break}case 5:{if(b.limits?.idontwant!=null&&v.idontwant===b.limits.idontwant)throw new Z('Streaming decode error - repeated field "idontwant" had too many elements');for(let P of s.ControlIDontWant.codec().stream(c,c.uint32(),`${d}.idontwant[]`,{limits:b.limits?.idontwant$}))yield{...P,index:v.idontwant};v.idontwant++;break}default:{c.skipType(D&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(r=s.ControlMessage||(s.ControlMessage={}));let n;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),c.topicID!=null&&(h.uint32(10),h.string(c.topicID)),c.messageIDs!=null&&c.messageIDs.length>0)for(let b of c.messageIDs)h.uint32(18),h.bytes(b);d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={messageIDs:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{b.topicID=c.string();break}case 2:{if(d.limits?.messageIDs!=null&&b.messageIDs.length===d.limits.messageIDs)throw new Z('Decode error - repeated field "messageIDs" had too many elements');b.messageIDs.push(c.bytes());break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v={messageIDs:0},_=h==null?c.len:c.pos+h;for(;c.pos<_;){let D=c.uint32();switch(D>>>3){case 1:{yield{field:`${d}.topicID`,value:c.string()};break}case 2:{if(b.limits?.messageIDs!=null&&v.messageIDs===b.limits.messageIDs)throw new Z('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:c.bytes()},v.messageIDs++;break}default:{c.skipType(D&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(n=s.ControlIHave||(s.ControlIHave={}));let i;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),c.messageIDs!=null&&c.messageIDs.length>0)for(let b of c.messageIDs)h.uint32(10),h.bytes(b);d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={messageIDs:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{if(d.limits?.messageIDs!=null&&b.messageIDs.length===d.limits.messageIDs)throw new Z('Decode error - repeated field "messageIDs" had too many elements');b.messageIDs.push(c.bytes());break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v={messageIDs:0},_=h==null?c.len:c.pos+h;for(;c.pos<_;){let D=c.uint32();switch(D>>>3){case 1:{if(b.limits?.messageIDs!=null&&v.messageIDs===b.limits.messageIDs)throw new Z('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:c.bytes()},v.messageIDs++;break}default:{c.skipType(D&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(i=s.ControlIWant||(s.ControlIWant={}));let o;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),c.topicID!=null&&(h.uint32(10),h.string(c.topicID)),d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();_>>>3===1?b.topicID=c.string():c.skipType(_&7)}return b},function*(c,h,d,b={}){let v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();_>>>3===1?yield{field:`${d}.topicID`,value:c.string()}:c.skipType(_&7)}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(o=s.ControlGraft||(s.ControlGraft={}));let a;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),c.topicID!=null&&(h.uint32(10),h.string(c.topicID)),c.peers!=null&&c.peers.length>0)for(let b of c.peers)h.uint32(18),s.PeerInfo.codec().encode(b,h);c.backoff!=null&&(h.uint32(24),h.uint64Number(c.backoff)),d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={peers:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{b.topicID=c.string();break}case 2:{if(d.limits?.peers!=null&&b.peers.length===d.limits.peers)throw new Z('Decode error - repeated field "peers" had too many elements');b.peers.push(s.PeerInfo.codec().decode(c,c.uint32(),{limits:d.limits?.peers$}));break}case 3:{b.backoff=c.uint64Number();break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v={peers:0},_=h==null?c.len:c.pos+h;for(;c.pos<_;){let D=c.uint32();switch(D>>>3){case 1:{yield{field:`${d}.topicID`,value:c.string()};break}case 2:{if(b.limits?.peers!=null&&v.peers===b.limits.peers)throw new Z('Streaming decode error - repeated field "peers" had too many elements');for(let P of s.PeerInfo.codec().stream(c,c.uint32(),`${d}.peers[]`,{limits:b.limits?.peers$}))yield{...P,index:v.peers};v.peers++;break}case 3:{yield{field:`${d}.backoff`,value:c.uint64Number()};break}default:{c.skipType(D&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(a=s.ControlPrune||(s.ControlPrune={}));let l;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),c.peerID!=null&&(h.uint32(10),h.bytes(c.peerID)),c.signedPeerRecord!=null&&(h.uint32(18),h.bytes(c.signedPeerRecord)),d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{b.peerID=c.bytes();break}case 2:{b.signedPeerRecord=c.bytes();break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{yield{field:`${d}.peerID`,value:c.bytes()};break}case 2:{yield{field:`${d}.signedPeerRecord`,value:c.bytes()};break}default:{c.skipType(_&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(l=s.PeerInfo||(s.PeerInfo={}));let u;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),c.messageIDs!=null&&c.messageIDs.length>0)for(let b of c.messageIDs)h.uint32(10),h.bytes(b);d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={messageIDs:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{if(d.limits?.messageIDs!=null&&b.messageIDs.length===d.limits.messageIDs)throw new Z('Decode error - repeated field "messageIDs" had too many elements');b.messageIDs.push(c.bytes());break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v={messageIDs:0},_=h==null?c.len:c.pos+h;for(;c.pos<_;){let D=c.uint32();switch(D>>>3){case 1:{if(b.limits?.messageIDs!=null&&v.messageIDs===b.limits.messageIDs)throw new Z('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:c.bytes()},v.messageIDs++;break}default:{c.skipType(D&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(u=s.ControlIDontWant||(s.ControlIDontWant={}));let p;s.codec=()=>(p==null&&(p=ve((f,g,w={})=>{if(w.lengthDelimited!==!1&&g.fork(),f.subscriptions!=null&&f.subscriptions.length>0)for(let E of f.subscriptions)g.uint32(10),s.SubOpts.codec().encode(E,g);if(f.messages!=null&&f.messages.length>0)for(let E of f.messages)g.uint32(18),s.Message.codec().encode(E,g);f.control!=null&&(g.uint32(26),s.ControlMessage.codec().encode(f.control,g)),w.lengthDelimited!==!1&&g.ldelim()},(f,g,w={})=>{let E={subscriptions:[],messages:[]},S=g==null?f.len:f.pos+g;for(;f.pos<S;){let c=f.uint32();switch(c>>>3){case 1:{if(w.limits?.subscriptions!=null&&E.subscriptions.length===w.limits.subscriptions)throw new Z('Decode error - repeated field "subscriptions" had too many elements');E.subscriptions.push(s.SubOpts.codec().decode(f,f.uint32(),{limits:w.limits?.subscriptions$}));break}case 2:{if(w.limits?.messages!=null&&E.messages.length===w.limits.messages)throw new Z('Decode error - repeated field "messages" had too many elements');E.messages.push(s.Message.codec().decode(f,f.uint32(),{limits:w.limits?.messages$}));break}case 3:{E.control=s.ControlMessage.codec().decode(f,f.uint32(),{limits:w.limits?.control});break}default:{f.skipType(c&7);break}}}return E},function*(f,g,w,E={}){let S={subscriptions:0,messages:0},c=g==null?f.len:f.pos+g;for(;f.pos<c;){let h=f.uint32();switch(h>>>3){case 1:{if(E.limits?.subscriptions!=null&&S.subscriptions===E.limits.subscriptions)throw new Z('Streaming decode error - repeated field "subscriptions" had too many elements');for(let d of s.SubOpts.codec().stream(f,f.uint32(),`${w}.subscriptions[]`,{limits:E.limits?.subscriptions$}))yield{...d,index:S.subscriptions};S.subscriptions++;break}case 2:{if(E.limits?.messages!=null&&S.messages===E.limits.messages)throw new Z('Streaming decode error - repeated field "messages" had too many elements');for(let d of s.Message.codec().stream(f,f.uint32(),`${w}.messages[]`,{limits:E.limits?.messages$}))yield{...d,index:S.messages};S.messages++;break}case 3:{yield*s.ControlMessage.codec().stream(f,f.uint32(),`${w}.control`,{limits:E.limits?.control});break}default:{f.skipType(h&7);break}}}})),p);function m(f){return we(f,s.codec())}s.encode=m;function x(f,g){return ye(f,s.codec(),g)}s.decode=x;function y(f,g){return xe(f,s.codec(),g)}s.stream=y})(rt||(rt={}));var Lr=class{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,r){this.gossip=e,this.msgIdToStrFn=r;for(let n=0;n<t;n++)this.history[n]=[]}get size(){return this.msgs.size}put(e,t,r=!1){let{msgIdStr:n}=e;return this.msgs.has(n)?!1:(this.msgs.set(n,{message:t,validated:r,originatingPeers:new Set,iwantCounts:new Map}),this.history[0].push({...e,topic:t.topic}),r||this.notValidatedCount++,!0)}observeDuplicate(e,t){let r=this.msgs.get(e);r!=null&&!r.validated&&r.originatingPeers.add(t)}get(e){return this.msgs.get(this.msgIdToStrFn(e))?.message}getWithIWantCount(e,t){let r=this.msgs.get(e);if(r==null)return null;let n=(r.iwantCounts.get(t)??0)+1;return r.iwantCounts.set(t,n),{msg:r.message,count:n}}getGossipIDs(e){let t=new Map;for(let r=0;r<this.gossip;r++)this.history[r].forEach(n=>{if((this.msgs.get(n.msgIdStr)?.validated??!1)&&e.has(n.topic)){let o=t.get(n.topic);o==null&&(o=[],t.set(n.topic,o)),o.push(n.msgId)}});return t}validate(e){let t=this.msgs.get(e);if(t==null)return null;t.validated||this.notValidatedCount--;let{message:r,originatingPeers:n}=t;return t.validated=!0,t.originatingPeers=new Set,{message:r,originatingPeers:n}}shift(){this.history[this.history.length-1].forEach(t=>{let r=this.msgs.get(t.msgIdStr);r!=null&&(this.msgs.delete(t.msgIdStr),r.validated||this.notValidatedCount--)}),this.history.pop(),this.history.unshift([])}remove(e){let t=this.msgs.get(e);return t==null?null:(this.msgs.delete(e),t)}};var cc;(function(s){s.StrictSign="StrictSign",s.StrictNoSign="StrictNoSign"})(cc||(cc={}));var yt;(function(s){s[s.Signing=0]="Signing",s[s.Anonymous=1]="Anonymous"})(yt||(yt={}));var Ee;(function(s){s.Error="error",s.Ignore="ignore",s.Reject="reject",s.Blacklisted="blacklisted"})(Ee||(Ee={}));var le;(function(s){s.InvalidSignature="invalid_signature",s.InvalidSeqno="invalid_seqno",s.InvalidPeerId="invalid_peerid",s.SignaturePresent="signature_present",s.SeqnoPresent="seqno_present",s.FromPresent="from_present",s.TransformFailed="transform_failed"})(le||(le={}));var pe;(function(s){s.duplicate="duplicate",s.invalid="invalid",s.valid="valid"})(pe||(pe={}));function zi(s){switch(s){case me.Ignore:return Ee.Ignore;case me.Reject:return Ee.Reject;default:throw new Error("Unreachable")}}var lc;(function(s){s.forward="forward",s.publish="publish"})(lc||(lc={}));var ge;(function(s){s.Fanout="fanout",s.Random="random",s.Subscribed="subscribed",s.Outbound="outbound",s.NotEnough="not_enough",s.Opportunistic="opportunistic"})(ge||(ge={}));var Ke;(function(s){s.Dc="disconnected",s.BadScore="bad_score",s.Prune="prune",s.Excess="excess"})(Ke||(Ke={}));var cs;(function(s){s.GraftBackoff="graft_backoff",s.BrokenPromise="broken_promise",s.MessageDeficit="message_deficit",s.IPColocation="IP_colocation"})(cs||(cs={}));var ls;(function(s){s.LowScore="low_score",s.MaxIhave="max_ihave",s.MaxIasked="max_iasked"})(ls||(ls={}));var as;(function(s){s.graylist="graylist",s.publish="publish",s.gossip="gossip",s.mesh="mesh"})(as||(as={}));function uc(s,e,t){return{protocolsEnabled:s.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:s.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:s.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:s.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEventsFanout:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_fanout_total",help:"Number of times we include peers in a topic mesh for fanout reasons",labelNames:["topic"]}),meshPeerInclusionEventsRandom:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_random_total",help:"Number of times we include peers in a topic mesh for random reasons",labelNames:["topic"]}),meshPeerInclusionEventsSubscribed:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_subscribed_total",help:"Number of times we include peers in a topic mesh for subscribed reasons",labelNames:["topic"]}),meshPeerInclusionEventsOutbound:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_outbound_total",help:"Number of times we include peers in a topic mesh for outbound reasons",labelNames:["topic"]}),meshPeerInclusionEventsNotEnough:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_not_enough_total",help:"Number of times we include peers in a topic mesh for not_enough reasons",labelNames:["topic"]}),meshPeerInclusionEventsOpportunistic:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_opportunistic_total",help:"Number of times we include peers in a topic mesh for opportunistic reasons",labelNames:["topic"]}),meshPeerInclusionEventsUnknown:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_unknown_total",help:"Number of times we include peers in a topic mesh for unknown reasons",labelNames:["topic"]}),meshPeerChurnEventsDisconnected:s.gauge({name:"gossipsub_peer_churn_events_disconnected_total",help:"Number of times we remove peers in a topic mesh for disconnected reasons",labelNames:["topic"]}),meshPeerChurnEventsBadScore:s.gauge({name:"gossipsub_peer_churn_events_bad_score_total",help:"Number of times we remove peers in a topic mesh for bad_score reasons",labelNames:["topic"]}),meshPeerChurnEventsPrune:s.gauge({name:"gossipsub_peer_churn_events_prune_total",help:"Number of times we remove peers in a topic mesh for prune reasons",labelNames:["topic"]}),meshPeerChurnEventsExcess:s.gauge({name:"gossipsub_peer_churn_events_excess_total",help:"Number of times we remove peers in a topic mesh for excess reasons",labelNames:["topic"]}),meshPeerChurnEventsUnknown:s.gauge({name:"gossipsub_peer_churn_events_unknown_total",help:"Number of times we remove peers in a topic mesh for unknown reasons",labelNames:["topic"]}),peersPerProtocol:s.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:s.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:s.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),acceptedMessagesTotal:s.gauge({name:"gossipsub_accepted_messages_total",help:"Total accepted messages for each topic",labelNames:["topic"]}),ignoredMessagesTotal:s.gauge({name:"gossipsub_ignored_messages_total",help:"Total ignored messages for each topic",labelNames:["topic"]}),rejectedMessagesTotal:s.gauge({name:"gossipsub_rejected_messages_total",help:"Total rejected messages for each topic",labelNames:["topic"]}),unknownValidationResultsTotal:s.gauge({name:"gossipsub_unknown_validation_results_total",help:"Total unknown validation results for each topic",labelNames:["topic"]}),asyncValidationMcacheHit:s.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),asyncValidationDelayFromFirstSeenSec:s.histogram({name:"gossipsub_async_validation_delay_from_first_seen",help:"Async validation report delay from first seen in second",buckets:[.01,.03,.1,.3,1,3,10]}),asyncValidationUnknownFirstSeen:s.gauge({name:"gossipsub_async_validation_unknown_first_seen_count_total",help:"Async validation report unknown first seen value for message"}),peerReadStreamError:s.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:s.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:s.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:s.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:s.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:s.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:s.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:s.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:s.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:s.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:s.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:s.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:s.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:s.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:s.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:s.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:s.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:s.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:s.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:s.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:s.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:s.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),rpcSentIDontWant:s.gauge({name:"gossipsub_rpc_sent_idontwant_total",help:"RPC sent"}),msgPublishCount:s.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeersByTopic:s.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),directPeersPublishedTotal:s.gauge({name:"gossipsub_direct_peers_published_total",help:"Total direct peers that we publish a msg to",labelNames:["topic"]}),floodsubPeersPublishedTotal:s.gauge({name:"gossipsub_floodsub_peers_published_total",help:"Total floodsub peers that we publish a msg to",labelNames:["topic"]}),meshPeersPublishedTotal:s.gauge({name:"gossipsub_mesh_peers_published_total",help:"Total mesh peers that we publish a msg to",labelNames:["topic"]}),fanoutPeersPublishedTotal:s.gauge({name:"gossipsub_fanout_peers_published_total",help:"Total fanout peers that we publish a msg to",labelNames:["topic"]}),msgPublishBytes:s.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgPublishTime:s.histogram({name:"gossipsub_msg_publish_seconds",help:"Total time in seconds to publish a message",buckets:[.001,.002,.005,.01,.1,.5,1],labelNames:["topic"]}),msgForwardCount:s.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:s.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:s.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:s.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),prevalidationInvalidTotal:s.gauge({name:"gossipsub_pre_validation_invalid_total",help:"Total count of invalid messages received",labelNames:["topic"]}),prevalidationValidTotal:s.gauge({name:"gossipsub_pre_validation_valid_total",help:"Total count of valid messages received",labelNames:["topic"]}),prevalidationDuplicateTotal:s.gauge({name:"gossipsub_pre_validation_duplicate_total",help:"Total count of duplicate messages received",labelNames:["topic"]}),prevalidationUnknownTotal:s.gauge({name:"gossipsub_pre_validation_unknown_status_total",help:"Total count of unknown_status messages received",labelNames:["topic"]}),msgReceivedInvalid:s.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["error"]}),msgReceivedInvalidByTopic:s.gauge({name:"gossipsub_msg_received_invalid_by_topic_total",help:"Tracks specific invalid message by topic",labelNames:["topic"]}),duplicateMsgDeliveryDelay:s.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*t.maxMeshMessageDeliveriesWindowSec,.5*t.maxMeshMessageDeliveriesWindowSec,Number(t.maxMeshMessageDeliveriesWindowSec),2*t.maxMeshMessageDeliveriesWindowSec,4*t.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:s.gauge({name:"gossisub_duplicate_msg_late_delivery_total",help:"Total count of late duplicate message delivery by topic, which triggers P3 penalty",labelNames:["topic"]}),duplicateMsgIgnored:s.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:s.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:s.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:s.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:s.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:s.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores"}),scoreWeights:s.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:s.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:s.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:s.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*t.behaviourPenaltyThreshold,.5*t.behaviourPenaltyThreshold,Number(t.behaviourPenaltyThreshold),2*t.behaviourPenaltyThreshold,4*t.behaviourPenaltyThreshold]}),ihaveRcvIgnored:s.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:s.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:s.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:s.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:s.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),idontwantRcvMsgids:s.gauge({name:"gossipsub_idontwant_rcv_msgids_total",help:"Total received IDONTWANT messages"}),idontwantRcvDonthaveMsgids:s.gauge({name:"gossipsub_idontwant_rcv_dont_have_msgids_total",help:"Total received IDONTWANT messageIDs that we do not have in mcache"}),iwantPromiseStarted:s.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:s.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:s.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:s.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:s.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:s.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:s.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*t.gossipPromiseExpireSec,Number(t.gossipPromiseExpireSec),2*t.gossipPromiseExpireSec,4*t.gossipPromiseExpireSec]}),iwantPromiseUntracked:s.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),connectedPeersBackoffSec:s.histogram({name:"gossipsub_connected_peers_backoff_seconds",help:"Backoff time in seconds",buckets:[1,2,4,10,20,60,120]}),cacheSize:s.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:s.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:s.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:s.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:s.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:e,toTopic(r){return this.topicStrToLabel.get(r)??r},onJoin(r){this.topicSubscriptionStatus.set({topicStr:r},1),this.meshPeerCounts.set({topicStr:r},0)},onLeave(r){this.topicSubscriptionStatus.set({topicStr:r},0),this.meshPeerCounts.set({topicStr:r},0)},onAddToMesh(r,n,i){let o=this.toTopic(r);switch(n){case ge.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:o},i);break;case ge.Random:this.meshPeerInclusionEventsRandom.inc({topic:o},i);break;case ge.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:o},i);break;case ge.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:o},i);break;case ge.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:o},i);break;case ge.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:o},i);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:o},i);break}},onRemoveFromMesh(r,n,i){let o=this.toTopic(r);switch(n){case Ke.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:o},i);break;case Ke.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:o},i);break;case Ke.Prune:this.meshPeerChurnEventsPrune.inc({topic:o},i);break;case Ke.Excess:this.meshPeerChurnEventsExcess.inc({topic:o},i);break;default:this.meshPeerChurnEventsUnknown.inc({topic:o},i);break}},onReportValidation(r,n,i){if(this.asyncValidationMcacheHit.inc({hit:r!=null?"hit":"miss"}),r!=null){let o=this.toTopic(r.message.topic);switch(n){case me.Accept:this.acceptedMessagesTotal.inc({topic:o});break;case me.Ignore:this.ignoredMessagesTotal.inc({topic:o});break;case me.Reject:this.rejectedMessagesTotal.inc({topic:o});break;default:this.unknownValidationResultsTotal.inc({topic:o});break}}i!=null?this.asyncValidationDelayFromFirstSeenSec.observe((Date.now()-i)/1e3):this.asyncValidationUnknownFirstSeen.inc()},onScorePenalty(r){this.scoringPenalties.inc({penalty:r},1)},onIhaveRcv(r,n,i){let o=this.toTopic(r);this.ihaveRcvMsgids.inc({topic:o},n),this.ihaveRcvNotSeenMsgids.inc({topic:o},i)},onIwantRcv(r,n){for(let[i,o]of r){let a=this.toTopic(i);this.iwantRcvMsgids.inc({topic:a},o)}this.iwantRcvDonthaveMsgids.inc(n)},onIdontwantRcv(r,n){this.idontwantRcvMsgids.inc(r),this.idontwantRcvDonthaveMsgids.inc(n)},onForwardMsg(r,n){let i=this.toTopic(r);this.msgForwardCount.inc({topic:i},1),this.msgForwardPeers.inc({topic:i},n)},onPublishMsg(r,n,i,o,a){let l=this.toTopic(r);this.msgPublishCount.inc({topic:l},1),this.msgPublishBytes.inc({topic:l},i*o),this.msgPublishPeersByTopic.inc({topic:l},i),this.directPeersPublishedTotal.inc({topic:l},n.direct),this.floodsubPeersPublishedTotal.inc({topic:l},n.floodsub),this.meshPeersPublishedTotal.inc({topic:l},n.mesh),this.fanoutPeersPublishedTotal.inc({topic:l},n.fanout),this.msgPublishTime.observe({topic:l},a/1e3)},onMsgRecvPreValidation(r){let n=this.toTopic(r);this.msgReceivedPreValidation.inc({topic:n},1)},onMsgRecvError(r){let n=this.toTopic(r);this.msgReceivedError.inc({topic:n},1)},onPrevalidationResult(r,n){let i=this.toTopic(r);switch(n){case pe.duplicate:this.prevalidationDuplicateTotal.inc({topic:i});break;case pe.invalid:this.prevalidationInvalidTotal.inc({topic:i});break;case pe.valid:this.prevalidationValidTotal.inc({topic:i});break;default:this.prevalidationUnknownTotal.inc({topic:i});break}},onMsgRecvInvalid(r,n){let i=this.toTopic(r),o=n.reason===Ee.Error?n.error:n.reason;this.msgReceivedInvalid.inc({error:o},1),this.msgReceivedInvalidByTopic.inc({topic:i},1)},onDuplicateMsgDelivery(r,n,i){let o=this.toTopic(r);this.duplicateMsgDeliveryDelay.observe({topic:o},n/1e3),i&&this.duplicateMsgLateDelivery.inc({topic:o},1)},onPublishDuplicateMsg(r){let n=this.toTopic(r);this.duplicateMsgIgnored.inc({topic:n},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(r,n){this.rpcRecvBytes.inc(n),this.rpcRecvCount.inc(1),r.subscriptions!=null&&this.rpcRecvSubscription.inc(r.subscriptions.length),r.messages!=null&&this.rpcRecvMessage.inc(r.messages.length),r.control!=null&&(this.rpcRecvControl.inc(1),r.control.ihave!=null&&this.rpcRecvIHave.inc(r.control.ihave.length),r.control.iwant!=null&&this.rpcRecvIWant.inc(r.control.iwant.length),r.control.graft!=null&&this.rpcRecvGraft.inc(r.control.graft.length),r.control.prune!=null&&this.rpcRecvPrune.inc(r.control.prune.length))},onRpcSent(r,n){if(this.rpcSentBytes.inc(n),this.rpcSentCount.inc(1),r.subscriptions!=null&&this.rpcSentSubscription.inc(r.subscriptions.length),r.messages!=null&&this.rpcSentMessage.inc(r.messages.length),r.control!=null){let i=r.control.ihave?.length??0,o=r.control.iwant?.length??0,a=r.control.graft?.length??0,l=r.control.prune?.length??0,u=r.control.idontwant?.length??0;i>0&&this.rpcSentIHave.inc(i),o>0&&this.rpcSentIWant.inc(o),a>0&&this.rpcSentGraft.inc(a),l>0&&this.rpcSentPrune.inc(l),u>0&&this.rpcSentIDontWant.inc(u),(i>0||o>0||a>0||l>0||u>0)&&this.rpcSentControl.inc(1)}},registerScores(r,n){let i=0,o=0,a=0,l=0;for(let u of r)u>=n.graylistThreshold&&i++,u>=n.publishThreshold&&o++,u>=n.gossipThreshold&&a++,u>=0&&l++;this.peersByScoreThreshold.set({threshold:as.graylist},i),this.peersByScoreThreshold.set({threshold:as.publish},o),this.peersByScoreThreshold.set({threshold:as.gossip},a),this.peersByScoreThreshold.set({threshold:as.mesh},l),this.score.set(r)},registerScoreWeights(r){for(let[n,i]of r.byTopic)this.scoreWeights.set({topic:n,p:"p1"},i.p1w),this.scoreWeights.set({topic:n,p:"p2"},i.p2w),this.scoreWeights.set({topic:n,p:"p3"},i.p3w),this.scoreWeights.set({topic:n,p:"p3b"},i.p3bw),this.scoreWeights.set({topic:n,p:"p4"},i.p4w);this.scoreWeights.set({p:"p5"},r.p5w),this.scoreWeights.set({p:"p6"},r.p6w),this.scoreWeights.set({p:"p7"},r.p7w)},registerScorePerMesh(r,n){let i=new Map;r.forEach((o,a)=>{let l=this.topicStrToLabel.get(a)??"unknown",u=i.get(l);u==null&&(u=new Set,i.set(l,u)),o.forEach(p=>u?.add(p))});for(let[o,a]of i){let l=[];a.forEach(u=>{l.push(n.get(u)??0)}),this.scorePerMesh.set({topic:o},l)}}}}var V=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var Zh={topics:{},topicScoreCap:10,appSpecificScore:()=>0,appSpecificWeight:10,IPColocationFactorWeight:-5,IPColocationFactorThreshold:10,IPColocationFactorWhitelist:new Set,behaviourPenaltyWeight:-10,behaviourPenaltyThreshold:0,behaviourPenaltyDecay:.2,decayInterval:1e3,decayToZero:.1,retainScore:3600*1e3},Yh={topicWeight:.5,timeInMeshWeight:1,timeInMeshQuantum:1,timeInMeshCap:3600,firstMessageDeliveriesWeight:1,firstMessageDeliveriesDecay:.5,firstMessageDeliveriesCap:2e3,meshMessageDeliveriesWeight:-1,meshMessageDeliveriesDecay:.5,meshMessageDeliveriesCap:100,meshMessageDeliveriesThreshold:20,meshMessageDeliveriesWindow:10,meshMessageDeliveriesActivation:5e3,meshFailurePenaltyWeight:-1,meshFailurePenaltyDecay:.5,invalidMessageDeliveriesWeight:-1,invalidMessageDeliveriesDecay:.3};function hc(s={}){return{...Zh,...s,topics:s.topics!=null?Object.entries(s.topics).reduce((e,[t,r])=>(e[t]=Xh(r),e),{}):{}}}function Xh(s={}){return{...Yh,...s}}function fc(s){for(let[e,t]of Object.entries(s.topics))try{Jh(t)}catch(r){throw new V(`invalid score parameters for topic ${e}: ${r.message}`)}if(s.topicScoreCap<0)throw new V("invalid topic score cap; must be positive (or 0 for no cap)");if(s.appSpecificScore===null||s.appSpecificScore===void 0)throw new V("missing application specific score function");if(s.IPColocationFactorWeight>0)throw new V("invalid IPColocationFactorWeight; must be negative (or 0 to disable)");if(s.IPColocationFactorWeight!==0&&s.IPColocationFactorThreshold<1)throw new V("invalid IPColocationFactorThreshold; must be at least 1");if(s.behaviourPenaltyWeight>0)throw new V("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)");if(s.behaviourPenaltyWeight!==0&&(s.behaviourPenaltyDecay<=0||s.behaviourPenaltyDecay>=1))throw new V("invalid BehaviourPenaltyDecay; must be between 0 and 1");if(s.decayInterval<1e3)throw new V("invalid DecayInterval; must be at least 1s");if(s.decayToZero<=0||s.decayToZero>=1)throw new V("invalid DecayToZero; must be between 0 and 1")}function Jh(s){if(s.topicWeight<0)throw new V("invalid topic weight; must be >= 0");if(s.timeInMeshQuantum===0)throw new V("invalid TimeInMeshQuantum; must be non zero");if(s.timeInMeshWeight<0)throw new V("invalid TimeInMeshWeight; must be positive (or 0 to disable)");if(s.timeInMeshWeight!==0&&s.timeInMeshQuantum<=0)throw new V("invalid TimeInMeshQuantum; must be positive");if(s.timeInMeshWeight!==0&&s.timeInMeshCap<=0)throw new V("invalid TimeInMeshCap; must be positive");if(s.firstMessageDeliveriesWeight<0)throw new V("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)");if(s.firstMessageDeliveriesWeight!==0&&(s.firstMessageDeliveriesDecay<=0||s.firstMessageDeliveriesDecay>=1))throw new V("invalid FirstMessageDeliveriesDecay; must be between 0 and 1");if(s.firstMessageDeliveriesWeight!==0&&s.firstMessageDeliveriesCap<=0)throw new V("invalid FirstMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight>0)throw new V("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.meshMessageDeliveriesWeight!==0&&(s.meshMessageDeliveriesDecay<=0||s.meshMessageDeliveriesDecay>=1))throw new V("invalid MeshMessageDeliveriesDecay; must be between 0 and 1");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesCap<=0)throw new V("invalid MeshMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesThreshold<=0)throw new V("invalid MeshMessageDeliveriesThreshold; must be positive");if(s.meshMessageDeliveriesWindow<0)throw new V("invalid MeshMessageDeliveriesWindow; must be non-negative");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesActivation<1e3)throw new V("invalid MeshMessageDeliveriesActivation; must be at least 1s");if(s.meshFailurePenaltyWeight>0)throw new V("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)");if(s.meshFailurePenaltyWeight!==0&&(s.meshFailurePenaltyDecay<=0||s.meshFailurePenaltyDecay>=1))throw new V("invalid MeshFailurePenaltyDecay; must be between 0 and 1");if(s.invalidMessageDeliveriesWeight>0)throw new V("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.invalidMessageDeliveriesDecay<=0||s.invalidMessageDeliveriesDecay>=1)throw new V("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1")}var Qh={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function dc(s={}){return{...Qh,...s}}function Fr(s,e,t=()=>!0){let r=new Set;if(e<=0)return r;for(let n of s){if(r.size>=e)break;t(n)&&(r.add(n),s.delete(n))}return r}function pc(s,e){return Fr(s,e,()=>!0)}var Cr=class extends Map{getDefault;constructor(e){super(),this.getDefault=e}getOrDefault(e){let t=super.get(e);return t===void 0&&(t=this.getDefault(),this.set(e,t)),t}};function mc(s,e,t,r){let n=0;Object.entries(e.topics).forEach(([o,a])=>{let l=t.topics[o];if(l===void 0)return;let u=0;if(a.inMesh){let y=a.meshTime/l.timeInMeshQuantum;y>l.timeInMeshCap&&(y=l.timeInMeshCap),u+=y*l.timeInMeshWeight}let p=a.firstMessageDeliveries;if(p>l.firstMessageDeliveriesCap&&(p=l.firstMessageDeliveriesCap),u+=p*l.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries<l.meshMessageDeliveriesThreshold){let y=l.meshMessageDeliveriesThreshold-a.meshMessageDeliveries,f=y*y;u+=f*l.meshMessageDeliveriesWeight}let m=a.meshFailurePenalty;u+=m*l.meshFailurePenaltyWeight;let x=a.invalidMessageDeliveries*a.invalidMessageDeliveries;u+=x*l.invalidMessageDeliveriesWeight,n+=u*l.topicWeight}),t.topicScoreCap>0&&n>t.topicScoreCap&&(n=t.topicScoreCap);let i=t.appSpecificScore(s);if(n+=i*t.appSpecificWeight,e.knownIPs.forEach(o=>{if(t.IPColocationFactorWhitelist.has(o))return;let a=r.get(o),l=a!=null?a.size:0;if(l>t.IPColocationFactorThreshold){let u=l-t.IPColocationFactorThreshold,p=u*u;n+=p*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let o=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=o*o;n+=a*t.behaviourPenaltyWeight}return n}var yc=Gc(bc(),1);var Se;(function(s){s[s.unknown=0]="unknown",s[s.valid=1]="valid",s[s.invalid=2]="invalid",s[s.ignored=3]="ignored"})(Se||(Se={}));var Nr=class{records;queue;constructor(){this.records=new Map,this.queue=new yc.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:Se.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let r={msgId:e,expire:Date.now()+12e4};return this.queue.push(r),t}gc(){let e=Date.now(),t=this.queue.peekFront();for(;t!=null&&t.expire<e;)this.records.delete(t.msgId),this.queue.shift(),t=this.queue.peekFront()}clear(){this.records.clear(),this.queue.clear()}};var Or=class{params;metrics;peerStats=new Map;peerIPs=new Cr(()=>new Set);scoreCache=new Map;deliveryRecords=new Nr;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,r,n){this.params=e,this.metrics=t,fc(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??mc,this.log=r.forComponent("libp2p:gossipsub:score")}get size(){return this.peerStats.size}start(){if(this._backgroundInterval!=null){this.log("Peer score already running");return}this._backgroundInterval=setInterval(()=>{this.background()},this.params.decayInterval),this.log("started")}stop(){if(this._backgroundInterval==null){this.log("Peer score already stopped");return}clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),this.log("stopped")}background(){this.refreshScores(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map(([e,t])=>[e,t]))}messageFirstSeenTimestampMs(e){let t=this.deliveryRecords.getRecord(e);return t!=null?t.firstSeenTsMs:null}refreshScores(){let e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach((r,n)=>{if(!r.connected){e>r.expire&&(this.removeIPsForPeer(n,r.knownIPs),this.peerStats.delete(n),this.scoreCache.delete(n));return}Object.entries(r.topics).forEach(([i,o])=>{let a=this.params.topics[i];a!==void 0&&(o.firstMessageDeliveries*=a.firstMessageDeliveriesDecay,o.firstMessageDeliveries<t&&(o.firstMessageDeliveries=0),o.meshMessageDeliveries*=a.meshMessageDeliveriesDecay,o.meshMessageDeliveries<t&&(o.meshMessageDeliveries=0),o.meshFailurePenalty*=a.meshFailurePenaltyDecay,o.meshFailurePenalty<t&&(o.meshFailurePenalty=0),o.invalidMessageDeliveries*=a.invalidMessageDeliveriesDecay,o.invalidMessageDeliveries<t&&(o.invalidMessageDeliveries=0),o.inMesh&&(o.meshTime=e-o.graftTime,o.meshTime>a.meshMessageDeliveriesActivation&&(o.meshMessageDeliveriesActive=!0)))}),r.behaviourPenalty*=this.params.behaviourPenaltyDecay,r.behaviourPenalty<t&&(r.behaviourPenalty=0)})}score(e){this.metrics?.scoreFnCalls.inc();let t=this.peerStats.get(e);if(t==null)return 0;let r=Date.now(),n=this.scoreCache.get(e);if(n!=null&&n.cacheUntil>r)return n.score;this.metrics?.scoreFnRuns.inc();let i=this.computeScore(e,t,this.params,this.peerIPs),o=r+this.scoreCacheValidityMs;return n!=null?(this.metrics?.scoreCachedDelta.observe(Math.abs(i-n.score)),n.score=i,n.cacheUntil=o):this.scoreCache.set(e,{score:i,cacheUntil:o}),i}addPenalty(e,t,r){let n=this.peerStats.get(e);n!=null&&(n.behaviourPenalty+=t,this.metrics?.onScorePenalty(r))}addPeer(e){let t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){let r=this.peerStats.get(e);r?.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){let r=this.peerStats.get(e);r?.knownIPs.delete(t);let n=this.peerIPs.get(t);n!=null&&(n.delete(e),n.size===0&&this.peerIPs.delete(t))}removePeer(e){let t=this.peerStats.get(e);if(t!=null){if(this.score(e)>0){this.removeIPsForPeer(e,t.knownIPs),this.peerStats.delete(e);return}Object.entries(t.topics).forEach(([r,n])=>{n.firstMessageDeliveries=0;let i=this.params.topics[r].meshMessageDeliveriesThreshold;if(n.inMesh&&n.meshMessageDeliveriesActive&&n.meshMessageDeliveries<i){let o=i-n.meshMessageDeliveries;n.meshFailurePenalty+=o*o}n.inMesh=!1,n.meshMessageDeliveriesActive=!1}),t.connected=!1,t.expire=Date.now()+this.params.retainScore}}graft(e,t){let r=this.peerStats.get(e);if(r!=null){let n=this.getPtopicStats(r,t);n!=null&&(n.inMesh=!0,n.graftTime=Date.now(),n.meshTime=0,n.meshMessageDeliveriesActive=!1)}}prune(e,t){let r=this.peerStats.get(e);if(r!=null){let n=this.getPtopicStats(r,t);if(n!=null){let i=this.params.topics[t].meshMessageDeliveriesThreshold;if(n.meshMessageDeliveriesActive&&n.meshMessageDeliveries<i){let o=i-n.meshMessageDeliveries;n.meshFailurePenalty+=o*o}n.meshMessageDeliveriesActive=!1,n.inMesh=!1}}}validateMessage(e){this.deliveryRecords.ensureRecord(e)}deliverMessage(e,t,r){this.markFirstMessageDelivery(e,r);let n=this.deliveryRecords.ensureRecord(t),i=Date.now();if(n.status!==Se.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,i-n.firstSeenTsMs,Se[n.status]);return}n.status=Se.valid,n.validated=i,n.peers.forEach(o=>{o!==e.toString()&&this.markDuplicateMessageDelivery(o,r)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,r,n){switch(n){case Ee.Error:this.markInvalidMessageDelivery(e,r);return;case Ee.Blacklisted:return}let i=this.deliveryRecords.ensureRecord(t);if(i.status!==Se.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-i.firstSeenTsMs,Se[i.status]);return}if(n===Ee.Ignore){i.status=Se.ignored,i.peers.clear();return}i.status=Se.invalid,this.markInvalidMessageDelivery(e,r),i.peers.forEach(o=>{this.markInvalidMessageDelivery(o,r)}),i.peers.clear()}duplicateMessage(e,t,r){let n=this.deliveryRecords.ensureRecord(t);if(!n.peers.has(e))switch(n.status){case Se.unknown:n.peers.add(e);break;case Se.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,r,n.validated);break;case Se.invalid:this.markInvalidMessageDelivery(e,r);break;case Se.ignored:break}}markInvalidMessageDelivery(e,t){let r=this.peerStats.get(e);if(r!=null){let n=this.getPtopicStats(r,t);n!=null&&(n.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){let r=this.peerStats.get(e);if(r!=null){let n=this.getPtopicStats(r,t);if(n!=null){let i=this.params.topics[t].firstMessageDeliveriesCap;n.firstMessageDeliveries=Math.min(i,n.firstMessageDeliveries+1),n.inMesh&&(i=this.params.topics[t].meshMessageDeliveriesCap,n.meshMessageDeliveries=Math.min(i,n.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,r){let n=this.peerStats.get(e);if(n!=null){let i=r!==void 0?Date.now():0,o=this.getPtopicStats(n,t);if(o!=null&&o.inMesh){let a=this.params.topics[t];if(r!==void 0){let u=i-r,p=u>a.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,u,p),p)return}let l=a.meshMessageDeliveriesCap;o.meshMessageDeliveries=Math.min(l,o.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(let r of t){let n=this.peerIPs.get(r);n!=null&&(n.delete(e),n.size===0&&this.peerIPs.delete(r))}}getPtopicStats(e,t){let r=e.topics[t];return r!==void 0?r:this.params.topics[t]!==void 0?(r={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=r,r):null}};function ef(s,e,t,r,n){let i=0,o=new Map;if(Object.entries(e.topics).forEach(([x,y])=>{let f=n.get(x)??"unknown",g=t.topics[x];if(g===void 0)return;let w=o.get(f);w==null&&(w={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},o.set(f,w));let E=0,S=0,c=0,h=0,d=0;if(y.inMesh){let D=Math.max(y.meshTime/g.timeInMeshQuantum,g.timeInMeshCap);E+=D*g.timeInMeshWeight}let b=y.firstMessageDeliveries;if(b>g.firstMessageDeliveriesCap&&(b=g.firstMessageDeliveriesCap),S+=b*g.firstMessageDeliveriesWeight,y.meshMessageDeliveriesActive&&y.meshMessageDeliveries<g.meshMessageDeliveriesThreshold){let D=g.meshMessageDeliveriesThreshold-y.meshMessageDeliveries,P=D*D;c+=P*g.meshMessageDeliveriesWeight}let v=y.meshFailurePenalty;h+=v*g.meshFailurePenaltyWeight;let _=y.invalidMessageDeliveries*y.invalidMessageDeliveries;d+=_*g.invalidMessageDeliveriesWeight,i+=(E+S+c+h+d)*g.topicWeight,w.p1w+=E,w.p2w+=S,w.p3w+=c,w.p3bw+=h,w.p4w+=d}),t.topicScoreCap>0&&i>t.topicScoreCap){i=t.topicScoreCap;let x=t.topicScoreCap/i;for(let y of o.values())y.p1w*=x,y.p2w*=x,y.p3w*=x,y.p3bw*=x,y.p4w*=x}let a=0,l=0,u=0,p=t.appSpecificScore(s);a+=p*t.appSpecificWeight,e.knownIPs.forEach(x=>{if(t.IPColocationFactorWhitelist.has(x))return;let y=r.get(x),f=y!=null?y.size:0;if(f>t.IPColocationFactorThreshold){let g=f-t.IPColocationFactorThreshold,w=g*g;l+=w*t.IPColocationFactorWeight}});let m=e.behaviourPenalty*e.behaviourPenalty;return u+=m*t.behaviourPenaltyWeight,i+=a+l+u,{byTopic:o,p5w:a,p6w:l,p7w:u,score:i}}function wc(s,e,t,r,n){let i={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let o of s){let a=e.get(o);if(a!=null){let l=ef(o,a,t,r,n);for(let[u,p]of l.byTopic){let m=i.byTopic.get(u);m==null&&(m={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},i.byTopic.set(u,m)),m.p1w.push(p.p1w),m.p2w.push(p.p2w),m.p3w.push(p.p3w),m.p3bw.push(p.p3bw),m.p4w.push(p.p4w)}i.p5w.push(l.p5w),i.p6w.push(l.p6w),i.p7w.push(l.p7w),i.score.push(l.score)}else i.p5w.push(0),i.p6w.push(0),i.p7w.push(0),i.score.push(0)}return i}function qi(s){let e=s.getComponents(),t={},r=0;return e[r]?.name==="ip6zone"&&(t.zone=`${e[r].value}`,r++),e[r]?.name==="ip4"||e[r]?.name==="ip6"||e[r]?.name==="dns"||e[r]?.name==="dns4"||e[r]?.name==="dns6"?(t.type=e[r].name,t.host=e[r].value,r++):e[r]?.name==="dnsaddr"&&(t.type=e[r].name,t.host=`_dnsaddr.${e[r].value}`,r++),(e[r]?.name==="tcp"||e[r]?.name==="udp")&&(t.protocol=e[r].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[r].value}`),r++),e[r]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[r].value}`):t.type==="ip6"&&(t.cidr=`${e[r].value}`),r++),t.type==null||t.host==null?null:(e[r]?.name==="tls"&&e[r+1]?.name==="sni"&&(t.sni=e[r+1].value,r+=2),t)}function xc(s){let e=qi(s);if(e==null)throw new re(`Multiaddr ${s} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function vc(s){return qi(s)!==null}var Gi=class s extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,s)}},Ec=s=>s.reason??new DOMException("This operation was aborted.","AbortError");function Hi(s,e){let{milliseconds:t,fallback:r,message:n,customTimers:i={setTimeout,clearTimeout},signal:o}=e,a,l,p=new Promise((m,x)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(o?.aborted){x(Ec(o));return}if(o&&(l=()=>{x(Ec(o))},o.addEventListener("abort",l,{once:!0})),s.then(m,x),t===Number.POSITIVE_INFINITY)return;let y=new Gi;a=i.setTimeout.call(void 0,()=>{if(r){try{m(r())}catch(f){x(f)}return}typeof s.cancel=="function"&&s.cancel(),n===!1?m():n instanceof Error?x(n):(y.message=n??`Promise timed out after ${t} milliseconds`,x(y))},t)}).finally(()=>{p.clear(),l&&o&&o.removeEventListener("abort",l)});return p.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},p}var tf=s=>{let e=s.addEventListener||s.on||s.addListener,t=s.removeEventListener||s.off||s.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(s),removeListener:t.bind(s)}};function sf(s,e,t){let r,n=new Promise((i,o)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),l=[],{addListener:u,removeListener:p}=tf(s),m=async(...y)=>{let f=t.multiArgs?y:y[0];if(t.filter)try{if(!await t.filter(f))return}catch(g){r(),o(g);return}l.push(f),t.count===l.length&&(r(),i(l))},x=(...y)=>{r(),o(t.rejectionMultiArgs?y:y[0])};r=()=>{for(let y of a)p(y,m);for(let y of t.rejectionEvents)a.includes(y)||p(y,x)};for(let y of a)u(y,m);for(let y of t.rejectionEvents)a.includes(y)||u(y,x);t.signal&&t.signal.addEventListener("abort",()=>{x(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(l)});if(n.cancel=r,typeof t.timeout=="number"){let i=Hi(n,{milliseconds:t.timeout});return i.cancel=()=>{r(),i.clear()},i}return n}function Sc(s,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let r=sf(s,e,t),n=r.then(i=>i[0]);return n.cancel=r.cancel,n}function rf(s){return s?.addEventListener!=null}function nf(s){let e=Ct(),t,r=o=>{e.push(o.data)},n=()=>{e.end(),s.removeEventListener("message",r),s.removeEventListener("close",i),s.removeEventListener("remoteCloseWrite",n)},i=o=>{e.end(o.error),o.error!=null&&t?.reject(o.error),s.removeEventListener("message",r),s.removeEventListener("close",i),s.removeEventListener("remoteCloseWrite",n)};return s.addEventListener("message",r),s.addEventListener("close",i,{once:!0}),s.addEventListener("remoteCloseWrite",n,{once:!0}),{source:e,async sink(o){async function*a(){yield*o}let l=a();for(;;){t=Promise.withResolvers();let{done:u,value:p}=await Promise.race([l.next(),t.promise]);if(s.writeStatus==="closing"||s.writeStatus==="closed"||(p!=null&&(s.send(p)||await Promise.race([Sc(s,"drain",{rejectionEvents:["close"]})])),u===!0))break}await s.close()}}}function _c(...s){let e=s.map(t=>rf(t)?nf(t):t);return Ns(...e)}var Ur=class{rawStream;constructor(e,t,r){this.rawStream=e,r.maxBufferSize!=null&&(e.maxWriteBufferLength=r.maxBufferSize),e.addEventListener("close",n=>{n.error!=null&&t(n.error)})}get protocol(){return this.rawStream.protocol}push(e){this.pushPrefixed(is.single(e))}pushPrefixed(e){this.rawStream.send(e)}async close(e){await this.rawStream.close(e).catch(t=>{this.rawStream.abort(t)})}},Kr=class{source;rawStream;closeController;constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(r=>{e.abort(r)})}),this.source=_c(this.rawStream,r=>Fs(r,t))}async close(){this.closeController.abort()}};var zr=class{gossipsubIWantFollowupMs;msgIdToStrFn;metrics;promises=new Map;requestMsByMsg=new Map;requestMsByMsgExpire;constructor(e,t,r){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=r,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){let r=Math.floor(Math.random()*t.length),n=t[r],i=this.msgIdToStrFn(n),o=this.promises.get(i);o==null&&(o=new Map,this.promises.set(i,o));let a=Date.now();o.has(e)||(o.set(e,a+this.gossipsubIWantFollowupMs),this.metrics!=null&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(i)||this.requestMsByMsg.set(i,a)))}getBrokenPromises(){let e=Date.now(),t=new Map,r=0;return this.promises.forEach((n,i)=>{n.forEach((o,a)=>{o<e&&(t.set(a,(t.get(a)??0)+1),n.delete(a),r++)}),n.size===0&&this.promises.delete(i)}),this.metrics?.iwantPromiseBroken.inc(r),t}deliverMessage(e,t=!1){this.trackMessage(e);let r=this.promises.get(e);r!=null&&(this.promises.delete(e),this.metrics!=null&&(this.metrics.iwantPromiseResolved.inc(1),t&&this.metrics.iwantPromiseResolvedFromDuplicate.inc(1),this.metrics.iwantPromiseResolvedPeers.inc(r.size)))}rejectMessage(e,t){this.trackMessage(e),t!==Ee.Error&&this.promises.delete(e)}clear(){this.promises.clear()}prune(){let e=Date.now()-this.requestMsByMsgExpire,t=0;for(let[r,n]of this.requestMsByMsg.entries())if(n<e)this.requestMsByMsg.delete(r),t++;else break;this.metrics?.iwantMessagePruned.inc(t)}trackMessage(e){if(this.metrics!=null){let t=this.requestMsByMsg.get(e);t!==void 0&&(this.metrics.iwantPromiseDeliveryTime.observe((Date.now()-t)/1e3),this.requestMsByMsg.delete(e))}}};var Ic=j("libp2p-pubsub:"),of=BigInt(Date.now())*1000000n;function af(){let s=++of,e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,s,!1),e}async function Tc(s,e,t,r){switch(s.type){case yt.Signing:{let n={from:s.author.toMultihash().bytes,data:r,seqno:af(),topic:e,signature:void 0,key:void 0},i=Et([Ic,rt.Message.encode(n)]);n.signature=await s.privateKey.sign(i),n.key=s.key;let o={type:"signed",from:s.author,data:t,sequenceNumber:BigInt(`0x${$(n.seqno??new Uint8Array(0),"base16")}`),topic:e,signature:n.signature,key:Ci(n.key)};return{raw:n,msg:o}}case yt.Anonymous:return{raw:{from:void 0,data:r,seqno:void 0,topic:e,signature:void 0,key:void 0},msg:{type:"unsigned",data:t,topic:e}};default:throw new Error("Unreachable")}}async function Dc(s,e){switch(s){case Ft:return e.signature!=null?{valid:!1,error:le.SignaturePresent}:e.seqno!=null?{valid:!1,error:le.SeqnoPresent}:e.key!=null?{valid:!1,error:le.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case wt:{if(e.seqno==null)return{valid:!1,error:le.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:le.InvalidSeqno};if(e.signature==null)return{valid:!1,error:le.InvalidSignature};if(e.from==null)return{valid:!1,error:le.InvalidPeerId};let t;try{t=rs(Ye(e.from))}catch{return{valid:!1,error:le.InvalidPeerId}}let r;if(e.key!=null){try{r=Ci(e.key)}catch{return{valid:!1,error:le.InvalidPeerId}}if(!t.equals(r.toMultihash().bytes))return{valid:!1,error:le.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:le.InvalidPeerId};r=t.publicKey}let n={from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0},i=Et([Ic,rt.Message.encode(n)]),o;try{o=await r.verify(i,e.signature)}catch{o=!1}return o?{valid:!0,message:{type:"signed",from:t,data:e.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${$(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:r}}:{valid:!1,error:le.InvalidSignature}}default:throw new Error("Unreachable")}}function ze(s=[],e){return{subscriptions:[],messages:s,control:e!==void 0?{graft:e.graft??[],prune:e.prune??[],ihave:e.ihave??[],iwant:e.iwant??[],idontwant:e.idontwant??[]}:void 0}}function Wi(s){return s.control===void 0&&(s.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),s}function Ze(s){if(s.length<=1)return s;let e=()=>Math.floor(Math.random()*Math.floor(s.length));for(let t=0;t<s.length;t++){let r=e(),n=s[t];s[t]=s[r],s[r]=n}return s}function Ac(s){return $(s,"base64")}function Mc(s,e,t){switch(s){case wt:return{type:yt.Signing,author:e,key:We(t.publicKey),privateKey:t};case Ft:return{type:yt.Anonymous};default:throw new Error(`Unknown signature policy "${s}"`)}}var cf=(s,e)=>{let t=j(e.toString(16).padStart(16,"0"),"base16"),r=We(s),n=new Uint8Array(r.byteLength+t.length);return n.set(r,0),n.set(t,r.byteLength),n};function Pc(s){if(s.type!=="signed")throw new Error("expected signed message type");if(s.sequenceNumber==null)throw Error("missing seqno field");return cf(s.from.publicKey??s.key,s.sequenceNumber)}async function Bc(s){return St.encode(s.data)}function kc(s){if(vc(s)){let e=xc(s);switch(e.type){case"ip4":case"ip6":return e.host;default:break}}return null}var us=class{entries=new Map;validityMs;constructor(e){this.validityMs=e.validityMs}get size(){return this.entries.size}put(e,t){return this.entries.has(e)?!0:(this.entries.set(e,{value:t,validUntilMs:Date.now()+this.validityMs}),!1)}prune(){let e=Date.now();for(let[t,r]of this.entries.entries())if(r.validUntilMs<e)this.entries.delete(t);else break}has(e){return this.entries.has(e)}get(e){let t=this.entries.get(e);return t!=null&&t.validUntilMs>=Date.now()?t.value:void 0}clear(){this.entries.clear()}};var Pe;(function(s){s[s.started=0]="started",s[s.stopped=1]="stopped"})(Pe||(Pe={}));var qr=class extends zs{globalSignaturePolicy;protocols=[Ot,ji,Wr];publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=Ct({objectMode:!0});direct=new Set;floodsubPeers=new Set;seenCache;acceptFromWhitelist=new Map;topics=new Map;subscriptions=new Set;mesh=new Map;fanout=new Map;fanoutLastpub=new Map;gossip=new Map;control=new Map;peerhave=new Map;iasked=new Map;iwantCounts=new Map;backoff=new Map;outbound=new Map;msgIdFn;fastMsgIdFn;msgIdToStrFn;fastMsgIdCache;publishedMessageIds;mcache;score;topicValidators=new Map;log;heartbeatTicks=0;gossipTracer;idontwantCounts=new Map;idontwants=new Map;components;directPeerInitial=null;static multicodec=Ot;opts;decodeRpcLimits;metrics;status={code:Pe.stopped};maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;allowedTopics;maxTopicBytesPerPeer;peerTopicBytes=new Map;heartbeatTimer=null;constructor(e,t={}){super();let r={fallbackToFloodsub:!0,floodPublish:!0,batchPublish:!1,tagMeshPeers:!0,doPX:!1,directPeers:[],D:6,Dlo:4,Dhi:12,Dscore:4,Dout:2,Dlazy:6,heartbeatInterval:1e3,fanoutTTL:6e4,mcacheLength:5,mcacheGossip:3,seenTTL:12e4,gossipsubIWantFollowupMs:3e3,prunePeers:16,pruneBackoff:6e4,unsubcribeBackoff:1e4,graftFloodThreshold:1e4,opportunisticGraftPeers:2,opportunisticGraftTicks:60,directConnectTicks:300,gossipFactor:.25,idontwantMinDataSize:512,idontwantMaxMessages:512,...t,scoreParams:hc(t.scoreParams),scoreThresholds:dc(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=r.decodeRpcLimits??ac,this.globalSignaturePolicy=r.globalSignaturePolicy??wt,r.fallbackToFloodsub&&this.protocols.push(Hr),this.log=e.logger.forComponent(r.debugName??"libp2p:gossipsub"),this.opts=r,this.direct=new Set(r.directPeers.map(n=>n.id.toString())),this.seenCache=new us({validityMs:r.seenTTL}),this.publishedMessageIds=new us({validityMs:r.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case wt:this.msgIdFn=Pc;break;case Ft:this.msgIdFn=Bc;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new us({validityMs:r.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??Ac,this.mcache=t.messageCache??new Lr(r.mcacheGossip,r.mcacheLength,this.msgIdToStrFn),t.dataTransform!=null&&(this.dataTransform=t.dataTransform),t.metricsRegister!=null){if(t.metricsTopicStrToLabel==null)throw Error("Must set metricsTopicStrToLabel with metrics");let n=Math.max(...Object.values(r.scoreParams.topics).map(o=>o.meshMessageDeliveriesWindow),1e3),i=uc(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:r.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:n/1e3});i.mcacheSize.addCollect(()=>{this.onScrapeMetrics(i)});for(let o of this.protocols)i.protocolsEnabled.set({protocol:o},1);this.metrics=i}else this.metrics=null;this.gossipTracer=new zr(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new Or(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:r.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnLimitedConnection=t.runOnLimitedConnection,this.allowedTopics=r.allowedTopics!=null?new Set(r.allowedTopics):null,this.maxTopicBytesPerPeer=r.maxTopicBytesPerPeer??1048576}[Symbol.toStringTag]="@libp2p/gossipsub";[Qi]=["@libp2p/pubsub"];[eo]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===Pe.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=Mc(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=Ct({objectMode:!0}),Ns(this.outboundInflightQueue,async i=>{for await(let{peerId:o,connection:a}of i)await this.createOutboundStream(o,a)}).catch(i=>{this.log.error("outbound inflight queue error",i)}),await Promise.all(this.opts.directPeers.map(async i=>{await this.components.peerStore.merge(i.id,{multiaddrs:i.addrs})}));let e=this.components.registrar;await Promise.all(this.protocols.map(async i=>e.handle(i,this.onIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection})));let t={onConnect:this.onPeerConnected.bind(this),onDisconnect:this.onPeerDisconnected.bind(this),notifyOnLimitedConnection:this.runOnLimitedConnection},r=await Promise.all(this.protocols.map(async i=>e.register(i,t))),n=setTimeout(this.runHeartbeat,100);this.status={code:Pe.started,registrarTopologyIds:r,heartbeatTimeout:n,hearbeatStartMs:Date.now()+100},this.score.start(),this.directPeerInitial=setTimeout(()=>{Promise.resolve().then(async()=>{await Promise.all(Array.from(this.direct).map(async i=>this.connect(i)))}).catch(i=>{this.log(i)})},1e3),this.opts.tagMeshPeers&&(this.addEventListener("gossipsub:graft",this.tagMeshPeer),this.addEventListener("gossipsub:prune",this.untagMeshPeer)),this.log("started")}async stop(){if(this.log("stopping"),this.status.code!==Pe.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:Pe.stopped},this.opts.tagMeshPeers&&(this.removeEventListener("gossipsub:graft",this.tagMeshPeer),this.removeEventListener("gossipsub:prune",this.untagMeshPeer));let t=this.components.registrar;await Promise.all(this.protocols.map(async n=>t.unhandle(n))),e.forEach(n=>{t.unregister(n)}),this.outboundInflightQueue.end();let r=[];for(let n of this.streamsOutbound.values())r.push(n.close());this.streamsOutbound.clear();for(let n of this.streamsInbound.values())r.push(n.close());this.streamsInbound.clear(),await Promise.all(r),this.peers.clear(),this.subscriptions.clear(),this.topics.clear(),this.peerTopicBytes.clear(),this.heartbeatTimer!=null&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.iwantCounts.clear(),this.backoff.clear(),this.outbound.clear(),this.gossipTracer.clear(),this.seenCache.clear(),this.fastMsgIdCache!=null&&this.fastMsgIdCache.clear(),this.directPeerInitial!=null&&clearTimeout(this.directPeerInitial),this.idontwantCounts.clear(),this.idontwants.clear(),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream(e,t){if(!this.isStarted())return;let r=t.remotePeer;this.addPeer(r,t.direction,t.remoteAddr),this.createInboundStream(r,e),this.outboundInflightQueue.push({peerId:r,connection:t})}onPeerConnected(e,t){this.metrics?.newConnectionCount.inc({status:t.status}),!(!this.isStarted()||t.status!=="open")&&(this.addPeer(e,t.direction,t.remoteAddr),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}async createOutboundStream(e,t){if(!this.isStarted())return;let r=e.toString();if(this.peers.has(r)&&!this.streamsOutbound.has(r))try{let n=await t.newStream(this.protocols,{runOnLimitedConnection:this.runOnLimitedConnection}),i=new Ur(n,a=>{this.log.error("outbound pipe error",a)},{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(r,i);let o=i.protocol;o===Hr&&this.floodsubPeers.add(r),this.metrics?.peersPerProtocol.inc({protocol:o},1),n.addEventListener("close",()=>{this.streamsOutbound.get(r)===i&&(this.streamsOutbound.delete(r),this.floodsubPeers.delete(r),this.metrics?.peersPerProtocol.inc({protocol:o},-1))},{once:!0}),this.subscriptions.size>0&&(this.log("send subscriptions to",r),this.sendSubscriptions(r,Array.from(this.subscriptions),!0))}catch(n){this.log.error("createOutboundStream error",n)}}createInboundStream(e,t){if(!this.isStarted())return;let r=e.toString();if(!this.peers.has(r))return;let n=this.streamsInbound.get(r);n!==void 0&&(this.log("replacing existing inbound steam %s",r),n.close().catch(o=>{this.log.error(o)})),this.log("create inbound stream %s",r);let i=new Kr(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(r,i),this.pipePeerReadStream(e,i.source).catch(o=>{this.log(o)})}addPeer(e,t,r){let n=e.toString();if(!this.peers.has(n)){this.peers.set(n,e),this.score.addPeer(n);let i=kc(r);i!==null?this.score.addIP(n,i):this.log("Added peer has no IP in current address %s %s",n,r.toString()),this.outbound.has(n)||this.outbound.set(n,t==="outbound")}}removePeer(e){let t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);let r=this.streamsOutbound.get(t),n=this.streamsInbound.get(t);r!=null&&this.metrics?.peersPerProtocol.inc({protocol:r.protocol},-1),r?.close().catch(i=>{this.log.error(i)}),n?.close().catch(i=>{this.log.error(i)}),this.streamsOutbound.delete(t),this.streamsInbound.delete(t);for(let[i,o]of this.topics)o.delete(t),o.size===0&&this.topics.delete(i);this.peerTopicBytes.delete(t);for(let[i,o]of this.mesh)o.delete(t)&&this.metrics?.onRemoveFromMesh(i,Ke.Dc,1);for(let i of this.fanout.values())i.delete(t);this.floodsubPeers.delete(t),this.gossip.delete(t),this.control.delete(t),this.outbound.delete(t),this.idontwantCounts.delete(t),this.idontwants.delete(t),this.score.removePeer(t),this.acceptFromWhitelist.delete(t)}get started(){return this.status.code===Pe.started}getMeshPeers(e){let t=this.mesh.get(e);return t!=null?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(t!=null?Array.from(t):[]).map(r=>this.peers.get(r)??Rt(r))}getTopics(){return Array.from(this.subscriptions)}decodeRpc(e){return rt.decode(e,{limits:{subscriptions:this.decodeRpcLimits.maxSubscriptions,messages:this.decodeRpcLimits.maxMessages,control:{ihave:this.decodeRpcLimits.maxControlMessages,ihave$:{messageIDs:this.decodeRpcLimits.maxIhaveMessageIDs},iwant:this.decodeRpcLimits.maxControlMessages,iwant$:{messageIDs:this.decodeRpcLimits.maxIwantMessageIDs},graft:this.decodeRpcLimits.maxControlMessages,prune:this.decodeRpcLimits.maxControlMessages,prune$:{peers:this.decodeRpcLimits.maxPeerInfos},idontwant:this.decodeRpcLimits.maxControlMessages,idontwant$:{messageIDs:this.decodeRpcLimits.maxIdontwantMessageIDs}}}})}async pipePeerReadStream(e,t){try{await Ns(t,async r=>{for await(let n of r)try{let i=n.subarray(),o=this.decodeRpc(i);if(this.metrics?.onRpcRecv(o,i.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,o)}catch(a){this.metrics?.onRpcRecvError(),this.log(a)}else this.handleReceivedRpc(e,o).catch(a=>{this.metrics?.onRpcRecvError(),this.log(a)})}catch(i){this.metrics?.onRpcDataError(),this.log(i)}})}catch(r){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(r,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){if(!this.acceptFrom(e.toString())){this.log("received message from unacceptable peer %p",e),this.metrics?.rpcRecvNotAccepted.inc();return}let r=t.subscriptions!=null?t.subscriptions.length:0,n=t.messages!=null?t.messages.length:0,i=0,o=0,a=0,l=0;if(t.control!=null&&(t.control.ihave!=null&&(i=t.control.ihave.length),t.control.iwant!=null&&(o=t.control.iwant.length),t.control.graft!=null&&(a=t.control.graft.length),t.control.prune!=null&&(l=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${r} messages ${n} ihave ${i} iwant ${o} graft ${a} prune ${l}`),t.subscriptions!=null&&t.subscriptions.length>0){let u=[],p=e.toString(),m=[];t.subscriptions.forEach(x=>{let y=x.topic,f=x.subscribe===!0;if(y!=null){if(this.allowedTopics!=null&&!this.allowedTopics.has(y)||!this.handleReceivedSubscription(e,y,f))return;f&&this.graftOnSubscribe(p,y)&&m.push(y),u.push({topic:y,subscribe:f})}}),m.length>0&&this.sendGraft(p,m),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:u}})}for(let u of t.messages){if(this.allowedTopics!=null&&!this.allowedTopics.has(u.topic))continue;let p=this.handleReceivedMessage(e,u).catch(m=>{this.metrics?.onMsgRecvError(u.topic),this.log(m)});this.opts.awaitRpcMessageHandler&&await p}t.control!=null&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,r){this.log("subscription update from %p topic %s",e,t);let n=e.toString(),i=this.topics.get(t),o=t.length+1024;if(r){if(i?.has(n)===!0)return!0;let a=this.peerTopicBytes.get(n)??0;if(a+o>this.maxTopicBytesPerPeer)return this.log("ignoring subscription from %p topic %s, over per-peer topic budget",e,t),!1;this.peerTopicBytes.set(n,a+o),i==null&&(i=new Set,this.topics.set(t,i)),i.add(n)}else i?.has(n)===!0&&(i.delete(n),this.peerTopicBytes.set(n,Math.max(0,(this.peerTopicBytes.get(n)??0)-o)),i.size===0&&this.topics.delete(t));return!0}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);let r=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,r.code);let n=r.code;switch(n){case pe.duplicate:this.score.duplicateMessage(e.toString(),r.msgIdStr,t.topic),this.gossipTracer.deliverMessage(r.msgIdStr,!0),this.mcache.observeDuplicate(r.msgIdStr,e.toString());return;case pe.invalid:if(r.msgIdStr!=null){let i=r.msgIdStr;this.score.rejectMessage(e.toString(),i,t.topic,r.reason),this.gossipTracer.rejectMessage(i,r.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);this.metrics?.onMsgRecvInvalid(t.topic,r);return;case pe.valid:this.score.validateMessage(r.messageId.msgIdStr),this.gossipTracer.deliverMessage(r.messageId.msgIdStr),this.mcache.put(r.messageId,t,!this.opts.asyncValidation),this.subscriptions.has(t.topic)&&(!this.components.peerId.equals(e)||this.opts.emitSelf)&&(super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:e,msgId:r.messageId.msgIdStr,msg:r.msg}})),super.dispatchEvent(new CustomEvent("message",{detail:r.msg}))),this.opts.asyncValidation||this.forwardMessage(r.messageId.msgIdStr,t,e.toString());break;default:throw new Error(`Invalid validation result: ${n}`)}}async validateReceivedMessage(e,t){let r=this.fastMsgIdFn?.(t),n=r!==void 0?this.fastMsgIdCache?.get(r):void 0;if(n!=null)return{code:pe.duplicate,msgIdStr:n};let i=await Dc(this.globalSignaturePolicy,t);if(!i.valid)return{code:pe.invalid,reason:Ee.Error,error:i.error};let o=i.message;try{this.dataTransform!=null&&(o.data=this.dataTransform.inboundTransform(t.topic,o.data))}catch(m){return this.log("Invalid message, transform failed",m),{code:pe.invalid,reason:Ee.Error,error:le.TransformFailed}}let a=await this.msgIdFn(o),l=this.msgIdToStrFn(a),u={msgId:a,msgIdStr:l};if(r!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(r,l)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(l))return{code:pe.duplicate,msgIdStr:l};this.seenCache.put(l),(t.data?.length??0)>=this.opts.idontwantMinDataSize&&this.sendIDontWants(a,t.topic,e.toString());let p=this.topicValidators.get(t.topic);if(p!=null){let m;try{m=await p(e,o)}catch(x){let y=x.code;y===Yi&&(m=me.Ignore),y===Zi?m=me.Reject:m=me.Ignore}if(m!==me.Accept)return{code:pe.invalid,reason:zi(m),msgIdStr:l}}return{code:pe.valid,messageId:u,msg:o}}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,r){this.sendRpc(e,{subscriptions:t.map(n=>({topic:n,subscribe:r})),messages:[]})}async handleControlMessage(e,t){if(t===void 0)return;let r=t.ihave?.length>0?this.handleIHave(e,t.ihave):[],n=t.iwant?.length>0?this.handleIWant(e,t.iwant):[],i=t.graft?.length>0?await this.handleGraft(e,t.graft):[];if(t.prune?.length>0&&await this.handlePrune(e,t.prune),t.idontwant?.length>0&&this.handleIdontwant(e,t.idontwant),r.length===0&&n.length===0&&i.length===0)return;let o=this.sendRpc(e,ze(n,{iwant:r,prune:i})),a=r[0]?.messageIDs;a!=null&&(o?this.gossipTracer.addPromise(e,a):this.metrics?.iwantPromiseUntracked.inc(1))}acceptFrom(e){if(this.direct.has(e))return!0;let t=Date.now(),r=this.acceptFromWhitelist.get(e);if(r!=null&&r.messagesAccepted<128&&r.acceptUntil>=t)return r.messagesAccepted+=1,!0;let n=this.score.score(e);return n>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),n>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){if(t.length===0)return[];let r=this.score.score(e);if(r<this.opts.scoreThresholds.gossipThreshold)return this.log("IHAVE: ignoring peer %s with score below threshold [ score = %d ]",e,r),this.metrics?.ihaveRcvIgnored.inc({reason:ls.LowScore}),[];let n=(this.peerhave.get(e)??0)+1;if(this.peerhave.set(e,n),n>10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:ls.MaxIhave}),[];let i=this.iasked.get(e)??0;if(i>=5e3)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,i),this.metrics?.ihaveRcvIgnored.inc({reason:ls.MaxIasked}),[];let o=new Map,a=0;e:for(let{topicID:p,messageIDs:m}of t){if(p==null||m==null||!this.mesh.has(p))continue;let x=0;for(let y of m){if(a>=5e3)break e;a++;let f=this.msgIdToStrFn(y);this.seenCache.has(f)||(o.set(f,y),x++)}this.metrics?.onIhaveRcv(p,m.length,x)}if(o.size===0)return[];let l=o.size;l+i>5e3&&(l=5e3-i),this.log("IHAVE: Asking for %d out of %d messages from %s",l,o.size,e);let u=Array.from(o.values());return Ze(u),u=u.slice(0,l),this.iasked.set(e,i+l),[{messageIDs:u}]}handleIWant(e,t){if(t.length===0)return[];let r=this.score.score(e);if(r<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,r),[];let n=(this.iwantCounts.get(e)??0)+1;if(this.iwantCounts.set(e,n),n>10)return this.log("IWANT: peer %s has requested too many times within this heartbeat interval; ignoring",e),[];let i=new Map,o=new Map,a=0,l=0;e:for(let{messageIDs:u}of t)if(u!=null)for(let p of u){if(l>=5e3)break e;l++;let m=this.msgIdToStrFn(p),x=this.mcache.getWithIWantCount(m,e);if(x==null){a++;continue}if(o.set(x.msg.topic,1+(o.get(x.msg.topic)??0)),x.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,p);continue}i.set(m,x.msg)}return this.metrics?.onIwantRcv(o,a),i.size===0?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",i.size,e),Array.from(i.values()))}async handleGraft(e,t){let r=[],n=this.score.score(e),i=Date.now(),o=this.opts.doPX;if(t.forEach(({topicID:l})=>{if(l==null)return;let u=this.mesh.get(l);if(u==null){o=!1;return}if(u.has(e))return;let p=this.backoff.get(l)?.get(e);if(this.direct.has(e))this.log("GRAFT: ignoring request from direct peer %s",e),r.push(l),o=!1;else if(typeof p=="number"&&i<p){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,cs.GraftBackoff),o=!1;let m=p+this.opts.graftFloodThreshold-this.opts.pruneBackoff;i<m&&this.score.addPenalty(e,1,cs.GraftBackoff),this.addBackoff(e,l),r.push(l)}else n<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,n,l),r.push(l),o=!1,this.addBackoff(e,l)):u.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(r.push(l),this.addBackoff(e,l)):(this.log("GRAFT: Add mesh link from %s in %s",e,l),this.addToMesh(e,l,ge.Subscribed));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:l,direction:"inbound"}})}),r.length===0)return[];let a=!1;return Promise.all(r.map(async l=>this.makePrune(e,l,o,a)))}async handlePrune(e,t){let r=this.score.score(e);for(let{topicID:n,backoff:i,peers:o}of t){if(n==null)continue;let a=this.mesh.get(n);if(a==null)return;this.log("PRUNE: Remove mesh link to %s in %s",e,n),this.score.prune(e,n),a.has(e)&&(a.delete(e),this.metrics?.onRemoveFromMesh(n,Ke.Prune,1)),typeof i=="number"&&i>0?this.doAddBackoff(e,n,i*1e3):this.addBackoff(e,n),o!=null&&o.length>0&&(r<this.opts.scoreThresholds.acceptPXThreshold?this.log("PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]",e,r,n):await this.pxConnect(o)),this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:n,direction:"inbound"}})}}handleIdontwant(e,t){let r=this.idontwantCounts.get(e)??0;if(r>=this.opts.idontwantMaxMessages)return;let n=r,i=this.idontwants.get(e);i==null&&(i=new Map,this.idontwants.set(e,i));let o=0;e:for(let{messageIDs:l}of t)for(let u of l){if(r>=this.opts.idontwantMaxMessages)break e;r++;let p=this.msgIdToStrFn(u);i.set(p,this.heartbeatTicks),this.mcache.msgs.has(p)||o++}this.idontwantCounts.set(e,r);let a=r-n;this.metrics?.onIdontwantRcv(a,o)}addBackoff(e,t){this.doAddBackoff(e,t,this.opts.pruneBackoff)}doAddBackoff(e,t,r){let n=this.backoff.get(t);n==null&&(n=new Map,this.backoff.set(t,n));let i=Date.now()+r;(n.get(e)??0)<i&&n.set(e,i)}applyIwantPenalties(){this.gossipTracer.getBrokenPromises().forEach((e,t)=>{this.log("peer %s didn't follow up in %d IWANT requests; adding penalty",t,e),this.score.addPenalty(t,e,cs.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!==0)return;let e=Date.now();this.backoff.forEach((t,r)=>{t.forEach((n,i)=>{n+1*this.opts.heartbeatInterval<e&&t.delete(i)}),t.size===0&&this.backoff.delete(r)})}async directConnect(){let e=[];this.direct.forEach(t=>{this.streamsOutbound.has(t)||e.push(t)}),await Promise.all(e.map(async t=>this.connect(t)))}async pxConnect(e){e.length>this.opts.prunePeers&&(Ze(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async r=>{if(r.peerID==null)return;let n=rs(Ye(r.peerID)),i=n.toString();if(!this.peers.has(i)){if(r.signedPeerRecord==null){t.push(i);return}try{if(!await this.components.peerStore.consumePeerRecord(r.signedPeerRecord,{expectedPeer:n})){this.log("bogus peer record obtained through px: could not add peer record to address book");return}t.push(i)}catch{this.log("bogus peer record obtained through px: invalid signature or not a peer record")}}})),t.length!==0&&await Promise.all(t.map(async r=>this.connect(r)))}async connect(e){this.log("Initiating connection with %s",e);let t=Rt(e),r=await this.components.connectionManager.openConnection(t);for(let n of this.protocols)for(let i of this.components.registrar.getTopologies(n))i.onConnect?.(t,r)}subscribe(e){if(this.status.code!==Pe.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(let t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==Pe.started)throw new Error("Pubsub is not started");let t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(let r of this.peers.keys())this.sendSubscriptions(r,[e],!1);this.leave(e)}join(e){if(this.status.code!==Pe.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);let t=new Set,r=this.backoff.get(e),n=this.fanout.get(e);if(n!=null&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),n.forEach(i=>{!this.direct.has(i)&&this.score.score(i)>=0&&r?.has(i)!==!0&&t.add(i)}),this.metrics?.onAddToMesh(e,ge.Fanout,t.size)),t.size<this.opts.D){let i=t.size;this.getRandomGossipPeers(e,this.opts.D,a=>!t.has(a)&&!this.direct.has(a)&&this.score.score(a)>=0&&r?.has(a)!==!0).forEach(a=>{t.add(a)}),this.metrics?.onAddToMesh(e,ge.Random,t.size-i)}this.mesh.set(e,t),t.forEach(i=>{this.log("JOIN: Add mesh link to %s in %s",i,e),this.sendGraft(i,[e])})}leave(e){if(this.status.code!==Pe.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);let t=this.mesh.get(e);t!=null&&(Promise.all(Array.from(t).map(async r=>{this.log("LEAVE: Remove mesh link to %s in %s",r,e),await this.sendPrune(r,e)})).catch(r=>{this.log("Error sending prunes to mesh peers",r)}),this.mesh.delete(e))}selectPeersToForward(e,t,r){let n=new Set,i=this.topics.get(e);i!=null&&(this.direct.forEach(a=>{i.has(a)&&t!==a&&!(r?.has(a)??!1)&&n.add(a)}),this.floodsubPeers.forEach(a=>{i.has(a)&&t!==a&&!(r?.has(a)??!1)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&n.add(a)}));let o=this.mesh.get(e);return o!=null&&o.size>0&&o.forEach(a=>{t!==a&&!(r?.has(a)??!1)&&n.add(a)}),n}selectPeersToPublish(e){let t=new Set,r={direct:0,floodsub:0,mesh:0,fanout:0},n=this.topics.get(e);if(n!=null)if(this.opts.floodPublish)n.forEach(i=>{this.direct.has(i)?(t.add(i),r.direct++):this.score.score(i)>=this.opts.scoreThresholds.publishThreshold&&(t.add(i),r.floodsub++)});else{this.direct.forEach(o=>{n.has(o)&&(t.add(o),r.direct++)}),this.floodsubPeers.forEach(o=>{n.has(o)&&this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),r.floodsub++)});let i=this.mesh.get(e);if(i!=null&&i.size>0)i.forEach(o=>{t.add(o),r.mesh++}),i.size<this.opts.D&&this.getRandomGossipPeers(e,this.opts.D-i.size,a=>!i.has(a)&&!this.direct.has(a)&&!this.floodsubPeers.has(a)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold).forEach(a=>{t.add(a),r.mesh++});else{let o=this.fanout.get(e);if(o!=null&&o.size>0)o.forEach(a=>{t.add(a),r.fanout++});else{let a=this.getRandomGossipPeers(e,this.opts.D,l=>this.score.score(l)>=this.opts.scoreThresholds.publishThreshold);a.size>0&&(this.fanout.set(e,a),a.forEach(l=>{t.add(l),r.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:r}}forwardMessage(e,t,r,n){r!=null&&this.score.deliverMessage(r,e,t.topic);let i=this.selectPeersToForward(t.topic,r,n);i.forEach(o=>{this.sendRpc(o,ze([t]))}),this.metrics?.onForwardMsg(t.topic,i.size)}async publish(e,t,r){let n=Date.now(),i=this.dataTransform!=null?this.dataTransform.outboundTransform(e,t):t;if(this.publishConfig==null)throw Error("PublishError.Uninitialized");let{raw:o,msg:a}=await Tc(this.publishConfig,e,t,i),l=await this.msgIdFn(a),u=this.msgIdToStrFn(l),p=r?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(u)){if(p)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:m,tosendCount:x}=this.selectPeersToPublish(e),y=this.opts.emitSelf&&this.subscriptions.has(e),f=r?.allowPublishToZeroTopicPeers??this.opts.allowPublishToZeroTopicPeers;if(m.size===0&&!f&&!y)throw Error("PublishError.NoPeersSubscribedToTopic");this.seenCache.put(u),this.mcache.put({msgId:l,msgIdStr:u},o,!0),this.gossipTracer.deliverMessage(u),this.publishedMessageIds.put(u);let g=r?.batchPublish??this.opts.batchPublish,w=ze([o]);if(g)this.sendRpcInBatch(m,w);else for(let S of m)this.sendRpc(S,w)||m.delete(S);let E=Date.now()-n;return this.metrics?.onPublishMsg(e,x,m.size,o.data!=null?o.data.length:0,E),y&&(m.add(this.components.peerId.toString()),super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:u,msg:a}})),super.dispatchEvent(new CustomEvent("message",{detail:a}))),{recipients:Array.from(m.values()).map(S=>this.peers.get(S)??Rt(S))}}sendRpcInBatch(e,t){let r=rt.encode(t),n=is.single(r);for(let i of e){let o=this.streamsOutbound.get(i);if(o==null){this.log(`Cannot send RPC to ${i} as there is no open stream to it available`),e.delete(i);continue}try{o.pushPrefixed(n)}catch(a){e.delete(i),this.log.error(`Cannot send rpc to ${i}`,a)}this.metrics?.onRpcSent(t,r.length)}}reportMessageValidationResult(e,t,r){let n;if(r===me.Accept){if(n=this.mcache.validate(e),n!=null){let{message:o,originatingPeers:a}=n;this.score.deliverMessage(t,e,o.topic),this.forwardMessage(e,n.message,t,a)}}else if(n=this.mcache.remove(e),n!=null){let o=zi(r),{message:a,originatingPeers:l}=n;this.score.rejectMessage(t,e,a.topic,o);for(let u of l)this.score.rejectMessage(u,e,a.topic,o)}let i=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(n,r,i)}sendGraft(e,t){let r=t.map(i=>({topicID:i})),n=ze([],{graft:r});this.sendRpc(e,n)}addToMesh(e,t,r){this.score.graft(e,t),this.mesh.get(t)?.add(e),this.metrics?.onAddToMesh(t,r,1)}graftOnSubscribe(e,t){let r=this.mesh.get(t);if(r==null||r.has(e)||r.size>=this.opts.Dlo)return!1;let n=this.streamsOutbound.get(e);return n==null||!this.protocols.includes(n.protocol)||this.direct.has(e)||this.score.score(e)<0||(this.backoff.get(t)?.has(e)??!1)?!1:(this.addToMesh(e,t,ge.Subscribed),!0)}async sendPrune(e,t){let n=[await this.makePrune(e,t,this.opts.doPX,!0)],i=ze([],{prune:n});this.sendRpc(e,i)}sendIDontWants(e,t,r){let n=this.mesh.get(t);if(n==null)return;let i=new Set(n);i.delete(r);for(let a of i)this.streamsOutbound.get(a)?.protocol!==Ot&&i.delete(a);let o=ze([],{idontwant:[{messageIDs:[e]}]});this.sendRpcInBatch(i,o)}sendRpc(e,t){let r=this.streamsOutbound.get(e);if(r==null)return this.log(`Cannot send RPC to ${e} as there is no open stream to it available`),!1;let n=this.control.get(e);n!=null&&(this.piggybackControl(e,t,n),this.control.delete(e));let i=this.gossip.get(e);i!=null&&(this.piggybackGossip(e,t,i),this.gossip.delete(e));let o=rt.encode(t);try{r.push(o)}catch(a){return this.log.error(`Cannot send rpc to ${e}`,a),n!=null&&this.control.set(e,n),i!=null&&this.gossip.set(e,i),!1}if(this.metrics?.onRpcSent(t,o.length),t.control?.graft!=null)for(let a of t.control?.graft)a.topicID!=null&&this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:a.topicID,direction:"outbound"}});if(t.control?.prune!=null)for(let a of t.control?.prune)a.topicID!=null&&this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:a.topicID,direction:"outbound"}});return!0}piggybackControl(e,t,r){let n=Wi(t);for(let i of r.graft)i.topicID!=null&&(this.mesh.get(i.topicID)?.has(e)??!1)&&n.control.graft.push(i);for(let i of r.prune)i.topicID!=null&&!(this.mesh.get(i.topicID)?.has(e)??!1)&&n.control.prune.push(i)}piggybackGossip(e,t,r){let n=Wi(t);n.control.ihave=r}async sendGraftPrune(e,t,r){let n=this.opts.doPX,i=!1;for(let[o,a]of e){let l=a.map(m=>({topicID:m})),u=[],p=t.get(o);p!=null&&(u=await Promise.all(p.map(async m=>this.makePrune(o,m,n&&!(r.get(o)??!1),i))),t.delete(o)),this.sendRpc(o,ze([],{graft:l,prune:u}))}for(let[o,a]of t){let l=await Promise.all(a.map(async u=>this.makePrune(o,u,n&&!(r.get(o)??!1),i)));this.sendRpc(o,ze([],{prune:l}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[r,n]of e)this.doEmitGossip(r,n,t.get(r)??[])}doEmitGossip(e,t,r){if(r.length===0||(Ze(r),r.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",r.length),t.size===0))return;let n=this.opts.Dlazy,o=this.opts.gossipFactor*t.size,a=t;o>n&&(n=o),n>a.size?n=a.size:a=Ze(Array.from(a)).slice(0,n),a.forEach(l=>{let u=r;r.length>5e3&&(u=Ze(u.slice()).slice(0,5e3)),this.pushGossip(l,{topicID:e,messageIDs:u})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,ze([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let r=ze([],{graft:t.graft,prune:t.prune});this.sendRpc(e,r)}}pushGossip(e,t){this.log("Add gossip to %s",e);let r=this.gossip.get(e)??[];this.gossip.set(e,r.concat(t))}async makePrune(e,t,r,n){if(this.score.prune(e,t),this.streamsOutbound.get(e)?.protocol===Wr)return{topicID:t,peers:[]};let i=n?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,o=i/1e3;if(this.doAddBackoff(e,t,i),!r)return{topicID:t,peers:[],backoff:o};let a=this.getRandomGossipPeers(t,this.opts.prunePeers,u=>u!==e&&this.score.score(u)>=0),l=await Promise.all(Array.from(a).map(async u=>{let p=this.peers.get(u)??Rt(u),m;try{m=await this.components.peerStore.get(p)}catch(x){if(x.name!=="NotFoundError")throw x}return{peerID:p.toMultihash().bytes,signedPeerRecord:m?.peerRecordEnvelope}}));return{topicID:t,peers:l,backoff:o}}runHeartbeat=()=>{let e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch(t=>{this.log("Error running heartbeat",t)}).finally(()=>{if(e?.(),this.status.code===Pe.started){clearTimeout(this.status.heartbeatTimeout);let t=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;t<this.opts.heartbeatInterval*.25&&(t+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,t)}})};async heartbeat(){let{D:e,Dlo:t,Dhi:r,Dscore:n,Dout:i,fanoutTTL:o}=this.opts;this.heartbeatTicks++;let a=new Map,l=f=>{let g=a.get(f);return g===void 0&&(g=this.score.score(f),a.set(f,g)),g},u=new Map,p=new Map,m=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.iwantCounts.clear(),this.applyIwantPenalties(),this.idontwantCounts.clear();for(let f of this.idontwants.values())for(let[g,w]of f)this.heartbeatTicks-w>=this.opts.mcacheLength&&f.delete(g);this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let x=new Map;this.mesh.forEach((f,g)=>{let w=this.topics.get(g),E=new Set,S=new Set;if(x.set(g,S),w!=null){let d=Ze(Array.from(w)),b=this.backoff.get(g);for(let v of d){let _=this.streamsOutbound.get(v);if(_!=null&&this.protocols.includes(_.protocol)&&!f.has(v)&&!this.direct.has(v)){let D=l(v);b?.has(v)!==!0&&D>=0&&E.add(v),D>=this.opts.scoreThresholds.gossipThreshold&&S.add(v)}}}let c=(d,b)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",d,g),this.addBackoff(d,g),f.delete(d),l(d)>=this.opts.scoreThresholds.gossipThreshold&&S.add(d),this.metrics?.onRemoveFromMesh(g,b,1);let v=p.get(d);v==null?p.set(d,[g]):v.push(g)},h=(d,b)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",d,g),this.addToMesh(d,g,b),S.delete(d);let v=u.get(d);v==null?u.set(d,[g]):v.push(g)};if(f.forEach(d=>{let b=l(d);b<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",d,b,g),c(d,Ke.BadScore),m.set(d,!0))}),f.size<t){let d=e-f.size;pc(E,d).forEach(v=>{h(v,ge.NotEnough)})}if(f.size>r){let d=Array.from(f);d.sort((v,_)=>l(_)-l(v)),d=d.slice(0,n).concat(Ze(d.slice(n)));let b=0;if(d.slice(0,e).forEach(v=>{(this.outbound.get(v)??!1)&&b++}),b<i){let v=D=>{let P=d[D];for(let K=D;K>0;K--)d[K]=d[K-1];d[0]=P};if(b>0){let D=b;for(let P=1;P<e&&D>0;P++)(this.outbound.get(d[P])??!1)&&(v(P),D--)}let _=e-b;for(let D=e;D<d.length&&_>0;D++)(this.outbound.get(d[D])??!1)&&(v(D),_--)}d.slice(e).forEach(v=>{c(v,Ke.Excess)})}if(f.size>=t){let d=0;if(f.forEach(b=>{(this.outbound.get(b)??!1)&&d++}),d<i){let b=i-d;Fr(E,b,_=>this.outbound.get(_)===!0).forEach(_=>{h(_,ge.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&f.size>1){let d=Array.from(f).sort((_,D)=>l(_)-l(D)),b=Math.floor(f.size/2),v=l(d[b]);if(v<this.opts.scoreThresholds.opportunisticGraftThreshold){let _=this.opts.opportunisticGraftPeers,D=Fr(E,_,P=>l(P)>v);for(let P of D)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",P,g),h(P,ge.Opportunistic)}}});let y=Date.now();this.fanoutLastpub.forEach((f,g)=>{f+o<y&&(this.fanout.delete(g),this.fanoutLastpub.delete(g))}),this.fanout.forEach((f,g)=>{let w=this.topics.get(g);f.forEach(h=>{(!(w?.has(h)??!1)||l(h)<this.opts.scoreThresholds.publishThreshold)&&f.delete(h)});let E=this.topics.get(g),S=[],c=new Set;if(x.set(g,c),E!=null){let h=Ze(Array.from(E));for(let d of h){let b=this.streamsOutbound.get(d);if(b!=null&&this.protocols.includes(b.protocol)&&!f.has(d)&&!this.direct.has(d)){let v=l(d);v>=this.opts.scoreThresholds.publishThreshold&&S.push(d),v>=this.opts.scoreThresholds.gossipThreshold&&c.add(d)}}}if(f.size<e){let h=e-f.size;S.slice(0,h).forEach(d=>{f.add(d),c?.delete(d)})}}),this.emitGossip(x),await this.sendGraftPrune(u,p,m),this.flush(),this.mcache.shift(),this.dispatchEvent(new CustomEvent("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,r=()=>!0){let n=this.topics.get(e);if(n==null)return new Set;let i=[];return n.forEach(o=>{let a=this.streamsOutbound.get(o);a!=null&&this.protocols.includes(a.protocol)&&r(o)&&i.push(o)}),i=Ze(i),t>0&&i.length>t&&(i=i.slice(0,t)),new Set(i)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0,r=Date.now();e.connectedPeersBackoffSec.reset();for(let l of this.backoff.values()){t+=l.size;for(let[u,p]of l.entries())this.peers.has(u)&&e.connectedPeersBackoffSec.observe(Math.max(0,p-r)/1e3)}e.cacheSize.set({cache:"backoff"},t);let n=0;for(let l of this.idontwants.values())n+=l.size;e.cacheSize.set({cache:"idontwants"},n);for(let[l,u]of this.topics)e.topicPeersCount.set({topicStr:l},u.size);for(let[l,u]of this.mesh)e.meshPeerCounts.set({topicStr:l},u.size);let i=[],o=new Map;e.behaviourPenalty.reset();for(let l of this.peers.keys()){let u=this.score.score(l);i.push(u),o.set(l,u),e.behaviourPenalty.observe(this.score.peerStats.get(l)?.behaviourPenalty??0)}e.registerScores(i,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,o);let a=wc(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(a)}tagMeshPeer=e=>{let{peerId:t,topic:r}=e.detail;this.components.peerStore.merge(this.peers.get(t)??Rt(t),{tags:{[r]:{value:100}}}).catch(n=>{this.log.error("Error tagging peer %s with topic %s",t,r,n)})};untagMeshPeer=e=>{let{peerId:t,topic:r}=e.detail;this.components.peerStore.merge(this.peers.get(t)??Rt(t),{tags:{[r]:void 0}}).catch(n=>{this.log.error("Error untagging peer %s with topic %s",t,r,n)})}};var wt="StrictSign",Ft="StrictNoSign",me;(function(s){s.Accept="accept",s.Ignore="ignore",s.Reject="reject"})(me||(me={}));var Uf=Ot;function Kf(s={}){return e=>new qr(e,s)}return Hc(zf);})();
3
3
  /*! Bundled license information:
4
4
 
5
5
  @noble/curves/utils.js: