@libp2p/gossipsub 17.1.1 → 17.1.2-183116ba0

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 El=Object.create;var zs=Object.defineProperty;var Sl=Object.getOwnPropertyDescriptor;var _l=Object.getOwnPropertyNames;var Il=Object.getPrototypeOf,Tl=Object.prototype.hasOwnProperty;var Dl=(s,e)=>()=>{try{return e||s((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Ae=(s,e)=>{for(var t in e)zs(s,t,{get:e[t],enumerable:!0})},Xi=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of _l(e))!Tl.call(s,n)&&n!==t&&zs(s,n,{get:()=>e[n],enumerable:!(r=Sl(e,n))||r.enumerable});return s};var Al=(s,e,t)=>(t=s!=null?El(Il(s)):{},Xi(e||!s||!s.__esModule?zs(t,"default",{value:s,enumerable:!0}):t,s)),Ml=s=>Xi(zs({},"__esModule",{value:!0}),s);var rl=Dl((hy,sl)=>{"use strict";function ie(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))}ie.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]}};ie.prototype.get=function(e){return this.peekAt(e)};ie.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};ie.prototype.peekFront=function(){return this.peek()};ie.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(ie.prototype,"length",{get:function(){return this.size()}});ie.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ie.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)};ie.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}};ie.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)};ie.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}};ie.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}}};ie.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 c;for(n=new Array(t),c=0;c<t;c++)n[c]=this._list[this._head+r+c&this._capacityMask];if(r=this._head+r&this._capacityMask,e+t===o){for(this._tail=this._tail-t+a&this._capacityMask,c=t;c>0;c--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(e===0){for(this._head=this._head+t+a&this._capacityMask,c=t-1;c>0;c--)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,c=e;c>0;c--)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,c=o-(t+e);c>0;c--)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}}};ie.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,c=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);c>p;)this.unshift(arguments[--c]);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<c;)this.push(arguments[p++]);for(i=0;i<m;i++)this.push(o[i])}return a}else return this.remove(r,t)}};ie.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0};ie.prototype.isEmpty=function(){return this._head===this._tail};ie.prototype.toArray=function(){return this._copyArray(!1)};ie.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]};ie.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,c;if(e||this._head>this._tail){for(c=this._head;c<n;c++)o[a++]=r[c];for(c=0;c<this._tail;c++)o[a++]=r[c]}else for(c=this._head;c<this._tail;c++)o[a++]=r[c];return o};ie.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};ie.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1};ie.prototype._nextPowerOf2=function(e){var t=Math.log(e)/Math.log(2),r=1<<t+1;return Math.max(r,4)};sl.exports=ie});var Qf={};Ae(Qf,{StrictNoSign:()=>Ut,StrictSign:()=>Et,TopicValidatorResult:()=>xe,gossipsub:()=>Jf,multicodec:()=>Xf});var jr="/floodsub/1.0.0",Pl="/meshsub/1.0.0",Ji="/meshsub/1.1.0",Kt="/meshsub/1.2.0",Bl=[Pl,Ji,Kt],qs=Bl,St;(function(s){s.Backoff="Backoff",s.IDontWant="IDontWant"})(St||(St={}));var kl={[St.Backoff]:Ji,[St.IDontWant]:Kt};function Zr(s,e){if(s==null)return!1;let t=qs.indexOf(s);return t===-1?!1:t>=qs.indexOf(kl[e])}var Qi=6,eo=4,to=12,so=4,ro=2,no=5,io=3,oo=6,ao=.25,co=3,Yr=100,lo=1e3,uo=6e4,ho=16,fo=6e4,po=10*1e3,mo=15;var td=30*1e3,go=300,bo=1e3,yo=60,wo=2,xo=10*1e3,Qe=5e3,vo=10,Eo=10,So=3*1e3,_o=2*6e4,Io=120*1e3,To="ERR_TOPIC_VALIDATOR_REJECT",Do="ERR_TOPIC_VALIDATOR_IGNORE",Ao=0,Mo=128,Po=1e3,Bo=1e3,ko=1,Ro=512,Lo=512,Co=1024*1024,Oo=1024;var oe=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},zt=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Gs=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Hs=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var qt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Xr=Symbol.for("@libp2p/peer-id");function Rl(s){return typeof s?.handleEvent=="function"}function Ll(s){return s===!0||s===!1}function Cl(s){return Ll(s)?s:s?.capture??!1}function Jr(s){let e={capture:Cl(s),once:!!s?.once};return s?.passive!=null&&(e.passive=s?.passive),s?.signal!=null&&(e.signal=s?.signal),e}function No(s,e){return Jr(s).capture===Jr(e).capture}var Ws=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=Jr(r);if(n?.signal?.aborted===!0)return;let i=u=>{n.once&&this.removeEventListener(e,t,n),Rl(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:No(u.options,n)))return;super.addEventListener(e,i,n);let c=()=>{this.removeEventListener(e,t,n)};n.signal?.addEventListener("abort",c),o.push({callback:t,wrapper:i,options:n,onAbort:c})}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&&No(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 Uo=Symbol.for("@libp2p/service-capabilities"),Ko=Symbol.for("@libp2p/service-dependencies");var rn={};Ae(rn,{base58btc:()=>ce,base58flickr:()=>Gl});var Pd=new Uint8Array(0);function qo(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 Oe(s){if(s instanceof Uint8Array&&s.constructor.name==="Uint8Array")return _t(s);if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return _t(new Uint8Array(s.buffer,s.byteOffset,s.byteLength));throw new Error("Unknown type, must be binary type")}function Go(s){let e=new Uint8Array(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}var zo=4096;function Ho(s){let e=s.length;if(e<=zo)return String.fromCharCode.apply(String,s);let t="",r=0;for(;r<e;)t+=String.fromCharCode.apply(String,s.subarray(r,r+=zo));return t}function Ol(s){return s?.buffer instanceof ArrayBuffer}function _t(s){return Ol(s)?s:s.slice()}function Fl(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 c=o.toLowerCase().charCodeAt(0),u=o.toUpperCase().charCodeAt(0);c!==a&&(r[c]=i),u!==a&&(r[u]=i)}}var p=s.length,m=s.charAt(0),E=Math.log(p)/Math.log(256),y=Math.log(256)/Math.log(p);function f(S){if(S instanceof Uint8Array||(ArrayBuffer.isView(S)?S=new Uint8Array(S.buffer,S.byteOffset,S.byteLength):Array.isArray(S)&&(S=Uint8Array.from(S))),!(S instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(S.length===0)return"";for(var _=0,l=0,h=0,d=S.length;h!==d&&S[h]===0;)h++,_++;for(var b=(d-h)*y+1>>>0,v=new Uint8Array(b);h!==d;){for(var I=S[h],D=0,M=b-1;(I!==0||D<l)&&M!==-1;M--,D++)I+=256*v[M]>>>0,v[M]=I%p>>>0,I=I/p>>>0;if(I!==0)throw new Error("Non-zero carry");l=D,h++}for(var U=b-l;U!==b&&v[U]===0;)U++;for(var z=m.repeat(_);U<b;++U)z+=s.charAt(v[U]);return z}function g(S){if(typeof S!="string")throw new TypeError("Expected String");if(S.length===0)return new Uint8Array;var _=0;if(S[_]!==" "){for(var l=0,h=0;S[_]===m;)l++,_++;for(var d=(S.length-_)*E+1>>>0,b=new Uint8Array(d);S[_];){var v=r[S.charCodeAt(_)];if(v===255)return;for(var I=0,D=d-1;(v!==0||I<h)&&D!==-1;D--,I++)v+=p*b[D]>>>0,b[D]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");h=I,_++}if(S[_]!==" "){for(var M=d-h;M!==d&&b[M]===0;)M++;for(var U=new Uint8Array(l+(d-M)),z=l;M!==d;)U[z++]=b[M++];return U}}}function w(S){var _=g(S);if(_)return _;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:g,decode:w}}var Nl=Fl,Ul=Nl,Vo=Ul;var Qr=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")}},en=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 $o(this,e)}},tn=class{decoders;constructor(e){this.decoders=e}or(e){return $o(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 $o(s,e){return new tn({...s.decoders??{[s.prefix]:s},...e.decoders??{[e.prefix]:e}})}var sn=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 Qr(e,t,r),this.decoder=new en(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Gt({name:s,prefix:e,encode:t,decode:r}){return new sn(s,e,t,r)}function lt({name:s,prefix:e,alphabet:t,caseInsensitive:r=!1}){let{encode:n,decode:i}=Vo(t,s,r);return Gt({prefix:e,name:s,encode:n,decode:o=>Oe(i(o))})}function Kl(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,c=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[c++]=255&a>>o)}if(o>=t||(255&a<<8-o)!==0)throw new SyntaxError("Unexpected end of data");return i}function zl(s,e,t){let r=e[e.length-1]==="=",n=(1<<t)-1,i="",o=0,a=0;for(let c=0;c<s.length;++c)for(a=a<<8|s[c],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 ql(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 ae({name:s,prefix:e,bitsPerChar:t,alphabet:r,caseInsensitive:n=!1}){let i=ql(r,n);return Gt({prefix:e,name:s,encode(o){return zl(o,r,t)},decode(o){return Kl(o,i,t,s)}})}var ce=lt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Gl=lt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var nn={};Ae(nn,{base32:()=>Ht,base32hex:()=>$l,base32hexpad:()=>Zl,base32hexpadupper:()=>Yl,base32hexupper:()=>jl,base32pad:()=>Wl,base32padupper:()=>Vl,base32upper:()=>Hl,base32z:()=>Xl});var Ht=ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),Hl=ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),Wl=ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),Vl=ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),$l=ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),jl=ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),Zl=ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),Yl=ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),Xl=ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var on={};Ae(on,{base36:()=>ps,base36upper:()=>Jl});var ps=lt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),Jl=lt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var Ql=Yo,jo=128,eu=127,tu=~eu,su=Math.pow(2,31);function Yo(s,e,t){e=e||[],t=t||0;for(var r=t;s>=su;)e[t++]=s&255|jo,s/=128;for(;s&tu;)e[t++]=s&255|jo,s>>>=7;return e[t]=s|0,Yo.bytes=t-r+1,e}var ru=an,nu=128,Zo=127;function an(s,r){var t=0,r=r||0,n=0,i=r,o,a=s.length;do{if(i>=a)throw an.bytes=0,new RangeError("Could not decode varint");o=s[i++],t+=n<28?(o&Zo)<<n:(o&Zo)*Math.pow(2,n),n+=7}while(o>=nu);return an.bytes=i-r,t}var iu=Math.pow(2,7),ou=Math.pow(2,14),au=Math.pow(2,21),cu=Math.pow(2,28),lu=Math.pow(2,35),uu=Math.pow(2,42),hu=Math.pow(2,49),fu=Math.pow(2,56),du=Math.pow(2,63),pu=function(s){return s<iu?1:s<ou?2:s<au?3:s<cu?4:s<lu?5:s<uu?6:s<hu?7:s<fu?8:s<du?9:10},mu={encode:Ql,decode:ru,encodingLength:pu},gu=mu,ms=gu;function gs(s,e=0){let t=ms.decode(s,e),r=ms.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 Wt(s,e,t=0){return ms.encode(s,e,t),e}function Vt(s){return ms.encodingLength(s)}function $e(s,e){let t=e.byteLength,r=Vt(s),n=r+Vt(t),i=new Uint8Array(n+t);return Wt(s,i,0),Wt(t,i,r),i.set(e,n),new $t(s,t,e,i)}function et(s){let e=Oe(s),[t,r]=gs(e),[n,i]=gs(e.subarray(r)),o=e.subarray(r+i);if(o.byteLength!==n)throw new Error("Incorrect length");return new $t(t,n,o,e)}function Xo(s,e){if(s===e)return!0;{let t=e;return s.code===t.code&&s.size===t.size&&t.bytes instanceof Uint8Array&&qo(s.bytes,t.bytes)}}var $t=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=_t(r),this.bytes=_t(n)}};function Jo(s,e){let{bytes:t,version:r}=s;return r===0?yu(t,cn(s),e??ce.encoder):wu(t,cn(s),e??Ht.encoder)}var Qo=new WeakMap;function cn(s){let e=Qo.get(s);if(e==null){let t=new Map;return Qo.set(s,t),t}return e}var pe=class s{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=_t(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!==bs)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==xu)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=$e(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&&Xo(e.multihash,r.multihash)}toString(e){return Jo(this,e)}toJSON(){return{"/":Jo(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??ea(r,n,i.bytes))}else if(t[vu]===!0){let{version:r,multihash:n,code:i}=t,o=et(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!==bs)throw new Error(`Version 0 CID must use dag-pb (code: ${bs}) block encoding`);return new s(e,t,r,r.bytes)}case 1:{let n=ea(e,t,r.bytes);return new s(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return s.create(0,bs,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=Oe(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 $t(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,E]=gs(e.subarray(t));return t+=E,m},n=r(),i=bs;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(),c=r(),u=t+c,p=u-o;return{version:n,codec:i,multihashCode:a,digestSize:c,multihashSize:p,size:u}}static parse(e,t){let[r,n]=bu(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 cn(i).set(r,e),i}};function bu(s,e){switch(s[0]){case"Q":{let t=e??ce;return[ce.prefix,t.decode(`${ce.prefix}${s}`)]}case ce.prefix:{let t=e??ce;return[ce.prefix,t.decode(s)]}case Ht.prefix:{let t=e??Ht;return[Ht.prefix,t.decode(s)]}case ps.prefix:{let t=e??ps;return[ps.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 yu(s,e,t){let{prefix:r}=t;if(r!==ce.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 wu(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 bs=112,xu=18;function ea(s,e,t){let r=Vt(s),n=r+Vt(e),i=new Uint8Array(n+t.byteLength);return Wt(s,i,0),Wt(e,i,r),i.set(t,n),i}var vu=Symbol.for("@ipld/js-cid/CID");var ln={};Ae(ln,{identity:()=>qe});var ta=0,Eu="identity",sa=Oe;function Su(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 $e(ta,sa(s))}var qe={code:ta,name:Eu,encode:sa,digest:Su};function Me(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 _u(s){return s.buffer instanceof ArrayBuffer}function Fe(s){return _u(s)?s:s.slice()}async function ra(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,Fe(e),Fe(t.subarray()));return r?.signal?.throwIfAborted(),i}function tt(s=0){return new Uint8Array(s)}function ge(s=0){return new Uint8Array(s)}function Iu(s){return s?.buffer instanceof ArrayBuffer}function na(s){if(Iu(s))return s;let e=s.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function It(s,e){e==null&&(e=s.reduce((n,i)=>n+i.length,0));let t=ge(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return na(t)}var oa=Symbol.for("@achingbrain/uint8arraylist");function ia(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 $s(s){return!!s?.[oa]}var de=class s{bufs;length;[oa]=!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($s(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($s(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=ia(this.bufs,e);return t.buf[t.index]}set(e,t){let r=ia(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($s(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 It(r,n)}subarray(e,t){let{bufs:r,length:n}=this._subList(e,t);return r.length===1?r[0]:It(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,c=a+o.byteLength;if(n=c,e>=c)continue;let u=e>=a&&e<c,p=t>a&&t<=c;if(u&&p){if(e===a&&t===c){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===c){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(!$s(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,c=this.byteLength-r.byteLength,u=r.byteLength-1,p;for(let m=t;m<=c;m+=p){p=0;for(let E=u;E>=0;E--){let y=this.get(m+E);if(r[E]!==y){p=Math.max(1,E-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=ge(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=tt(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=tt(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=tt(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=ge(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=tt(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=tt(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=tt(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=tt(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=tt(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(!Me(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 un={};Ae(un,{base10:()=>Tu});var Tu=lt({prefix:"9",name:"base10",alphabet:"0123456789"});var hn={};Ae(hn,{base16:()=>Du,base16upper:()=>Au});var Du=ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),Au=ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var fn={};Ae(fn,{base2:()=>Mu});var Mu=ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var dn={};Ae(dn,{base256emoji:()=>Lu});var aa=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}"),Pu=aa.reduce((s,e,t)=>(s[t]=e,s),[]),Bu=aa.reduce((s,e,t)=>{let r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return s[r]=t,s},[]);function ku(s){return s.reduce((e,t)=>(e+=Pu[t],e),"")}function Ru(s){let e=[];for(let t of s){let r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);let n=Bu[r];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Lu=Gt({prefix:"\u{1F680}",name:"base256emoji",encode:ku,decode:Ru});var pn={};Ae(pn,{base64:()=>Cu,base64pad:()=>Ou,base64url:()=>Fu,base64urlpad:()=>Nu});var Cu=ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ou=ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Fu=ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Nu=ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var mn={};Ae(mn,{base8:()=>Uu});var Uu=ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var gn={};Ae(gn,{identity:()=>Ku});var Ku=Gt({prefix:"\0",name:"identity",encode:s=>Ho(Oe(s)),decode:s=>Oe(Go(s))});var mp=new TextEncoder,gp=new TextDecoder;var wn={};Ae(wn,{sha256:()=>Tt,sha512:()=>Hu});var Gu=20;function yn({name:s,code:e,encode:t,minDigestLength:r,maxDigestLength:n}){return new bn(s,e,t,r,n)}var bn=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,r,n,i){this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??Gu,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?ca(r,this.code,t?.truncate):r.then(n=>ca(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ca(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 $e(e,s)}function ua(s){return async e=>new Uint8Array(await crypto.subtle.digest(s,e))}var Tt=yn({name:"sha2-256",code:18,encode:ua("SHA-256")}),Hu=yn({name:"sha2-512",code:19,encode:ua("SHA-512")});var xn={...gn,...fn,...mn,...un,...hn,...nn,...on,...rn,...pn,...dn},Ap={...wn,...ln};function fa(s,e,t,r){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:r}}}var ha=fa("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),vn=fa("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=ge(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),Wu={utf8:ha,"utf-8":ha,hex:xn.base16,latin1:vn,ascii:vn,binary:vn,...xn},js=Wu;function Y(s,e="utf8"){let t=js[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${s}`)}function j(s,e="utf8"){let t=js[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(s).substring(1)}var Vu=parseInt("11111",2),En=parseInt("10000000",2),$u=parseInt("01111111",2),da={0:ys,1:ys,2:ju,3:Xu,4:Ju,5:Yu,6:Zu,16:ys,22:ys,48:ys};function st(s,e={offset:0}){let t=s[e.offset]&Vu;if(e.offset++,da[t]!=null)return da[t](s,e);throw new Error("No decoder for tag "+t)}function ws(s,e){let t=0;if((s[e.offset]&En)===En){let r=s[e.offset]&$u,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 ys(s,e){ws(s,e);let t=[];for(;!(e.offset>=s.byteLength);){let r=st(s,e);if(r===null)break;t.push(r)}return t}function ju(s,e){let t=ws(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 Zu(s,e){let t=ws(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}`,c=[];for(;e.offset<r;){let u=s[e.offset];if(e.offset++,c.push(u&127),u<128){c.reverse();let p=0;for(let m=0;m<c.length;m++)p+=c[m]<<m*7;a+=`.${p}`,c=[]}}return a}function Yu(s,e){return e.offset++,null}function Xu(s,e){let t=ws(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 Ju(s,e){let t=ws(s,e),r=s.subarray(e.offset,e.offset+t);return e.offset+=t,r}function Qu(s){let e=s.toString(16);e.length%2===1&&(e="0"+e);let t=new de;for(let r=0;r<e.length;r+=2)t.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return t}function Sn(s){if(s.byteLength<128)return Uint8Array.from([s.byteLength]);let e=Qu(s.byteLength);return new de(Uint8Array.from([e.byteLength|En]),e)}function Pe(s){let e=new de,t=128;return(s.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(s),new de(Uint8Array.from([2]),Sn(e),e)}function Zs(s){let e=Uint8Array.from([0]),t=new de(e,s);return new de(Uint8Array.from([3]),Sn(t),t)}function ht(s,e=48){let t=new de;for(let r of s)t.append(r);return new de(Uint8Array.from([e]),Sn(t),t)}var eh=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),th=Uint8Array.from([6,5,43,129,4,0,34]),sh=Uint8Array.from([6,5,43,129,4,0,35]),rh={ext:!0,kty:"EC",crv:"P-256"},nh={ext:!0,kty:"EC",crv:"P-384"},ih={ext:!0,kty:"EC",crv:"P-521"},_n=32,In=48,Tn=66;function Dn(s){let e=st(s);return pa(e)}function pa(s){let e=s[1][1][0],t=1,r,n;if(e.byteLength===_n*2+1)return r=j(e.subarray(t,t+_n),"base64url"),n=j(e.subarray(t+_n),"base64url"),new jt({...rh,key_ops:["verify"],x:r,y:n});if(e.byteLength===In*2+1)return r=j(e.subarray(t,t+In),"base64url"),n=j(e.subarray(t+In),"base64url"),new jt({...nh,key_ops:["verify"],x:r,y:n});if(e.byteLength===Tn*2+1)return r=j(e.subarray(t,t+Tn),"base64url"),n=j(e.subarray(t+Tn),"base64url"),new jt({...ih,key_ops:["verify"],x:r,y:n});throw new oe(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function ma(s){return ht([Pe(Uint8Array.from([1])),ht([oh(s.crv)],160),ht([Zs(new de(Uint8Array.from([4]),Y(s.x??"","base64url"),Y(s.y??"","base64url")))],161)]).subarray()}function oh(s){if(s==="P-256")return eh;if(s==="P-384")return th;if(s==="P-521")return sh;throw new oe(`Invalid curve ${s}`)}var jt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=ma(this.jwk)),this._raw}toMultihash(){return qe.digest(je(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Me(this.raw,e.raw)}async verify(e,t,r){return ra(this.jwk,t,e,r)}};var Ys=BigInt(4294967295),ga=BigInt(32);function ah(s,e=!1){return e?{h:Number(s&Ys),l:Number(s>>ga&Ys)}:{h:Number(s>>ga&Ys)|0,l:Number(s&Ys)|0}}function ba(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}=ah(s[i],e);[r[i],n[i]]=[o,a]}return[r,n]}var ch=s=>s/2**32|0,lh=s=>s>>>0;function ya(s,e,t,r){let n=ch(t),i=lh(t);s.setUint32(e,r?i:n,r),s.setUint32(e+4,r?n:i,r)}var An=(s,e,t)=>s>>>t,Mn=(s,e,t)=>s<<32-t|e>>>t,Dt=(s,e,t)=>s>>>t|e<<32-t,At=(s,e,t)=>s<<32-t|e>>>t,xs=(s,e,t)=>s<<64-t|e>>>t-32,vs=(s,e,t)=>s>>>t-32|e<<64-t;function Ze(s,e,t,r){let n=(e>>>0)+(r>>>0);return{h:s+t+(n/2**32|0)|0,l:n|0}}var wa=(s,e,t)=>(s>>>0)+(e>>>0)+(t>>>0),xa=(s,e,t,r)=>e+t+r+(s/2**32|0)|0,va=(s,e,t,r)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0),Ea=(s,e,t,r,n)=>e+t+r+n+(s/2**32|0)|0,Sa=(s,e,t,r,n)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),_a=(s,e,t,r,n,i)=>e+t+r+n+i+(s/2**32|0)|0;function Xs(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in s&&s.BYTES_PER_ELEMENT===1}var Pn=s=>s?`"${s}" `:"";function rt(s,e=""){if(typeof s!="number")throw new TypeError(Pn(e)+"expected number, got "+typeof s);if(!Number.isSafeInteger(s)||s<0)throw new RangeError(Pn(e)+"expected integer >= 0, got "+s);return s}function Ne(s,e,t=""){if(Xs(s)&&(e===void 0||s.length===e))return s;e!==void 0&&rt(e,"length");let r=Xs(s),n=e!==void 0?` of length ${e}`:"",i=r?`length=${s.length}`:`type=${typeof s}`,o=Pn(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(rt(s.outputLen),rt(s.blockLen),s.outputLen<1||s.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var hh=(s,e)=>{if(s===null||typeof s!="object"||Array.isArray(s))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof s)},Ia=(s,e)=>{hh(s,e);let t=Object.getPrototypeOf(s);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(s,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function Zt(s,e=!0){if(s.destroyed)throw new Error("hash was destroyed");if(e&&s.finished)throw new Error("digest() was already called")}function Qs(s,e){Ne(s,void 0,"output");let t=e.outputLen;if(!(s.length>=t))throw new RangeError('"output" expected length >= '+t)}function Mt(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function er(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Ge(s,e){return s<<32-e|s>>>e}var Da=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",fh=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function tr(s){if(Ne(s),Da)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=fh[s[t]];return e}function Ta(s){return s>=48&&s<=57?s-48:s>=65&&s<=70?s-55:s>=97&&s<=102?s-87:void 0}function sr(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);if(Da)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=Ta(s.charCodeAt(i)),a=Ta(s.charCodeAt(i+1));if(o===void 0||a===void 0){let c=s[i]+s[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}r[n]=o*16+a}return r}function Bn(...s){let e=0;for(let r=0;r<s.length;r++){let n=s[r];Ne(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 dh(s,e,t="opts"){return Ia(s,"defaults"),e!==void 0&&Ia(e,t),Object.assign(Object.create(null),s,e)}function kn(s,e={}){if(typeof s!="function")throw new TypeError('"hashCons" expected function, got type='+typeof s);e=dh({},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 Aa(s=32){rt(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 Rn=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function Ma(s,e,t){return s&e^~s&t}function Pa(s,e,t){return s&e^s&t^e&t}var Es=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=er(this.buffer)}update(e){Zt(this),Ne(e);let{view:t,buffer:r,blockLen:n}=this,i=e.length,o=!1;for(let a=0;a<i;){let c=Math.min(n-this.pos,i-a);if(c===n){let u=er(e);for(;n<=i-a;a+=n)this.process(u,a);o=!0;continue}r.set(a===0&&c===i?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===n&&(this.process(t,0),this.pos=0,o=!0)}return this.length+=e.length,o&&this.roundClean(),this}digestInto(e){Zt(this),Qs(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)),ya(r,n-8,this.length*8,i),this.process(r,0),this.roundClean();let a=e===t?r:er(e),c=this.outputLen,u=c/4,p=this.get();if(c%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()}},Ba=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ka=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var ph=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]),ft=new Uint32Array(64),Ln=class extends Es{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:c}=this;return[e,t,r,n,i,o,a,c]}set(e,t,r,n,i,o,a,c){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=c|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)ft[m]=e.getUint32(t,!1);for(let m=16;m<64;m++){let E=ft[m-15],y=ft[m-2],f=Ge(E,7)^Ge(E,18)^E>>>3,g=Ge(y,17)^Ge(y,19)^y>>>10;ft[m]=g+ft[m-7]+f+ft[m-16]|0}let{A:r,B:n,C:i,D:o,E:a,F:c,G:u,H:p}=this;for(let m=0;m<64;m++){let E=Ge(a,6)^Ge(a,11)^Ge(a,25),y=p+E+Ma(a,c,u)+ph[m]+ft[m]|0,g=(Ge(r,2)^Ge(r,13)^Ge(r,22))+Pa(r,n,i)|0;p=u,u=c,c=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,c=c+this.F|0,u=u+this.G|0,p=p+this.H|0,this.set(r,n,i,o,a,c,u,p)}roundClean(){Mt(ft)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Mt(this.buffer)}},Cn=class extends Ln{constructor(){super(32,Ba)}};var Ra=ba(["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))),mh=Ra[0],gh=Ra[1],dt=new Uint32Array(80),pt=new Uint32Array(80),On=class extends Es{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:c,Eh:u,El:p,Fh:m,Fl:E,Gh:y,Gl:f,Hh:g,Hl:w}=this;return[e,t,r,n,i,o,a,c,u,p,m,E,y,f,g,w]}set(e,t,r,n,i,o,a,c,u,p,m,E,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=c|0,this.Eh=u|0,this.El=p|0,this.Fh=m|0,this.Fl=E|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 l=0;l<16;l++,t+=4)dt[l]=e.getUint32(t),pt[l]=e.getUint32(t+=4);for(let l=16;l<80;l++){let h=dt[l-15]|0,d=pt[l-15]|0,b=Dt(h,d,1)^Dt(h,d,8)^An(h,d,7),v=At(h,d,1)^At(h,d,8)^Mn(h,d,7),I=dt[l-2]|0,D=pt[l-2]|0,M=Dt(I,D,19)^xs(I,D,61)^An(I,D,6),U=At(I,D,19)^vs(I,D,61)^Mn(I,D,6),z=va(v,U,pt[l-7],pt[l-16]),Z=Ea(z,b,M,dt[l-7],dt[l-16]);dt[l]=Z|0,pt[l]=z|0}let{Ah:r,Al:n,Bh:i,Bl:o,Ch:a,Cl:c,Dh:u,Dl:p,Eh:m,El:E,Fh:y,Fl:f,Gh:g,Gl:w,Hh:S,Hl:_}=this;for(let l=0;l<80;l++){let h=Dt(m,E,14)^Dt(m,E,18)^xs(m,E,41),d=At(m,E,14)^At(m,E,18)^vs(m,E,41),b=m&y^~m&g,v=E&f^~E&w,I=Sa(_,d,v,gh[l],pt[l]),D=_a(I,S,h,b,mh[l],dt[l]),M=I|0,U=Dt(r,n,28)^xs(r,n,34)^xs(r,n,39),z=At(r,n,28)^vs(r,n,34)^vs(r,n,39),Z=r&i^r&a^i&a,k=n&o^n&c^o&c;S=g|0,_=w|0,g=y|0,w=f|0,y=m|0,f=E|0,{h:m,l:E}=Ze(u|0,p|0,D|0,M|0),u=a|0,p=c|0,a=i|0,c=o|0,i=r|0,o=n|0;let N=wa(M,z,k);r=xa(N,D,U,Z),n=N|0}({h:r,l:n}=Ze(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=Ze(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=Ze(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:p}=Ze(this.Dh|0,this.Dl|0,u|0,p|0),{h:m,l:E}=Ze(this.Eh|0,this.El|0,m|0,E|0),{h:y,l:f}=Ze(this.Fh|0,this.Fl|0,y|0,f|0),{h:g,l:w}=Ze(this.Gh|0,this.Gl|0,g|0,w|0),{h:S,l:_}=Ze(this.Hh|0,this.Hl|0,S|0,_|0),this.set(r,n,i,o,a,c,u,p,m,E,y,f,g,w,S,_)}roundClean(){Mt(dt,pt)}destroy(){this.destroyed=!0,Mt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Fn=class extends On{constructor(){super(64,ka)}};var Yt=kn(()=>new Cn,Rn(1));var Nn=kn(()=>new Fn,Rn(3));function nr(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 H=(s,e,t)=>Ne(s,e,t),Un=rt;function Ca(s,e=""){if(typeof s!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof s)}return s}function mt(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 Pt(s,e){if(typeof s!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof s}`);return s}var Ss=tr,Ue=(...s)=>Bn(...s),Xt=s=>sr(s),bt=Xs,Bt=s=>Aa(s),rr=BigInt(0),La=BigInt(1),bh=s=>s?`"${s}" `:"";function Be(s,e=""){if(typeof s!="boolean")throw new TypeError(bh(e)+"expected boolean, got type="+typeof s);return s}function ir(s){if(typeof s=="bigint"){if(!gt(s))throw new RangeError("positive bigint expected, got "+s)}else Un(s);return s}function nt(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 _s(s){let e=ir(s).toString(16);return e.length&1?"0"+e:e}function Oa(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);return s===""?rr:BigInt("0x"+s)}function Ye(s){return Oa(tr(s))}function kt(s){return Oa(tr(Is(Ne(s)).reverse()))}function or(s,e){if(rt(e),e===0)throw new Error("zero output length is invalid");s=ir(s);let t=e*2,r=s.toString(16);if(r.length>t)throw new RangeError("number is too large");return sr(r.padStart(t,"0"))}function Kn(s,e){return or(s,e).reverse()}function Is(s){return Uint8Array.from(H(s))}function gt(s){return typeof s=="bigint"&&rr<=s}function zn(s,e,t){return gt(s)&&gt(e)&&gt(t)&&e<=s&&s<t}function Jt(s,e,t,r){if(!zn(e,t,r))throw new RangeError("expected valid "+s+": "+t+" <= n < "+r+", got "+e)}function Qt(s){if(s<rr)throw new Error("expected non-negative bigint, got "+s);return s===rr?0:s.toString(2).length}var Ts=s=>(nt(s,"n"),(La<<BigInt(s))-La);function Fa(s,e,t){if(rt(s,"hashLen"),rt(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,c=r(s),u=r(s),p=0,m=()=>{c.fill(1),u.fill(0),p=0},E=(...w)=>t(u,Ue(c,...w)),y=(w=n)=>{u=E(i,w),c=E(),w.length!==0&&(u=E(o,w),c=E())},f=()=>{if(p++>=a)throw new Error("drbg: tried max amount of iterations");let w=0,S=[];for(;w<e;){c=E();let _=c.slice();S.push(_),w+=c.length}return Ue(...S)};return(w,S)=>{m(),y(w);let _;for(;(_=S(f()))===void 0;)y();return m(),_}}function ke(s,e={},t={},r="object"){mt(s,r),mt(e,"fields"),mt(t,"optFields");function n(o,a,c){let u=r==="object"?`param "${String(o)}"`:`"${r}.${String(o)}"`,p=s[o];if(!Object.hasOwn(s,o)&&(c?p!==void 0:a!=="function"))throw new TypeError(`${u} is invalid: expected own property`);if(c&&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(([c,u])=>n(c,u,a));i(e,!1),i(t,!0)}var he=BigInt(0),W=BigInt(1),yt=BigInt(2),Ka=BigInt(3),qn=BigInt(4),za=BigInt(5),yh=BigInt(7),qa=BigInt(8),wh=BigInt(9),xh=BigInt(15),Ga=BigInt(16),vh=BigInt("0x10000000000000000");function re(s,e){if(e<=he)throw new Error("mod: expected positive modulus, got "+e);let t=s%e;return t>=he?t:e+t}function Ha(s,e,t){if(t<=W)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<he)throw new Error("invalid exponent, negatives unsupported");if(e===he)return W;if(e===W)return s;let r=s%t;if(r<he&&(r+=t),e<vh){let a=W;for(;e>he;)e&W&&(a=a*r%t),r=r*r%t,e>>=W;return a}let n=[];for(;e>he;)n.push(Number(e&xh)),e>>=qn;let i=new Array(16);i[0]=W,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 c=n[a];c!==0&&(o=o*i[c]%t)}return o}function te(s,e,t){if(t<=W)throw new Error("pow2: expected modulus > 1, got "+t);if(e<he)throw new Error("pow2: expected non-negative exponent, got "+e);let r=s;for(;e-- >he;)r*=r,r%=t;return r}function Na(s,e){if(s===he)throw new Error("invert: expected non-zero number");if(e<=W)throw new Error("invert: expected modulus > 1, got "+e);let t=re(s,e),r=e,n=he,i=W;for(;t!==he;){let a=r/t,c=r-t*a,u=n-i*a;r=t,t=c,n=i,i=u}if(r!==W)throw new Error("invert: does not exist");return re(n,e)}function Wa(s,e){if(e<=W)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=re(s,e);if(t===he)throw new Error("invertCt: expected non-zero number");let r=Ha(t,e-yt,e);if(re(t*r,e)!==W)throw new Error("invertCt: does not exist");return r}function Gn(s,e,t){let r=s;if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function Hn(s,e){if((s&W)===he)throw new Error(e+": expected odd modulus, got "+s)}function Va(s,e){let t=s,r=(t.ORDER+W)/qn,n=t.pow(e,r);return Gn(t,n,e),n}function Eh(s,e){let t=s,r=(t.ORDER-za)/qa,n=t.mul(e,yt),i=t.pow(n,r),o=t.mul(e,i),a=t.mul(t.mul(o,yt),i),c=t.mul(o,t.sub(a,t.ONE));return Gn(t,c,e),c}function Sh(s){let e=ts(s),t=$a(s),r=t(e,e.neg(e.ONE)),n=t(e,r),i=t(e,e.neg(r)),o=(s+yh)/Ga;return((a,c)=>{let u=a,p=u.pow(c,o),m=u.mul(p,r),E=u.mul(p,n),y=u.mul(p,i),f=u.eql(u.sqr(m),c),g=u.eql(u.sqr(E),c);p=u.cmov(p,m,f),m=u.cmov(y,E,g);let w=u.eql(u.sqr(m),c),S=u.cmov(p,m,w);return Gn(u,S,c),S})}function $a(s){if(s<Ka)throw new Error("sqrt is not defined for small field");Hn(s,"tonelliShanks");let e=s-W,t=0;for(;e%yt===he;)e/=yt,t++;let r=yt,n=ts(s);for(;Ds(n,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Va;let i=n.pow(r,e),o=(e+W)/yt;return function(c,u){let p=c;if(p.is0(u))return u;if(Ds(p,u)!==1)throw new Error("Cannot find square root");let m=t,E=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 S=W<<BigInt(m-g-1),_=p.pow(E,S);m=g,E=p.sqr(_),y=p.mul(y,E),f=p.mul(f,_)}return f}}function _h(s){return Hn(s,"Fp.sqrt"),s%qn===Ka?Va:s%qa===za?Eh:s%Ga===wh?Sh(s):$a(s)}var ja=(s,e)=>(re(s,e)&W)===W,Ih=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function es(s){if(mt(s,"field"),typeof s.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof s.ORDER);nt(s.BYTES,"BYTES"),nt(s.BITS,"BITS");for(let e of Ih)Pt(s[e],"field."+e);if(s.BYTES<1||s.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(s.ORDER<=W)throw new Error("invalid field: expected ORDER > 1, got "+s.ORDER);return s}function cr(s,e,t=!1){es(s),nr(e,"nums"),Be(t,"passZero");let r=s,n=new Array(e.length).fill(t?r.ZERO:void 0),i=e.reduce((a,c,u)=>r.is0(c)?a:(n[u]=a,r.mul(a,c)),r.ONE),o=r.inv(i);return e.reduceRight((a,c,u)=>r.is0(c)?a:(n[u]=r.mul(a,n[u]),r.mul(a,c)),o),n}function Ds(s,e){es(s);let t=s;Hn(t.ORDER,"FpLegendre");let r=(t.ORDER-W)/yt,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 Th(s,e){if(e!==void 0&&Un(e),s<=he)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=Qt(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 Ua=new WeakMap,ar=class{ORDER;BITS;BYTES;isLE;ZERO=he;ONE=W;_lengths;_mod;constructor(e,t={}){if(e<=W)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}=Th(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 re(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return he<=e&&e<this.ORDER}is0(e){return e===he}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&W)===W}neg(e){return re(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return re(e*e,this.ORDER)}add(e,t){return re(e+t,this.ORDER)}sub(e,t){return re(e-t,this.ORDER)}mul(e,t){return re(e*t,this.ORDER)}pow(e,t){return Ha(e,t,this.ORDER)}div(e,t){return re(e*Na(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 Na(e,this.ORDER)}sqrt(e){let t=Ua.get(this);return t||Ua.set(this,t=_h(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Kn(e,this.BYTES):or(e,this.BYTES)}fromBytes(e,t=!1){H(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 c=i?kt(e):Ye(e);if(a&&(c=re(c,o)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return cr(this,e,!0)}cmov(e,t,r){return Be(r,"condition"),r?t:e}};function ts(s,e={}){return Object.freeze(ar.prototype),new ar(s,e)}function Za(s){if(typeof s!="bigint")throw new Error("field order must be bigint");if(s<=W)throw new Error("field order must be greater than 1");let e=Qt(s-W);return Math.ceil(e/8)}function lr(s){let e=Za(s);return e+Math.ceil(e/2)}function ur(s,e,t=!1){H(s);let r=s.length,n=Za(e),i=Math.max(lr(e),16);if(r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let o=t?kt(s):Ye(s),a=re(o,e-W)+W;return t?Kn(a,n):or(a,n)}var $n=BigInt(0),As=BigInt(1),Dh=BigInt(4),Wn=16,Ya=128,Ah=5,Xa=2**31;function wt(s){let e=s;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof s);Pt(e.fromAffine,"Point.fromAffine"),Pt(e.fromBytes,"Point.fromBytes"),Pt(e.fromHex,"Point.fromHex"),mt(e.BASE,"Point.BASE"),mt(e.ZERO,"Point.ZERO"),es(e.Fp),es(e.Fn)}function hr(s,e){wt(s),Qa(e,s);let t=cr(s.Fp,e.map(r=>r.Z));return e.map((r,n)=>s.fromAffine(r.toAffine(t[n])))}function Mh(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 Ph(s,e){let t=s*(4*e+128);if(t>Xa)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+Xa/2**20+" MiB")}function jn(s,e){if(s!==void 0){Pt(s,"randomBytes");try{let t=s(e);if(!bt(t)||t.length!==e)return}catch{return}return s}}function Qa(s,e){nr(s,"points"),s.forEach((t,r)=>{if(!(t instanceof e))throw new Error("invalid point at index "+r)})}function Bh(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):gt(r)&&r<t))throw new Error("invalid scalar at index "+n)})}var ec=new WeakMap;function Vn(s){return ec.get(s)||1}function kh(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 Rh(s,e){let t=2**e,r=t/2,n=BigInt(t-1),i=[];for(;s>$n;){let o=0;s&As&&(o=Number(s&n),o>=r&&(o-=t),s-=BigInt(o)),i.push(o),s>>=As}return i}function Lh(s,e,t){let r=2**e,n=r/2,i=BigInt(r-1),o=BigInt(e),a=[];for(let c=0;c<t;c++){let u=Number(s&i);s>>=o,u>n&&(u-=r,s+=As),a.push(u)}if(s!==$n)throw new Error("invalid wnaf");return a}function Ch(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 c=e[o][Math.abs(a)-1>>1];n=n.add(a<0?c.negate():c)}}}return n}var ss=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){wt(e),this.randomBytes=jn(t,Wn),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 c=0;c<n;c++){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=Lh(t,r,n),c=this.ZERO,u=this.BASE;for(let p=0;p<n;p++){let m=a[p],E=p*o,y=Math.abs(m)-1,f=i[E];for(let w=1;w<o;w++)f=w===y?i[E+w]:f;let g=f.negate();m===0?u=u.add(i[E]):c=c.add(m<0?g:f)}return{p:c,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),!zn(t,As,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,r,n){let i=Vn(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+Ya,i=this.randomBytes(Wn);if(!bt(i)||i.length!==Wn)throw new Error("randomBytes returned invalid byte array");i[0]=i[0]&63|128;let o=t+Ye(i)*this.Point.Fn.ORDER;return this.runCT(e,o,n,r)}fixedWindowCT(e,t,r){let n=Ah,i=1<<n,o=Ts(n),a=new Array(i);a[0]=this.ZERO;for(let p=1;p<i;p++)a[p]=a[p-1].add(e);let c=Math.ceil(r/n),u=this.ZERO;for(let p=c-1;p>=0;p--){if(p!==c-1)for(let y=0;y<n;y++)u=u.double();let m=Number(t>>BigInt(p*n)&o),E=a[0];for(let y=1;y<i;y++)E=y===m?a[y]:E;u=u.add(E)}return{p:u,f:u}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===As?!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),!gt(t))throw new Error("invalid scalar");let n=Vn(e);if(n===1||t>=this.Point.Fn.ORDER)return fr(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),Mh(t,this.bits);let r=Math.ceil((this.bits+Ya)/t)+1;Ph(r*2**(t-1),this.Point.Fp.BYTES),ec.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Vn(e)!==1}};function fr(s,e,t,r=!1){if(wt(s),Qa(e,s),Be(r,"allowOversized"),Bh(t,s.Fn,r?s.Fn.ORDER**Dh:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let n=e.map(o=>kh(o,4)),i=t.map(o=>Rh(o,4));return Ch(s.ZERO,n,i)}function Ja(s,e,t){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return es(e),e}else return ts(s,{isLE:t})}function dr(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`);ke(t);for(let c of["p","n","h"]){let u=e[c];if(!(gt(u)&&u!==$n))throw new Error(`CURVE.${c} must be positive bigint`)}let n=Ja(e.p,t.Fp,r),i=Ja(e.n,t.Fn,r),a=["Gx","Gy","a",s==="weierstrass"?"b":"d"];for(let c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function pr(s,e){return function(r){let n=s(r);return{secretKey:n,publicKey:e(n)}}}var mr=BigInt(0),gr=BigInt(1),br=BigInt(2),Oh=BigInt(4),tc=BigInt(8);function Fh(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 sc(s,e={}){ke(e,{},{},"extraOpts");let t=e,r=dr("edwards",s,t,t.FpFnLE),{Fp:n,Fn:i}=r,o=r.CURVE,{h:a}=o;if(Ds(n,o.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Ds(n,o.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");ke(t,{},{uvRatio:"function",randomBytes:"function"});let c=t.randomBytes===void 0?Bt:t.randomBytes,u=br<<BigInt(n.BYTES*8)-gr;function p(_){if(!n.isOdd)throw new Error("Field does not have .isOdd()");return n.isOdd(_)}let m=t.uvRatio===void 0?(_,l)=>{try{return{isValid:!0,value:n.sqrt(n.div(_,l))}}catch{return{isValid:!1,value:mr}}}:t.uvRatio;if(!Fh(n,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");let E=n.eql(o.a,n.neg(n.ONE))?_=>n.neg(_):n.eql(o.a,n.ONE)?_=>_:_=>n.mul(o.a,_);function y(_,l,h=!1){let d=h?gr:mr;return Jt("coordinate "+_,l,d,u),l}function f(_){if(!(_ 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(l,h,d,b){this.X=y("x",l),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(l){if(l instanceof g)throw new Error("extended point not allowed");let{x:h,y:d}=l||{};return y("x",h),y("y",d),new g(h,d,n.ONE,n.mul(h,d))}static fromBytes(l,h=!1){let d=n.BYTES,{a:b,d:v}=o;l=Is(H(l,d,"point")),Be(h,"zip215");let I=Is(l),D=l[d-1];I[d-1]=D&-129;let M=kt(I),U=h?u:n.ORDER;Jt("point.y",M,mr,U);let z=n.sqr(M),Z=n.sub(z,n.ONE),k=n.sub(n.mulN(v,z),b),{isValid:N,value:K}=m(Z,k);if(!N)throw new Error("bad point: invalid y coordinate");let C=p(K),J=(D&128)!==0;if(!h&&n.is0(K)&&J)throw new Error("bad point: x=0 and x_0=1");return J!==C&&(K=n.neg(K)),g.fromAffine({x:K,y:M})}static fromHex(l,h=!1){return g.fromBytes(Xt(l),h)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(l=6,h=!0){return S.setWindowSize(this,l),h||this.multiply(br),this}assertValidity(){let l=this,{a:h,d}=o;if(l.is0())throw new Error("bad point: ZERO");let{X:b,Y:v,Z:I,T:D}=l,M=n.sqr(b),U=n.sqr(v),z=n.sqr(I),Z=n.sqr(z),k=n.mul(M,h),N=n.mul(n.add(k,U),z),K=n.add(Z,n.mul(d,n.mul(M,U)));if(!n.eql(N,K))throw new Error("bad point: equation left != right (1)");let C=n.mul(b,v),J=n.mul(I,D);if(!n.eql(C,J))throw new Error("bad point: equation left != right (2)")}equals(l){f(l);let{X:h,Y:d,Z:b}=this,{X:v,Y:I,Z:D}=l,M=n.mul(h,D),U=n.mul(v,b),z=n.mul(d,D),Z=n.mul(I,b);return n.eql(M,U)&&n.eql(z,Z)}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:l,Y:h,Z:d}=this,b=n.sqr(l),v=n.sqr(h),I=n.mul(n.sqr(d),br),D=E(b),M=n.addN(l,h),U=n.sub(n.subN(n.sqr(M),b),v),z=n.addN(D,v),Z=n.subN(z,I),k=n.subN(D,v),N=n.mul(U,Z),K=n.mul(z,k),C=n.mul(U,k),J=n.mul(Z,z);return new g(N,K,J,C)}add(l){f(l);let{d:h}=o,{X:d,Y:b,Z:v,T:I}=this,{X:D,Y:M,Z:U,T:z}=l,Z=n.mul(d,D),k=n.mul(b,M),N=n.mul(n.mulN(I,h),z),K=n.mul(v,U),C=n.sub(n.subN(n.mulN(n.addN(d,b),n.addN(D,M)),Z),k),J=n.subN(K,N),se=n.addN(K,N),P=n.sub(k,E(Z)),x=n.mul(C,J),T=n.mul(se,P),A=n.mul(C,P),B=n.mul(J,se);return new g(x,T,B,A)}subtract(l){return f(l),this.add(l.negate())}multiply(l){if(!i.isValidNot0(l))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:h,f:d}=S.mulSecret(this,l,a,w);return w([h,d])[0]}multiplyUnsafe(l){if(!i.isValid(l))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return l===mr?g.ZERO:this.is0()||l===gr?this:S.mulUnsafe(this,l,w)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return S.mulUnsafe(this,o.n).is0()}toAffine(l){let h=this,d=l;if(d!=null&&typeof d!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof d);let{X:b,Y:v,Z:I}=h,D=h.is0();d==null&&(d=D?n.create(tc):n.inv(I));let M=n.mul(b,d),U=n.mul(v,d),z=n.mul(I,d);if(D)return{x:n.ZERO,y:n.ONE};if(!n.eql(z,n.ONE))throw new Error("invZ was invalid");return{x:M,y:U}}clearCofactor(){return a===gr?this:a===br?this.double():a===Oh?this.double().double():a===tc?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:l,y:h}=this.toAffine(),d=n.toBytes(h);return d[d.length-1]|=p(l)?128:0,d}toHex(){return Ss(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let w=_=>hr(g,_),S=new ss(g,c);return S.bits>=6&&g.BASE.precompute(6),Object.freeze(g.prototype),Object.freeze(g),g}function rc(s,e,t={}){if(wt(s),typeof e!="function")throw new Error('"hash" function param is required');let r=e,n=t;ke(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:c}=s,u=r.outputLen,p=2*a.BYTES;if(u!==void 0&&(nt(u,"hash.outputLen"),u!==p))throw new Error(`hash.outputLen must be ${p}, got ${u}`);let m=n.randomBytes===void 0?Bt:n.randomBytes,E=n.toMontgomery,y=n.toMontgomerySecret,f=n.adjustScalarBytes===void 0?k=>k:n.adjustScalarBytes,g=n.domain===void 0?(k,N,K)=>{if(Be(K,"phflag"),N.length||K)throw new Error("Contexts/pre-hash are not supported");return k}:n.domain;function w(k){return c.create(kt(k))}function S(k){let N=D.secretKey;H(k,D.secretKey,"secretKey");let K=H(r(k),2*N,"hashedSecretKey"),C=f(K.slice(0,N)),J=K.slice(N,2*N),se=w(C);return{head:C,prefix:J,scalar:se}}function _(k){let{head:N,prefix:K,scalar:C}=S(k),J=o.multiply(C),se=J.toBytes();return{head:N,prefix:K,scalar:C,point:J,pointBytes:se}}function l(k){return _(k).pointBytes}function h(k=Uint8Array.of(),...N){let K=Ue(...N);return w(r(g(K,H(k,void 0,"context"),!!i)))}function d(k,N,K={}){ke(K,{},{},"options"),k=Is(H(k,void 0,"message")),i&&(k=i(k));let{prefix:C,scalar:J,pointBytes:se}=_(N),P=h(K.context,C,k),x=o.multiply(P).toBytes(),T=h(K.context,x,se,k),A=c.create(P+T*J);if(!c.isValid(A))throw new Error("sign failed: invalid s");let B=Ue(x,c.toBytes(A));return H(B,D.signature,"result")}let b={zip215:n.zip215};function v(k,N,K,C=b){ke(C);let{context:J}=C,se=C.zip215===void 0?!!b.zip215:C.zip215,P=D.signature;k=H(k,P,"signature"),N=H(N,void 0,"message"),K=H(K,D.publicKey,"publicKey"),se!==void 0&&Be(se,"zip215"),i&&(N=i(N));let x=P/2,T=k.subarray(0,x),A=kt(k.subarray(x,P)),B,R,L;try{B=s.fromBytes(K,se),R=s.fromBytes(T,se),L=o.multiplyUnsafe(A)}catch{return!1}if(!se&&B.isSmallOrder())return!1;let O=h(J,T,K,N);return R.add(B.multiplyUnsafe(O)).subtract(L).clearCofactor().is0()}let I=a.BYTES,D={secretKey:I,publicKey:I,signature:2*I,seed:I};function M(k){return k=k===void 0?m(D.seed):k,H(k,D.seed,"seed")}function U(k){return bt(k)&&k.length===D.secretKey}function z(k,N){try{return!!s.fromBytes(k,N===void 0?b.zip215:N)}catch{return!1}}let Z={getExtendedPublicKey:_,randomSecretKey:M,isValidSecretKey:U,isValidPublicKey:z,toMontgomery(k){if(E===void 0)throw new Error("Montgomery conversion is not supported for this curve");return E(s.fromBytes(k))},toMontgomerySecret(k){if(y===void 0)throw new Error("Montgomery conversion is not supported for this curve");return y(k)}};return Object.freeze(D),Object.freeze(Z),Object.freeze({keygen:pr(M,l),getPublicKey:l,sign:d,verify:v,utils:Z,Point:s,lengths:D})}var Zn=BigInt(1),nc=BigInt(2);var Nh=BigInt(5),Uh=BigInt(8),Yn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Kh={p:Yn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Uh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function zh(s){let e=BigInt(10),t=BigInt(20),r=BigInt(40),n=BigInt(80),i=Yn,a=s*s%i*s%i,c=te(a,nc,i)*a%i,u=te(c,Zn,i)*s%i,p=te(u,Nh,i)*u%i,m=te(p,e,i)*p%i,E=te(m,t,i)*m%i,y=te(E,r,i)*E%i,f=te(y,n,i)*y%i,g=te(f,n,i)*y%i,w=te(g,e,i)*p%i;return{pow_p_5_8:te(w,nc,i)*s%i,b2:a}}function ac(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}var ic=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function qh(s,e){let t=Yn,r=re(e*e*e,t),n=re(r*r*e,t),i=zh(s*n).pow_p_5_8,o=re(s*r*i,t),a=re(e*o*o,t),c=o,u=re(o*ic,t),p=a===s,m=a===re(-s,t),E=a===re(-s*ic,t);return p&&(o=c),(m||E)&&(o=u),ja(o,t)&&(o=re(-o,t)),{isValid:p||m,value:o}}var Xn=sc(Kh,{uvRatio:qh}),oc=Xn.Fp;function Gh(s){let{y:e}=s;return oc.toBytes(oc.div(Zn+e,Zn-e))}function Hh(s){let e=Xn.Fp.BYTES;return Ne(s,e),ac(Nn(s.subarray(0,e))).subarray(0,e)}function Wh(s){return rc(Xn,Nn,Object.assign({adjustScalarBytes:ac,toMontgomery:Gh,toMontgomerySecret:Hh,zip215:!0},s))}var cc=Wh({});var Ms=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},yr=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ke={get(s=globalThis){let e=s.crypto;if(e?.subtle==null)throw new yr("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 wr=32;var Jn,Vh=(async()=>{try{return await Ke.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function $h(s,e,t){if(s.buffer instanceof ArrayBuffer){let r=await Ke.get().subtle.importKey("raw",s.buffer,{name:"Ed25519"},!1,["verify"]);return await Ke.get().subtle.verify({name:"Ed25519"},r,Fe(e),Fe(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function jh(s,e,t){return cc.verify(e,t instanceof Uint8Array?t:t.subarray(),s)}async function lc(s,e,t){return Jn==null&&(Jn=await Vh),Jn?$h(s,e,t):jh(s,e,t)}function xr(s){return s==null?!1:typeof s.then=="function"&&typeof s.catch=="function"&&typeof s.finally=="function"}var vr=class{type="Ed25519";raw;constructor(e){this.raw=Qn(e,wr)}toMultihash(){return qe.digest(je(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Me(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();let n=lc(this.raw,t,e);return xr(n)?n.then(i=>(r?.signal?.throwIfAborted(),i)):n}};function ei(s){return s=Qn(s,wr),new vr(s)}function Qn(s,e){if(s=Uint8Array.from(s??[]),s.length!==e)throw new oe(`Key must be a Uint8Array of length ${e}, got ${s.length}`);return s}var Yh=Math.pow(2,7),Xh=Math.pow(2,14),Jh=Math.pow(2,21),ti=Math.pow(2,28),si=Math.pow(2,35),ri=Math.pow(2,42),ni=Math.pow(2,49),V=128,be=127;function ze(s){if(s<Yh)return 1;if(s<Xh)return 2;if(s<Jh)return 3;if(s<ti)return 4;if(s<si)return 5;if(s<ri)return 6;if(s<ni)return 7;if(Number.MAX_SAFE_INTEGER!=null&&s>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ii(s,e,t=0){switch(ze(s)){case 8:e[t++]=s&255|V,s/=128;case 7:e[t++]=s&255|V,s/=128;case 6:e[t++]=s&255|V,s/=128;case 5:e[t++]=s&255|V,s/=128;case 4:e[t++]=s&255|V,s>>>=7;case 3:e[t++]=s&255|V,s>>>=7;case 2:e[t++]=s&255|V,s>>>=7;case 1:{e[t++]=s&255,s>>>=7;break}default:throw new Error("unreachable")}return e}function Qh(s,e,t=0){switch(ze(s)){case 8:e.set(t++,s&255|V),s/=128;case 7:e.set(t++,s&255|V),s/=128;case 6:e.set(t++,s&255|V),s/=128;case 5:e.set(t++,s&255|V),s/=128;case 4:e.set(t++,s&255|V),s>>>=7;case 3:e.set(t++,s&255|V),s>>>=7;case 2:e.set(t++,s&255|V),s>>>=7;case 1:{e.set(t++,s&255),s>>>=7;break}default:throw new Error("unreachable")}return e}function oi(s,e){let t=s[e],r=0;if(r+=t&be,t<V||(t=s[e+1],r+=(t&be)<<7,t<V)||(t=s[e+2],r+=(t&be)<<14,t<V)||(t=s[e+3],r+=(t&be)<<21,t<V)||(t=s[e+4],r+=(t&be)*ti,t<V)||(t=s[e+5],r+=(t&be)*si,t<V)||(t=s[e+6],r+=(t&be)*ri,t<V)||(t=s[e+7],r+=(t&be)*ni,t<V))return r;throw new RangeError("Could not decode varint")}function ef(s,e){let t=s.get(e),r=0;if(r+=t&be,t<V||(t=s.get(e+1),r+=(t&be)<<7,t<V)||(t=s.get(e+2),r+=(t&be)<<14,t<V)||(t=s.get(e+3),r+=(t&be)<<21,t<V)||(t=s.get(e+4),r+=(t&be)*ti,t<V)||(t=s.get(e+5),r+=(t&be)*si,t<V)||(t=s.get(e+6),r+=(t&be)*ri,t<V)||(t=s.get(e+7),r+=(t&be)*ni,t<V))return r;throw new RangeError("Could not decode varint")}function ai(s,e,t=0){return e==null&&(e=ge(ze(s))),e instanceof Uint8Array?ii(s,e,t):Qh(s,e,t)}function ci(s,e=0){return s instanceof Uint8Array?oi(s,e):ef(s,e)}var ui=new Float32Array([-0]),xt=new Uint8Array(ui.buffer);function hc(s,e,t){ui[0]=s,e[t]=xt[0],e[t+1]=xt[1],e[t+2]=xt[2],e[t+3]=xt[3]}function fc(s,e){return xt[0]=s[e],xt[1]=s[e+1],xt[2]=s[e+2],xt[3]=s[e+3],ui[0]}var hi=new Float64Array([-0]),ye=new Uint8Array(hi.buffer);function dc(s,e,t){hi[0]=s,e[t]=ye[0],e[t+1]=ye[1],e[t+2]=ye[2],e[t+3]=ye[3],e[t+4]=ye[4],e[t+5]=ye[5],e[t+6]=ye[6],e[t+7]=ye[7]}function pc(s,e){return ye[0]=s[e],ye[1]=s[e+1],ye[2]=s[e+2],ye[3]=s[e+3],ye[4]=s[e+4],ye[5]=s[e+5],ye[6]=s[e+6],ye[7]=s[e+7],hi[0]}var tf=BigInt(Number.MAX_SAFE_INTEGER),sf=BigInt(Number.MIN_SAFE_INTEGER),Re=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 Rt;if(e<tf&&e>sf)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>mc&&(n=0n,++r>mc&&(r=0n))),new s(Number(n),Number(r))}static fromNumber(e){if(e===0)return Rt;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):Rt}},Rt=new Re(0,0);Rt.toBigInt=function(){return 0n};Rt.zzEncode=Rt.zzDecode=function(){return this};Rt.length=function(){return 1};var mc=4294967296n;function gc(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 bc(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 fi(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 He(s,e){return RangeError(`index out of range: ${s.pos} + ${e??1} > ${s.len}`)}function Er(s,e){return(s[e-4]|s[e-3]<<8|s[e-2]<<16|s[e-1]<<24)>>>0}var di=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Fe(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,He(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 He(this,4);return Er(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw He(this,4);return Er(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw He(this,4);let e=fc(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw He(this,4);let e=pc(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 He(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){let e=this.bytes();return bc(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw He(this,e);this.pos+=e}else do if(this.pos>=this.len)throw He(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 Re(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 He(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 He(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 He(this,8);let e=Er(this.buf,this.pos+=4),t=Er(this.buf,this.pos+=4);return new Re(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=oi(this.buf,this.pos);return this.pos+=ze(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 Ps(s){return new di(s instanceof Uint8Array?s:s.subarray())}function Ee(s,e,t){let r=Ps(s);return e.decode(r,void 0,t)}function pi(s){let e=s??8192,t=e>>>1,r,n=e;return function(o){if(o<1||o>t)return ge(o);n+o>e&&(r=ge(e),n=0);let a=r.subarray(n,n+=o);return(n&7)!==0&&(n=(n|7)+1),a}}var Lt=class{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}};function mi(){}var bi=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},rf=pi();function nf(s){return globalThis.Buffer!=null?ge(s):rf(s)}var ks=class{len;head;tail;states;constructor(){this.len=0,this.head=new Lt(mi,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new Lt(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new yi((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(Sr,10,Re.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Re.fromBigInt(e);return this._push(Sr,t.length(),t)}uint64Number(e){return this._push(ii,ze(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=Re.fromBigInt(e).zzEncode();return this._push(Sr,t.length(),t)}sint64Number(e){let t=Re.fromNumber(e).zzEncode();return this._push(Sr,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(gi,1,e?1:0)}fixed32(e){return this._push(Bs,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Re.fromBigInt(e);return this._push(Bs,4,t.lo)._push(Bs,4,t.hi)}fixed64Number(e){let t=Re.fromNumber(e);return this._push(Bs,4,t.lo)._push(Bs,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(hc,4,e)}double(e){return this._push(dc,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(gi,1,0):this.uint32(t)._push(af,t,e)}string(e){let t=gc(e);return t!==0?this.uint32(t)._push(fi,t,e):this._push(gi,1,0)}fork(){return this.states=new bi(this),this.head=this.tail=new Lt(mi,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Lt(mi,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=nf(this.len),r=0;for(;e!=null;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}};function gi(s,e,t){e[t]=s&255}function of(s,e,t){for(;s>127;)e[t++]=s&127|128,s>>>=7;e[t]=s}var yi=class extends Lt{next;constructor(e,t){super(of,e,t),this.next=void 0}};function Sr(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 Bs(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 af(s,e,t){e.set(s,t)}globalThis.Buffer!=null&&(ks.prototype.bytes=function(s){let e=s.length>>>0;return this.uint32(e),e>0&&this._push(cf,e,s),this},ks.prototype.string=function(s){let e=globalThis.Buffer.byteLength(s);return this.uint32(e),e>0&&this._push(lf,e,s),this});function cf(s,e,t){e.set(s,t)}function lf(s,e,t){s.length<40?fi(s,e,t):e.utf8Write!=null?e.utf8Write(s,t):e.set(Y(s),t)}function wi(){return new ks}function Se(s,e){let t=wi();return e.encode(s,t,{lengthDelimited:!1}),t.finish()}function*_e(s,e,t){let r=Ps(s);yield*e.stream(r,void 0,"$",t)}var _r={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Ir(s,e,t,r,n){return{name:s,type:e,encode:t,decode:r,stream:n}}function xi(s){function e(i){if(s[i.toString()]==null)throw new Error("Invalid enum value");return s[i]}let t=function(o,a){let c=e(o);a.int32(c)},r=function(o){let a=o.int32();return e(a)},n=function*(o){let a=o.int32();yield e(a)};return Ir("enum",_r.VARINT,t,r,n)}function Ie(s,e,t){return Ir("message",_r.LENGTH_DELIMITED,s,e,t)}var X=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ne;(function(s){s.RSA="RSA",s.Ed25519="Ed25519",s.secp256k1="secp256k1",s.ECDSA="ECDSA"})(ne||(ne={}));var vi;(function(s){s[s.RSA=0]="RSA",s[s.Ed25519=1]="Ed25519",s[s.secp256k1=2]="secp256k1",s[s.ECDSA=3]="ECDSA"})(vi||(vi={}));(function(s){s.codec=()=>xi(vi)})(ne||(ne={}));var Xe;(function(s){let e;s.codec=()=>(e==null&&(e=Ie((i,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),i.Type!=null&&(o.uint32(8),ne.codec().encode(i.Type,o)),i.Data!=null&&(o.uint32(18),o.bytes(i.Data)),a.lengthDelimited!==!1&&o.ldelim()},(i,o,a={})=>{let c={},u=o==null?i.len:i.pos+o;for(;i.pos<u;){let p=i.uint32();switch(p>>>3){case 1:{c.Type=ne.codec().decode(i);break}case 2:{c.Data=i.bytes();break}default:{i.skipType(p&7);break}}}return c},function*(i,o,a,c={}){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:ne.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 Se(i,s.codec())}s.encode=t;function r(i,o){return Ee(i,s.codec(),o)}s.decode=r;function n(i,o){return _e(i,s.codec(),o)}s.stream=n})(Xe||(Xe={}));var Ei;(function(s){let e;s.codec=()=>(e==null&&(e=Ie((i,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),i.Type!=null&&(o.uint32(8),ne.codec().encode(i.Type,o)),i.Data!=null&&(o.uint32(18),o.bytes(i.Data)),a.lengthDelimited!==!1&&o.ldelim()},(i,o,a={})=>{let c={},u=o==null?i.len:i.pos+o;for(;i.pos<u;){let p=i.uint32();switch(p>>>3){case 1:{c.Type=ne.codec().decode(i);break}case 2:{c.Data=i.bytes();break}default:{i.skipType(p&7);break}}}return c},function*(i,o,a,c={}){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:ne.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 Se(i,s.codec())}s.encode=t;function r(i,o){return Ee(i,s.codec(),o)}s.decode=r;function n(i,o){return _e(i,s.codec(),o)}s.stream=n})(Ei||(Ei={}));var Ls={};Ae(Ls,{MAX_RSA_KEY_SIZE:()=>Si,generateRSAKeyPair:()=>Sc,jwkToJWKKeyPair:()=>_c,jwkToPkcs1:()=>df,jwkToPkix:()=>Di,jwkToRSAPrivateKey:()=>Bi,pkcs1MessageToJwk:()=>Ii,pkcs1MessageToRSAPrivateKey:()=>Ai,pkcs1ToJwk:()=>ff,pkcs1ToRSAPrivateKey:()=>Ec,pkixMessageToJwk:()=>Ti,pkixMessageToRSAPublicKey:()=>Pi,pkixToJwk:()=>pf,pkixToRSAPublicKey:()=>Mi});var rs=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Ls.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return pe.createV1(114,this._multihash)}toString(){return ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Me(this.raw,e.raw)}verify(e,t,r){return vc(this.jwk,t,e,r)}},Rs=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Ls.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Me(this.raw,e.raw)}sign(e,t){return xc(this.jwk,e,t)}};var Si=8192,_i=18,uf=1062,hf=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function ff(s){let e=st(s);return Ii(e)}function Ii(s){return{n:j(s[1],"base64url"),e:j(s[2],"base64url"),d:j(s[3],"base64url"),p:j(s[4],"base64url"),q:j(s[5],"base64url"),dp:j(s[6],"base64url"),dq:j(s[7],"base64url"),qi:j(s[8],"base64url"),kty:"RSA"}}function df(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 oe("JWK was missing components");return ht([Pe(Uint8Array.from([0])),Pe(Y(s.n,"base64url")),Pe(Y(s.e,"base64url")),Pe(Y(s.d,"base64url")),Pe(Y(s.p,"base64url")),Pe(Y(s.q,"base64url")),Pe(Y(s.dp,"base64url")),Pe(Y(s.dq,"base64url")),Pe(Y(s.qi,"base64url"))]).subarray()}function pf(s){let e=st(s,{offset:0});return Ti(e)}function Ti(s){let e=st(s[1],{offset:0});return{kty:"RSA",n:j(e[0],"base64url"),e:j(e[1],"base64url")}}function Di(s){if(s.n==null||s.e==null)throw new oe("JWK was missing components");return ht([hf,Zs(ht([Pe(Y(s.n,"base64url")),Pe(Y(s.e,"base64url"))]))]).subarray()}function Ec(s){let e=st(s);return Ai(e)}function Ai(s){let e=Ii(s);return Bi(e)}function Mi(s,e){if(s.byteLength>=uf)throw new zt("Key size is too large");let t=st(s,{offset:0});return Pi(t,s,e)}function Pi(s,e,t){let r=Ti(s);if(t==null){let n=Yt(Xe.encode({Type:ne.RSA,Data:e}));t=$e(_i,n)}return new rs(r,t)}function Bi(s){if(Tc(s)>Si)throw new oe("Key size is too large");let e=_c(s),t=Yt(Xe.encode({Type:ne.RSA,Data:Di(e.publicKey)})),r=$e(_i,t);return new Rs(e.privateKey,new rs(e.publicKey,r))}async function Sc(s){if(s>Si)throw new oe("Key size is too large");let e=await Ic(s),t=Yt(Xe.encode({Type:ne.RSA,Data:Di(e.publicKey)})),r=$e(_i,t);return new Rs(e.privateKey,new rs(e.publicKey,r))}function _c(s){if(s==null)throw new oe("Missing key parameter");return{privateKey:s,publicKey:{kty:s.kty,n:s.n,e:s.e}}}async function Ic(s,e){let t=await Ke.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 mf(t,e);return{privateKey:r[0],publicKey:r[1]}}async function xc(s,e,t){let r=await Ke.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let n=await Ke.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,Fe(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(n,0,n.byteLength)}async function vc(s,e,t,r){let n=await Ke.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();let i=await Ke.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,Fe(e),Fe(t instanceof Uint8Array?t:t.subarray()));return r?.signal?.throwIfAborted(),i}async function mf(s,e){if(s.privateKey==null||s.publicKey==null)throw new oe("Private and public key are required");let t=await Promise.all([Ke.get().subtle.exportKey("jwk",s.privateKey),Ke.get().subtle.exportKey("jwk",s.publicKey)]);return e?.signal?.throwIfAborted(),t}function Tc(s){if(s.kty!=="RSA")throw new oe("invalid key type");if(s.n==null)throw new oe("invalid key modulus");return Y(s.n,"base64url").length*8}var Tr=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Js(e),Ne(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),Mt(n)}update(e){return Zt(this),this.iHash.update(e),this}digestInto(e){Zt(this),Qs(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:c}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.canXOF=c,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()}},Dc=(()=>{let s=((e,t,r)=>new Tr(e,t).update(r).digest());return s.create=(e,t)=>new Tr(e,t),s})();var gf=BigInt(0),ki=class extends Error{constructor(e=""){super(e)}},it={Err:ki,_tlv:{encode:(s,e)=>{let{Err:t}=it;if(nt(s,"tag"),s<0||s>255)throw new t("tlv.encode: wrong tag");if(Ca(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let r=e.length/2,n=_s(r);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let i=r>127?_s(n.length/2|128):"";return _s(s)+i+n+e},decode(s,e){let{Err:t}=it;e=H(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 c=n&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(r,r+c);if(u.length!==c)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+=c,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}=it;if(ir(s),s<gf)throw new e("integer: negative integers are not allowed");let t=_s(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}=it;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 Ye(s)}},toSig(s,e){let{Err:t,_int:r,_tlv:n}=it;if(e!==void 0&&(nt(e,"maxScalarBytes"),e<1))throw new t("invalid signature: maxScalarBytes must be positive");let i=H(s,void 0,"signature"),{v:o,l:a}=n.decode(48,i);if(a.length)throw new t("invalid signature: left bytes after parsing");let{v:c,l:u}=n.decode(2,o),{v:p,l:m}=n.decode(2,u);if(m.length)throw new t("invalid signature: left bytes after parsing");if(e!==void 0&&(c.length>e||p.length>e))throw new t("invalid signature: integer too large");return{r:r.decode(c),s:r.decode(p)}},hexFromSig(s){let{_tlv:e,_int:t}=it;ke(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)}},Dr=(Object.freeze(it._tlv),Object.freeze(it._int),Object.freeze(it));var Ac=(s,e)=>(s+(s>=0?e:-e)/Mc)/e;function bf(s,e,t){Jt("scalar",s,ot,t);let[[r,n],[i,o]]=e,a=Ac(o*s,t),c=Ac(-n*s,t),u=s-a*r-c*i,p=-a*n-c*o,m=u<ot,E=p<ot;m&&(u=-u),E&&(p=-p);let y=Ts(Math.ceil(Qt(t)/2))+Ct;if(u<ot||u>=y||p<ot||p>=y)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:m,k1:u,k2neg:E,k2:p}}function Ci(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function Ri(s,e){ke(s);let t={};for(let r of Object.keys(e))t[r]=s[r]===void 0?e[r]:s[r];return Be(t.lowS,"lowS"),Be(t.prehash,"prehash"),t.format!==void 0&&Ci(t.format),t}var ot=BigInt(0),Ct=BigInt(1),Mc=BigInt(2),Li=BigInt(3),yf=BigInt(4);function Pc(s,e={}){let t=dr("weierstrass",s,e),r=t.Fp,n=t.Fn,i=t.CURVE,{h:o,n:a}=i;ke(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:u,clearCofactor:p,isTorsionFree:m,fromBytes:E,toBytes:y}=e,f=e.randomBytes===void 0?Bt:e.randomBytes;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let g=c?{beta:c.beta,basises:c.basises.map(P=>[...P])}:void 0,w=kc(r,n);function S(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function _(P,x,T){if(x.is0()){if(!u)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:A,y:B}=x.toAffine(),R=r.toBytes(A);if(Be(T,"isCompressed"),T){S();let L=!r.isOdd(B);return Ue(Bc(L),R)}else return Ue(Uint8Array.of(4),R,r.toBytes(B))}function l(P){H(P,void 0,"Point");let{publicKey:x,publicKeyUncompressed:T}=w,A=P.length,B=P[0],R=P.subarray(1);if(u&&A===1&&B===0)return{x:r.ZERO,y:r.ZERO};if(A===x&&(B===2||B===3)){let L=r.fromBytes(R);if(!r.isValid(L))throw new Error("bad point: is not on curve, wrong x");let O=I(L),F;try{F=r.sqrt(O)}catch(le){let Q=le instanceof Error?": "+le.message:"";throw new Error("bad point: is not on curve, sqrt error"+Q)}S();let G=r.isOdd(F);return(B&1)===1!==G&&(F=r.neg(F)),{x:L,y:F}}else if(A===T&&B===4){let L=r.BYTES,O=r.fromBytes(R.subarray(0,L)),F=r.fromBytes(R.subarray(L,L*2));if(!D(O,F))throw new Error("bad point: is not on curve");return{x:O,y:F}}else throw new Error(`bad point: got length ${A}, expected compressed=${x} or uncompressed=${T}`)}let h=y===void 0?_:y,d=E===void 0?l:E,b=r.mul(i.b,Li),v=r.is0(i.a)?P=>r.ZERO:P=>r.mul(i.a,P);function I(P){let x=r.sqr(P),T=r.mul(x,P);return r.add(r.add(T,r.mul(P,i.a)),i.b)}function D(P,x){let T=r.sqr(x),A=I(P);return r.eql(T,A)}if(!D(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let M=r.mul(r.pow(i.a,Li),yf),U=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(M,U)))throw new Error("bad curve params: a or b");function z(P,x,T=!1){if(!r.isValid(x)||T&&r.is0(x))throw new Error(`bad point coordinate ${P}`);return typeof x=="object"&&x!==null?r.create(x):x}function Z(P){if(!(P instanceof C))throw new Error("Weierstrass Point expected")}function k(P){if(!g||!g.basises)throw new Error("no endo");return bf(P,g.basises,n.ORDER)}function N(P,x,T,A){if(!n.isValid(A))throw new RangeError("invalid scalar: out of range");if(g){let{k1neg:B,k1:R,k2neg:L,k2:O}=k(A),F=new C(r.mul(T.X,g.beta),T.Y,T.Z);P.push(B?T.negate():T,L?F.negate():F),x.push(R,O)}else P.push(T),x.push(A)}let K=new WeakSet;class C{static BASE=new C(i.Gx,i.Gy,r.ONE);static ZERO=new C(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=n;X;Y;Z;constructor(x,T,A){this.X=z("x",x),this.Y=z("y",T,!0),this.Z=z("z",A),Object.freeze(this)}static CURVE(){return i}static fromAffine(x){let{x:T,y:A}=x||{};if(!x||!r.isValid(T)||!r.isValid(A))throw new Error("invalid affine point");if(x instanceof C)throw new Error("projective point not allowed");return r.is0(T)&&r.is0(A)?C.ZERO:new C(T,A,r.ONE)}static fromBytes(x){let T=C.fromAffine(d(H(x,void 0,"point")));return T.assertValidity(),T}static fromHex(x){return C.fromBytes(Xt(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=6,T=!0){return se.setWindowSize(this,x),T||this.multiply(Li),this}assertValidity(){let x=this;if(x.is0()){if(u&&r.is0(x.X)&&r.eql(x.Y,r.ONE)&&r.is0(x.Z))return;throw new Error("bad point: ZERO")}if(K.has(x))return;let{x:T,y:A}=x.toAffine();if(!r.isValid(T)||!r.isValid(A))throw new Error("bad point: x or y not field elements");if(!D(T,A))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");K.add(x)}hasEvenY(){let{y:x}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(x)}equals(x){Z(x);let{X:T,Y:A,Z:B}=this,{X:R,Y:L,Z:O}=x,F=r.eql(r.mul(T,O),r.mul(R,B)),G=r.eql(r.mul(A,O),r.mul(L,B));return F&&G}negate(){return new C(this.X,r.neg(this.Y),this.Z)}double(){let{X:x,Y:T,Z:A}=this,B=r.ZERO,R=r.ZERO,L=r.ZERO,O=r.mul(x,x),F=r.mul(T,T),G=r.mul(A,A),q=r.mul(x,T);return q=r.add(q,q),L=r.mul(x,A),L=r.add(L,L),B=v(L),R=r.mul(b,G),R=r.add(B,R),B=r.sub(F,R),R=r.add(F,R),R=r.mul(B,R),B=r.mul(q,B),L=r.mul(b,L),G=v(G),q=r.sub(O,G),q=v(q),q=r.add(q,L),L=r.add(O,O),O=r.add(L,O),O=r.add(O,G),O=r.mul(O,q),R=r.add(R,O),G=r.mul(T,A),G=r.add(G,G),O=r.mul(G,q),B=r.sub(B,O),L=r.mul(G,F),L=r.add(L,L),L=r.add(L,L),new C(B,R,L)}add(x){Z(x);let{X:T,Y:A,Z:B}=this,{X:R,Y:L,Z:O}=x,F=r.ZERO,G=r.ZERO,q=r.ZERO,le=r.mul(T,R),Q=r.mul(A,L),fe=r.mul(B,O),Ce=r.add(T,A),ee=r.add(R,L);Ce=r.mul(Ce,ee),ee=r.add(le,Q),Ce=r.sub(Ce,ee),ee=r.add(T,B);let ue=r.add(R,O);return ee=r.mul(ee,ue),ue=r.add(le,fe),ee=r.sub(ee,ue),ue=r.add(A,B),F=r.add(L,O),ue=r.mul(ue,F),F=r.add(Q,fe),ue=r.sub(ue,F),q=v(ee),F=r.mul(b,fe),q=r.add(F,q),F=r.sub(Q,q),q=r.add(Q,q),G=r.mul(F,q),Q=r.add(le,le),Q=r.add(Q,le),fe=v(fe),ee=r.mul(b,ee),Q=r.add(Q,fe),fe=r.sub(le,fe),fe=v(fe),ee=r.add(ee,fe),le=r.mul(Q,ee),G=r.add(G,le),le=r.mul(ue,ee),F=r.mul(Ce,F),F=r.sub(F,le),le=r.mul(Ce,Q),q=r.mul(ue,q),q=r.add(q,le),new C(F,G,q)}subtract(x){return Z(x),this.add(x.negate())}is0(){return this.equals(C.ZERO)}multiply(x){if(!n.isValidNot0(x))throw new RangeError("invalid scalar: out of range");let{p:T,f:A}=se.mulSecret(this,x,o,J);return J([T,A])[0]}multiplyUnsafe(x){let T=this,A=x;if(!n.isValid(A))throw new RangeError("invalid scalar: out of range");if(A===ot||T.is0())return C.ZERO;if(A===Ct)return T;if(se.hasWindowSize(this))return se.mulUnsafe(T,A,J);let B=[],R=[];return N(B,R,T,A),fr(C,B,R)}mulAddUnsafe(x,T,A){Z(T);let B=[],R=[];return N(B,R,this,x),N(B,R,T,A),fr(C,B,R)}toAffine(x){let T=this,A=x;if(A!=null&&!r.isValid(A))throw new RangeError('"invertedZ" expected valid field element');let{X:B,Y:R,Z:L}=T;if(r.eql(L,r.ONE))return{x:B,y:R};let O=T.is0();A==null&&(A=O?r.ONE:r.inv(L));let F=r.mul(B,A),G=r.mul(R,A),q=r.mul(L,A);if(O)return{x:r.ZERO,y:r.ZERO};if(!r.eql(q,r.ONE))throw new Error("invZ was invalid");return{x:F,y:G}}isTorsionFree(){return o===Ct?!0:m?m(C,this):se.mulUnsafe(this,a).is0()}clearCofactor(){return o===Ct?this:p?p(C,this):this.multiplyUnsafe(o)}isSmallOrder(){return o===Ct?this.is0():this.clearCofactor().is0()}toBytes(x=!0){return Be(x,"isCompressed"),this.assertValidity(),h(C,this,x)}toHex(x=!0){return Ss(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let J=P=>hr(C,P),se=new ss(C,f);return se.bits>=6&&C.BASE.precompute(6),Object.freeze(C.prototype),Object.freeze(C),C}function Bc(s){return Uint8Array.of(s?2:3)}function kc(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function wf(s,e={}){wt(s);let{Fn:t}=s,r=e.randomBytes===void 0?Bt:e.randomBytes,n=Object.assign(kc(s.Fp,t),{seed:Math.max(lr(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 S=y.length;return f===!0&&S!==g||f===!1&&S!==w?!1:!s.fromBytes(y).is0()}catch{return!1}}function a(y){return y=y===void 0?r(n.seed):y,ur(H(y,n.seed,"seed"),t.ORDER)}function c(y,f=!0){return s.BASE.multiply(t.fromBytes(y)).toBytes(f)}function u(y){let{secretKey:f,publicKey:g,publicKeyUncompressed:w}=n,S=t._lengths;if(!bt(y))return;let _=H(y,void 0,"key").length,l=_===g||_===w,h=_===f||!!S?.includes(_);if(!(l&&h))return l}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),S=s.fromBytes(f);if(S.is0())throw new Error("invalid public key: point at infinity");return S.multiply(w).toBytes(g)}let m={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},E=pr(a,c);return Object.freeze(m),Object.freeze(n),Object.freeze({getPublicKey:c,getSharedSecret:p,keygen:E,Point:s,utils:m,lengths:n})}function Rc(s,e,t={}){wt(s);let r=e;Js(r),ke(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=Object.assign({},t),i=n.randomBytes===void 0?Bt:n.randomBytes,o=n.hmac===void 0?(P,x)=>Dc(r,P,x):n.hmac,{Fp:a,Fn:c}=s,{ORDER:u,BITS:p}=c,m=lr(u),E=jn(i,m),{keygen:y,getPublicKey:f,getSharedSecret:g,utils:w,lengths:S}=wf(s,n),_={prehash:!0,lowS:typeof n.lowS=="boolean"?n.lowS:!0,format:"compact",extraEntropy:!1},l=u*Mc+Ct<a.ORDER;function h(P){let x=u>>Ct;return P>x}function d(P,x){if(!c.isValidNot0(x))throw new Error(`invalid signature ${P}: out of range 1..Point.Fn.ORDER`);return x}function b(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function v(P,x,T){return b(),(P===T?0:2)|Number(a.isOdd(x))}function I(){if(l)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function D(P,x){Ci(x);let T=S.signature,A=x==="compact"?T:x==="recovered"?T+1:void 0;return H(P,A)}class M{r;s;recovery;constructor(x,T,A){if(this.r=d("r",x),this.s=d("s",T),A!=null){if(I(),![0,1,2,3].includes(A))throw new Error("invalid recovery id");this.recovery=A}Object.freeze(this)}static fromBytes(x,T=_.format){D(x,T);let A;if(T==="der"){if(x.length>2*c.BYTES+16)throw new Dr.Err("invalid signature: DER signature too long");let{r:O,s:F}=Dr.toSig(H(x),c.BYTES+1);return new M(O,F)}T==="recovered"&&(A=x[0],T="compact",x=x.subarray(1));let B=S.signature/2,R=x.subarray(0,B),L=x.subarray(B,B*2);return new M(c.fromBytes(R),c.fromBytes(L),A)}static fromHex(x,T){return this.fromBytes(Xt(x),T)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new M(this.r,this.s,x)}recoverPublicKey(x){let{r:T,s:A}=this,B=this.assertRecovery(),R=B===2||B===3?T+u:T;if(!a.isValid(R))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let L=a.toBytes(R),O=s.fromBytes(Ue(Bc((B&1)===0),L)),F=c.inv(R),G=z(H(x,void 0,"msgHash")),q=c.create(-G*F),le=c.create(A*F),Q=s.BASE.mulAddUnsafe(q,O,le);if(Q.is0())throw new Error("invalid recovery: point at infinify");return Q.assertValidity(),Q}hasHighS(){return h(this.s)}toBytes(x=_.format){if(Ci(x),x==="der")return Xt(Dr.hexFromSig(this));let{r:T,s:A}=this,B=c.toBytes(T),R=c.toBytes(A);return x==="recovered"?(I(),Ue(Uint8Array.of(this.assertRecovery()),B,R)):Ue(B,R)}toHex(x){return Ss(this.toBytes(x))}}Object.freeze(M.prototype),Object.freeze(M);let U=n.bits2int===void 0?function(x){if(x.length>8192)throw new Error("input is too large");let T=Ye(x),A=x.length*8-p;return A>0?T>>BigInt(A):T}:n.bits2int,z=n.bits2int_modN===void 0?function(x){return c.create(U(x))}:n.bits2int_modN,Z=Ts(p);function k(P){return Jt("num < 2^"+p,P,ot,Z),c.toBytes(P)}function N(P,x){return H(P,void 0,"message"),x?H(r(P),void 0,"prehashed message"):P}function K(P,x,T){let{lowS:A,prehash:B,extraEntropy:R}=Ri(T,_);P=N(P,B);let L=z(P),O=c.fromBytes(x);if(!c.isValidNot0(O))throw new Error("invalid private key");let F=[k(O),k(L)];if(R!=null&&R!==!1){let Q=R===!0?i(S.secretKey):R;F.push(H(Q,void 0,"extraEntropy"))}let G=Ue(...F),q=L;function le(Q){let fe=U(Q);if(!c.isValidNot0(fe))return;let Ce=s.BASE.multiply(fe).toAffine(),ee=c.create(Ce.x);if(ee===ot)return;let ue;if(E!==void 0){let ds=Ye(ur(E(m),u)),wl=c.inv(c.mul(ds,fe)),xl=c.mul(ds,q),vl=c.mul(ds,O);ue=c.create(wl*c.create(xl+vl*ee))}else{let ds=Wa(fe,u);ue=c.create(ds*c.create(q+ee*O))}if(ue===ot)return;let $r=v(Ce.x,Ce.y,ee),Yi=ue;return A&&h(ue)&&(Yi=c.neg(ue),$r^=1),new M(ee,Yi,l?void 0:$r)}return{seed:G,k2sig:le}}function C(P,x,T={}){let{seed:A,k2sig:B}=K(P,x,T);return Fa(r.outputLen,c.BYTES,o)(A,B).toBytes(T.format)}function J(P,x,T,A={}){let{lowS:B,prehash:R,format:L}=Ri(A,_);if(T=H(T,void 0,"publicKey"),x=N(x,R),!bt(P)){let O=P instanceof M?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+O)}D(P,L);try{let O=M.fromBytes(P,L),F=s.fromBytes(T);if(F.is0()||B&&O.hasHighS())return!1;let{r:G,s:q}=O,le=z(x),Q=c.inv(q),fe=c.create(le*Q),Ce=c.create(G*Q),ee=s.BASE.mulAddUnsafe(fe,F,Ce);if(ee.is0())return!1;let ue=ee.toAffine();return!(c.create(ue.x)!==G||L==="recovered"&&O.recovery!==v(ue.x,ue.y,G))}catch{return!1}}function se(P,x,T={}){let{prehash:A}=Ri(T,_);return x=N(x,A),M.fromBytes(P,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:y,getPublicKey:f,getSharedSecret:g,utils:w,lengths:S,Point:s,sign:C,verify:J,recoverPublicKey:se,Signature:M,hash:r})}var Fi={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},xf={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Lc=BigInt(2);function vf(s){let e=Fi.p,t=BigInt(3),r=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),u=s*s*s%e,p=u*u*s%e,m=te(p,t,e)*p%e,E=te(m,t,e)*p%e,y=te(E,Lc,e)*u%e,f=te(y,n,e)*y%e,g=te(f,i,e)*f%e,w=te(g,a,e)*g%e,S=te(w,c,e)*w%e,_=te(S,a,e)*g%e,l=te(_,t,e)*p%e,h=te(l,o,e)*f%e,d=te(h,r,e)*u%e,b=te(d,Lc,e);if(!Oi.eql(Oi.sqr(b),s))throw new Error("Cannot find square root");return b}var Oi=ts(Fi.p,{sqrt:vf}),Ef=Pc(Fi,{Fp:Oi,endo:xf}),ns=Rc(Ef,Yt);function Cc(s,e,t,r){let n=Tt.digest(t instanceof Uint8Array?t:t.subarray());if(xr(n))return n.then(({digest:i})=>(r?.signal?.throwIfAborted(),ns.verify(e,i,s,{prehash:!1,format:"der"}))).catch(i=>{throw i.name==="AbortError"?i:new Ms(String(i))});try{return r?.signal?.throwIfAborted(),ns.verify(e,n.digest,s,{prehash:!1,format:"der"})}catch(i){throw new Ms(String(i))}}var Ar=class{type="secp256k1";raw;_key;constructor(e){this._key=Fc(e),this.raw=Oc(this._key)}toMultihash(){return qe.digest(je(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Me(this.raw,e.raw)}verify(e,t,r){return Cc(this._key,t,e,r)}};function Ni(s){return new Ar(s)}function Oc(s){return ns.Point.fromBytes(s).toBytes()}function Fc(s){try{return ns.Point.fromBytes(s),s}catch(e){throw new zt(String(e))}}function Ui(s,e){let{Type:t,Data:r}=Xe.decode(s),n=r??new Uint8Array;switch(t){case ne.RSA:return Mi(n,e);case ne.Ed25519:return ei(n);case ne.secp256k1:return Ni(n);case ne.ECDSA:return Dn(n);default:throw new qt}}function Nc(s){let{Type:e,Data:t}=Xe.decode(s.digest),r=t??new Uint8Array;switch(e){case ne.Ed25519:return ei(r);case ne.secp256k1:return Ni(r);case ne.ECDSA:return Dn(r);default:throw new qt}}function je(s){return Xe.encode({Type:ne[s.type],Data:s.raw})}var Uc=Symbol.for("nodejs.util.inspect.custom"),Sf=114,Cs=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()})`}[Xr]=!0;toString(){return this.string==null&&(this.string=ce.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return pe.createV1(Sf,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Me(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Me(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Uc](){return`PeerId(${this.toString()})`}},Mr=class extends Cs{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Pr=class extends Cs{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Br=class extends Cs{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},_f=2336,Os=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=qe.digest(Y(this.url))}[Uc](){return`PeerId(${this.url})`}[Xr]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return pe.createV1(_f,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=j(e)),e.toString()===this.toString())}};var If=114,Kc=2336;function Ot(s,e){let t;if(s.charAt(0)==="1"||s.charAt(0)==="Q")t=et(ce.decode(`z${s}`));else{if(s.startsWith("k51qzi5uqu5")||s.startsWith("kzwfwjn5ji4")||s.startsWith("k2k4r8")||s.startsWith("bafz"))return Tf(pe.parse(s));if(e==null)throw new oe('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=et(e.decode(s))}return is(t)}function is(s){if(Af(s))return new Mr({multihash:s});if(Df(s))try{let e=Nc(s);if(e.type==="Ed25519")return new Pr({multihash:s,publicKey:e});if(e.type==="secp256k1")return new Br({multihash:s,publicKey:e})}catch{let t=j(s.digest);return new Os(new URL(t))}throw new Hs("Supplied PeerID Multihash is invalid")}function Tf(s){if(s?.multihash==null||s.version==null||s.version===1&&s.code!==If&&s.code!==Kc)throw new Gs("Supplied PeerID CID is invalid");if(s.code===Kc){let e=j(s.multihash.digest);return new Os(new URL(e))}return is(s.multihash)}function Df(s){return s.code===qe.code}function Af(s){return s.code===Tt.code}var kr=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},os=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Rr=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Fs=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Lr(s){return s[Symbol.asyncIterator]!=null}function zc(s,e){if(s.byteLength>e)throw new os("Message length too long")}var Or=s=>{let e=ze(s),t=ge(e);return ai(s,t),Or.bytes=e,t};Or.bytes=0;function as(s,e){e=e??{};let t=e.lengthEncoder??Or,r=e?.maxDataLength??4194304;function*n(i){zc(i,r);let o=t(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return Lr(s)?(async function*(){for await(let i of s)yield*n(i)})():(function*(){for(let i of s)yield*n(i)})()}as.single=(s,e)=>{e=e??{};let t=e.lengthEncoder??Or,r=e?.maxDataLength??4194304;return zc(s,r),new de(t(s.byteLength),s)};var Ft;(function(s){s[s.LENGTH=0]="LENGTH",s[s.DATA=1]="DATA"})(Ft||(Ft={}));var Ki=s=>{let e=ci(s);return Ki.bytes=ze(e),e};Ki.bytes=0;function Ns(s,e){let t=new de,r=Ft.LENGTH,n=-1,i=e?.lengthDecoder??Ki,o=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(r===Ft.LENGTH)try{if(n=i(t),n<0)throw new kr("Invalid message length");if(n>a)throw new os("Message length too long");let u=i.bytes;t.consume(u),e?.onLength!=null&&e.onLength(n),r=Ft.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>o)throw new Rr("Message length length too long");break}throw u}if(r===Ft.DATA){if(t.byteLength<n)break;let u=t.sublist(0,n);t.consume(n),e?.onData!=null&&e.onData(u),yield u,r=Ft.LENGTH}}}return Lr(s)?(async function*(){for await(let u of s)t.append(u),yield*c();if(t.byteLength>0)throw new Fs("Unexpected end of input")})():(function*(){for(let u of s)t.append(u),yield*c();if(t.byteLength>0)throw new Fs("Unexpected end of input")})()}Ns.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 Ns(r,{...e??{},onLength:i=>{t=i}})};function at(){let s={};return s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),s}var Fr=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}},cs=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Fr(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 Fr(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 zi=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Nt(s={}){return Pf(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 Pf(s,e){e=e??{};let t=e.onEnd,r=new cs,n,i,o,a=at(),c=async()=>{try{return r.isEmpty()?o?{done:!0}:await new Promise((w,S)=>{i=_=>{i=null,r.push(_);try{w(s(r))}catch(l){S(l)}return n}}):s(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=at()})}},u=w=>i!=null?i(w):(r.push(w),n),p=w=>(r=new cs,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})},E=w=>o?n:(o=!0,w!=null?p(w):u({done:!0})),y=()=>(r=new cs,E(),{done:!0}),f=w=>(E(w),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:c,return:y,throw:f,push:m,end:E,get readableLength(){return r.size},onEmpty:async w=>{let S=w?.signal;if(S?.throwIfAborted(),r.isEmpty())return;let _,l;S!=null&&(_=new Promise((h,d)=>{l=()=>{d(new zi)},S.addEventListener("abort",l)}));try{await Promise.race([a.promise,_])}finally{l!=null&&S!=null&&S?.removeEventListener("abort",l)}}},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 Bf(s){return s.reason}function qi(s,e,t){if(e==null||s==null)return s;let r=t?.translateError??Bf;if(e.aborted)return s.catch(()=>{}),Promise.reject(r(e));let n;return Promise.race([s,new Promise((i,o)=>{n=()=>{o(r(e))},e.addEventListener("abort",n)})]).finally(()=>{n!=null&&e.removeEventListener("abort",n)})}var Gi=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=at(),this.haveNext=at()}[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=at(),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=at(),await qi(this.readNext.promise,t?.signal,t)}};function qc(){return new Gi}function Gc(s){return s[Symbol.asyncIterator]!=null}async function kf(s,e,t){try{await Promise.all(s.map(async r=>{for(;;){let{value:n,done:i}=await r.next();if(i===!0)break;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*Rf(s){let e=new AbortController,t=qc(),r=s.map(n=>Gc(n)?n[Symbol.asyncIterator]():n[Symbol.iterator]());kf(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort();for(let n of r)try{Promise.resolve(n.return?.()).catch(()=>{})}catch{}}}function*Lf(s){for(let e of s)yield*e}function Cf(...s){let e=[];for(let t of s)Gc(t)||e.push(t);return e.length===s.length?Lf(e):Rf(s)}var Hc=Cf;function Us(s,...e){if(s==null)throw new Error("Empty pipeline");if(Hi(s)){let r=s;s=()=>r.source}else if(Vc(s)||Wc(s)){let r=s;s=()=>r}let t=[s,...e];if(t.length>1&&Hi(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++)Hi(t[r])&&(t[r]=Ff(t[r]));return Of(...t)}var Of=(...s)=>{let e;for(;s.length>0;)e=s.shift()(e);return e},Wc=s=>s?.[Symbol.asyncIterator]!=null,Vc=s=>s?.[Symbol.iterator]!=null,Hi=s=>s==null?!1:s.sink!=null&&s.source!=null,Ff=s=>e=>{let t=s.sink(e);if(t?.then!=null){let r=Nt({objectMode:!0});t.then(()=>{r.end()},o=>{r.end(o)});let n,i=s.source;if(Wc(i))n=async function*(){yield*i,r.end()};else if(Vc(i))n=function*(){yield*i,r.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Hc(r,n())}return s.source};var $c={maxSubscriptions:5e3,maxMessages:5e3,maxIhaveMessageIDs:5e3,maxIwantMessageIDs:5e3,maxControlMessages:5e3,maxIdontwantMessageIDs:512,maxPeerInfos:16};var ct;(function(s){let e;(function(f){let g;f.codec=()=>(g==null&&(g=Ie((l,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),l.subscribe!=null&&(h.uint32(8),h.bool(l.subscribe)),l.topic!=null&&(h.uint32(18),h.string(l.topic)),d.lengthDelimited!==!1&&h.ldelim()},(l,h,d={})=>{let b={},v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{b.subscribe=l.bool();break}case 2:{b.topic=l.string();break}default:{l.skipType(I&7);break}}}return b},function*(l,h,d,b={}){let v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{yield{field:`${d}.subscribe`,value:l.bool()};break}case 2:{yield{field:`${d}.topic`,value:l.string()};break}default:{l.skipType(I&7);break}}}})),g);function w(l){return Se(l,f.codec())}f.encode=w;function S(l,h){return Ee(l,f.codec(),h)}f.decode=S;function _(l,h){return _e(l,f.codec(),h)}f.stream=_})(e=s.SubOpts||(s.SubOpts={}));let t;(function(f){let g;f.codec=()=>(g==null&&(g=Ie((l,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),l.from!=null&&(h.uint32(10),h.bytes(l.from)),l.data!=null&&(h.uint32(18),h.bytes(l.data)),l.seqno!=null&&(h.uint32(26),h.bytes(l.seqno)),l.topic!=null&&l.topic!==""&&(h.uint32(34),h.string(l.topic)),l.signature!=null&&(h.uint32(42),h.bytes(l.signature)),l.key!=null&&(h.uint32(50),h.bytes(l.key)),d.lengthDelimited!==!1&&h.ldelim()},(l,h,d={})=>{let b={topic:""},v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{b.from=l.bytes();break}case 2:{b.data=l.bytes();break}case 3:{b.seqno=l.bytes();break}case 4:{b.topic=l.string();break}case 5:{b.signature=l.bytes();break}case 6:{b.key=l.bytes();break}default:{l.skipType(I&7);break}}}return b},function*(l,h,d,b={}){let v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{yield{field:`${d}.from`,value:l.bytes()};break}case 2:{yield{field:`${d}.data`,value:l.bytes()};break}case 3:{yield{field:`${d}.seqno`,value:l.bytes()};break}case 4:{yield{field:`${d}.topic`,value:l.string()};break}case 5:{yield{field:`${d}.signature`,value:l.bytes()};break}case 6:{yield{field:`${d}.key`,value:l.bytes()};break}default:{l.skipType(I&7);break}}}})),g);function w(l){return Se(l,f.codec())}f.encode=w;function S(l,h){return Ee(l,f.codec(),h)}f.decode=S;function _(l,h){return _e(l,f.codec(),h)}f.stream=_})(t=s.Message||(s.Message={}));let r;(function(f){let g;f.codec=()=>(g==null&&(g=Ie((l,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),l.ihave!=null&&l.ihave.length>0)for(let b of l.ihave)h.uint32(10),s.ControlIHave.codec().encode(b,h);if(l.iwant!=null&&l.iwant.length>0)for(let b of l.iwant)h.uint32(18),s.ControlIWant.codec().encode(b,h);if(l.graft!=null&&l.graft.length>0)for(let b of l.graft)h.uint32(26),s.ControlGraft.codec().encode(b,h);if(l.prune!=null&&l.prune.length>0)for(let b of l.prune)h.uint32(34),s.ControlPrune.codec().encode(b,h);if(l.idontwant!=null&&l.idontwant.length>0)for(let b of l.idontwant)h.uint32(42),s.ControlIDontWant.codec().encode(b,h);d.lengthDelimited!==!1&&h.ldelim()},(l,h,d={})=>{let b={ihave:[],iwant:[],graft:[],prune:[],idontwant:[]},v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{if(d.limits?.ihave!=null&&b.ihave.length===d.limits.ihave)throw new X('Decode error - repeated field "ihave" had too many elements');b.ihave.push(s.ControlIHave.codec().decode(l,l.uint32(),{limits:d.limits?.ihave$}));break}case 2:{if(d.limits?.iwant!=null&&b.iwant.length===d.limits.iwant)throw new X('Decode error - repeated field "iwant" had too many elements');b.iwant.push(s.ControlIWant.codec().decode(l,l.uint32(),{limits:d.limits?.iwant$}));break}case 3:{if(d.limits?.graft!=null&&b.graft.length===d.limits.graft)throw new X('Decode error - repeated field "graft" had too many elements');b.graft.push(s.ControlGraft.codec().decode(l,l.uint32(),{limits:d.limits?.graft$}));break}case 4:{if(d.limits?.prune!=null&&b.prune.length===d.limits.prune)throw new X('Decode error - repeated field "prune" had too many elements');b.prune.push(s.ControlPrune.codec().decode(l,l.uint32(),{limits:d.limits?.prune$}));break}case 5:{if(d.limits?.idontwant!=null&&b.idontwant.length===d.limits.idontwant)throw new X('Decode error - repeated field "idontwant" had too many elements');b.idontwant.push(s.ControlIDontWant.codec().decode(l,l.uint32(),{limits:d.limits?.idontwant$}));break}default:{l.skipType(I&7);break}}}return b},function*(l,h,d,b={}){let v={ihave:0,iwant:0,graft:0,prune:0,idontwant:0},I=h==null?l.len:l.pos+h;for(;l.pos<I;){let D=l.uint32();switch(D>>>3){case 1:{if(b.limits?.ihave!=null&&v.ihave===b.limits.ihave)throw new X('Streaming decode error - repeated field "ihave" had too many elements');for(let M of s.ControlIHave.codec().stream(l,l.uint32(),`${d}.ihave[]`,{limits:b.limits?.ihave$}))yield{...M,index:v.ihave};v.ihave++;break}case 2:{if(b.limits?.iwant!=null&&v.iwant===b.limits.iwant)throw new X('Streaming decode error - repeated field "iwant" had too many elements');for(let M of s.ControlIWant.codec().stream(l,l.uint32(),`${d}.iwant[]`,{limits:b.limits?.iwant$}))yield{...M,index:v.iwant};v.iwant++;break}case 3:{if(b.limits?.graft!=null&&v.graft===b.limits.graft)throw new X('Streaming decode error - repeated field "graft" had too many elements');for(let M of s.ControlGraft.codec().stream(l,l.uint32(),`${d}.graft[]`,{limits:b.limits?.graft$}))yield{...M,index:v.graft};v.graft++;break}case 4:{if(b.limits?.prune!=null&&v.prune===b.limits.prune)throw new X('Streaming decode error - repeated field "prune" had too many elements');for(let M of s.ControlPrune.codec().stream(l,l.uint32(),`${d}.prune[]`,{limits:b.limits?.prune$}))yield{...M,index:v.prune};v.prune++;break}case 5:{if(b.limits?.idontwant!=null&&v.idontwant===b.limits.idontwant)throw new X('Streaming decode error - repeated field "idontwant" had too many elements');for(let M of s.ControlIDontWant.codec().stream(l,l.uint32(),`${d}.idontwant[]`,{limits:b.limits?.idontwant$}))yield{...M,index:v.idontwant};v.idontwant++;break}default:{l.skipType(D&7);break}}}})),g);function w(l){return Se(l,f.codec())}f.encode=w;function S(l,h){return Ee(l,f.codec(),h)}f.decode=S;function _(l,h){return _e(l,f.codec(),h)}f.stream=_})(r=s.ControlMessage||(s.ControlMessage={}));let n;(function(f){let g;f.codec=()=>(g==null&&(g=Ie((l,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),l.topicID!=null&&(h.uint32(10),h.string(l.topicID)),l.messageIDs!=null&&l.messageIDs.length>0)for(let b of l.messageIDs)h.uint32(18),h.bytes(b);d.lengthDelimited!==!1&&h.ldelim()},(l,h,d={})=>{let b={messageIDs:[]},v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{b.topicID=l.string();break}case 2:{if(d.limits?.messageIDs!=null&&b.messageIDs.length===d.limits.messageIDs)throw new X('Decode error - repeated field "messageIDs" had too many elements');b.messageIDs.push(l.bytes());break}default:{l.skipType(I&7);break}}}return b},function*(l,h,d,b={}){let v={messageIDs:0},I=h==null?l.len:l.pos+h;for(;l.pos<I;){let D=l.uint32();switch(D>>>3){case 1:{yield{field:`${d}.topicID`,value:l.string()};break}case 2:{if(b.limits?.messageIDs!=null&&v.messageIDs===b.limits.messageIDs)throw new X('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:l.bytes()},v.messageIDs++;break}default:{l.skipType(D&7);break}}}})),g);function w(l){return Se(l,f.codec())}f.encode=w;function S(l,h){return Ee(l,f.codec(),h)}f.decode=S;function _(l,h){return _e(l,f.codec(),h)}f.stream=_})(n=s.ControlIHave||(s.ControlIHave={}));let i;(function(f){let g;f.codec=()=>(g==null&&(g=Ie((l,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),l.messageIDs!=null&&l.messageIDs.length>0)for(let b of l.messageIDs)h.uint32(10),h.bytes(b);d.lengthDelimited!==!1&&h.ldelim()},(l,h,d={})=>{let b={messageIDs:[]},v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{if(d.limits?.messageIDs!=null&&b.messageIDs.length===d.limits.messageIDs)throw new X('Decode error - repeated field "messageIDs" had too many elements');b.messageIDs.push(l.bytes());break}default:{l.skipType(I&7);break}}}return b},function*(l,h,d,b={}){let v={messageIDs:0},I=h==null?l.len:l.pos+h;for(;l.pos<I;){let D=l.uint32();switch(D>>>3){case 1:{if(b.limits?.messageIDs!=null&&v.messageIDs===b.limits.messageIDs)throw new X('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:l.bytes()},v.messageIDs++;break}default:{l.skipType(D&7);break}}}})),g);function w(l){return Se(l,f.codec())}f.encode=w;function S(l,h){return Ee(l,f.codec(),h)}f.decode=S;function _(l,h){return _e(l,f.codec(),h)}f.stream=_})(i=s.ControlIWant||(s.ControlIWant={}));let o;(function(f){let g;f.codec=()=>(g==null&&(g=Ie((l,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),l.topicID!=null&&(h.uint32(10),h.string(l.topicID)),d.lengthDelimited!==!1&&h.ldelim()},(l,h,d={})=>{let b={},v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();I>>>3===1?b.topicID=l.string():l.skipType(I&7)}return b},function*(l,h,d,b={}){let v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();I>>>3===1?yield{field:`${d}.topicID`,value:l.string()}:l.skipType(I&7)}})),g);function w(l){return Se(l,f.codec())}f.encode=w;function S(l,h){return Ee(l,f.codec(),h)}f.decode=S;function _(l,h){return _e(l,f.codec(),h)}f.stream=_})(o=s.ControlGraft||(s.ControlGraft={}));let a;(function(f){let g;f.codec=()=>(g==null&&(g=Ie((l,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),l.topicID!=null&&(h.uint32(10),h.string(l.topicID)),l.peers!=null&&l.peers.length>0)for(let b of l.peers)h.uint32(18),s.PeerInfo.codec().encode(b,h);l.backoff!=null&&(h.uint32(24),h.uint64Number(l.backoff)),d.lengthDelimited!==!1&&h.ldelim()},(l,h,d={})=>{let b={peers:[]},v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{b.topicID=l.string();break}case 2:{if(d.limits?.peers!=null&&b.peers.length===d.limits.peers)throw new X('Decode error - repeated field "peers" had too many elements');b.peers.push(s.PeerInfo.codec().decode(l,l.uint32(),{limits:d.limits?.peers$}));break}case 3:{b.backoff=l.uint64Number();break}default:{l.skipType(I&7);break}}}return b},function*(l,h,d,b={}){let v={peers:0},I=h==null?l.len:l.pos+h;for(;l.pos<I;){let D=l.uint32();switch(D>>>3){case 1:{yield{field:`${d}.topicID`,value:l.string()};break}case 2:{if(b.limits?.peers!=null&&v.peers===b.limits.peers)throw new X('Streaming decode error - repeated field "peers" had too many elements');for(let M of s.PeerInfo.codec().stream(l,l.uint32(),`${d}.peers[]`,{limits:b.limits?.peers$}))yield{...M,index:v.peers};v.peers++;break}case 3:{yield{field:`${d}.backoff`,value:l.uint64Number()};break}default:{l.skipType(D&7);break}}}})),g);function w(l){return Se(l,f.codec())}f.encode=w;function S(l,h){return Ee(l,f.codec(),h)}f.decode=S;function _(l,h){return _e(l,f.codec(),h)}f.stream=_})(a=s.ControlPrune||(s.ControlPrune={}));let c;(function(f){let g;f.codec=()=>(g==null&&(g=Ie((l,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),l.peerID!=null&&(h.uint32(10),h.bytes(l.peerID)),l.signedPeerRecord!=null&&(h.uint32(18),h.bytes(l.signedPeerRecord)),d.lengthDelimited!==!1&&h.ldelim()},(l,h,d={})=>{let b={},v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{b.peerID=l.bytes();break}case 2:{b.signedPeerRecord=l.bytes();break}default:{l.skipType(I&7);break}}}return b},function*(l,h,d,b={}){let v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{yield{field:`${d}.peerID`,value:l.bytes()};break}case 2:{yield{field:`${d}.signedPeerRecord`,value:l.bytes()};break}default:{l.skipType(I&7);break}}}})),g);function w(l){return Se(l,f.codec())}f.encode=w;function S(l,h){return Ee(l,f.codec(),h)}f.decode=S;function _(l,h){return _e(l,f.codec(),h)}f.stream=_})(c=s.PeerInfo||(s.PeerInfo={}));let u;(function(f){let g;f.codec=()=>(g==null&&(g=Ie((l,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),l.messageIDs!=null&&l.messageIDs.length>0)for(let b of l.messageIDs)h.uint32(10),h.bytes(b);d.lengthDelimited!==!1&&h.ldelim()},(l,h,d={})=>{let b={messageIDs:[]},v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{if(d.limits?.messageIDs!=null&&b.messageIDs.length===d.limits.messageIDs)throw new X('Decode error - repeated field "messageIDs" had too many elements');b.messageIDs.push(l.bytes());break}default:{l.skipType(I&7);break}}}return b},function*(l,h,d,b={}){let v={messageIDs:0},I=h==null?l.len:l.pos+h;for(;l.pos<I;){let D=l.uint32();switch(D>>>3){case 1:{if(b.limits?.messageIDs!=null&&v.messageIDs===b.limits.messageIDs)throw new X('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:l.bytes()},v.messageIDs++;break}default:{l.skipType(D&7);break}}}})),g);function w(l){return Se(l,f.codec())}f.encode=w;function S(l,h){return Ee(l,f.codec(),h)}f.decode=S;function _(l,h){return _e(l,f.codec(),h)}f.stream=_})(u=s.ControlIDontWant||(s.ControlIDontWant={}));let p;s.codec=()=>(p==null&&(p=Ie((f,g,w={})=>{if(w.lengthDelimited!==!1&&g.fork(),f.subscriptions!=null&&f.subscriptions.length>0)for(let S of f.subscriptions)g.uint32(10),s.SubOpts.codec().encode(S,g);if(f.messages!=null&&f.messages.length>0)for(let S of f.messages)g.uint32(18),s.Message.codec().encode(S,g);f.control!=null&&(g.uint32(26),s.ControlMessage.codec().encode(f.control,g)),w.lengthDelimited!==!1&&g.ldelim()},(f,g,w={})=>{let S={subscriptions:[],messages:[]},_=g==null?f.len:f.pos+g;for(;f.pos<_;){let l=f.uint32();switch(l>>>3){case 1:{if(w.limits?.subscriptions!=null&&S.subscriptions.length===w.limits.subscriptions)throw new X('Decode error - repeated field "subscriptions" had too many elements');S.subscriptions.push(s.SubOpts.codec().decode(f,f.uint32(),{limits:w.limits?.subscriptions$}));break}case 2:{if(w.limits?.messages!=null&&S.messages.length===w.limits.messages)throw new X('Decode error - repeated field "messages" had too many elements');S.messages.push(s.Message.codec().decode(f,f.uint32(),{limits:w.limits?.messages$}));break}case 3:{S.control=s.ControlMessage.codec().decode(f,f.uint32(),{limits:w.limits?.control});break}default:{f.skipType(l&7);break}}}return S},function*(f,g,w,S={}){let _={subscriptions:0,messages:0},l=g==null?f.len:f.pos+g;for(;f.pos<l;){let h=f.uint32();switch(h>>>3){case 1:{if(S.limits?.subscriptions!=null&&_.subscriptions===S.limits.subscriptions)throw new X('Streaming decode error - repeated field "subscriptions" had too many elements');for(let d of s.SubOpts.codec().stream(f,f.uint32(),`${w}.subscriptions[]`,{limits:S.limits?.subscriptions$}))yield{...d,index:_.subscriptions};_.subscriptions++;break}case 2:{if(S.limits?.messages!=null&&_.messages===S.limits.messages)throw new X('Streaming decode error - repeated field "messages" had too many elements');for(let d of s.Message.codec().stream(f,f.uint32(),`${w}.messages[]`,{limits:S.limits?.messages$}))yield{...d,index:_.messages};_.messages++;break}case 3:{yield*s.ControlMessage.codec().stream(f,f.uint32(),`${w}.control`,{limits:S.limits?.control});break}default:{f.skipType(h&7);break}}}})),p);function m(f){return Se(f,s.codec())}s.encode=m;function E(f,g){return Ee(f,s.codec(),g)}s.decode=E;function y(f,g){return _e(f,s.codec(),g)}s.stream=y})(ct||(ct={}));var Nr=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 jc;(function(s){s.StrictSign="StrictSign",s.StrictNoSign="StrictNoSign"})(jc||(jc={}));var vt;(function(s){s[s.Signing=0]="Signing",s[s.Anonymous=1]="Anonymous"})(vt||(vt={}));var Te;(function(s){s.Error="error",s.Ignore="ignore",s.Reject="reject",s.Blacklisted="blacklisted"})(Te||(Te={}));var me;(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"})(me||(me={}));var we;(function(s){s.duplicate="duplicate",s.invalid="invalid",s.valid="valid"})(we||(we={}));function Wi(s){switch(s){case xe.Ignore:return Te.Ignore;case xe.Reject:return Te.Reject;default:throw new Error("Unreachable")}}var Zc;(function(s){s.forward="forward",s.publish="publish"})(Zc||(Zc={}));var ve;(function(s){s.Fanout="fanout",s.Random="random",s.Subscribed="subscribed",s.Outbound="outbound",s.NotEnough="not_enough",s.Opportunistic="opportunistic"})(ve||(ve={}));var We;(function(s){s.Dc="disconnected",s.BadScore="bad_score",s.Prune="prune",s.Excess="excess"})(We||(We={}));var us;(function(s){s.GraftBackoff="graft_backoff",s.BrokenPromise="broken_promise",s.MessageDeficit="message_deficit",s.IPColocation="IP_colocation"})(us||(us={}));var hs;(function(s){s.LowScore="low_score",s.MaxIhave="max_ihave",s.MaxIasked="max_iasked"})(hs||(hs={}));var Ks;(function(s){s.forward="forward",s.iwant="iwant"})(Ks||(Ks={}));var ls;(function(s){s.graylist="graylist",s.publish="publish",s.gossip="gossip",s.mesh="mesh"})(ls||(ls={}));function Yc(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"}),idontwantSkippedSends:s.gauge({name:"gossipsub_idontwant_skipped_sends_total",help:"Total message sends skipped because the peer sent IDONTWANT for the message",labelNames:["on"]}),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 ve.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:o},i);break;case ve.Random:this.meshPeerInclusionEventsRandom.inc({topic:o},i);break;case ve.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:o},i);break;case ve.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:o},i);break;case ve.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:o},i);break;case ve.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 We.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:o},i);break;case We.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:o},i);break;case We.Prune:this.meshPeerChurnEventsPrune.inc({topic:o},i);break;case We.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 xe.Accept:this.acceptedMessagesTotal.inc({topic:o});break;case xe.Ignore:this.ignoredMessagesTotal.inc({topic:o});break;case xe.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)},onIdontwantSkippedSend(r){this.idontwantSkippedSends.inc({on:r},1)},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 c=this.toTopic(r);this.msgPublishCount.inc({topic:c},1),this.msgPublishBytes.inc({topic:c},i*o),this.msgPublishPeersByTopic.inc({topic:c},i),this.directPeersPublishedTotal.inc({topic:c},n.direct),this.floodsubPeersPublishedTotal.inc({topic:c},n.floodsub),this.meshPeersPublishedTotal.inc({topic:c},n.mesh),this.fanoutPeersPublishedTotal.inc({topic:c},n.fanout),this.msgPublishTime.observe({topic:c},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 we.duplicate:this.prevalidationDuplicateTotal.inc({topic:i});break;case we.invalid:this.prevalidationInvalidTotal.inc({topic:i});break;case we.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===Te.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,c=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),c>0&&this.rpcSentPrune.inc(c),u>0&&this.rpcSentIDontWant.inc(u),(i>0||o>0||a>0||c>0||u>0)&&this.rpcSentControl.inc(1)}},registerScores(r,n){let i=0,o=0,a=0,c=0;for(let u of r)u>=n.graylistThreshold&&i++,u>=n.publishThreshold&&o++,u>=n.gossipThreshold&&a++,u>=0&&c++;this.peersByScoreThreshold.set({threshold:ls.graylist},i),this.peersByScoreThreshold.set({threshold:ls.publish},o),this.peersByScoreThreshold.set({threshold:ls.gossip},a),this.peersByScoreThreshold.set({threshold:ls.mesh},c),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 c=this.topicStrToLabel.get(a)??"unknown",u=i.get(c);u==null&&(u=new Set,i.set(c,u)),o.forEach(p=>u?.add(p))});for(let[o,a]of i){let c=[];a.forEach(u=>{c.push(n.get(u)??0)}),this.scorePerMesh.set({topic:o},c)}}}}var $=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var Nf={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},Uf={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 Xc(s={}){return{...Nf,...s,topics:s.topics!=null?Object.entries(s.topics).reduce((e,[t,r])=>(e[t]=Kf(r),e),{}):{}}}function Kf(s={}){return{...Uf,...s}}function Jc(s){for(let[e,t]of Object.entries(s.topics))try{zf(t)}catch(r){throw new $(`invalid score parameters for topic ${e}: ${r.message}`)}if(s.topicScoreCap<0)throw new $("invalid topic score cap; must be positive (or 0 for no cap)");if(s.appSpecificScore===null||s.appSpecificScore===void 0)throw new $("missing application specific score function");if(s.IPColocationFactorWeight>0)throw new $("invalid IPColocationFactorWeight; must be negative (or 0 to disable)");if(s.IPColocationFactorWeight!==0&&s.IPColocationFactorThreshold<1)throw new $("invalid IPColocationFactorThreshold; must be at least 1");if(s.behaviourPenaltyWeight>0)throw new $("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)");if(s.behaviourPenaltyWeight!==0&&(s.behaviourPenaltyDecay<=0||s.behaviourPenaltyDecay>=1))throw new $("invalid BehaviourPenaltyDecay; must be between 0 and 1");if(s.decayInterval<1e3)throw new $("invalid DecayInterval; must be at least 1s");if(s.decayToZero<=0||s.decayToZero>=1)throw new $("invalid DecayToZero; must be between 0 and 1")}function zf(s){if(s.topicWeight<0)throw new $("invalid topic weight; must be >= 0");if(s.timeInMeshQuantum===0)throw new $("invalid TimeInMeshQuantum; must be non zero");if(s.timeInMeshWeight<0)throw new $("invalid TimeInMeshWeight; must be positive (or 0 to disable)");if(s.timeInMeshWeight!==0&&s.timeInMeshQuantum<=0)throw new $("invalid TimeInMeshQuantum; must be positive");if(s.timeInMeshWeight!==0&&s.timeInMeshCap<=0)throw new $("invalid TimeInMeshCap; must be positive");if(s.firstMessageDeliveriesWeight<0)throw new $("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)");if(s.firstMessageDeliveriesWeight!==0&&(s.firstMessageDeliveriesDecay<=0||s.firstMessageDeliveriesDecay>=1))throw new $("invalid FirstMessageDeliveriesDecay; must be between 0 and 1");if(s.firstMessageDeliveriesWeight!==0&&s.firstMessageDeliveriesCap<=0)throw new $("invalid FirstMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight>0)throw new $("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.meshMessageDeliveriesWeight!==0&&(s.meshMessageDeliveriesDecay<=0||s.meshMessageDeliveriesDecay>=1))throw new $("invalid MeshMessageDeliveriesDecay; must be between 0 and 1");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesCap<=0)throw new $("invalid MeshMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesThreshold<=0)throw new $("invalid MeshMessageDeliveriesThreshold; must be positive");if(s.meshMessageDeliveriesWindow<0)throw new $("invalid MeshMessageDeliveriesWindow; must be non-negative");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesActivation<1e3)throw new $("invalid MeshMessageDeliveriesActivation; must be at least 1s");if(s.meshFailurePenaltyWeight>0)throw new $("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)");if(s.meshFailurePenaltyWeight!==0&&(s.meshFailurePenaltyDecay<=0||s.meshFailurePenaltyDecay>=1))throw new $("invalid MeshFailurePenaltyDecay; must be between 0 and 1");if(s.invalidMessageDeliveriesWeight>0)throw new $("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.invalidMessageDeliveriesDecay<=0||s.invalidMessageDeliveriesDecay>=1)throw new $("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1")}var qf={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function Qc(s={}){return{...qf,...s}}function Kr(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 el(s,e){return Kr(s,e,()=>!0)}var Ur=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 tl(s,e,t,r){let n=0;Object.entries(e.topics).forEach(([o,a])=>{let c=t.topics[o];if(c===void 0)return;let u=0;if(a.inMesh){let y=a.meshTime/c.timeInMeshQuantum;y>c.timeInMeshCap&&(y=c.timeInMeshCap),u+=y*c.timeInMeshWeight}let p=a.firstMessageDeliveries;if(p>c.firstMessageDeliveriesCap&&(p=c.firstMessageDeliveriesCap),u+=p*c.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries<c.meshMessageDeliveriesThreshold){let y=c.meshMessageDeliveriesThreshold-a.meshMessageDeliveries,f=y*y;u+=f*c.meshMessageDeliveriesWeight}let m=a.meshFailurePenalty;u+=m*c.meshFailurePenaltyWeight;let E=a.invalidMessageDeliveries*a.invalidMessageDeliveries;u+=E*c.invalidMessageDeliveriesWeight,n+=u*c.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),c=a!=null?a.size:0;if(c>t.IPColocationFactorThreshold){let u=c-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 nl=Al(rl(),1);var De;(function(s){s[s.unknown=0]="unknown",s[s.valid=1]="valid",s[s.invalid=2]="invalid",s[s.ignored=3]="ignored"})(De||(De={}));var zr=class{records;queue;constructor(){this.records=new Map,this.queue=new nl.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:De.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let r={msgId:e,expire:Date.now()+Io};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 qr=class{params;metrics;peerStats=new Map;peerIPs=new Ur(()=>new Set);scoreCache=new Map;deliveryRecords=new zr;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,r,n){this.params=e,this.metrics=t,Jc(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??tl,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!==De.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,i-n.firstSeenTsMs,De[n.status]);return}n.status=De.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 Te.Error:this.markInvalidMessageDelivery(e,r);return;case Te.Blacklisted:return}let i=this.deliveryRecords.ensureRecord(t);if(i.status!==De.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-i.firstSeenTsMs,De[i.status]);return}if(n===Te.Ignore){i.status=De.ignored,i.peers.clear();return}i.status=De.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 De.unknown:n.peers.add(e);break;case De.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,r,n.validated);break;case De.invalid:this.markInvalidMessageDelivery(e,r);break;case De.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 c=a.meshMessageDeliveriesCap;o.meshMessageDeliveries=Math.min(c,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 Gf(s,e,t,r,n){let i=0,o=new Map;if(Object.entries(e.topics).forEach(([E,y])=>{let f=n.get(E)??"unknown",g=t.topics[E];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 S=0,_=0,l=0,h=0,d=0;if(y.inMesh){let D=Math.max(y.meshTime/g.timeInMeshQuantum,g.timeInMeshCap);S+=D*g.timeInMeshWeight}let b=y.firstMessageDeliveries;if(b>g.firstMessageDeliveriesCap&&(b=g.firstMessageDeliveriesCap),_+=b*g.firstMessageDeliveriesWeight,y.meshMessageDeliveriesActive&&y.meshMessageDeliveries<g.meshMessageDeliveriesThreshold){let D=g.meshMessageDeliveriesThreshold-y.meshMessageDeliveries,M=D*D;l+=M*g.meshMessageDeliveriesWeight}let v=y.meshFailurePenalty;h+=v*g.meshFailurePenaltyWeight;let I=y.invalidMessageDeliveries*y.invalidMessageDeliveries;d+=I*g.invalidMessageDeliveriesWeight,i+=(S+_+l+h+d)*g.topicWeight,w.p1w+=S,w.p2w+=_,w.p3w+=l,w.p3bw+=h,w.p4w+=d}),t.topicScoreCap>0&&i>t.topicScoreCap){i=t.topicScoreCap;let E=t.topicScoreCap/i;for(let y of o.values())y.p1w*=E,y.p2w*=E,y.p3w*=E,y.p3bw*=E,y.p4w*=E}let a=0,c=0,u=0,p=t.appSpecificScore(s);a+=p*t.appSpecificWeight,e.knownIPs.forEach(E=>{if(t.IPColocationFactorWhitelist.has(E))return;let y=r.get(E),f=y!=null?y.size:0;if(f>t.IPColocationFactorThreshold){let g=f-t.IPColocationFactorThreshold,w=g*g;c+=w*t.IPColocationFactorWeight}});let m=e.behaviourPenalty*e.behaviourPenalty;return u+=m*t.behaviourPenaltyWeight,i+=a+c+u,{byTopic:o,p5w:a,p6w:c,p7w:u,score:i}}function il(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 c=Gf(o,a,t,r,n);for(let[u,p]of c.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(c.p5w),i.p6w.push(c.p6w),i.p7w.push(c.p7w),i.score.push(c.score)}else i.p5w.push(0),i.p6w.push(0),i.p7w.push(0),i.score.push(0)}return i}function Vi(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 ol(s){let e=Vi(s);if(e==null)throw new oe(`Multiaddr ${s} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function al(s){return Vi(s)!==null}var $i=class s extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,s)}},cl=s=>s.reason??new DOMException("This operation was aborted.","AbortError");function ji(s,e){let{milliseconds:t,fallback:r,message:n,customTimers:i={setTimeout,clearTimeout},signal:o}=e,a,c,p=new Promise((m,E)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(o?.aborted){E(cl(o));return}if(o&&(c=()=>{E(cl(o))},o.addEventListener("abort",c,{once:!0})),s.then(m,E),t===Number.POSITIVE_INFINITY)return;let y=new $i;a=i.setTimeout.call(void 0,()=>{if(r){try{m(r())}catch(f){E(f)}return}typeof s.cancel=="function"&&s.cancel(),n===!1?m():n instanceof Error?E(n):(y.message=n??`Promise timed out after ${t} milliseconds`,E(y))},t)}).finally(()=>{p.clear(),c&&o&&o.removeEventListener("abort",c)});return p.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},p}var Hf=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 Wf(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(),c=[],{addListener:u,removeListener:p}=Hf(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}c.push(f),t.count===c.length&&(r(),i(c))},E=(...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,E)};for(let y of a)u(y,m);for(let y of t.rejectionEvents)a.includes(y)||u(y,E);t.signal&&t.signal.addEventListener("abort",()=>{E(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(n.cancel=r,typeof t.timeout=="number"){let i=ji(n,{milliseconds:t.timeout});return i.cancel=()=>{r(),i.clear()},i}return n}function ll(s,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let r=Wf(s,e,t),n=r.then(i=>i[0]);return n.cancel=r.cancel,n}function Vf(s){return s?.addEventListener!=null}function $f(s){let e=Nt(),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 c=a();for(;;){t=Promise.withResolvers();let{done:u,value:p}=await Promise.race([c.next(),t.promise]);if(s.writeStatus==="closing"||s.writeStatus==="closed"||(p!=null&&(s.send(p)||await Promise.race([ll(s,"drain",{rejectionEvents:["close"]})])),u===!0))break}await s.close()}}}function ul(...s){let e=s.map(t=>Vf(t)?$f(t):t);return Us(...e)}var Gr=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(as.single(e))}pushPrefixed(e){this.rawStream.send(e)}async close(e){await this.rawStream.close(e).catch(t=>{this.rawStream.abort(t)})}},Hr=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=ul(this.rawStream,r=>Ns(r,t))}async close(){this.closeController.abort()}};var Wr=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!==Te.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 hl=Y("libp2p-pubsub:"),jf=BigInt(Date.now())*1000000n;function Zf(){let s=++jf,e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,s,!1),e}async function fl(s,e,t,r){switch(s.type){case vt.Signing:{let n={from:s.author.toMultihash().bytes,data:r,seqno:Zf(),topic:e,signature:void 0,key:void 0},i=It([hl,ct.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${j(n.seqno??new Uint8Array(0),"base16")}`),topic:e,signature:n.signature,key:Ui(n.key)};return{raw:n,msg:o}}case vt.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 dl(s,e){switch(s){case Ut:return e.signature!=null?{valid:!1,error:me.SignaturePresent}:e.seqno!=null?{valid:!1,error:me.SeqnoPresent}:e.key!=null?{valid:!1,error:me.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case Et:{if(e.seqno==null)return{valid:!1,error:me.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:me.InvalidSeqno};if(e.signature==null)return{valid:!1,error:me.InvalidSignature};if(e.from==null)return{valid:!1,error:me.InvalidPeerId};let t;try{t=is(et(e.from))}catch{return{valid:!1,error:me.InvalidPeerId}}let r;if(e.key!=null){try{r=Ui(e.key)}catch{return{valid:!1,error:me.InvalidPeerId}}if(!t.equals(r.toMultihash().bytes))return{valid:!1,error:me.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:me.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=It([hl,ct.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${j(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:r}}:{valid:!1,error:me.InvalidSignature}}default:throw new Error("Unreachable")}}function Ve(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 Zi(s){return s.control===void 0&&(s.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),s}function Je(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 pl(s){return j(s,"base64")}function ml(s,e,t){switch(s){case Et:return{type:vt.Signing,author:e,key:je(t.publicKey),privateKey:t};case Ut:return{type:vt.Anonymous};default:throw new Error(`Unknown signature policy "${s}"`)}}var Yf=(s,e)=>{let t=Y(e.toString(16).padStart(16,"0"),"base16"),r=je(s),n=new Uint8Array(r.byteLength+t.length);return n.set(r,0),n.set(t,r.byteLength),n};function gl(s){if(s.type!=="signed")throw new Error("expected signed message type");if(s.sequenceNumber==null)throw Error("missing seqno field");return Yf(s.from.publicKey??s.key,s.sequenceNumber)}async function bl(s){return Tt.encode(s.data)}function yl(s){if(al(s)){let e=ol(s);switch(e.type){case"ip4":case"ip6":return e.host;default:break}}return null}var fs=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 Le;(function(s){s[s.started=0]="started",s[s.stopped=1]="stopped"})(Le||(Le={}));var Vr=class extends Ws{globalSignaturePolicy;protocols=[...qs].reverse();publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=Nt({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=Kt;opts;decodeRpcLimits;metrics;status={code:Le.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:Qi,Dlo:eo,Dhi:to,Dscore:so,Dout:ro,Dlazy:oo,heartbeatInterval:lo,fanoutTTL:uo,mcacheLength:no,mcacheGossip:io,seenTTL:_o,gossipsubIWantFollowupMs:So,prunePeers:ho,pruneBackoff:fo,unsubcribeBackoff:po,graftFloodThreshold:xo,opportunisticGraftPeers:wo,opportunisticGraftTicks:yo,directConnectTicks:go,gossipFactor:ao,idontwantMinDataSize:Ro,idontwantMaxMessages:Lo,...t,scoreParams:Xc(t.scoreParams),scoreThresholds:Qc(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=r.decodeRpcLimits??$c,this.globalSignaturePolicy=r.globalSignaturePolicy??Et,r.fallbackToFloodsub&&this.protocols.push(jr),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 fs({validityMs:r.seenTTL}),this.publishedMessageIds=new fs({validityMs:r.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case Et:this.msgIdFn=gl;break;case Ut:this.msgIdFn=bl;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new fs({validityMs:r.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??pl,this.mcache=t.messageCache??new Nr(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),Bo),i=Yc(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 Wr(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new qr(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??Co}[Symbol.toStringTag]="@libp2p/gossipsub";[Uo]=["@libp2p/pubsub"];[Ko]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===Le.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=ml(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=Nt({objectMode:!0}),Us(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,Yr);this.status={code:Le.started,registrarTopologyIds:r,heartbeatTimeout:n,hearbeatStartMs:Date.now()+Yr},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)})},bo),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!==Le.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:Le.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 Gr(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===jr&&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 Hr(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=yl(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,We.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===Le.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)??Ot(r))}getTopics(){return Array.from(this.subscriptions)}decodeRpc(e){return ct.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 Us(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,c=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&&(c=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${r} messages ${n} ihave ${i} iwant ${o} graft ${a} prune ${c}`),t.subscriptions!=null&&t.subscriptions.length>0){let u=[],p=e.toString(),m=[];t.subscriptions.forEach(E=>{let y=E.topic,f=E.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+Oo;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 we.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 we.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 we.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:we.duplicate,msgIdStr:n};let i=await dl(this.globalSignaturePolicy,t);if(!i.valid)return{code:we.invalid,reason:Te.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:we.invalid,reason:Te.Error,error:me.TransformFailed}}let a=await this.msgIdFn(o),c=this.msgIdToStrFn(a),u={msgId:a,msgIdStr:c};if(r!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(r,c)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(c))return{code:we.duplicate,msgIdStr:c};this.seenCache.put(c),(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(E){let y=E.code;y===Do&&(m=xe.Ignore),y===To?m=xe.Reject:m=xe.Ignore}if(m!==xe.Accept)return{code:we.invalid,reason:Wi(m),msgIdStr:c}}return{code:we.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,Ve(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<Mo&&r.acceptUntil>=t)return r.messagesAccepted+=1,!0;let n=this.score.score(e);return n>=Ao?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+Po}):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:hs.LowScore}),[];let n=(this.peerhave.get(e)??0)+1;if(this.peerhave.set(e,n),n>vo)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:hs.MaxIhave}),[];let i=this.iasked.get(e)??0;if(i>=Qe)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,i),this.metrics?.ihaveRcvIgnored.inc({reason:hs.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 E=0;for(let y of m){if(a>=Qe)break e;a++;let f=this.msgIdToStrFn(y);this.seenCache.has(f)||(o.set(f,y),E++)}this.metrics?.onIhaveRcv(p,m.length,E)}if(o.size===0)return[];let c=o.size;c+i>Qe&&(c=Qe-i),this.log("IHAVE: Asking for %d out of %d messages from %s",c,o.size,e);let u=Array.from(o.values());return Je(u),u=u.slice(0,c),this.iasked.set(e,i+c),[{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>Eo)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,c=0;e:for(let{messageIDs:u}of t)if(u!=null)for(let p of u){if(c>=Qe)break e;c++;let m=this.msgIdToStrFn(p),E=this.mcache.getWithIWantCount(m,e);if(E==null){a++;continue}if(this.idontwants.get(e)?.has(m)===!0){this.metrics?.onIdontwantSkippedSend(Ks.iwant);continue}if(o.set(E.msg.topic,1+(o.get(E.msg.topic)??0)),E.count>co){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,p);continue}i.set(m,E.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:c})=>{if(c==null)return;let u=this.mesh.get(c);if(u==null){o=!1;return}if(u.has(e))return;let p=this.backoff.get(c)?.get(e);if(this.direct.has(e))this.log("GRAFT: ignoring request from direct peer %s",e),r.push(c),o=!1;else if(typeof p=="number"&&i<p){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,us.GraftBackoff),o=!1;let m=p+this.opts.graftFloodThreshold-this.opts.pruneBackoff;i<m&&this.score.addPenalty(e,1,us.GraftBackoff),this.addBackoff(e,c),r.push(c)}else n<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,n,c),r.push(c),o=!1,this.addBackoff(e,c)):u.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(r.push(c),this.addBackoff(e,c)):(this.log("GRAFT: Add mesh link from %s in %s",e,c),this.addToMesh(e,c,ve.Subscribed));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:c,direction:"inbound"}})}),r.length===0)return[];let a=!1;return Promise.all(r.map(async c=>this.makePrune(e,c,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,We.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:c}of t)for(let u of c){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,us.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%mo!==0)return;let e=Date.now();this.backoff.forEach((t,r)=>{t.forEach((n,i)=>{n+ko*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&&(Je(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async r=>{if(r.peerID==null)return;let n=is(et(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=Ot(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!==Le.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!==Le.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!==Le.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,ve.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,ve.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!==Le.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,t){let r=new Set,n={direct:0,floodsub:0,mesh:0,fanout:0},i=this.topics.get(e);if(i!=null)if(t??this.opts.floodPublish)i.forEach(o=>{this.direct.has(o)?(r.add(o),n.direct++):this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(r.add(o),n.floodsub++)});else{this.direct.forEach(a=>{i.has(a)&&(r.add(a),n.direct++)}),this.floodsubPeers.forEach(a=>{i.has(a)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&(r.add(a),n.floodsub++)});let o=this.mesh.get(e);if(o!=null&&o.size>0)o.forEach(a=>{r.add(a),n.mesh++}),o.size<this.opts.D&&this.getRandomGossipPeers(e,this.opts.D-o.size,c=>!o.has(c)&&!this.direct.has(c)&&!this.floodsubPeers.has(c)&&this.score.score(c)>=this.opts.scoreThresholds.publishThreshold).forEach(c=>{r.add(c),n.mesh++});else{let a=this.fanout.get(e);if(a!=null&&a.size>0)a.forEach(c=>{r.add(c),n.fanout++});else{let c=this.getRandomGossipPeers(e,this.opts.D,u=>this.score.score(u)>=this.opts.scoreThresholds.publishThreshold);c.size>0&&(this.fanout.set(e,c),c.forEach(u=>{r.add(u),n.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:r,tosendCount:n}}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=>{if(this.idontwants.get(o)?.has(e)===!0){i.delete(o),this.metrics?.onIdontwantSkippedSend(Ks.forward);return}this.sendRpc(o,Ve([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 fl(this.publishConfig,e,t,i),c=await this.msgIdFn(a),u=this.msgIdToStrFn(c),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:E}=this.selectPeersToPublish(e,r?.floodPublish),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:c,msgIdStr:u},o,!0),this.gossipTracer.deliverMessage(u),this.publishedMessageIds.put(u);let g=r?.batchPublish??this.opts.batchPublish,w=Ve([o]);if(g)this.sendRpcInBatch(m,w);else for(let _ of m)this.sendRpc(_,w)||m.delete(_);let S=Date.now()-n;return this.metrics?.onPublishMsg(e,E,m.size,o.data!=null?o.data.length:0,S),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(_=>this.peers.get(_)??Ot(_))}}sendRpcInBatch(e,t){let r=ct.encode(t),n=as.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===xe.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=Wi(r),{message:a,originatingPeers:c}=n;this.score.rejectMessage(t,e,a.topic,o);for(let u of c)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=Ve([],{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,ve.Subscribed),!0)}async sendPrune(e,t){let n=[await this.makePrune(e,t,this.opts.doPX,!0)],i=Ve([],{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)Zr(this.streamsOutbound.get(a)?.protocol,St.IDontWant)||i.delete(a);let o=Ve([],{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=ct.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=Zi(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=Zi(t);n.control.ihave=r}async sendGraftPrune(e,t,r){let n=this.opts.doPX,i=!1;for(let[o,a]of e){let c=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,Ve([],{graft:c,prune:u}))}for(let[o,a]of t){let c=await Promise.all(a.map(async u=>this.makePrune(o,u,n&&!(r.get(o)??!1),i)));this.sendRpc(o,Ve([],{prune:c}))}}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||(Je(r),r.length>Qe&&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=Je(Array.from(a)).slice(0,n),a.forEach(c=>{let u=r;r.length>Qe&&(u=Je(u.slice()).slice(0,Qe)),this.pushGossip(c,{topicID:e,messageIDs:u})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,Ve([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let r=Ve([],{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),!Zr(this.streamsOutbound.get(e)?.protocol,St.Backoff))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),c=await Promise.all(Array.from(a).map(async u=>{let p=this.peers.get(u)??Ot(u),m;try{m=await this.components.peerStore.get(p)}catch(E){if(E.name!=="NotFoundError")throw E}return{peerID:p.toMultihash().bytes,signedPeerRecord:m?.peerRecordEnvelope}}));return{topicID:t,peers:c,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===Le.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,c=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 E=new Map;this.mesh.forEach((f,g)=>{let w=this.topics.get(g),S=new Set,_=new Set;if(E.set(g,_),w!=null){let d=Je(Array.from(w)),b=this.backoff.get(g);for(let v of d){let I=this.streamsOutbound.get(v);if(I!=null&&this.protocols.includes(I.protocol)&&!f.has(v)&&!this.direct.has(v)){let D=c(v);b?.has(v)!==!0&&D>=0&&S.add(v),D>=this.opts.scoreThresholds.gossipThreshold&&_.add(v)}}}let l=(d,b)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",d,g),this.addBackoff(d,g),f.delete(d),c(d)>=this.opts.scoreThresholds.gossipThreshold&&_.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),_.delete(d);let v=u.get(d);v==null?u.set(d,[g]):v.push(g)};if(f.forEach(d=>{let b=c(d);b<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",d,b,g),l(d,We.BadScore),m.set(d,!0))}),f.size<t){let d=e-f.size;el(S,d).forEach(v=>{h(v,ve.NotEnough)})}if(f.size>r){let d=Array.from(f);d.sort((v,I)=>c(I)-c(v)),d=d.slice(0,n).concat(Je(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 M=d[D];for(let U=D;U>0;U--)d[U]=d[U-1];d[0]=M};if(b>0){let D=b;for(let M=1;M<e&&D>0;M++)(this.outbound.get(d[M])??!1)&&(v(M),D--)}let I=e-b;for(let D=e;D<d.length&&I>0;D++)(this.outbound.get(d[D])??!1)&&(v(D),I--)}d.slice(e).forEach(v=>{l(v,We.Excess)})}if(f.size>=t){let d=0;if(f.forEach(b=>{(this.outbound.get(b)??!1)&&d++}),d<i){let b=i-d;Kr(S,b,I=>this.outbound.get(I)===!0).forEach(I=>{h(I,ve.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&f.size>1){let d=Array.from(f).sort((I,D)=>c(I)-c(D)),b=Math.floor(f.size/2),v=c(d[b]);if(v<this.opts.scoreThresholds.opportunisticGraftThreshold){let I=this.opts.opportunisticGraftPeers,D=Kr(S,I,M=>c(M)>v);for(let M of D)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",M,g),h(M,ve.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)||c(h)<this.opts.scoreThresholds.publishThreshold)&&f.delete(h)});let S=this.topics.get(g),_=[],l=new Set;if(E.set(g,l),S!=null){let h=Je(Array.from(S));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=c(d);v>=this.opts.scoreThresholds.publishThreshold&&_.push(d),v>=this.opts.scoreThresholds.gossipThreshold&&l.add(d)}}}if(f.size<e){let h=e-f.size;_.slice(0,h).forEach(d=>{f.add(d),l?.delete(d)})}}),this.emitGossip(E),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=Je(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 c of this.backoff.values()){t+=c.size;for(let[u,p]of c.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 c of this.idontwants.values())n+=c.size;e.cacheSize.set({cache:"idontwants"},n);for(let[c,u]of this.topics)e.topicPeersCount.set({topicStr:c},u.size);for(let[c,u]of this.mesh)e.meshPeerCounts.set({topicStr:c},u.size);let i=[],o=new Map;e.behaviourPenalty.reset();for(let c of this.peers.keys()){let u=this.score.score(c);i.push(u),o.set(c,u),e.behaviourPenalty.observe(this.score.peerStats.get(c)?.behaviourPenalty??0)}e.registerScores(i,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,o);let a=il(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)??Ot(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)??Ot(t),{tags:{[r]:void 0}}).catch(n=>{this.log.error("Error untagging peer %s with topic %s",t,r,n)})}};var Et="StrictSign",Ut="StrictNoSign",xe;(function(s){s.Accept="accept",s.Ignore="ignore",s.Reject="reject"})(xe||(xe={}));var Xf=Kt;function Jf(s={}){return e=>new Vr(e,s)}return Ml(Qf);})();
2
+ "use strict";var Libp2PGossipsub=(()=>{var El=Object.create;var zs=Object.defineProperty;var Sl=Object.getOwnPropertyDescriptor;var _l=Object.getOwnPropertyNames;var Il=Object.getPrototypeOf,Tl=Object.prototype.hasOwnProperty;var Dl=(s,e)=>()=>{try{return e||s((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Ae=(s,e)=>{for(var t in e)zs(s,t,{get:e[t],enumerable:!0})},Xi=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of _l(e))!Tl.call(s,n)&&n!==t&&zs(s,n,{get:()=>e[n],enumerable:!(r=Sl(e,n))||r.enumerable});return s};var Al=(s,e,t)=>(t=s!=null?El(Il(s)):{},Xi(e||!s||!s.__esModule?zs(t,"default",{value:s,enumerable:!0}):t,s)),Ml=s=>Xi(zs({},"__esModule",{value:!0}),s);var rl=Dl((hy,sl)=>{"use strict";function ie(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))}ie.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]}};ie.prototype.get=function(e){return this.peekAt(e)};ie.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};ie.prototype.peekFront=function(){return this.peek()};ie.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(ie.prototype,"length",{get:function(){return this.size()}});ie.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ie.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)};ie.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}};ie.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)};ie.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}};ie.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}}};ie.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 c;for(n=new Array(t),c=0;c<t;c++)n[c]=this._list[this._head+r+c&this._capacityMask];if(r=this._head+r&this._capacityMask,e+t===o){for(this._tail=this._tail-t+a&this._capacityMask,c=t;c>0;c--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(e===0){for(this._head=this._head+t+a&this._capacityMask,c=t-1;c>0;c--)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,c=e;c>0;c--)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,c=o-(t+e);c>0;c--)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}}};ie.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,c=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);c>p;)this.unshift(arguments[--c]);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<c;)this.push(arguments[p++]);for(i=0;i<m;i++)this.push(o[i])}return a}else return this.remove(r,t)}};ie.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0};ie.prototype.isEmpty=function(){return this._head===this._tail};ie.prototype.toArray=function(){return this._copyArray(!1)};ie.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]};ie.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,c;if(e||this._head>this._tail){for(c=this._head;c<n;c++)o[a++]=r[c];for(c=0;c<this._tail;c++)o[a++]=r[c]}else for(c=this._head;c<this._tail;c++)o[a++]=r[c];return o};ie.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};ie.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1};ie.prototype._nextPowerOf2=function(e){var t=Math.log(e)/Math.log(2),r=1<<t+1;return Math.max(r,4)};sl.exports=ie});var Qf={};Ae(Qf,{StrictNoSign:()=>Ut,StrictSign:()=>Et,TopicValidatorResult:()=>xe,gossipsub:()=>Jf,multicodec:()=>Xf});var jr="/floodsub/1.0.0",Pl="/meshsub/1.0.0",Ji="/meshsub/1.1.0",Kt="/meshsub/1.2.0",Bl=[Pl,Ji,Kt],qs=Bl,St;(function(s){s.Backoff="Backoff",s.IDontWant="IDontWant"})(St||(St={}));var kl={[St.Backoff]:Ji,[St.IDontWant]:Kt};function Zr(s,e){if(s==null)return!1;let t=qs.indexOf(s);return t===-1?!1:t>=qs.indexOf(kl[e])}var Qi=6,eo=4,to=12,so=4,ro=2,no=5,io=3,oo=6,ao=.25,co=3,Yr=100,lo=1e3,uo=6e4,ho=16,fo=6e4,po=10*1e3,mo=15;var td=30*1e3,go=300,bo=1e3,yo=60,wo=2,xo=10*1e3,Qe=5e3,vo=10,Eo=10,So=3*1e3,_o=2*6e4,Io=120*1e3,To="ERR_TOPIC_VALIDATOR_REJECT",Do="ERR_TOPIC_VALIDATOR_IGNORE",Ao=0,Mo=128,Po=1e3,Bo=1e3,ko=1,Ro=512,Lo=512,Co=1024*1024,Oo=1024;var oe=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},zt=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Gs=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Hs=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var qt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Xr=Symbol.for("@libp2p/peer-id");function Rl(s){return typeof s?.handleEvent=="function"}function Ll(s){return s===!0||s===!1}function Cl(s){return Ll(s)?s:s?.capture??!1}function Jr(s){let e={capture:Cl(s),once:!!s?.once};return s?.passive!=null&&(e.passive=s?.passive),s?.signal!=null&&(e.signal=s?.signal),e}function No(s,e){return Jr(s).capture===Jr(e).capture}var Ws=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=Jr(r);if(n?.signal?.aborted===!0)return;let i=u=>{n.once&&this.removeEventListener(e,t,n),Rl(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:No(u.options,n)))return;super.addEventListener(e,i,n);let c=()=>{this.removeEventListener(e,t,n)};n.signal?.addEventListener("abort",c),o.push({callback:t,wrapper:i,options:n,onAbort:c})}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&&No(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 Uo=Symbol.for("@libp2p/service-capabilities"),Ko=Symbol.for("@libp2p/service-dependencies");var rn={};Ae(rn,{base58btc:()=>ce,base58flickr:()=>Gl});var Pd=new Uint8Array(0);function qo(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 Oe(s){if(s instanceof Uint8Array&&s.constructor.name==="Uint8Array")return _t(s);if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return _t(new Uint8Array(s.buffer,s.byteOffset,s.byteLength));throw new Error("Unknown type, must be binary type")}function Go(s){let e=new Uint8Array(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}var zo=4096;function Ho(s){let e=s.length;if(e<=zo)return String.fromCharCode.apply(String,s);let t="",r=0;for(;r<e;)t+=String.fromCharCode.apply(String,s.subarray(r,r+=zo));return t}function Ol(s){return s?.buffer instanceof ArrayBuffer}function _t(s){return Ol(s)?s:s.slice()}function Fl(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 c=o.toLowerCase().charCodeAt(0),u=o.toUpperCase().charCodeAt(0);c!==a&&(r[c]=i),u!==a&&(r[u]=i)}}var p=s.length,m=s.charAt(0),E=Math.log(p)/Math.log(256),y=Math.log(256)/Math.log(p);function f(S){if(S instanceof Uint8Array||(ArrayBuffer.isView(S)?S=new Uint8Array(S.buffer,S.byteOffset,S.byteLength):Array.isArray(S)&&(S=Uint8Array.from(S))),!(S instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(S.length===0)return"";for(var _=0,l=0,h=0,d=S.length;h!==d&&S[h]===0;)h++,_++;for(var b=(d-h)*y+1>>>0,v=new Uint8Array(b);h!==d;){for(var I=S[h],D=0,M=b-1;(I!==0||D<l)&&M!==-1;M--,D++)I+=256*v[M]>>>0,v[M]=I%p>>>0,I=I/p>>>0;if(I!==0)throw new Error("Non-zero carry");l=D,h++}for(var U=b-l;U!==b&&v[U]===0;)U++;for(var z=m.repeat(_);U<b;++U)z+=s.charAt(v[U]);return z}function g(S){if(typeof S!="string")throw new TypeError("Expected String");if(S.length===0)return new Uint8Array;var _=0;if(S[_]!==" "){for(var l=0,h=0;S[_]===m;)l++,_++;for(var d=(S.length-_)*E+1>>>0,b=new Uint8Array(d);S[_];){var v=r[S.charCodeAt(_)];if(v===255)return;for(var I=0,D=d-1;(v!==0||I<h)&&D!==-1;D--,I++)v+=p*b[D]>>>0,b[D]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");h=I,_++}if(S[_]!==" "){for(var M=d-h;M!==d&&b[M]===0;)M++;for(var U=new Uint8Array(l+(d-M)),z=l;M!==d;)U[z++]=b[M++];return U}}}function w(S){var _=g(S);if(_)return _;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:g,decode:w}}var Nl=Fl,Ul=Nl,Vo=Ul;var Qr=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")}},en=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 $o(this,e)}},tn=class{decoders;constructor(e){this.decoders=e}or(e){return $o(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 $o(s,e){return new tn({...s.decoders??{[s.prefix]:s},...e.decoders??{[e.prefix]:e}})}var sn=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 Qr(e,t,r),this.decoder=new en(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Gt({name:s,prefix:e,encode:t,decode:r}){return new sn(s,e,t,r)}function lt({name:s,prefix:e,alphabet:t,caseInsensitive:r=!1}){let{encode:n,decode:i}=Vo(t,s,r);return Gt({prefix:e,name:s,encode:n,decode:o=>Oe(i(o))})}function Kl(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,c=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[c++]=255&a>>o)}if(o>=t||(255&a<<8-o)!==0)throw new SyntaxError("Unexpected end of data");return i}function zl(s,e,t){let r=e[e.length-1]==="=",n=(1<<t)-1,i="",o=0,a=0;for(let c=0;c<s.length;++c)for(a=a<<8|s[c],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 ql(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 ae({name:s,prefix:e,bitsPerChar:t,alphabet:r,caseInsensitive:n=!1}){let i=ql(r,n);return Gt({prefix:e,name:s,encode(o){return zl(o,r,t)},decode(o){return Kl(o,i,t,s)}})}var ce=lt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Gl=lt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var nn={};Ae(nn,{base32:()=>Ht,base32hex:()=>$l,base32hexpad:()=>Zl,base32hexpadupper:()=>Yl,base32hexupper:()=>jl,base32pad:()=>Wl,base32padupper:()=>Vl,base32upper:()=>Hl,base32z:()=>Xl});var Ht=ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),Hl=ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),Wl=ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),Vl=ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),$l=ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),jl=ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),Zl=ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),Yl=ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),Xl=ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var on={};Ae(on,{base36:()=>ps,base36upper:()=>Jl});var ps=lt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),Jl=lt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var Ql=Yo,jo=128,eu=127,tu=~eu,su=Math.pow(2,31);function Yo(s,e,t){e=e||[],t=t||0;for(var r=t;s>=su;)e[t++]=s&255|jo,s/=128;for(;s&tu;)e[t++]=s&255|jo,s>>>=7;return e[t]=s|0,Yo.bytes=t-r+1,e}var ru=an,nu=128,Zo=127;function an(s,r){var t=0,r=r||0,n=0,i=r,o,a=s.length;do{if(i>=a)throw an.bytes=0,new RangeError("Could not decode varint");o=s[i++],t+=n<28?(o&Zo)<<n:(o&Zo)*Math.pow(2,n),n+=7}while(o>=nu);return an.bytes=i-r,t}var iu=Math.pow(2,7),ou=Math.pow(2,14),au=Math.pow(2,21),cu=Math.pow(2,28),lu=Math.pow(2,35),uu=Math.pow(2,42),hu=Math.pow(2,49),fu=Math.pow(2,56),du=Math.pow(2,63),pu=function(s){return s<iu?1:s<ou?2:s<au?3:s<cu?4:s<lu?5:s<uu?6:s<hu?7:s<fu?8:s<du?9:10},mu={encode:Ql,decode:ru,encodingLength:pu},gu=mu,ms=gu;function gs(s,e=0){let t=ms.decode(s,e),r=ms.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 Wt(s,e,t=0){return ms.encode(s,e,t),e}function Vt(s){return ms.encodingLength(s)}function $e(s,e){let t=e.byteLength,r=Vt(s),n=r+Vt(t),i=new Uint8Array(n+t);return Wt(s,i,0),Wt(t,i,r),i.set(e,n),new $t(s,t,e,i)}function et(s){let e=Oe(s),[t,r]=gs(e),[n,i]=gs(e.subarray(r)),o=e.subarray(r+i);if(o.byteLength!==n)throw new Error("Incorrect length");return new $t(t,n,o,e)}function Xo(s,e){if(s===e)return!0;{let t=e;return s.code===t.code&&s.size===t.size&&t.bytes instanceof Uint8Array&&qo(s.bytes,t.bytes)}}var $t=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=_t(r),this.bytes=_t(n)}};function Jo(s,e){let{bytes:t,version:r}=s;return r===0?yu(t,cn(s),e??ce.encoder):wu(t,cn(s),e??Ht.encoder)}var Qo=new WeakMap;function cn(s){let e=Qo.get(s);if(e==null){let t=new Map;return Qo.set(s,t),t}return e}var pe=class s{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=_t(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!==bs)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==xu)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=$e(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&&Xo(e.multihash,r.multihash)}toString(e){return Jo(this,e)}toJSON(){return{"/":Jo(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??ea(r,n,i.bytes))}else if(t[vu]===!0){let{version:r,multihash:n,code:i}=t,o=et(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!==bs)throw new Error(`Version 0 CID must use dag-pb (code: ${bs}) block encoding`);return new s(e,t,r,r.bytes)}case 1:{let n=ea(e,t,r.bytes);return new s(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return s.create(0,bs,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=Oe(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 $t(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,E]=gs(e.subarray(t));return t+=E,m},n=r(),i=bs;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(),c=r(),u=t+c,p=u-o;return{version:n,codec:i,multihashCode:a,digestSize:c,multihashSize:p,size:u}}static parse(e,t){let[r,n]=bu(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 cn(i).set(r,e),i}};function bu(s,e){switch(s[0]){case"Q":{let t=e??ce;return[ce.prefix,t.decode(`${ce.prefix}${s}`)]}case ce.prefix:{let t=e??ce;return[ce.prefix,t.decode(s)]}case Ht.prefix:{let t=e??Ht;return[Ht.prefix,t.decode(s)]}case ps.prefix:{let t=e??ps;return[ps.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 yu(s,e,t){let{prefix:r}=t;if(r!==ce.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 wu(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 bs=112,xu=18;function ea(s,e,t){let r=Vt(s),n=r+Vt(e),i=new Uint8Array(n+t.byteLength);return Wt(s,i,0),Wt(e,i,r),i.set(t,n),i}var vu=Symbol.for("@ipld/js-cid/CID");var ln={};Ae(ln,{identity:()=>qe});var ta=0,Eu="identity",sa=Oe;function Su(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 $e(ta,sa(s))}var qe={code:ta,name:Eu,encode:sa,digest:Su};function Me(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 _u(s){return s.buffer instanceof ArrayBuffer}function Fe(s){return _u(s)?s:s.slice()}async function ra(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,Fe(e),Fe(t.subarray()));return r?.signal?.throwIfAborted(),i}function tt(s=0){return new Uint8Array(s)}function ge(s=0){return new Uint8Array(s)}function Iu(s){return s?.buffer instanceof ArrayBuffer}function na(s){if(Iu(s))return s;let e=s.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function It(s,e){e==null&&(e=s.reduce((n,i)=>n+i.length,0));let t=ge(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return na(t)}var oa=Symbol.for("@achingbrain/uint8arraylist");function ia(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 $s(s){return!!s?.[oa]}var de=class s{bufs;length;[oa]=!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($s(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($s(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=ia(this.bufs,e);return t.buf[t.index]}set(e,t){let r=ia(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($s(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 It(r,n)}subarray(e,t){let{bufs:r,length:n}=this._subList(e,t);return r.length===1?r[0]:It(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,c=a+o.byteLength;if(n=c,e>=c)continue;let u=e>=a&&e<c,p=t>a&&t<=c;if(u&&p){if(e===a&&t===c){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===c){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(!$s(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,c=this.byteLength-r.byteLength,u=r.byteLength-1,p;for(let m=t;m<=c;m+=p){p=0;for(let E=u;E>=0;E--){let y=this.get(m+E);if(r[E]!==y){p=Math.max(1,E-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=ge(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=tt(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=tt(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=tt(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=ge(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=tt(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=tt(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=tt(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=tt(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=tt(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(!Me(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 un={};Ae(un,{base10:()=>Tu});var Tu=lt({prefix:"9",name:"base10",alphabet:"0123456789"});var hn={};Ae(hn,{base16:()=>Du,base16upper:()=>Au});var Du=ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),Au=ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var fn={};Ae(fn,{base2:()=>Mu});var Mu=ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var dn={};Ae(dn,{base256emoji:()=>Lu});var aa=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}"),Pu=aa.reduce((s,e,t)=>(s[t]=e,s),[]),Bu=aa.reduce((s,e,t)=>{let r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return s[r]=t,s},[]);function ku(s){return s.reduce((e,t)=>(e+=Pu[t],e),"")}function Ru(s){let e=[];for(let t of s){let r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);let n=Bu[r];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Lu=Gt({prefix:"\u{1F680}",name:"base256emoji",encode:ku,decode:Ru});var pn={};Ae(pn,{base64:()=>Cu,base64pad:()=>Ou,base64url:()=>Fu,base64urlpad:()=>Nu});var Cu=ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ou=ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Fu=ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Nu=ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var mn={};Ae(mn,{base8:()=>Uu});var Uu=ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var gn={};Ae(gn,{identity:()=>Ku});var Ku=Gt({prefix:"\0",name:"identity",encode:s=>Ho(Oe(s)),decode:s=>Oe(Go(s))});var mp=new TextEncoder,gp=new TextDecoder;var wn={};Ae(wn,{sha256:()=>Tt,sha512:()=>Hu});var Gu=20;function yn({name:s,code:e,encode:t,minDigestLength:r,maxDigestLength:n}){return new bn(s,e,t,r,n)}var bn=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,r,n,i){this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??Gu,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?ca(r,this.code,t?.truncate):r.then(n=>ca(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ca(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 $e(e,s)}function ua(s){return async e=>new Uint8Array(await crypto.subtle.digest(s,e))}var Tt=yn({name:"sha2-256",code:18,encode:ua("SHA-256")}),Hu=yn({name:"sha2-512",code:19,encode:ua("SHA-512")});var xn={...gn,...fn,...mn,...un,...hn,...nn,...on,...rn,...pn,...dn},Ap={...wn,...ln};function fa(s,e,t,r){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:r}}}var ha=fa("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),vn=fa("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=ge(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),Wu={utf8:ha,"utf-8":ha,hex:xn.base16,latin1:vn,ascii:vn,binary:vn,...xn},js=Wu;function Y(s,e="utf8"){let t=js[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${s}`)}function j(s,e="utf8"){let t=js[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(s).substring(1)}var Vu=parseInt("11111",2),En=parseInt("10000000",2),$u=parseInt("01111111",2),da={0:ys,1:ys,2:ju,3:Xu,4:Ju,5:Yu,6:Zu,16:ys,22:ys,48:ys};function st(s,e={offset:0}){let t=s[e.offset]&Vu;if(e.offset++,da[t]!=null)return da[t](s,e);throw new Error("No decoder for tag "+t)}function ws(s,e){let t=0;if((s[e.offset]&En)===En){let r=s[e.offset]&$u,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 ys(s,e){ws(s,e);let t=[];for(;!(e.offset>=s.byteLength);){let r=st(s,e);if(r===null)break;t.push(r)}return t}function ju(s,e){let t=ws(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 Zu(s,e){let t=ws(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}`,c=[];for(;e.offset<r;){let u=s[e.offset];if(e.offset++,c.push(u&127),u<128){c.reverse();let p=0;for(let m=0;m<c.length;m++)p+=c[m]<<m*7;a+=`.${p}`,c=[]}}return a}function Yu(s,e){return e.offset++,null}function Xu(s,e){let t=ws(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 Ju(s,e){let t=ws(s,e),r=s.subarray(e.offset,e.offset+t);return e.offset+=t,r}function Qu(s){let e=s.toString(16);e.length%2===1&&(e="0"+e);let t=new de;for(let r=0;r<e.length;r+=2)t.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return t}function Sn(s){if(s.byteLength<128)return Uint8Array.from([s.byteLength]);let e=Qu(s.byteLength);return new de(Uint8Array.from([e.byteLength|En]),e)}function Pe(s){let e=new de,t=128;return(s.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(s),new de(Uint8Array.from([2]),Sn(e),e)}function Zs(s){let e=Uint8Array.from([0]),t=new de(e,s);return new de(Uint8Array.from([3]),Sn(t),t)}function ht(s,e=48){let t=new de;for(let r of s)t.append(r);return new de(Uint8Array.from([e]),Sn(t),t)}var eh=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),th=Uint8Array.from([6,5,43,129,4,0,34]),sh=Uint8Array.from([6,5,43,129,4,0,35]),rh={ext:!0,kty:"EC",crv:"P-256"},nh={ext:!0,kty:"EC",crv:"P-384"},ih={ext:!0,kty:"EC",crv:"P-521"},_n=32,In=48,Tn=66;function Dn(s){let e=st(s);return pa(e)}function pa(s){let e=s[1][1][0],t=1,r,n;if(e.byteLength===_n*2+1)return r=j(e.subarray(t,t+_n),"base64url"),n=j(e.subarray(t+_n),"base64url"),new jt({...rh,key_ops:["verify"],x:r,y:n});if(e.byteLength===In*2+1)return r=j(e.subarray(t,t+In),"base64url"),n=j(e.subarray(t+In),"base64url"),new jt({...nh,key_ops:["verify"],x:r,y:n});if(e.byteLength===Tn*2+1)return r=j(e.subarray(t,t+Tn),"base64url"),n=j(e.subarray(t+Tn),"base64url"),new jt({...ih,key_ops:["verify"],x:r,y:n});throw new oe(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function ma(s){return ht([Pe(Uint8Array.from([1])),ht([oh(s.crv)],160),ht([Zs(new de(Uint8Array.from([4]),Y(s.x??"","base64url"),Y(s.y??"","base64url")))],161)]).subarray()}function oh(s){if(s==="P-256")return eh;if(s==="P-384")return th;if(s==="P-521")return sh;throw new oe(`Invalid curve ${s}`)}var jt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=ma(this.jwk)),this._raw}toMultihash(){return qe.digest(je(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Me(this.raw,e.raw)}async verify(e,t,r){return ra(this.jwk,t,e,r)}};var Ys=BigInt(4294967295),ga=BigInt(32);function ah(s,e=!1){return e?{h:Number(s&Ys),l:Number(s>>ga&Ys)}:{h:Number(s>>ga&Ys)|0,l:Number(s&Ys)|0}}function ba(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}=ah(s[i],e);[r[i],n[i]]=[o,a]}return[r,n]}var ch=s=>s/2**32|0,lh=s=>s>>>0;function ya(s,e,t,r){let n=ch(t),i=lh(t);s.setUint32(e,r?i:n,r),s.setUint32(e+4,r?n:i,r)}var An=(s,e,t)=>s>>>t,Mn=(s,e,t)=>s<<32-t|e>>>t,Dt=(s,e,t)=>s>>>t|e<<32-t,At=(s,e,t)=>s<<32-t|e>>>t,xs=(s,e,t)=>s<<64-t|e>>>t-32,vs=(s,e,t)=>s>>>t-32|e<<64-t;function Ze(s,e,t,r){let n=(e>>>0)+(r>>>0);return{h:s+t+(n/2**32|0)|0,l:n|0}}var wa=(s,e,t)=>(s>>>0)+(e>>>0)+(t>>>0),xa=(s,e,t,r)=>e+t+r+(s/2**32|0)|0,va=(s,e,t,r)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0),Ea=(s,e,t,r,n)=>e+t+r+n+(s/2**32|0)|0,Sa=(s,e,t,r,n)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),_a=(s,e,t,r,n,i)=>e+t+r+n+i+(s/2**32|0)|0;function Xs(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in s&&s.BYTES_PER_ELEMENT===1}var Pn=s=>s?`"${s}" `:"";function rt(s,e=""){if(typeof s!="number")throw new TypeError(Pn(e)+"expected number, got "+typeof s);if(!Number.isSafeInteger(s)||s<0)throw new RangeError(Pn(e)+"expected integer >= 0, got "+s);return s}function Ne(s,e,t=""){if(Xs(s)&&(e===void 0||s.length===e))return s;e!==void 0&&rt(e,"length");let r=Xs(s),n=e!==void 0?` of length ${e}`:"",i=r?`length=${s.length}`:`type=${typeof s}`,o=Pn(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(rt(s.outputLen),rt(s.blockLen),s.outputLen<1||s.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var hh=(s,e)=>{if(s===null||typeof s!="object"||Array.isArray(s))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof s)},Ia=(s,e)=>{hh(s,e);let t=Object.getPrototypeOf(s);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(s,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function Zt(s,e=!0){if(s.destroyed)throw new Error("hash was destroyed");if(e&&s.finished)throw new Error("digest() was already called")}function Qs(s,e){Ne(s,void 0,"output");let t=e.outputLen;if(!(s.length>=t))throw new RangeError('"output" expected length >= '+t)}function Mt(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function er(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Ge(s,e){return s<<32-e|s>>>e}var Da=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",fh=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function tr(s){if(Ne(s),Da)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=fh[s[t]];return e}function Ta(s){return s>=48&&s<=57?s-48:s>=65&&s<=70?s-55:s>=97&&s<=102?s-87:void 0}function sr(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);if(Da)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=Ta(s.charCodeAt(i)),a=Ta(s.charCodeAt(i+1));if(o===void 0||a===void 0){let c=s[i]+s[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}r[n]=o*16+a}return r}function Bn(...s){let e=0;for(let r=0;r<s.length;r++){let n=s[r];Ne(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 dh(s,e,t="opts"){return Ia(s,"defaults"),e!==void 0&&Ia(e,t),Object.assign(Object.create(null),s,e)}function kn(s,e={}){if(typeof s!="function")throw new TypeError('"hashCons" expected function, got type='+typeof s);e=dh({},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 Aa(s=32){rt(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 Rn=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function Ma(s,e,t){return s&e^~s&t}function Pa(s,e,t){return s&e^s&t^e&t}var Es=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=er(this.buffer)}update(e){Zt(this),Ne(e);let{view:t,buffer:r,blockLen:n}=this,i=e.length,o=!1;for(let a=0;a<i;){let c=Math.min(n-this.pos,i-a);if(c===n){let u=er(e);for(;n<=i-a;a+=n)this.process(u,a);o=!0;continue}r.set(a===0&&c===i?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===n&&(this.process(t,0),this.pos=0,o=!0)}return this.length+=e.length,o&&this.roundClean(),this}digestInto(e){Zt(this),Qs(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)),ya(r,n-8,this.length*8,i),this.process(r,0),this.roundClean();let a=e===t?r:er(e),c=this.outputLen,u=c/4,p=this.get();if(c%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()}},Ba=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ka=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var ph=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]),ft=new Uint32Array(64),Ln=class extends Es{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:c}=this;return[e,t,r,n,i,o,a,c]}set(e,t,r,n,i,o,a,c){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=c|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)ft[m]=e.getUint32(t,!1);for(let m=16;m<64;m++){let E=ft[m-15],y=ft[m-2],f=Ge(E,7)^Ge(E,18)^E>>>3,g=Ge(y,17)^Ge(y,19)^y>>>10;ft[m]=g+ft[m-7]+f+ft[m-16]|0}let{A:r,B:n,C:i,D:o,E:a,F:c,G:u,H:p}=this;for(let m=0;m<64;m++){let E=Ge(a,6)^Ge(a,11)^Ge(a,25),y=p+E+Ma(a,c,u)+ph[m]+ft[m]|0,g=(Ge(r,2)^Ge(r,13)^Ge(r,22))+Pa(r,n,i)|0;p=u,u=c,c=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,c=c+this.F|0,u=u+this.G|0,p=p+this.H|0,this.set(r,n,i,o,a,c,u,p)}roundClean(){Mt(ft)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Mt(this.buffer)}},Cn=class extends Ln{constructor(){super(32,Ba)}};var Ra=ba(["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))),mh=Ra[0],gh=Ra[1],dt=new Uint32Array(80),pt=new Uint32Array(80),On=class extends Es{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:c,Eh:u,El:p,Fh:m,Fl:E,Gh:y,Gl:f,Hh:g,Hl:w}=this;return[e,t,r,n,i,o,a,c,u,p,m,E,y,f,g,w]}set(e,t,r,n,i,o,a,c,u,p,m,E,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=c|0,this.Eh=u|0,this.El=p|0,this.Fh=m|0,this.Fl=E|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 l=0;l<16;l++,t+=4)dt[l]=e.getUint32(t),pt[l]=e.getUint32(t+=4);for(let l=16;l<80;l++){let h=dt[l-15]|0,d=pt[l-15]|0,b=Dt(h,d,1)^Dt(h,d,8)^An(h,d,7),v=At(h,d,1)^At(h,d,8)^Mn(h,d,7),I=dt[l-2]|0,D=pt[l-2]|0,M=Dt(I,D,19)^xs(I,D,61)^An(I,D,6),U=At(I,D,19)^vs(I,D,61)^Mn(I,D,6),z=va(v,U,pt[l-7],pt[l-16]),Z=Ea(z,b,M,dt[l-7],dt[l-16]);dt[l]=Z|0,pt[l]=z|0}let{Ah:r,Al:n,Bh:i,Bl:o,Ch:a,Cl:c,Dh:u,Dl:p,Eh:m,El:E,Fh:y,Fl:f,Gh:g,Gl:w,Hh:S,Hl:_}=this;for(let l=0;l<80;l++){let h=Dt(m,E,14)^Dt(m,E,18)^xs(m,E,41),d=At(m,E,14)^At(m,E,18)^vs(m,E,41),b=m&y^~m&g,v=E&f^~E&w,I=Sa(_,d,v,gh[l],pt[l]),D=_a(I,S,h,b,mh[l],dt[l]),M=I|0,U=Dt(r,n,28)^xs(r,n,34)^xs(r,n,39),z=At(r,n,28)^vs(r,n,34)^vs(r,n,39),Z=r&i^r&a^i&a,k=n&o^n&c^o&c;S=g|0,_=w|0,g=y|0,w=f|0,y=m|0,f=E|0,{h:m,l:E}=Ze(u|0,p|0,D|0,M|0),u=a|0,p=c|0,a=i|0,c=o|0,i=r|0,o=n|0;let N=wa(M,z,k);r=xa(N,D,U,Z),n=N|0}({h:r,l:n}=Ze(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=Ze(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=Ze(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:p}=Ze(this.Dh|0,this.Dl|0,u|0,p|0),{h:m,l:E}=Ze(this.Eh|0,this.El|0,m|0,E|0),{h:y,l:f}=Ze(this.Fh|0,this.Fl|0,y|0,f|0),{h:g,l:w}=Ze(this.Gh|0,this.Gl|0,g|0,w|0),{h:S,l:_}=Ze(this.Hh|0,this.Hl|0,S|0,_|0),this.set(r,n,i,o,a,c,u,p,m,E,y,f,g,w,S,_)}roundClean(){Mt(dt,pt)}destroy(){this.destroyed=!0,Mt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Fn=class extends On{constructor(){super(64,ka)}};var Yt=kn(()=>new Cn,Rn(1));var Nn=kn(()=>new Fn,Rn(3));function nr(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 H=(s,e,t)=>Ne(s,e,t),Un=rt;function Ca(s,e=""){if(typeof s!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof s)}return s}function mt(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 Pt(s,e){if(typeof s!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof s}`);return s}var Ss=tr,Ue=(...s)=>Bn(...s),Xt=s=>sr(s),bt=Xs,Bt=s=>Aa(s),rr=BigInt(0),La=BigInt(1),bh=s=>s?`"${s}" `:"";function Be(s,e=""){if(typeof s!="boolean")throw new TypeError(bh(e)+"expected boolean, got type="+typeof s);return s}function ir(s){if(typeof s=="bigint"){if(!gt(s))throw new RangeError("positive bigint expected, got "+s)}else Un(s);return s}function nt(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 _s(s){let e=ir(s).toString(16);return e.length&1?"0"+e:e}function Oa(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);return s===""?rr:BigInt("0x"+s)}function Ye(s){return Oa(tr(s))}function kt(s){return Oa(tr(Is(Ne(s)).reverse()))}function or(s,e){if(rt(e),e===0)throw new Error("zero output length is invalid");s=ir(s);let t=e*2,r=s.toString(16);if(r.length>t)throw new RangeError("number is too large");return sr(r.padStart(t,"0"))}function Kn(s,e){return or(s,e).reverse()}function Is(s){return Uint8Array.from(H(s))}function gt(s){return typeof s=="bigint"&&rr<=s}function zn(s,e,t){return gt(s)&&gt(e)&&gt(t)&&e<=s&&s<t}function Jt(s,e,t,r){if(!zn(e,t,r))throw new RangeError("expected valid "+s+": "+t+" <= n < "+r+", got "+e)}function Qt(s){if(s<rr)throw new Error("expected non-negative bigint, got "+s);return s===rr?0:s.toString(2).length}var Ts=s=>(nt(s,"n"),(La<<BigInt(s))-La);function Fa(s,e,t){if(rt(s,"hashLen"),rt(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,c=r(s),u=r(s),p=0,m=()=>{c.fill(1),u.fill(0),p=0},E=(...w)=>t(u,Ue(c,...w)),y=(w=n)=>{u=E(i,w),c=E(),w.length!==0&&(u=E(o,w),c=E())},f=()=>{if(p++>=a)throw new Error("drbg: tried max amount of iterations");let w=0,S=[];for(;w<e;){c=E();let _=c.slice();S.push(_),w+=c.length}return Ue(...S)};return(w,S)=>{m(),y(w);let _;for(;(_=S(f()))===void 0;)y();return m(),_}}function ke(s,e={},t={},r="object"){mt(s,r),mt(e,"fields"),mt(t,"optFields");function n(o,a,c){let u=r==="object"?`param "${String(o)}"`:`"${r}.${String(o)}"`,p=s[o];if(!Object.hasOwn(s,o)&&(c?p!==void 0:a!=="function"))throw new TypeError(`${u} is invalid: expected own property`);if(c&&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(([c,u])=>n(c,u,a));i(e,!1),i(t,!0)}var he=BigInt(0),W=BigInt(1),yt=BigInt(2),Ka=BigInt(3),qn=BigInt(4),za=BigInt(5),yh=BigInt(7),qa=BigInt(8),wh=BigInt(9),xh=BigInt(15),Ga=BigInt(16),vh=BigInt("0x10000000000000000");function re(s,e){if(e<=he)throw new Error("mod: expected positive modulus, got "+e);let t=s%e;return t>=he?t:e+t}function Ha(s,e,t){if(t<=W)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<he)throw new Error("invalid exponent, negatives unsupported");if(e===he)return W;if(e===W)return s;let r=s%t;if(r<he&&(r+=t),e<vh){let a=W;for(;e>he;)e&W&&(a=a*r%t),r=r*r%t,e>>=W;return a}let n=[];for(;e>he;)n.push(Number(e&xh)),e>>=qn;let i=new Array(16);i[0]=W,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 c=n[a];c!==0&&(o=o*i[c]%t)}return o}function te(s,e,t){if(t<=W)throw new Error("pow2: expected modulus > 1, got "+t);if(e<he)throw new Error("pow2: expected non-negative exponent, got "+e);let r=s;for(;e-- >he;)r*=r,r%=t;return r}function Na(s,e){if(s===he)throw new Error("invert: expected non-zero number");if(e<=W)throw new Error("invert: expected modulus > 1, got "+e);let t=re(s,e),r=e,n=he,i=W;for(;t!==he;){let a=r/t,c=r-t*a,u=n-i*a;r=t,t=c,n=i,i=u}if(r!==W)throw new Error("invert: does not exist");return re(n,e)}function Wa(s,e){if(e<=W)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=re(s,e);if(t===he)throw new Error("invertCt: expected non-zero number");let r=Ha(t,e-yt,e);if(re(t*r,e)!==W)throw new Error("invertCt: does not exist");return r}function Gn(s,e,t){let r=s;if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function Hn(s,e){if((s&W)===he)throw new Error(e+": expected odd modulus, got "+s)}function Va(s,e){let t=s,r=(t.ORDER+W)/qn,n=t.pow(e,r);return Gn(t,n,e),n}function Eh(s,e){let t=s,r=(t.ORDER-za)/qa,n=t.mul(e,yt),i=t.pow(n,r),o=t.mul(e,i),a=t.mul(t.mul(o,yt),i),c=t.mul(o,t.sub(a,t.ONE));return Gn(t,c,e),c}function Sh(s){let e=ts(s),t=$a(s),r=t(e,e.neg(e.ONE)),n=t(e,r),i=t(e,e.neg(r)),o=(s+yh)/Ga;return((a,c)=>{let u=a,p=u.pow(c,o),m=u.mul(p,r),E=u.mul(p,n),y=u.mul(p,i),f=u.eql(u.sqr(m),c),g=u.eql(u.sqr(E),c);p=u.cmov(p,m,f),m=u.cmov(y,E,g);let w=u.eql(u.sqr(m),c),S=u.cmov(p,m,w);return Gn(u,S,c),S})}function $a(s){if(s<Ka)throw new Error("sqrt is not defined for small field");Hn(s,"tonelliShanks");let e=s-W,t=0;for(;e%yt===he;)e/=yt,t++;let r=yt,n=ts(s);for(;Ds(n,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Va;let i=n.pow(r,e),o=(e+W)/yt;return function(c,u){let p=c;if(p.is0(u))return u;if(Ds(p,u)!==1)throw new Error("Cannot find square root");let m=t,E=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 S=W<<BigInt(m-g-1),_=p.pow(E,S);m=g,E=p.sqr(_),y=p.mul(y,E),f=p.mul(f,_)}return f}}function _h(s){return Hn(s,"Fp.sqrt"),s%qn===Ka?Va:s%qa===za?Eh:s%Ga===wh?Sh(s):$a(s)}var ja=(s,e)=>(re(s,e)&W)===W,Ih=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function es(s){if(mt(s,"field"),typeof s.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof s.ORDER);nt(s.BYTES,"BYTES"),nt(s.BITS,"BITS");for(let e of Ih)Pt(s[e],"field."+e);if(s.BYTES<1||s.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(s.ORDER<=W)throw new Error("invalid field: expected ORDER > 1, got "+s.ORDER);return s}function cr(s,e,t=!1){es(s),nr(e,"nums"),Be(t,"passZero");let r=s,n=new Array(e.length).fill(t?r.ZERO:void 0),i=e.reduce((a,c,u)=>r.is0(c)?a:(n[u]=a,r.mul(a,c)),r.ONE),o=r.inv(i);return e.reduceRight((a,c,u)=>r.is0(c)?a:(n[u]=r.mul(a,n[u]),r.mul(a,c)),o),n}function Ds(s,e){es(s);let t=s;Hn(t.ORDER,"FpLegendre");let r=(t.ORDER-W)/yt,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 Th(s,e){if(e!==void 0&&Un(e),s<=he)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=Qt(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 Ua=new WeakMap,ar=class{ORDER;BITS;BYTES;isLE;ZERO=he;ONE=W;_lengths;_mod;constructor(e,t={}){if(e<=W)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}=Th(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 re(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return he<=e&&e<this.ORDER}is0(e){return e===he}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&W)===W}neg(e){return re(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return re(e*e,this.ORDER)}add(e,t){return re(e+t,this.ORDER)}sub(e,t){return re(e-t,this.ORDER)}mul(e,t){return re(e*t,this.ORDER)}pow(e,t){return Ha(e,t,this.ORDER)}div(e,t){return re(e*Na(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 Na(e,this.ORDER)}sqrt(e){let t=Ua.get(this);return t||Ua.set(this,t=_h(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Kn(e,this.BYTES):or(e,this.BYTES)}fromBytes(e,t=!1){H(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 c=i?kt(e):Ye(e);if(a&&(c=re(c,o)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return cr(this,e,!0)}cmov(e,t,r){return Be(r,"condition"),r?t:e}};function ts(s,e={}){return Object.freeze(ar.prototype),new ar(s,e)}function Za(s){if(typeof s!="bigint")throw new Error("field order must be bigint");if(s<=W)throw new Error("field order must be greater than 1");let e=Qt(s-W);return Math.ceil(e/8)}function lr(s){let e=Za(s);return e+Math.ceil(e/2)}function ur(s,e,t=!1){H(s);let r=s.length,n=Za(e),i=Math.max(lr(e),16);if(r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let o=t?kt(s):Ye(s),a=re(o,e-W)+W;return t?Kn(a,n):or(a,n)}var $n=BigInt(0),As=BigInt(1),Dh=BigInt(4),Wn=16,Ya=128,Ah=5,Xa=2**31;function wt(s){let e=s;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof s);Pt(e.fromAffine,"Point.fromAffine"),Pt(e.fromBytes,"Point.fromBytes"),Pt(e.fromHex,"Point.fromHex"),mt(e.BASE,"Point.BASE"),mt(e.ZERO,"Point.ZERO"),es(e.Fp),es(e.Fn)}function hr(s,e){wt(s),Qa(e,s);let t=cr(s.Fp,e.map(r=>r.Z));return e.map((r,n)=>s.fromAffine(r.toAffine(t[n])))}function Mh(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 Ph(s,e){let t=s*(4*e+128);if(t>Xa)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+Xa/2**20+" MiB")}function jn(s,e){if(s!==void 0){Pt(s,"randomBytes");try{let t=s(e);if(!bt(t)||t.length!==e)return}catch{return}return s}}function Qa(s,e){nr(s,"points"),s.forEach((t,r)=>{if(!(t instanceof e))throw new Error("invalid point at index "+r)})}function Bh(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):gt(r)&&r<t))throw new Error("invalid scalar at index "+n)})}var ec=new WeakMap;function Vn(s){return ec.get(s)||1}function kh(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 Rh(s,e){let t=2**e,r=t/2,n=BigInt(t-1),i=[];for(;s>$n;){let o=0;s&As&&(o=Number(s&n),o>=r&&(o-=t),s-=BigInt(o)),i.push(o),s>>=As}return i}function Lh(s,e,t){let r=2**e,n=r/2,i=BigInt(r-1),o=BigInt(e),a=[];for(let c=0;c<t;c++){let u=Number(s&i);s>>=o,u>n&&(u-=r,s+=As),a.push(u)}if(s!==$n)throw new Error("invalid wnaf");return a}function Ch(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 c=e[o][Math.abs(a)-1>>1];n=n.add(a<0?c.negate():c)}}}return n}var ss=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){wt(e),this.randomBytes=jn(t,Wn),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 c=0;c<n;c++){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=Lh(t,r,n),c=this.ZERO,u=this.BASE;for(let p=0;p<n;p++){let m=a[p],E=p*o,y=Math.abs(m)-1,f=i[E];for(let w=1;w<o;w++)f=w===y?i[E+w]:f;let g=f.negate();m===0?u=u.add(i[E]):c=c.add(m<0?g:f)}return{p:c,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),!zn(t,As,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,r,n){let i=Vn(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+Ya,i=this.randomBytes(Wn);if(!bt(i)||i.length!==Wn)throw new Error("randomBytes returned invalid byte array");i[0]=i[0]&63|128;let o=t+Ye(i)*this.Point.Fn.ORDER;return this.runCT(e,o,n,r)}fixedWindowCT(e,t,r){let n=Ah,i=1<<n,o=Ts(n),a=new Array(i);a[0]=this.ZERO;for(let p=1;p<i;p++)a[p]=a[p-1].add(e);let c=Math.ceil(r/n),u=this.ZERO;for(let p=c-1;p>=0;p--){if(p!==c-1)for(let y=0;y<n;y++)u=u.double();let m=Number(t>>BigInt(p*n)&o),E=a[0];for(let y=1;y<i;y++)E=y===m?a[y]:E;u=u.add(E)}return{p:u,f:u}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===As?!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),!gt(t))throw new Error("invalid scalar");let n=Vn(e);if(n===1||t>=this.Point.Fn.ORDER)return fr(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),Mh(t,this.bits);let r=Math.ceil((this.bits+Ya)/t)+1;Ph(r*2**(t-1),this.Point.Fp.BYTES),ec.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Vn(e)!==1}};function fr(s,e,t,r=!1){if(wt(s),Qa(e,s),Be(r,"allowOversized"),Bh(t,s.Fn,r?s.Fn.ORDER**Dh:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let n=e.map(o=>kh(o,4)),i=t.map(o=>Rh(o,4));return Ch(s.ZERO,n,i)}function Ja(s,e,t){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return es(e),e}else return ts(s,{isLE:t})}function dr(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`);ke(t);for(let c of["p","n","h"]){let u=e[c];if(!(gt(u)&&u!==$n))throw new Error(`CURVE.${c} must be positive bigint`)}let n=Ja(e.p,t.Fp,r),i=Ja(e.n,t.Fn,r),a=["Gx","Gy","a",s==="weierstrass"?"b":"d"];for(let c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function pr(s,e){return function(r){let n=s(r);return{secretKey:n,publicKey:e(n)}}}var mr=BigInt(0),gr=BigInt(1),br=BigInt(2),Oh=BigInt(4),tc=BigInt(8);function Fh(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 sc(s,e={}){ke(e,{},{},"extraOpts");let t=e,r=dr("edwards",s,t,t.FpFnLE),{Fp:n,Fn:i}=r,o=r.CURVE,{h:a}=o;if(Ds(n,o.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Ds(n,o.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");ke(t,{},{uvRatio:"function",randomBytes:"function"});let c=t.randomBytes===void 0?Bt:t.randomBytes,u=br<<BigInt(n.BYTES*8)-gr;function p(_){if(!n.isOdd)throw new Error("Field does not have .isOdd()");return n.isOdd(_)}let m=t.uvRatio===void 0?(_,l)=>{try{return{isValid:!0,value:n.sqrt(n.div(_,l))}}catch{return{isValid:!1,value:mr}}}:t.uvRatio;if(!Fh(n,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");let E=n.eql(o.a,n.neg(n.ONE))?_=>n.neg(_):n.eql(o.a,n.ONE)?_=>_:_=>n.mul(o.a,_);function y(_,l,h=!1){let d=h?gr:mr;return Jt("coordinate "+_,l,d,u),l}function f(_){if(!(_ 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(l,h,d,b){this.X=y("x",l),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(l){if(l instanceof g)throw new Error("extended point not allowed");let{x:h,y:d}=l||{};return y("x",h),y("y",d),new g(h,d,n.ONE,n.mul(h,d))}static fromBytes(l,h=!1){let d=n.BYTES,{a:b,d:v}=o;l=Is(H(l,d,"point")),Be(h,"zip215");let I=Is(l),D=l[d-1];I[d-1]=D&-129;let M=kt(I),U=h?u:n.ORDER;Jt("point.y",M,mr,U);let z=n.sqr(M),Z=n.sub(z,n.ONE),k=n.sub(n.mulN(v,z),b),{isValid:N,value:K}=m(Z,k);if(!N)throw new Error("bad point: invalid y coordinate");let C=p(K),J=(D&128)!==0;if(!h&&n.is0(K)&&J)throw new Error("bad point: x=0 and x_0=1");return J!==C&&(K=n.neg(K)),g.fromAffine({x:K,y:M})}static fromHex(l,h=!1){return g.fromBytes(Xt(l),h)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(l=6,h=!0){return S.setWindowSize(this,l),h||this.multiply(br),this}assertValidity(){let l=this,{a:h,d}=o;if(l.is0())throw new Error("bad point: ZERO");let{X:b,Y:v,Z:I,T:D}=l,M=n.sqr(b),U=n.sqr(v),z=n.sqr(I),Z=n.sqr(z),k=n.mul(M,h),N=n.mul(n.add(k,U),z),K=n.add(Z,n.mul(d,n.mul(M,U)));if(!n.eql(N,K))throw new Error("bad point: equation left != right (1)");let C=n.mul(b,v),J=n.mul(I,D);if(!n.eql(C,J))throw new Error("bad point: equation left != right (2)")}equals(l){f(l);let{X:h,Y:d,Z:b}=this,{X:v,Y:I,Z:D}=l,M=n.mul(h,D),U=n.mul(v,b),z=n.mul(d,D),Z=n.mul(I,b);return n.eql(M,U)&&n.eql(z,Z)}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:l,Y:h,Z:d}=this,b=n.sqr(l),v=n.sqr(h),I=n.mul(n.sqr(d),br),D=E(b),M=n.addN(l,h),U=n.sub(n.subN(n.sqr(M),b),v),z=n.addN(D,v),Z=n.subN(z,I),k=n.subN(D,v),N=n.mul(U,Z),K=n.mul(z,k),C=n.mul(U,k),J=n.mul(Z,z);return new g(N,K,J,C)}add(l){f(l);let{d:h}=o,{X:d,Y:b,Z:v,T:I}=this,{X:D,Y:M,Z:U,T:z}=l,Z=n.mul(d,D),k=n.mul(b,M),N=n.mul(n.mulN(I,h),z),K=n.mul(v,U),C=n.sub(n.subN(n.mulN(n.addN(d,b),n.addN(D,M)),Z),k),J=n.subN(K,N),se=n.addN(K,N),P=n.sub(k,E(Z)),x=n.mul(C,J),T=n.mul(se,P),A=n.mul(C,P),B=n.mul(J,se);return new g(x,T,B,A)}subtract(l){return f(l),this.add(l.negate())}multiply(l){if(!i.isValidNot0(l))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:h,f:d}=S.mulSecret(this,l,a,w);return w([h,d])[0]}multiplyUnsafe(l){if(!i.isValid(l))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return l===mr?g.ZERO:this.is0()||l===gr?this:S.mulUnsafe(this,l,w)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return S.mulUnsafe(this,o.n).is0()}toAffine(l){let h=this,d=l;if(d!=null&&typeof d!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof d);let{X:b,Y:v,Z:I}=h,D=h.is0();d==null&&(d=D?n.create(tc):n.inv(I));let M=n.mul(b,d),U=n.mul(v,d),z=n.mul(I,d);if(D)return{x:n.ZERO,y:n.ONE};if(!n.eql(z,n.ONE))throw new Error("invZ was invalid");return{x:M,y:U}}clearCofactor(){return a===gr?this:a===br?this.double():a===Oh?this.double().double():a===tc?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:l,y:h}=this.toAffine(),d=n.toBytes(h);return d[d.length-1]|=p(l)?128:0,d}toHex(){return Ss(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let w=_=>hr(g,_),S=new ss(g,c);return S.bits>=6&&g.BASE.precompute(6),Object.freeze(g.prototype),Object.freeze(g),g}function rc(s,e,t={}){if(wt(s),typeof e!="function")throw new Error('"hash" function param is required');let r=e,n=t;ke(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:c}=s,u=r.outputLen,p=2*a.BYTES;if(u!==void 0&&(nt(u,"hash.outputLen"),u!==p))throw new Error(`hash.outputLen must be ${p}, got ${u}`);let m=n.randomBytes===void 0?Bt:n.randomBytes,E=n.toMontgomery,y=n.toMontgomerySecret,f=n.adjustScalarBytes===void 0?k=>k:n.adjustScalarBytes,g=n.domain===void 0?(k,N,K)=>{if(Be(K,"phflag"),N.length||K)throw new Error("Contexts/pre-hash are not supported");return k}:n.domain;function w(k){return c.create(kt(k))}function S(k){let N=D.secretKey;H(k,D.secretKey,"secretKey");let K=H(r(k),2*N,"hashedSecretKey"),C=f(K.slice(0,N)),J=K.slice(N,2*N),se=w(C);return{head:C,prefix:J,scalar:se}}function _(k){let{head:N,prefix:K,scalar:C}=S(k),J=o.multiply(C),se=J.toBytes();return{head:N,prefix:K,scalar:C,point:J,pointBytes:se}}function l(k){return _(k).pointBytes}function h(k=Uint8Array.of(),...N){let K=Ue(...N);return w(r(g(K,H(k,void 0,"context"),!!i)))}function d(k,N,K={}){ke(K,{},{},"options"),k=Is(H(k,void 0,"message")),i&&(k=i(k));let{prefix:C,scalar:J,pointBytes:se}=_(N),P=h(K.context,C,k),x=o.multiply(P).toBytes(),T=h(K.context,x,se,k),A=c.create(P+T*J);if(!c.isValid(A))throw new Error("sign failed: invalid s");let B=Ue(x,c.toBytes(A));return H(B,D.signature,"result")}let b={zip215:n.zip215};function v(k,N,K,C=b){ke(C);let{context:J}=C,se=C.zip215===void 0?!!b.zip215:C.zip215,P=D.signature;k=H(k,P,"signature"),N=H(N,void 0,"message"),K=H(K,D.publicKey,"publicKey"),se!==void 0&&Be(se,"zip215"),i&&(N=i(N));let x=P/2,T=k.subarray(0,x),A=kt(k.subarray(x,P)),B,R,L;try{B=s.fromBytes(K,se),R=s.fromBytes(T,se),L=o.multiplyUnsafe(A)}catch{return!1}if(!se&&B.isSmallOrder())return!1;let O=h(J,T,K,N);return R.add(B.multiplyUnsafe(O)).subtract(L).clearCofactor().is0()}let I=a.BYTES,D={secretKey:I,publicKey:I,signature:2*I,seed:I};function M(k){return k=k===void 0?m(D.seed):k,H(k,D.seed,"seed")}function U(k){return bt(k)&&k.length===D.secretKey}function z(k,N){try{return!!s.fromBytes(k,N===void 0?b.zip215:N)}catch{return!1}}let Z={getExtendedPublicKey:_,randomSecretKey:M,isValidSecretKey:U,isValidPublicKey:z,toMontgomery(k){if(E===void 0)throw new Error("Montgomery conversion is not supported for this curve");return E(s.fromBytes(k))},toMontgomerySecret(k){if(y===void 0)throw new Error("Montgomery conversion is not supported for this curve");return y(k)}};return Object.freeze(D),Object.freeze(Z),Object.freeze({keygen:pr(M,l),getPublicKey:l,sign:d,verify:v,utils:Z,Point:s,lengths:D})}var Zn=BigInt(1),nc=BigInt(2);var Nh=BigInt(5),Uh=BigInt(8),Yn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Kh={p:Yn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Uh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function zh(s){let e=BigInt(10),t=BigInt(20),r=BigInt(40),n=BigInt(80),i=Yn,a=s*s%i*s%i,c=te(a,nc,i)*a%i,u=te(c,Zn,i)*s%i,p=te(u,Nh,i)*u%i,m=te(p,e,i)*p%i,E=te(m,t,i)*m%i,y=te(E,r,i)*E%i,f=te(y,n,i)*y%i,g=te(f,n,i)*y%i,w=te(g,e,i)*p%i;return{pow_p_5_8:te(w,nc,i)*s%i,b2:a}}function ac(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}var ic=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function qh(s,e){let t=Yn,r=re(e*e*e,t),n=re(r*r*e,t),i=zh(s*n).pow_p_5_8,o=re(s*r*i,t),a=re(e*o*o,t),c=o,u=re(o*ic,t),p=a===s,m=a===re(-s,t),E=a===re(-s*ic,t);return p&&(o=c),(m||E)&&(o=u),ja(o,t)&&(o=re(-o,t)),{isValid:p||m,value:o}}var Xn=sc(Kh,{uvRatio:qh}),oc=Xn.Fp;function Gh(s){let{y:e}=s;return oc.toBytes(oc.div(Zn+e,Zn-e))}function Hh(s){let e=Xn.Fp.BYTES;return Ne(s,e),ac(Nn(s.subarray(0,e))).subarray(0,e)}function Wh(s){return rc(Xn,Nn,Object.assign({adjustScalarBytes:ac,toMontgomery:Gh,toMontgomerySecret:Hh,zip215:!0},s))}var cc=Wh({});var Ms=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},yr=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ke={get(s=globalThis){let e=s.crypto;if(e?.subtle==null)throw new yr("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 wr=32;var Jn,Vh=(async()=>{try{return await Ke.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function $h(s,e,t){if(s.buffer instanceof ArrayBuffer){let r=await Ke.get().subtle.importKey("raw",s.buffer,{name:"Ed25519"},!1,["verify"]);return await Ke.get().subtle.verify({name:"Ed25519"},r,Fe(e),Fe(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function jh(s,e,t){return cc.verify(e,t instanceof Uint8Array?t:t.subarray(),s)}async function lc(s,e,t){return Jn==null&&(Jn=await Vh),Jn?$h(s,e,t):jh(s,e,t)}function xr(s){return s==null?!1:typeof s.then=="function"&&typeof s.catch=="function"&&typeof s.finally=="function"}var vr=class{type="Ed25519";raw;constructor(e){this.raw=Qn(e,wr)}toMultihash(){return qe.digest(je(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Me(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();let n=lc(this.raw,t,e);return xr(n)?n.then(i=>(r?.signal?.throwIfAborted(),i)):n}};function ei(s){return s=Qn(s,wr),new vr(s)}function Qn(s,e){if(s=Uint8Array.from(s??[]),s.length!==e)throw new oe(`Key must be a Uint8Array of length ${e}, got ${s.length}`);return s}var Yh=Math.pow(2,7),Xh=Math.pow(2,14),Jh=Math.pow(2,21),ti=Math.pow(2,28),si=Math.pow(2,35),ri=Math.pow(2,42),ni=Math.pow(2,49),V=128,be=127;function ze(s){if(s<Yh)return 1;if(s<Xh)return 2;if(s<Jh)return 3;if(s<ti)return 4;if(s<si)return 5;if(s<ri)return 6;if(s<ni)return 7;if(Number.MAX_SAFE_INTEGER!=null&&s>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ii(s,e,t=0){switch(ze(s)){case 8:e[t++]=s&255|V,s/=128;case 7:e[t++]=s&255|V,s/=128;case 6:e[t++]=s&255|V,s/=128;case 5:e[t++]=s&255|V,s/=128;case 4:e[t++]=s&255|V,s>>>=7;case 3:e[t++]=s&255|V,s>>>=7;case 2:e[t++]=s&255|V,s>>>=7;case 1:{e[t++]=s&255,s>>>=7;break}default:throw new Error("unreachable")}return e}function Qh(s,e,t=0){switch(ze(s)){case 8:e.set(t++,s&255|V),s/=128;case 7:e.set(t++,s&255|V),s/=128;case 6:e.set(t++,s&255|V),s/=128;case 5:e.set(t++,s&255|V),s/=128;case 4:e.set(t++,s&255|V),s>>>=7;case 3:e.set(t++,s&255|V),s>>>=7;case 2:e.set(t++,s&255|V),s>>>=7;case 1:{e.set(t++,s&255),s>>>=7;break}default:throw new Error("unreachable")}return e}function oi(s,e){let t=s[e],r=0;if(r+=t&be,t<V||(t=s[e+1],r+=(t&be)<<7,t<V)||(t=s[e+2],r+=(t&be)<<14,t<V)||(t=s[e+3],r+=(t&be)<<21,t<V)||(t=s[e+4],r+=(t&be)*ti,t<V)||(t=s[e+5],r+=(t&be)*si,t<V)||(t=s[e+6],r+=(t&be)*ri,t<V)||(t=s[e+7],r+=(t&be)*ni,t<V))return r;throw new RangeError("Could not decode varint")}function ef(s,e){let t=s.get(e),r=0;if(r+=t&be,t<V||(t=s.get(e+1),r+=(t&be)<<7,t<V)||(t=s.get(e+2),r+=(t&be)<<14,t<V)||(t=s.get(e+3),r+=(t&be)<<21,t<V)||(t=s.get(e+4),r+=(t&be)*ti,t<V)||(t=s.get(e+5),r+=(t&be)*si,t<V)||(t=s.get(e+6),r+=(t&be)*ri,t<V)||(t=s.get(e+7),r+=(t&be)*ni,t<V))return r;throw new RangeError("Could not decode varint")}function ai(s,e,t=0){return e==null&&(e=ge(ze(s))),e instanceof Uint8Array?ii(s,e,t):Qh(s,e,t)}function ci(s,e=0){return s instanceof Uint8Array?oi(s,e):ef(s,e)}var ui=new Float32Array([-0]),xt=new Uint8Array(ui.buffer);function hc(s,e,t){ui[0]=s,e[t]=xt[0],e[t+1]=xt[1],e[t+2]=xt[2],e[t+3]=xt[3]}function fc(s,e){return xt[0]=s[e],xt[1]=s[e+1],xt[2]=s[e+2],xt[3]=s[e+3],ui[0]}var hi=new Float64Array([-0]),ye=new Uint8Array(hi.buffer);function dc(s,e,t){hi[0]=s,e[t]=ye[0],e[t+1]=ye[1],e[t+2]=ye[2],e[t+3]=ye[3],e[t+4]=ye[4],e[t+5]=ye[5],e[t+6]=ye[6],e[t+7]=ye[7]}function pc(s,e){return ye[0]=s[e],ye[1]=s[e+1],ye[2]=s[e+2],ye[3]=s[e+3],ye[4]=s[e+4],ye[5]=s[e+5],ye[6]=s[e+6],ye[7]=s[e+7],hi[0]}var tf=BigInt(Number.MAX_SAFE_INTEGER),sf=BigInt(Number.MIN_SAFE_INTEGER),Re=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 Rt;if(e<tf&&e>sf)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>mc&&(n=0n,++r>mc&&(r=0n))),new s(Number(n),Number(r))}static fromNumber(e){if(e===0)return Rt;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):Rt}},Rt=new Re(0,0);Rt.toBigInt=function(){return 0n};Rt.zzEncode=Rt.zzDecode=function(){return this};Rt.length=function(){return 1};var mc=4294967296n;function gc(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 bc(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 fi(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 He(s,e){return RangeError(`index out of range: ${s.pos} + ${e??1} > ${s.len}`)}function Er(s,e){return(s[e-4]|s[e-3]<<8|s[e-2]<<16|s[e-1]<<24)>>>0}var di=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Fe(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,He(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 He(this,4);return Er(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw He(this,4);return Er(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw He(this,4);let e=fc(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw He(this,4);let e=pc(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 He(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){let e=this.bytes();return bc(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw He(this,e);this.pos+=e}else do if(this.pos>=this.len)throw He(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 Re(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 He(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 He(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 He(this,8);let e=Er(this.buf,this.pos+=4),t=Er(this.buf,this.pos+=4);return new Re(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=oi(this.buf,this.pos);return this.pos+=ze(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 Ps(s){return new di(s instanceof Uint8Array?s:s.subarray())}function Ee(s,e,t){let r=Ps(s);return e.decode(r,void 0,t)}function pi(s){let e=s??8192,t=e>>>1,r,n=e;return function(o){if(o<1||o>t)return ge(o);n+o>e&&(r=ge(e),n=0);let a=r.subarray(n,n+=o);return(n&7)!==0&&(n=(n|7)+1),a}}var Lt=class{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}};function mi(){}var bi=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},rf=pi();function nf(s){return globalThis.Buffer!=null?ge(s):rf(s)}var ks=class{len;head;tail;states;constructor(){this.len=0,this.head=new Lt(mi,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new Lt(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new yi((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(Sr,10,Re.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Re.fromBigInt(e);return this._push(Sr,t.length(),t)}uint64Number(e){return this._push(ii,ze(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=Re.fromBigInt(e).zzEncode();return this._push(Sr,t.length(),t)}sint64Number(e){let t=Re.fromNumber(e).zzEncode();return this._push(Sr,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(gi,1,e?1:0)}fixed32(e){return this._push(Bs,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Re.fromBigInt(e);return this._push(Bs,4,t.lo)._push(Bs,4,t.hi)}fixed64Number(e){let t=Re.fromNumber(e);return this._push(Bs,4,t.lo)._push(Bs,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(hc,4,e)}double(e){return this._push(dc,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(gi,1,0):this.uint32(t)._push(af,t,e)}string(e){let t=gc(e);return t!==0?this.uint32(t)._push(fi,t,e):this._push(gi,1,0)}fork(){return this.states=new bi(this),this.head=this.tail=new Lt(mi,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Lt(mi,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=nf(this.len),r=0;for(;e!=null;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}};function gi(s,e,t){e[t]=s&255}function of(s,e,t){for(;s>127;)e[t++]=s&127|128,s>>>=7;e[t]=s}var yi=class extends Lt{next;constructor(e,t){super(of,e,t),this.next=void 0}};function Sr(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 Bs(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 af(s,e,t){e.set(s,t)}globalThis.Buffer!=null&&(ks.prototype.bytes=function(s){let e=s.length>>>0;return this.uint32(e),e>0&&this._push(cf,e,s),this},ks.prototype.string=function(s){let e=globalThis.Buffer.byteLength(s);return this.uint32(e),e>0&&this._push(lf,e,s),this});function cf(s,e,t){e.set(s,t)}function lf(s,e,t){s.length<40?fi(s,e,t):e.utf8Write!=null?e.utf8Write(s,t):e.set(Y(s),t)}function wi(){return new ks}function Se(s,e){let t=wi();return e.encode(s,t,{lengthDelimited:!1}),t.finish()}function*_e(s,e,t){let r=Ps(s);yield*e.stream(r,void 0,".",t)}var _r={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Ir(s,e,t,r,n){return{name:s,type:e,encode:t,decode:r,stream:n}}function xi(s){function e(i){if(s[i.toString()]==null)throw new Error("Invalid enum value");return s[i]}let t=function(o,a){let c=e(o);a.int32(c)},r=function(o){let a=o.int32();return e(a)},n=function*(o,a){};return Ir("enum",_r.VARINT,t,r,n)}function Ie(s,e,t){return Ir("message",_r.LENGTH_DELIMITED,s,e,t)}var X=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var ne;(function(s){s.RSA="RSA",s.Ed25519="Ed25519",s.secp256k1="secp256k1",s.ECDSA="ECDSA"})(ne||(ne={}));var vi;(function(s){s[s.RSA=0]="RSA",s[s.Ed25519=1]="Ed25519",s[s.secp256k1=2]="secp256k1",s[s.ECDSA=3]="ECDSA"})(vi||(vi={}));(function(s){s.codec=()=>xi(vi)})(ne||(ne={}));var Xe;(function(s){let e;s.codec=()=>(e==null&&(e=Ie((i,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),i.Type!=null&&(o.uint32(8),ne.codec().encode(i.Type,o)),i.Data!=null&&(o.uint32(18),o.bytes(i.Data)),a.lengthDelimited!==!1&&o.ldelim()},(i,o,a={})=>{let c={},u=o==null?i.len:i.pos+o;for(;i.pos<u;){let p=i.uint32();switch(p>>>3){case 1:{c.Type=ne.codec().decode(i);break}case 2:{c.Data=i.bytes();break}default:{i.skipType(p&7);break}}}return c},function*(i,o,a,c={}){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:ne.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 Se(i,s.codec())}s.encode=t;function r(i,o){return Ee(i,s.codec(),o)}s.decode=r;function n(i,o){return _e(i,s.codec(),o)}s.stream=n})(Xe||(Xe={}));var Ei;(function(s){let e;s.codec=()=>(e==null&&(e=Ie((i,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),i.Type!=null&&(o.uint32(8),ne.codec().encode(i.Type,o)),i.Data!=null&&(o.uint32(18),o.bytes(i.Data)),a.lengthDelimited!==!1&&o.ldelim()},(i,o,a={})=>{let c={},u=o==null?i.len:i.pos+o;for(;i.pos<u;){let p=i.uint32();switch(p>>>3){case 1:{c.Type=ne.codec().decode(i);break}case 2:{c.Data=i.bytes();break}default:{i.skipType(p&7);break}}}return c},function*(i,o,a,c={}){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:ne.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 Se(i,s.codec())}s.encode=t;function r(i,o){return Ee(i,s.codec(),o)}s.decode=r;function n(i,o){return _e(i,s.codec(),o)}s.stream=n})(Ei||(Ei={}));var Ls={};Ae(Ls,{MAX_RSA_KEY_SIZE:()=>Si,generateRSAKeyPair:()=>Sc,jwkToJWKKeyPair:()=>_c,jwkToPkcs1:()=>df,jwkToPkix:()=>Di,jwkToRSAPrivateKey:()=>Bi,pkcs1MessageToJwk:()=>Ii,pkcs1MessageToRSAPrivateKey:()=>Ai,pkcs1ToJwk:()=>ff,pkcs1ToRSAPrivateKey:()=>Ec,pkixMessageToJwk:()=>Ti,pkixMessageToRSAPublicKey:()=>Pi,pkixToJwk:()=>pf,pkixToRSAPublicKey:()=>Mi});var rs=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Ls.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return pe.createV1(114,this._multihash)}toString(){return ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Me(this.raw,e.raw)}verify(e,t,r){return vc(this.jwk,t,e,r)}},Rs=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Ls.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Me(this.raw,e.raw)}sign(e,t){return xc(this.jwk,e,t)}};var Si=8192,_i=18,uf=1062,hf=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function ff(s){let e=st(s);return Ii(e)}function Ii(s){return{n:j(s[1],"base64url"),e:j(s[2],"base64url"),d:j(s[3],"base64url"),p:j(s[4],"base64url"),q:j(s[5],"base64url"),dp:j(s[6],"base64url"),dq:j(s[7],"base64url"),qi:j(s[8],"base64url"),kty:"RSA"}}function df(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 oe("JWK was missing components");return ht([Pe(Uint8Array.from([0])),Pe(Y(s.n,"base64url")),Pe(Y(s.e,"base64url")),Pe(Y(s.d,"base64url")),Pe(Y(s.p,"base64url")),Pe(Y(s.q,"base64url")),Pe(Y(s.dp,"base64url")),Pe(Y(s.dq,"base64url")),Pe(Y(s.qi,"base64url"))]).subarray()}function pf(s){let e=st(s,{offset:0});return Ti(e)}function Ti(s){let e=st(s[1],{offset:0});return{kty:"RSA",n:j(e[0],"base64url"),e:j(e[1],"base64url")}}function Di(s){if(s.n==null||s.e==null)throw new oe("JWK was missing components");return ht([hf,Zs(ht([Pe(Y(s.n,"base64url")),Pe(Y(s.e,"base64url"))]))]).subarray()}function Ec(s){let e=st(s);return Ai(e)}function Ai(s){let e=Ii(s);return Bi(e)}function Mi(s,e){if(s.byteLength>=uf)throw new zt("Key size is too large");let t=st(s,{offset:0});return Pi(t,s,e)}function Pi(s,e,t){let r=Ti(s);if(t==null){let n=Yt(Xe.encode({Type:ne.RSA,Data:e}));t=$e(_i,n)}return new rs(r,t)}function Bi(s){if(Tc(s)>Si)throw new oe("Key size is too large");let e=_c(s),t=Yt(Xe.encode({Type:ne.RSA,Data:Di(e.publicKey)})),r=$e(_i,t);return new Rs(e.privateKey,new rs(e.publicKey,r))}async function Sc(s){if(s>Si)throw new oe("Key size is too large");let e=await Ic(s),t=Yt(Xe.encode({Type:ne.RSA,Data:Di(e.publicKey)})),r=$e(_i,t);return new Rs(e.privateKey,new rs(e.publicKey,r))}function _c(s){if(s==null)throw new oe("Missing key parameter");return{privateKey:s,publicKey:{kty:s.kty,n:s.n,e:s.e}}}async function Ic(s,e){let t=await Ke.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 mf(t,e);return{privateKey:r[0],publicKey:r[1]}}async function xc(s,e,t){let r=await Ke.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let n=await Ke.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,Fe(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(n,0,n.byteLength)}async function vc(s,e,t,r){let n=await Ke.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();let i=await Ke.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,Fe(e),Fe(t instanceof Uint8Array?t:t.subarray()));return r?.signal?.throwIfAborted(),i}async function mf(s,e){if(s.privateKey==null||s.publicKey==null)throw new oe("Private and public key are required");let t=await Promise.all([Ke.get().subtle.exportKey("jwk",s.privateKey),Ke.get().subtle.exportKey("jwk",s.publicKey)]);return e?.signal?.throwIfAborted(),t}function Tc(s){if(s.kty!=="RSA")throw new oe("invalid key type");if(s.n==null)throw new oe("invalid key modulus");return Y(s.n,"base64url").length*8}var Tr=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Js(e),Ne(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),Mt(n)}update(e){return Zt(this),this.iHash.update(e),this}digestInto(e){Zt(this),Qs(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:c}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.canXOF=c,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()}},Dc=(()=>{let s=((e,t,r)=>new Tr(e,t).update(r).digest());return s.create=(e,t)=>new Tr(e,t),s})();var gf=BigInt(0),ki=class extends Error{constructor(e=""){super(e)}},it={Err:ki,_tlv:{encode:(s,e)=>{let{Err:t}=it;if(nt(s,"tag"),s<0||s>255)throw new t("tlv.encode: wrong tag");if(Ca(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let r=e.length/2,n=_s(r);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let i=r>127?_s(n.length/2|128):"";return _s(s)+i+n+e},decode(s,e){let{Err:t}=it;e=H(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 c=n&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(r,r+c);if(u.length!==c)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+=c,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}=it;if(ir(s),s<gf)throw new e("integer: negative integers are not allowed");let t=_s(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}=it;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 Ye(s)}},toSig(s,e){let{Err:t,_int:r,_tlv:n}=it;if(e!==void 0&&(nt(e,"maxScalarBytes"),e<1))throw new t("invalid signature: maxScalarBytes must be positive");let i=H(s,void 0,"signature"),{v:o,l:a}=n.decode(48,i);if(a.length)throw new t("invalid signature: left bytes after parsing");let{v:c,l:u}=n.decode(2,o),{v:p,l:m}=n.decode(2,u);if(m.length)throw new t("invalid signature: left bytes after parsing");if(e!==void 0&&(c.length>e||p.length>e))throw new t("invalid signature: integer too large");return{r:r.decode(c),s:r.decode(p)}},hexFromSig(s){let{_tlv:e,_int:t}=it;ke(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)}},Dr=(Object.freeze(it._tlv),Object.freeze(it._int),Object.freeze(it));var Ac=(s,e)=>(s+(s>=0?e:-e)/Mc)/e;function bf(s,e,t){Jt("scalar",s,ot,t);let[[r,n],[i,o]]=e,a=Ac(o*s,t),c=Ac(-n*s,t),u=s-a*r-c*i,p=-a*n-c*o,m=u<ot,E=p<ot;m&&(u=-u),E&&(p=-p);let y=Ts(Math.ceil(Qt(t)/2))+Ct;if(u<ot||u>=y||p<ot||p>=y)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:m,k1:u,k2neg:E,k2:p}}function Ci(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function Ri(s,e){ke(s);let t={};for(let r of Object.keys(e))t[r]=s[r]===void 0?e[r]:s[r];return Be(t.lowS,"lowS"),Be(t.prehash,"prehash"),t.format!==void 0&&Ci(t.format),t}var ot=BigInt(0),Ct=BigInt(1),Mc=BigInt(2),Li=BigInt(3),yf=BigInt(4);function Pc(s,e={}){let t=dr("weierstrass",s,e),r=t.Fp,n=t.Fn,i=t.CURVE,{h:o,n:a}=i;ke(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:u,clearCofactor:p,isTorsionFree:m,fromBytes:E,toBytes:y}=e,f=e.randomBytes===void 0?Bt:e.randomBytes;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let g=c?{beta:c.beta,basises:c.basises.map(P=>[...P])}:void 0,w=kc(r,n);function S(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function _(P,x,T){if(x.is0()){if(!u)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:A,y:B}=x.toAffine(),R=r.toBytes(A);if(Be(T,"isCompressed"),T){S();let L=!r.isOdd(B);return Ue(Bc(L),R)}else return Ue(Uint8Array.of(4),R,r.toBytes(B))}function l(P){H(P,void 0,"Point");let{publicKey:x,publicKeyUncompressed:T}=w,A=P.length,B=P[0],R=P.subarray(1);if(u&&A===1&&B===0)return{x:r.ZERO,y:r.ZERO};if(A===x&&(B===2||B===3)){let L=r.fromBytes(R);if(!r.isValid(L))throw new Error("bad point: is not on curve, wrong x");let O=I(L),F;try{F=r.sqrt(O)}catch(le){let Q=le instanceof Error?": "+le.message:"";throw new Error("bad point: is not on curve, sqrt error"+Q)}S();let G=r.isOdd(F);return(B&1)===1!==G&&(F=r.neg(F)),{x:L,y:F}}else if(A===T&&B===4){let L=r.BYTES,O=r.fromBytes(R.subarray(0,L)),F=r.fromBytes(R.subarray(L,L*2));if(!D(O,F))throw new Error("bad point: is not on curve");return{x:O,y:F}}else throw new Error(`bad point: got length ${A}, expected compressed=${x} or uncompressed=${T}`)}let h=y===void 0?_:y,d=E===void 0?l:E,b=r.mul(i.b,Li),v=r.is0(i.a)?P=>r.ZERO:P=>r.mul(i.a,P);function I(P){let x=r.sqr(P),T=r.mul(x,P);return r.add(r.add(T,r.mul(P,i.a)),i.b)}function D(P,x){let T=r.sqr(x),A=I(P);return r.eql(T,A)}if(!D(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let M=r.mul(r.pow(i.a,Li),yf),U=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(M,U)))throw new Error("bad curve params: a or b");function z(P,x,T=!1){if(!r.isValid(x)||T&&r.is0(x))throw new Error(`bad point coordinate ${P}`);return typeof x=="object"&&x!==null?r.create(x):x}function Z(P){if(!(P instanceof C))throw new Error("Weierstrass Point expected")}function k(P){if(!g||!g.basises)throw new Error("no endo");return bf(P,g.basises,n.ORDER)}function N(P,x,T,A){if(!n.isValid(A))throw new RangeError("invalid scalar: out of range");if(g){let{k1neg:B,k1:R,k2neg:L,k2:O}=k(A),F=new C(r.mul(T.X,g.beta),T.Y,T.Z);P.push(B?T.negate():T,L?F.negate():F),x.push(R,O)}else P.push(T),x.push(A)}let K=new WeakSet;class C{static BASE=new C(i.Gx,i.Gy,r.ONE);static ZERO=new C(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=n;X;Y;Z;constructor(x,T,A){this.X=z("x",x),this.Y=z("y",T,!0),this.Z=z("z",A),Object.freeze(this)}static CURVE(){return i}static fromAffine(x){let{x:T,y:A}=x||{};if(!x||!r.isValid(T)||!r.isValid(A))throw new Error("invalid affine point");if(x instanceof C)throw new Error("projective point not allowed");return r.is0(T)&&r.is0(A)?C.ZERO:new C(T,A,r.ONE)}static fromBytes(x){let T=C.fromAffine(d(H(x,void 0,"point")));return T.assertValidity(),T}static fromHex(x){return C.fromBytes(Xt(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=6,T=!0){return se.setWindowSize(this,x),T||this.multiply(Li),this}assertValidity(){let x=this;if(x.is0()){if(u&&r.is0(x.X)&&r.eql(x.Y,r.ONE)&&r.is0(x.Z))return;throw new Error("bad point: ZERO")}if(K.has(x))return;let{x:T,y:A}=x.toAffine();if(!r.isValid(T)||!r.isValid(A))throw new Error("bad point: x or y not field elements");if(!D(T,A))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");K.add(x)}hasEvenY(){let{y:x}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(x)}equals(x){Z(x);let{X:T,Y:A,Z:B}=this,{X:R,Y:L,Z:O}=x,F=r.eql(r.mul(T,O),r.mul(R,B)),G=r.eql(r.mul(A,O),r.mul(L,B));return F&&G}negate(){return new C(this.X,r.neg(this.Y),this.Z)}double(){let{X:x,Y:T,Z:A}=this,B=r.ZERO,R=r.ZERO,L=r.ZERO,O=r.mul(x,x),F=r.mul(T,T),G=r.mul(A,A),q=r.mul(x,T);return q=r.add(q,q),L=r.mul(x,A),L=r.add(L,L),B=v(L),R=r.mul(b,G),R=r.add(B,R),B=r.sub(F,R),R=r.add(F,R),R=r.mul(B,R),B=r.mul(q,B),L=r.mul(b,L),G=v(G),q=r.sub(O,G),q=v(q),q=r.add(q,L),L=r.add(O,O),O=r.add(L,O),O=r.add(O,G),O=r.mul(O,q),R=r.add(R,O),G=r.mul(T,A),G=r.add(G,G),O=r.mul(G,q),B=r.sub(B,O),L=r.mul(G,F),L=r.add(L,L),L=r.add(L,L),new C(B,R,L)}add(x){Z(x);let{X:T,Y:A,Z:B}=this,{X:R,Y:L,Z:O}=x,F=r.ZERO,G=r.ZERO,q=r.ZERO,le=r.mul(T,R),Q=r.mul(A,L),fe=r.mul(B,O),Ce=r.add(T,A),ee=r.add(R,L);Ce=r.mul(Ce,ee),ee=r.add(le,Q),Ce=r.sub(Ce,ee),ee=r.add(T,B);let ue=r.add(R,O);return ee=r.mul(ee,ue),ue=r.add(le,fe),ee=r.sub(ee,ue),ue=r.add(A,B),F=r.add(L,O),ue=r.mul(ue,F),F=r.add(Q,fe),ue=r.sub(ue,F),q=v(ee),F=r.mul(b,fe),q=r.add(F,q),F=r.sub(Q,q),q=r.add(Q,q),G=r.mul(F,q),Q=r.add(le,le),Q=r.add(Q,le),fe=v(fe),ee=r.mul(b,ee),Q=r.add(Q,fe),fe=r.sub(le,fe),fe=v(fe),ee=r.add(ee,fe),le=r.mul(Q,ee),G=r.add(G,le),le=r.mul(ue,ee),F=r.mul(Ce,F),F=r.sub(F,le),le=r.mul(Ce,Q),q=r.mul(ue,q),q=r.add(q,le),new C(F,G,q)}subtract(x){return Z(x),this.add(x.negate())}is0(){return this.equals(C.ZERO)}multiply(x){if(!n.isValidNot0(x))throw new RangeError("invalid scalar: out of range");let{p:T,f:A}=se.mulSecret(this,x,o,J);return J([T,A])[0]}multiplyUnsafe(x){let T=this,A=x;if(!n.isValid(A))throw new RangeError("invalid scalar: out of range");if(A===ot||T.is0())return C.ZERO;if(A===Ct)return T;if(se.hasWindowSize(this))return se.mulUnsafe(T,A,J);let B=[],R=[];return N(B,R,T,A),fr(C,B,R)}mulAddUnsafe(x,T,A){Z(T);let B=[],R=[];return N(B,R,this,x),N(B,R,T,A),fr(C,B,R)}toAffine(x){let T=this,A=x;if(A!=null&&!r.isValid(A))throw new RangeError('"invertedZ" expected valid field element');let{X:B,Y:R,Z:L}=T;if(r.eql(L,r.ONE))return{x:B,y:R};let O=T.is0();A==null&&(A=O?r.ONE:r.inv(L));let F=r.mul(B,A),G=r.mul(R,A),q=r.mul(L,A);if(O)return{x:r.ZERO,y:r.ZERO};if(!r.eql(q,r.ONE))throw new Error("invZ was invalid");return{x:F,y:G}}isTorsionFree(){return o===Ct?!0:m?m(C,this):se.mulUnsafe(this,a).is0()}clearCofactor(){return o===Ct?this:p?p(C,this):this.multiplyUnsafe(o)}isSmallOrder(){return o===Ct?this.is0():this.clearCofactor().is0()}toBytes(x=!0){return Be(x,"isCompressed"),this.assertValidity(),h(C,this,x)}toHex(x=!0){return Ss(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let J=P=>hr(C,P),se=new ss(C,f);return se.bits>=6&&C.BASE.precompute(6),Object.freeze(C.prototype),Object.freeze(C),C}function Bc(s){return Uint8Array.of(s?2:3)}function kc(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function wf(s,e={}){wt(s);let{Fn:t}=s,r=e.randomBytes===void 0?Bt:e.randomBytes,n=Object.assign(kc(s.Fp,t),{seed:Math.max(lr(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 S=y.length;return f===!0&&S!==g||f===!1&&S!==w?!1:!s.fromBytes(y).is0()}catch{return!1}}function a(y){return y=y===void 0?r(n.seed):y,ur(H(y,n.seed,"seed"),t.ORDER)}function c(y,f=!0){return s.BASE.multiply(t.fromBytes(y)).toBytes(f)}function u(y){let{secretKey:f,publicKey:g,publicKeyUncompressed:w}=n,S=t._lengths;if(!bt(y))return;let _=H(y,void 0,"key").length,l=_===g||_===w,h=_===f||!!S?.includes(_);if(!(l&&h))return l}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),S=s.fromBytes(f);if(S.is0())throw new Error("invalid public key: point at infinity");return S.multiply(w).toBytes(g)}let m={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},E=pr(a,c);return Object.freeze(m),Object.freeze(n),Object.freeze({getPublicKey:c,getSharedSecret:p,keygen:E,Point:s,utils:m,lengths:n})}function Rc(s,e,t={}){wt(s);let r=e;Js(r),ke(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=Object.assign({},t),i=n.randomBytes===void 0?Bt:n.randomBytes,o=n.hmac===void 0?(P,x)=>Dc(r,P,x):n.hmac,{Fp:a,Fn:c}=s,{ORDER:u,BITS:p}=c,m=lr(u),E=jn(i,m),{keygen:y,getPublicKey:f,getSharedSecret:g,utils:w,lengths:S}=wf(s,n),_={prehash:!0,lowS:typeof n.lowS=="boolean"?n.lowS:!0,format:"compact",extraEntropy:!1},l=u*Mc+Ct<a.ORDER;function h(P){let x=u>>Ct;return P>x}function d(P,x){if(!c.isValidNot0(x))throw new Error(`invalid signature ${P}: out of range 1..Point.Fn.ORDER`);return x}function b(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function v(P,x,T){return b(),(P===T?0:2)|Number(a.isOdd(x))}function I(){if(l)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function D(P,x){Ci(x);let T=S.signature,A=x==="compact"?T:x==="recovered"?T+1:void 0;return H(P,A)}class M{r;s;recovery;constructor(x,T,A){if(this.r=d("r",x),this.s=d("s",T),A!=null){if(I(),![0,1,2,3].includes(A))throw new Error("invalid recovery id");this.recovery=A}Object.freeze(this)}static fromBytes(x,T=_.format){D(x,T);let A;if(T==="der"){if(x.length>2*c.BYTES+16)throw new Dr.Err("invalid signature: DER signature too long");let{r:O,s:F}=Dr.toSig(H(x),c.BYTES+1);return new M(O,F)}T==="recovered"&&(A=x[0],T="compact",x=x.subarray(1));let B=S.signature/2,R=x.subarray(0,B),L=x.subarray(B,B*2);return new M(c.fromBytes(R),c.fromBytes(L),A)}static fromHex(x,T){return this.fromBytes(Xt(x),T)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new M(this.r,this.s,x)}recoverPublicKey(x){let{r:T,s:A}=this,B=this.assertRecovery(),R=B===2||B===3?T+u:T;if(!a.isValid(R))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let L=a.toBytes(R),O=s.fromBytes(Ue(Bc((B&1)===0),L)),F=c.inv(R),G=z(H(x,void 0,"msgHash")),q=c.create(-G*F),le=c.create(A*F),Q=s.BASE.mulAddUnsafe(q,O,le);if(Q.is0())throw new Error("invalid recovery: point at infinify");return Q.assertValidity(),Q}hasHighS(){return h(this.s)}toBytes(x=_.format){if(Ci(x),x==="der")return Xt(Dr.hexFromSig(this));let{r:T,s:A}=this,B=c.toBytes(T),R=c.toBytes(A);return x==="recovered"?(I(),Ue(Uint8Array.of(this.assertRecovery()),B,R)):Ue(B,R)}toHex(x){return Ss(this.toBytes(x))}}Object.freeze(M.prototype),Object.freeze(M);let U=n.bits2int===void 0?function(x){if(x.length>8192)throw new Error("input is too large");let T=Ye(x),A=x.length*8-p;return A>0?T>>BigInt(A):T}:n.bits2int,z=n.bits2int_modN===void 0?function(x){return c.create(U(x))}:n.bits2int_modN,Z=Ts(p);function k(P){return Jt("num < 2^"+p,P,ot,Z),c.toBytes(P)}function N(P,x){return H(P,void 0,"message"),x?H(r(P),void 0,"prehashed message"):P}function K(P,x,T){let{lowS:A,prehash:B,extraEntropy:R}=Ri(T,_);P=N(P,B);let L=z(P),O=c.fromBytes(x);if(!c.isValidNot0(O))throw new Error("invalid private key");let F=[k(O),k(L)];if(R!=null&&R!==!1){let Q=R===!0?i(S.secretKey):R;F.push(H(Q,void 0,"extraEntropy"))}let G=Ue(...F),q=L;function le(Q){let fe=U(Q);if(!c.isValidNot0(fe))return;let Ce=s.BASE.multiply(fe).toAffine(),ee=c.create(Ce.x);if(ee===ot)return;let ue;if(E!==void 0){let ds=Ye(ur(E(m),u)),wl=c.inv(c.mul(ds,fe)),xl=c.mul(ds,q),vl=c.mul(ds,O);ue=c.create(wl*c.create(xl+vl*ee))}else{let ds=Wa(fe,u);ue=c.create(ds*c.create(q+ee*O))}if(ue===ot)return;let $r=v(Ce.x,Ce.y,ee),Yi=ue;return A&&h(ue)&&(Yi=c.neg(ue),$r^=1),new M(ee,Yi,l?void 0:$r)}return{seed:G,k2sig:le}}function C(P,x,T={}){let{seed:A,k2sig:B}=K(P,x,T);return Fa(r.outputLen,c.BYTES,o)(A,B).toBytes(T.format)}function J(P,x,T,A={}){let{lowS:B,prehash:R,format:L}=Ri(A,_);if(T=H(T,void 0,"publicKey"),x=N(x,R),!bt(P)){let O=P instanceof M?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+O)}D(P,L);try{let O=M.fromBytes(P,L),F=s.fromBytes(T);if(F.is0()||B&&O.hasHighS())return!1;let{r:G,s:q}=O,le=z(x),Q=c.inv(q),fe=c.create(le*Q),Ce=c.create(G*Q),ee=s.BASE.mulAddUnsafe(fe,F,Ce);if(ee.is0())return!1;let ue=ee.toAffine();return!(c.create(ue.x)!==G||L==="recovered"&&O.recovery!==v(ue.x,ue.y,G))}catch{return!1}}function se(P,x,T={}){let{prehash:A}=Ri(T,_);return x=N(x,A),M.fromBytes(P,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:y,getPublicKey:f,getSharedSecret:g,utils:w,lengths:S,Point:s,sign:C,verify:J,recoverPublicKey:se,Signature:M,hash:r})}var Fi={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},xf={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Lc=BigInt(2);function vf(s){let e=Fi.p,t=BigInt(3),r=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),u=s*s*s%e,p=u*u*s%e,m=te(p,t,e)*p%e,E=te(m,t,e)*p%e,y=te(E,Lc,e)*u%e,f=te(y,n,e)*y%e,g=te(f,i,e)*f%e,w=te(g,a,e)*g%e,S=te(w,c,e)*w%e,_=te(S,a,e)*g%e,l=te(_,t,e)*p%e,h=te(l,o,e)*f%e,d=te(h,r,e)*u%e,b=te(d,Lc,e);if(!Oi.eql(Oi.sqr(b),s))throw new Error("Cannot find square root");return b}var Oi=ts(Fi.p,{sqrt:vf}),Ef=Pc(Fi,{Fp:Oi,endo:xf}),ns=Rc(Ef,Yt);function Cc(s,e,t,r){let n=Tt.digest(t instanceof Uint8Array?t:t.subarray());if(xr(n))return n.then(({digest:i})=>(r?.signal?.throwIfAborted(),ns.verify(e,i,s,{prehash:!1,format:"der"}))).catch(i=>{throw i.name==="AbortError"?i:new Ms(String(i))});try{return r?.signal?.throwIfAborted(),ns.verify(e,n.digest,s,{prehash:!1,format:"der"})}catch(i){throw new Ms(String(i))}}var Ar=class{type="secp256k1";raw;_key;constructor(e){this._key=Fc(e),this.raw=Oc(this._key)}toMultihash(){return qe.digest(je(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Me(this.raw,e.raw)}verify(e,t,r){return Cc(this._key,t,e,r)}};function Ni(s){return new Ar(s)}function Oc(s){return ns.Point.fromBytes(s).toBytes()}function Fc(s){try{return ns.Point.fromBytes(s),s}catch(e){throw new zt(String(e))}}function Ui(s,e){let{Type:t,Data:r}=Xe.decode(s),n=r??new Uint8Array;switch(t){case ne.RSA:return Mi(n,e);case ne.Ed25519:return ei(n);case ne.secp256k1:return Ni(n);case ne.ECDSA:return Dn(n);default:throw new qt}}function Nc(s){let{Type:e,Data:t}=Xe.decode(s.digest),r=t??new Uint8Array;switch(e){case ne.Ed25519:return ei(r);case ne.secp256k1:return Ni(r);case ne.ECDSA:return Dn(r);default:throw new qt}}function je(s){return Xe.encode({Type:ne[s.type],Data:s.raw})}var Uc=Symbol.for("nodejs.util.inspect.custom"),Sf=114,Cs=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()})`}[Xr]=!0;toString(){return this.string==null&&(this.string=ce.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return pe.createV1(Sf,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Me(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Me(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Uc](){return`PeerId(${this.toString()})`}},Mr=class extends Cs{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Pr=class extends Cs{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Br=class extends Cs{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},_f=2336,Os=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=qe.digest(Y(this.url))}[Uc](){return`PeerId(${this.url})`}[Xr]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return pe.createV1(_f,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=j(e)),e.toString()===this.toString())}};var If=114,Kc=2336;function Ot(s,e){let t;if(s.charAt(0)==="1"||s.charAt(0)==="Q")t=et(ce.decode(`z${s}`));else{if(s.startsWith("k51qzi5uqu5")||s.startsWith("kzwfwjn5ji4")||s.startsWith("k2k4r8")||s.startsWith("bafz"))return Tf(pe.parse(s));if(e==null)throw new oe('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=et(e.decode(s))}return is(t)}function is(s){if(Af(s))return new Mr({multihash:s});if(Df(s))try{let e=Nc(s);if(e.type==="Ed25519")return new Pr({multihash:s,publicKey:e});if(e.type==="secp256k1")return new Br({multihash:s,publicKey:e})}catch{let t=j(s.digest);return new Os(new URL(t))}throw new Hs("Supplied PeerID Multihash is invalid")}function Tf(s){if(s?.multihash==null||s.version==null||s.version===1&&s.code!==If&&s.code!==Kc)throw new Gs("Supplied PeerID CID is invalid");if(s.code===Kc){let e=j(s.multihash.digest);return new Os(new URL(e))}return is(s.multihash)}function Df(s){return s.code===qe.code}function Af(s){return s.code===Tt.code}var kr=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},os=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Rr=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Fs=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Lr(s){return s[Symbol.asyncIterator]!=null}function zc(s,e){if(s.byteLength>e)throw new os("Message length too long")}var Or=s=>{let e=ze(s),t=ge(e);return ai(s,t),Or.bytes=e,t};Or.bytes=0;function as(s,e){e=e??{};let t=e.lengthEncoder??Or,r=e?.maxDataLength??4194304;function*n(i){zc(i,r);let o=t(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return Lr(s)?(async function*(){for await(let i of s)yield*n(i)})():(function*(){for(let i of s)yield*n(i)})()}as.single=(s,e)=>{e=e??{};let t=e.lengthEncoder??Or,r=e?.maxDataLength??4194304;return zc(s,r),new de(t(s.byteLength),s)};var Ft;(function(s){s[s.LENGTH=0]="LENGTH",s[s.DATA=1]="DATA"})(Ft||(Ft={}));var Ki=s=>{let e=ci(s);return Ki.bytes=ze(e),e};Ki.bytes=0;function Ns(s,e){let t=new de,r=Ft.LENGTH,n=-1,i=e?.lengthDecoder??Ki,o=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(r===Ft.LENGTH)try{if(n=i(t),n<0)throw new kr("Invalid message length");if(n>a)throw new os("Message length too long");let u=i.bytes;t.consume(u),e?.onLength!=null&&e.onLength(n),r=Ft.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>o)throw new Rr("Message length length too long");break}throw u}if(r===Ft.DATA){if(t.byteLength<n)break;let u=t.sublist(0,n);t.consume(n),e?.onData!=null&&e.onData(u),yield u,r=Ft.LENGTH}}}return Lr(s)?(async function*(){for await(let u of s)t.append(u),yield*c();if(t.byteLength>0)throw new Fs("Unexpected end of input")})():(function*(){for(let u of s)t.append(u),yield*c();if(t.byteLength>0)throw new Fs("Unexpected end of input")})()}Ns.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 Ns(r,{...e??{},onLength:i=>{t=i}})};function at(){let s={};return s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),s}var Fr=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}},cs=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Fr(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 Fr(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 zi=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Nt(s={}){return Pf(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 Pf(s,e){e=e??{};let t=e.onEnd,r=new cs,n,i,o,a=at(),c=async()=>{try{return r.isEmpty()?o?{done:!0}:await new Promise((w,S)=>{i=_=>{i=null,r.push(_);try{w(s(r))}catch(l){S(l)}return n}}):s(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=at()})}},u=w=>i!=null?i(w):(r.push(w),n),p=w=>(r=new cs,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})},E=w=>o?n:(o=!0,w!=null?p(w):u({done:!0})),y=()=>(r=new cs,E(),{done:!0}),f=w=>(E(w),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:c,return:y,throw:f,push:m,end:E,get readableLength(){return r.size},onEmpty:async w=>{let S=w?.signal;if(S?.throwIfAborted(),r.isEmpty())return;let _,l;S!=null&&(_=new Promise((h,d)=>{l=()=>{d(new zi)},S.addEventListener("abort",l)}));try{await Promise.race([a.promise,_])}finally{l!=null&&S!=null&&S?.removeEventListener("abort",l)}}},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 Bf(s){return s.reason}function qi(s,e,t){if(e==null||s==null)return s;let r=t?.translateError??Bf;if(e.aborted)return s.catch(()=>{}),Promise.reject(r(e));let n;return Promise.race([s,new Promise((i,o)=>{n=()=>{o(r(e))},e.addEventListener("abort",n)})]).finally(()=>{n!=null&&e.removeEventListener("abort",n)})}var Gi=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=at(),this.haveNext=at()}[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=at(),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=at(),await qi(this.readNext.promise,t?.signal,t)}};function qc(){return new Gi}function Gc(s){return s[Symbol.asyncIterator]!=null}async function kf(s,e,t){try{await Promise.all(s.map(async r=>{for(;;){let{value:n,done:i}=await r.next();if(i===!0)break;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*Rf(s){let e=new AbortController,t=qc(),r=s.map(n=>Gc(n)?n[Symbol.asyncIterator]():n[Symbol.iterator]());kf(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort();for(let n of r)try{Promise.resolve(n.return?.()).catch(()=>{})}catch{}}}function*Lf(s){for(let e of s)yield*e}function Cf(...s){let e=[];for(let t of s)Gc(t)||e.push(t);return e.length===s.length?Lf(e):Rf(s)}var Hc=Cf;function Us(s,...e){if(s==null)throw new Error("Empty pipeline");if(Hi(s)){let r=s;s=()=>r.source}else if(Vc(s)||Wc(s)){let r=s;s=()=>r}let t=[s,...e];if(t.length>1&&Hi(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++)Hi(t[r])&&(t[r]=Ff(t[r]));return Of(...t)}var Of=(...s)=>{let e;for(;s.length>0;)e=s.shift()(e);return e},Wc=s=>s?.[Symbol.asyncIterator]!=null,Vc=s=>s?.[Symbol.iterator]!=null,Hi=s=>s==null?!1:s.sink!=null&&s.source!=null,Ff=s=>e=>{let t=s.sink(e);if(t?.then!=null){let r=Nt({objectMode:!0});t.then(()=>{r.end()},o=>{r.end(o)});let n,i=s.source;if(Wc(i))n=async function*(){yield*i,r.end()};else if(Vc(i))n=function*(){yield*i,r.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Hc(r,n())}return s.source};var $c={maxSubscriptions:5e3,maxMessages:5e3,maxIhaveMessageIDs:5e3,maxIwantMessageIDs:5e3,maxControlMessages:5e3,maxIdontwantMessageIDs:512,maxPeerInfos:16};var ct;(function(s){let e;(function(f){let g;f.codec=()=>(g==null&&(g=Ie((l,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),l.subscribe!=null&&(h.uint32(8),h.bool(l.subscribe)),l.topic!=null&&(h.uint32(18),h.string(l.topic)),d.lengthDelimited!==!1&&h.ldelim()},(l,h,d={})=>{let b={},v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{b.subscribe=l.bool();break}case 2:{b.topic=l.string();break}default:{l.skipType(I&7);break}}}return b},function*(l,h,d,b={}){let v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{yield{field:`${d}.subscribe`,value:l.bool()};break}case 2:{yield{field:`${d}.topic`,value:l.string()};break}default:{l.skipType(I&7);break}}}})),g);function w(l){return Se(l,f.codec())}f.encode=w;function S(l,h){return Ee(l,f.codec(),h)}f.decode=S;function _(l,h){return _e(l,f.codec(),h)}f.stream=_})(e=s.SubOpts||(s.SubOpts={}));let t;(function(f){let g;f.codec=()=>(g==null&&(g=Ie((l,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),l.from!=null&&(h.uint32(10),h.bytes(l.from)),l.data!=null&&(h.uint32(18),h.bytes(l.data)),l.seqno!=null&&(h.uint32(26),h.bytes(l.seqno)),l.topic!=null&&l.topic!==""&&(h.uint32(34),h.string(l.topic)),l.signature!=null&&(h.uint32(42),h.bytes(l.signature)),l.key!=null&&(h.uint32(50),h.bytes(l.key)),d.lengthDelimited!==!1&&h.ldelim()},(l,h,d={})=>{let b={topic:""},v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{b.from=l.bytes();break}case 2:{b.data=l.bytes();break}case 3:{b.seqno=l.bytes();break}case 4:{b.topic=l.string();break}case 5:{b.signature=l.bytes();break}case 6:{b.key=l.bytes();break}default:{l.skipType(I&7);break}}}return b},function*(l,h,d,b={}){let v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{yield{field:`${d}.from`,value:l.bytes()};break}case 2:{yield{field:`${d}.data`,value:l.bytes()};break}case 3:{yield{field:`${d}.seqno`,value:l.bytes()};break}case 4:{yield{field:`${d}.topic`,value:l.string()};break}case 5:{yield{field:`${d}.signature`,value:l.bytes()};break}case 6:{yield{field:`${d}.key`,value:l.bytes()};break}default:{l.skipType(I&7);break}}}})),g);function w(l){return Se(l,f.codec())}f.encode=w;function S(l,h){return Ee(l,f.codec(),h)}f.decode=S;function _(l,h){return _e(l,f.codec(),h)}f.stream=_})(t=s.Message||(s.Message={}));let r;(function(f){let g;f.codec=()=>(g==null&&(g=Ie((l,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),l.ihave!=null&&l.ihave.length>0)for(let b of l.ihave)h.uint32(10),s.ControlIHave.codec().encode(b,h);if(l.iwant!=null&&l.iwant.length>0)for(let b of l.iwant)h.uint32(18),s.ControlIWant.codec().encode(b,h);if(l.graft!=null&&l.graft.length>0)for(let b of l.graft)h.uint32(26),s.ControlGraft.codec().encode(b,h);if(l.prune!=null&&l.prune.length>0)for(let b of l.prune)h.uint32(34),s.ControlPrune.codec().encode(b,h);if(l.idontwant!=null&&l.idontwant.length>0)for(let b of l.idontwant)h.uint32(42),s.ControlIDontWant.codec().encode(b,h);d.lengthDelimited!==!1&&h.ldelim()},(l,h,d={})=>{let b={ihave:[],iwant:[],graft:[],prune:[],idontwant:[]},v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{if(d.limits?.ihave!=null&&b.ihave.length===d.limits.ihave)throw new X('Decode error - repeated field "ihave" had too many elements');b.ihave.push(s.ControlIHave.codec().decode(l,l.uint32(),{limits:d.limits?.ihave$}));break}case 2:{if(d.limits?.iwant!=null&&b.iwant.length===d.limits.iwant)throw new X('Decode error - repeated field "iwant" had too many elements');b.iwant.push(s.ControlIWant.codec().decode(l,l.uint32(),{limits:d.limits?.iwant$}));break}case 3:{if(d.limits?.graft!=null&&b.graft.length===d.limits.graft)throw new X('Decode error - repeated field "graft" had too many elements');b.graft.push(s.ControlGraft.codec().decode(l,l.uint32(),{limits:d.limits?.graft$}));break}case 4:{if(d.limits?.prune!=null&&b.prune.length===d.limits.prune)throw new X('Decode error - repeated field "prune" had too many elements');b.prune.push(s.ControlPrune.codec().decode(l,l.uint32(),{limits:d.limits?.prune$}));break}case 5:{if(d.limits?.idontwant!=null&&b.idontwant.length===d.limits.idontwant)throw new X('Decode error - repeated field "idontwant" had too many elements');b.idontwant.push(s.ControlIDontWant.codec().decode(l,l.uint32(),{limits:d.limits?.idontwant$}));break}default:{l.skipType(I&7);break}}}return b},function*(l,h,d,b={}){let v={ihave:0,iwant:0,graft:0,prune:0,idontwant:0},I=h==null?l.len:l.pos+h;for(;l.pos<I;){let D=l.uint32();switch(D>>>3){case 1:{if(b.limits?.ihave!=null&&v.ihave===b.limits.ihave)throw new X('Streaming decode error - repeated field "ihave" had too many elements');for(let M of s.ControlIHave.codec().stream(l,l.uint32(),`${d}.ihave[]`,{limits:b.limits?.ihave$}))yield{...M,index:v.ihave};v.ihave++;break}case 2:{if(b.limits?.iwant!=null&&v.iwant===b.limits.iwant)throw new X('Streaming decode error - repeated field "iwant" had too many elements');for(let M of s.ControlIWant.codec().stream(l,l.uint32(),`${d}.iwant[]`,{limits:b.limits?.iwant$}))yield{...M,index:v.iwant};v.iwant++;break}case 3:{if(b.limits?.graft!=null&&v.graft===b.limits.graft)throw new X('Streaming decode error - repeated field "graft" had too many elements');for(let M of s.ControlGraft.codec().stream(l,l.uint32(),`${d}.graft[]`,{limits:b.limits?.graft$}))yield{...M,index:v.graft};v.graft++;break}case 4:{if(b.limits?.prune!=null&&v.prune===b.limits.prune)throw new X('Streaming decode error - repeated field "prune" had too many elements');for(let M of s.ControlPrune.codec().stream(l,l.uint32(),`${d}.prune[]`,{limits:b.limits?.prune$}))yield{...M,index:v.prune};v.prune++;break}case 5:{if(b.limits?.idontwant!=null&&v.idontwant===b.limits.idontwant)throw new X('Streaming decode error - repeated field "idontwant" had too many elements');for(let M of s.ControlIDontWant.codec().stream(l,l.uint32(),`${d}.idontwant[]`,{limits:b.limits?.idontwant$}))yield{...M,index:v.idontwant};v.idontwant++;break}default:{l.skipType(D&7);break}}}})),g);function w(l){return Se(l,f.codec())}f.encode=w;function S(l,h){return Ee(l,f.codec(),h)}f.decode=S;function _(l,h){return _e(l,f.codec(),h)}f.stream=_})(r=s.ControlMessage||(s.ControlMessage={}));let n;(function(f){let g;f.codec=()=>(g==null&&(g=Ie((l,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),l.topicID!=null&&(h.uint32(10),h.string(l.topicID)),l.messageIDs!=null&&l.messageIDs.length>0)for(let b of l.messageIDs)h.uint32(18),h.bytes(b);d.lengthDelimited!==!1&&h.ldelim()},(l,h,d={})=>{let b={messageIDs:[]},v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{b.topicID=l.string();break}case 2:{if(d.limits?.messageIDs!=null&&b.messageIDs.length===d.limits.messageIDs)throw new X('Decode error - repeated field "messageIDs" had too many elements');b.messageIDs.push(l.bytes());break}default:{l.skipType(I&7);break}}}return b},function*(l,h,d,b={}){let v={messageIDs:0},I=h==null?l.len:l.pos+h;for(;l.pos<I;){let D=l.uint32();switch(D>>>3){case 1:{yield{field:`${d}.topicID`,value:l.string()};break}case 2:{if(b.limits?.messageIDs!=null&&v.messageIDs===b.limits.messageIDs)throw new X('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:l.bytes()},v.messageIDs++;break}default:{l.skipType(D&7);break}}}})),g);function w(l){return Se(l,f.codec())}f.encode=w;function S(l,h){return Ee(l,f.codec(),h)}f.decode=S;function _(l,h){return _e(l,f.codec(),h)}f.stream=_})(n=s.ControlIHave||(s.ControlIHave={}));let i;(function(f){let g;f.codec=()=>(g==null&&(g=Ie((l,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),l.messageIDs!=null&&l.messageIDs.length>0)for(let b of l.messageIDs)h.uint32(10),h.bytes(b);d.lengthDelimited!==!1&&h.ldelim()},(l,h,d={})=>{let b={messageIDs:[]},v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{if(d.limits?.messageIDs!=null&&b.messageIDs.length===d.limits.messageIDs)throw new X('Decode error - repeated field "messageIDs" had too many elements');b.messageIDs.push(l.bytes());break}default:{l.skipType(I&7);break}}}return b},function*(l,h,d,b={}){let v={messageIDs:0},I=h==null?l.len:l.pos+h;for(;l.pos<I;){let D=l.uint32();switch(D>>>3){case 1:{if(b.limits?.messageIDs!=null&&v.messageIDs===b.limits.messageIDs)throw new X('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:l.bytes()},v.messageIDs++;break}default:{l.skipType(D&7);break}}}})),g);function w(l){return Se(l,f.codec())}f.encode=w;function S(l,h){return Ee(l,f.codec(),h)}f.decode=S;function _(l,h){return _e(l,f.codec(),h)}f.stream=_})(i=s.ControlIWant||(s.ControlIWant={}));let o;(function(f){let g;f.codec=()=>(g==null&&(g=Ie((l,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),l.topicID!=null&&(h.uint32(10),h.string(l.topicID)),d.lengthDelimited!==!1&&h.ldelim()},(l,h,d={})=>{let b={},v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();I>>>3===1?b.topicID=l.string():l.skipType(I&7)}return b},function*(l,h,d,b={}){let v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();I>>>3===1?yield{field:`${d}.topicID`,value:l.string()}:l.skipType(I&7)}})),g);function w(l){return Se(l,f.codec())}f.encode=w;function S(l,h){return Ee(l,f.codec(),h)}f.decode=S;function _(l,h){return _e(l,f.codec(),h)}f.stream=_})(o=s.ControlGraft||(s.ControlGraft={}));let a;(function(f){let g;f.codec=()=>(g==null&&(g=Ie((l,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),l.topicID!=null&&(h.uint32(10),h.string(l.topicID)),l.peers!=null&&l.peers.length>0)for(let b of l.peers)h.uint32(18),s.PeerInfo.codec().encode(b,h);l.backoff!=null&&(h.uint32(24),h.uint64Number(l.backoff)),d.lengthDelimited!==!1&&h.ldelim()},(l,h,d={})=>{let b={peers:[]},v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{b.topicID=l.string();break}case 2:{if(d.limits?.peers!=null&&b.peers.length===d.limits.peers)throw new X('Decode error - repeated field "peers" had too many elements');b.peers.push(s.PeerInfo.codec().decode(l,l.uint32(),{limits:d.limits?.peers$}));break}case 3:{b.backoff=l.uint64Number();break}default:{l.skipType(I&7);break}}}return b},function*(l,h,d,b={}){let v={peers:0},I=h==null?l.len:l.pos+h;for(;l.pos<I;){let D=l.uint32();switch(D>>>3){case 1:{yield{field:`${d}.topicID`,value:l.string()};break}case 2:{if(b.limits?.peers!=null&&v.peers===b.limits.peers)throw new X('Streaming decode error - repeated field "peers" had too many elements');for(let M of s.PeerInfo.codec().stream(l,l.uint32(),`${d}.peers[]`,{limits:b.limits?.peers$}))yield{...M,index:v.peers};v.peers++;break}case 3:{yield{field:`${d}.backoff`,value:l.uint64Number()};break}default:{l.skipType(D&7);break}}}})),g);function w(l){return Se(l,f.codec())}f.encode=w;function S(l,h){return Ee(l,f.codec(),h)}f.decode=S;function _(l,h){return _e(l,f.codec(),h)}f.stream=_})(a=s.ControlPrune||(s.ControlPrune={}));let c;(function(f){let g;f.codec=()=>(g==null&&(g=Ie((l,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),l.peerID!=null&&(h.uint32(10),h.bytes(l.peerID)),l.signedPeerRecord!=null&&(h.uint32(18),h.bytes(l.signedPeerRecord)),d.lengthDelimited!==!1&&h.ldelim()},(l,h,d={})=>{let b={},v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{b.peerID=l.bytes();break}case 2:{b.signedPeerRecord=l.bytes();break}default:{l.skipType(I&7);break}}}return b},function*(l,h,d,b={}){let v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{yield{field:`${d}.peerID`,value:l.bytes()};break}case 2:{yield{field:`${d}.signedPeerRecord`,value:l.bytes()};break}default:{l.skipType(I&7);break}}}})),g);function w(l){return Se(l,f.codec())}f.encode=w;function S(l,h){return Ee(l,f.codec(),h)}f.decode=S;function _(l,h){return _e(l,f.codec(),h)}f.stream=_})(c=s.PeerInfo||(s.PeerInfo={}));let u;(function(f){let g;f.codec=()=>(g==null&&(g=Ie((l,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),l.messageIDs!=null&&l.messageIDs.length>0)for(let b of l.messageIDs)h.uint32(10),h.bytes(b);d.lengthDelimited!==!1&&h.ldelim()},(l,h,d={})=>{let b={messageIDs:[]},v=h==null?l.len:l.pos+h;for(;l.pos<v;){let I=l.uint32();switch(I>>>3){case 1:{if(d.limits?.messageIDs!=null&&b.messageIDs.length===d.limits.messageIDs)throw new X('Decode error - repeated field "messageIDs" had too many elements');b.messageIDs.push(l.bytes());break}default:{l.skipType(I&7);break}}}return b},function*(l,h,d,b={}){let v={messageIDs:0},I=h==null?l.len:l.pos+h;for(;l.pos<I;){let D=l.uint32();switch(D>>>3){case 1:{if(b.limits?.messageIDs!=null&&v.messageIDs===b.limits.messageIDs)throw new X('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:l.bytes()},v.messageIDs++;break}default:{l.skipType(D&7);break}}}})),g);function w(l){return Se(l,f.codec())}f.encode=w;function S(l,h){return Ee(l,f.codec(),h)}f.decode=S;function _(l,h){return _e(l,f.codec(),h)}f.stream=_})(u=s.ControlIDontWant||(s.ControlIDontWant={}));let p;s.codec=()=>(p==null&&(p=Ie((f,g,w={})=>{if(w.lengthDelimited!==!1&&g.fork(),f.subscriptions!=null&&f.subscriptions.length>0)for(let S of f.subscriptions)g.uint32(10),s.SubOpts.codec().encode(S,g);if(f.messages!=null&&f.messages.length>0)for(let S of f.messages)g.uint32(18),s.Message.codec().encode(S,g);f.control!=null&&(g.uint32(26),s.ControlMessage.codec().encode(f.control,g)),w.lengthDelimited!==!1&&g.ldelim()},(f,g,w={})=>{let S={subscriptions:[],messages:[]},_=g==null?f.len:f.pos+g;for(;f.pos<_;){let l=f.uint32();switch(l>>>3){case 1:{if(w.limits?.subscriptions!=null&&S.subscriptions.length===w.limits.subscriptions)throw new X('Decode error - repeated field "subscriptions" had too many elements');S.subscriptions.push(s.SubOpts.codec().decode(f,f.uint32(),{limits:w.limits?.subscriptions$}));break}case 2:{if(w.limits?.messages!=null&&S.messages.length===w.limits.messages)throw new X('Decode error - repeated field "messages" had too many elements');S.messages.push(s.Message.codec().decode(f,f.uint32(),{limits:w.limits?.messages$}));break}case 3:{S.control=s.ControlMessage.codec().decode(f,f.uint32(),{limits:w.limits?.control});break}default:{f.skipType(l&7);break}}}return S},function*(f,g,w,S={}){let _={subscriptions:0,messages:0},l=g==null?f.len:f.pos+g;for(;f.pos<l;){let h=f.uint32();switch(h>>>3){case 1:{if(S.limits?.subscriptions!=null&&_.subscriptions===S.limits.subscriptions)throw new X('Streaming decode error - repeated field "subscriptions" had too many elements');for(let d of s.SubOpts.codec().stream(f,f.uint32(),`${w}.subscriptions[]`,{limits:S.limits?.subscriptions$}))yield{...d,index:_.subscriptions};_.subscriptions++;break}case 2:{if(S.limits?.messages!=null&&_.messages===S.limits.messages)throw new X('Streaming decode error - repeated field "messages" had too many elements');for(let d of s.Message.codec().stream(f,f.uint32(),`${w}.messages[]`,{limits:S.limits?.messages$}))yield{...d,index:_.messages};_.messages++;break}case 3:{yield*s.ControlMessage.codec().stream(f,f.uint32(),`${w}.control`,{limits:S.limits?.control});break}default:{f.skipType(h&7);break}}}})),p);function m(f){return Se(f,s.codec())}s.encode=m;function E(f,g){return Ee(f,s.codec(),g)}s.decode=E;function y(f,g){return _e(f,s.codec(),g)}s.stream=y})(ct||(ct={}));var Nr=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 jc;(function(s){s.StrictSign="StrictSign",s.StrictNoSign="StrictNoSign"})(jc||(jc={}));var vt;(function(s){s[s.Signing=0]="Signing",s[s.Anonymous=1]="Anonymous"})(vt||(vt={}));var Te;(function(s){s.Error="error",s.Ignore="ignore",s.Reject="reject",s.Blacklisted="blacklisted"})(Te||(Te={}));var me;(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"})(me||(me={}));var we;(function(s){s.duplicate="duplicate",s.invalid="invalid",s.valid="valid"})(we||(we={}));function Wi(s){switch(s){case xe.Ignore:return Te.Ignore;case xe.Reject:return Te.Reject;default:throw new Error("Unreachable")}}var Zc;(function(s){s.forward="forward",s.publish="publish"})(Zc||(Zc={}));var ve;(function(s){s.Fanout="fanout",s.Random="random",s.Subscribed="subscribed",s.Outbound="outbound",s.NotEnough="not_enough",s.Opportunistic="opportunistic"})(ve||(ve={}));var We;(function(s){s.Dc="disconnected",s.BadScore="bad_score",s.Prune="prune",s.Excess="excess"})(We||(We={}));var us;(function(s){s.GraftBackoff="graft_backoff",s.BrokenPromise="broken_promise",s.MessageDeficit="message_deficit",s.IPColocation="IP_colocation"})(us||(us={}));var hs;(function(s){s.LowScore="low_score",s.MaxIhave="max_ihave",s.MaxIasked="max_iasked"})(hs||(hs={}));var Ks;(function(s){s.forward="forward",s.iwant="iwant"})(Ks||(Ks={}));var ls;(function(s){s.graylist="graylist",s.publish="publish",s.gossip="gossip",s.mesh="mesh"})(ls||(ls={}));function Yc(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"}),idontwantSkippedSends:s.gauge({name:"gossipsub_idontwant_skipped_sends_total",help:"Total message sends skipped because the peer sent IDONTWANT for the message",labelNames:["on"]}),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 ve.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:o},i);break;case ve.Random:this.meshPeerInclusionEventsRandom.inc({topic:o},i);break;case ve.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:o},i);break;case ve.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:o},i);break;case ve.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:o},i);break;case ve.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 We.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:o},i);break;case We.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:o},i);break;case We.Prune:this.meshPeerChurnEventsPrune.inc({topic:o},i);break;case We.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 xe.Accept:this.acceptedMessagesTotal.inc({topic:o});break;case xe.Ignore:this.ignoredMessagesTotal.inc({topic:o});break;case xe.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)},onIdontwantSkippedSend(r){this.idontwantSkippedSends.inc({on:r},1)},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 c=this.toTopic(r);this.msgPublishCount.inc({topic:c},1),this.msgPublishBytes.inc({topic:c},i*o),this.msgPublishPeersByTopic.inc({topic:c},i),this.directPeersPublishedTotal.inc({topic:c},n.direct),this.floodsubPeersPublishedTotal.inc({topic:c},n.floodsub),this.meshPeersPublishedTotal.inc({topic:c},n.mesh),this.fanoutPeersPublishedTotal.inc({topic:c},n.fanout),this.msgPublishTime.observe({topic:c},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 we.duplicate:this.prevalidationDuplicateTotal.inc({topic:i});break;case we.invalid:this.prevalidationInvalidTotal.inc({topic:i});break;case we.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===Te.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,c=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),c>0&&this.rpcSentPrune.inc(c),u>0&&this.rpcSentIDontWant.inc(u),(i>0||o>0||a>0||c>0||u>0)&&this.rpcSentControl.inc(1)}},registerScores(r,n){let i=0,o=0,a=0,c=0;for(let u of r)u>=n.graylistThreshold&&i++,u>=n.publishThreshold&&o++,u>=n.gossipThreshold&&a++,u>=0&&c++;this.peersByScoreThreshold.set({threshold:ls.graylist},i),this.peersByScoreThreshold.set({threshold:ls.publish},o),this.peersByScoreThreshold.set({threshold:ls.gossip},a),this.peersByScoreThreshold.set({threshold:ls.mesh},c),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 c=this.topicStrToLabel.get(a)??"unknown",u=i.get(c);u==null&&(u=new Set,i.set(c,u)),o.forEach(p=>u?.add(p))});for(let[o,a]of i){let c=[];a.forEach(u=>{c.push(n.get(u)??0)}),this.scorePerMesh.set({topic:o},c)}}}}var $=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var Nf={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},Uf={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 Xc(s={}){return{...Nf,...s,topics:s.topics!=null?Object.entries(s.topics).reduce((e,[t,r])=>(e[t]=Kf(r),e),{}):{}}}function Kf(s={}){return{...Uf,...s}}function Jc(s){for(let[e,t]of Object.entries(s.topics))try{zf(t)}catch(r){throw new $(`invalid score parameters for topic ${e}: ${r.message}`)}if(s.topicScoreCap<0)throw new $("invalid topic score cap; must be positive (or 0 for no cap)");if(s.appSpecificScore===null||s.appSpecificScore===void 0)throw new $("missing application specific score function");if(s.IPColocationFactorWeight>0)throw new $("invalid IPColocationFactorWeight; must be negative (or 0 to disable)");if(s.IPColocationFactorWeight!==0&&s.IPColocationFactorThreshold<1)throw new $("invalid IPColocationFactorThreshold; must be at least 1");if(s.behaviourPenaltyWeight>0)throw new $("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)");if(s.behaviourPenaltyWeight!==0&&(s.behaviourPenaltyDecay<=0||s.behaviourPenaltyDecay>=1))throw new $("invalid BehaviourPenaltyDecay; must be between 0 and 1");if(s.decayInterval<1e3)throw new $("invalid DecayInterval; must be at least 1s");if(s.decayToZero<=0||s.decayToZero>=1)throw new $("invalid DecayToZero; must be between 0 and 1")}function zf(s){if(s.topicWeight<0)throw new $("invalid topic weight; must be >= 0");if(s.timeInMeshQuantum===0)throw new $("invalid TimeInMeshQuantum; must be non zero");if(s.timeInMeshWeight<0)throw new $("invalid TimeInMeshWeight; must be positive (or 0 to disable)");if(s.timeInMeshWeight!==0&&s.timeInMeshQuantum<=0)throw new $("invalid TimeInMeshQuantum; must be positive");if(s.timeInMeshWeight!==0&&s.timeInMeshCap<=0)throw new $("invalid TimeInMeshCap; must be positive");if(s.firstMessageDeliveriesWeight<0)throw new $("invalid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)");if(s.firstMessageDeliveriesWeight!==0&&(s.firstMessageDeliveriesDecay<=0||s.firstMessageDeliveriesDecay>=1))throw new $("invalid FirstMessageDeliveriesDecay; must be between 0 and 1");if(s.firstMessageDeliveriesWeight!==0&&s.firstMessageDeliveriesCap<=0)throw new $("invalid FirstMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight>0)throw new $("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.meshMessageDeliveriesWeight!==0&&(s.meshMessageDeliveriesDecay<=0||s.meshMessageDeliveriesDecay>=1))throw new $("invalid MeshMessageDeliveriesDecay; must be between 0 and 1");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesCap<=0)throw new $("invalid MeshMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesThreshold<=0)throw new $("invalid MeshMessageDeliveriesThreshold; must be positive");if(s.meshMessageDeliveriesWindow<0)throw new $("invalid MeshMessageDeliveriesWindow; must be non-negative");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesActivation<1e3)throw new $("invalid MeshMessageDeliveriesActivation; must be at least 1s");if(s.meshFailurePenaltyWeight>0)throw new $("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)");if(s.meshFailurePenaltyWeight!==0&&(s.meshFailurePenaltyDecay<=0||s.meshFailurePenaltyDecay>=1))throw new $("invalid MeshFailurePenaltyDecay; must be between 0 and 1");if(s.invalidMessageDeliveriesWeight>0)throw new $("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.invalidMessageDeliveriesDecay<=0||s.invalidMessageDeliveriesDecay>=1)throw new $("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1")}var qf={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function Qc(s={}){return{...qf,...s}}function Kr(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 el(s,e){return Kr(s,e,()=>!0)}var Ur=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 tl(s,e,t,r){let n=0;Object.entries(e.topics).forEach(([o,a])=>{let c=t.topics[o];if(c===void 0)return;let u=0;if(a.inMesh){let y=a.meshTime/c.timeInMeshQuantum;y>c.timeInMeshCap&&(y=c.timeInMeshCap),u+=y*c.timeInMeshWeight}let p=a.firstMessageDeliveries;if(p>c.firstMessageDeliveriesCap&&(p=c.firstMessageDeliveriesCap),u+=p*c.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries<c.meshMessageDeliveriesThreshold){let y=c.meshMessageDeliveriesThreshold-a.meshMessageDeliveries,f=y*y;u+=f*c.meshMessageDeliveriesWeight}let m=a.meshFailurePenalty;u+=m*c.meshFailurePenaltyWeight;let E=a.invalidMessageDeliveries*a.invalidMessageDeliveries;u+=E*c.invalidMessageDeliveriesWeight,n+=u*c.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),c=a!=null?a.size:0;if(c>t.IPColocationFactorThreshold){let u=c-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 nl=Al(rl(),1);var De;(function(s){s[s.unknown=0]="unknown",s[s.valid=1]="valid",s[s.invalid=2]="invalid",s[s.ignored=3]="ignored"})(De||(De={}));var zr=class{records;queue;constructor(){this.records=new Map,this.queue=new nl.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:De.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let r={msgId:e,expire:Date.now()+Io};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 qr=class{params;metrics;peerStats=new Map;peerIPs=new Ur(()=>new Set);scoreCache=new Map;deliveryRecords=new zr;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,r,n){this.params=e,this.metrics=t,Jc(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??tl,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!==De.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,i-n.firstSeenTsMs,De[n.status]);return}n.status=De.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 Te.Error:this.markInvalidMessageDelivery(e,r);return;case Te.Blacklisted:return}let i=this.deliveryRecords.ensureRecord(t);if(i.status!==De.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-i.firstSeenTsMs,De[i.status]);return}if(n===Te.Ignore){i.status=De.ignored,i.peers.clear();return}i.status=De.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 De.unknown:n.peers.add(e);break;case De.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,r,n.validated);break;case De.invalid:this.markInvalidMessageDelivery(e,r);break;case De.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 c=a.meshMessageDeliveriesCap;o.meshMessageDeliveries=Math.min(c,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 Gf(s,e,t,r,n){let i=0,o=new Map;if(Object.entries(e.topics).forEach(([E,y])=>{let f=n.get(E)??"unknown",g=t.topics[E];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 S=0,_=0,l=0,h=0,d=0;if(y.inMesh){let D=Math.max(y.meshTime/g.timeInMeshQuantum,g.timeInMeshCap);S+=D*g.timeInMeshWeight}let b=y.firstMessageDeliveries;if(b>g.firstMessageDeliveriesCap&&(b=g.firstMessageDeliveriesCap),_+=b*g.firstMessageDeliveriesWeight,y.meshMessageDeliveriesActive&&y.meshMessageDeliveries<g.meshMessageDeliveriesThreshold){let D=g.meshMessageDeliveriesThreshold-y.meshMessageDeliveries,M=D*D;l+=M*g.meshMessageDeliveriesWeight}let v=y.meshFailurePenalty;h+=v*g.meshFailurePenaltyWeight;let I=y.invalidMessageDeliveries*y.invalidMessageDeliveries;d+=I*g.invalidMessageDeliveriesWeight,i+=(S+_+l+h+d)*g.topicWeight,w.p1w+=S,w.p2w+=_,w.p3w+=l,w.p3bw+=h,w.p4w+=d}),t.topicScoreCap>0&&i>t.topicScoreCap){i=t.topicScoreCap;let E=t.topicScoreCap/i;for(let y of o.values())y.p1w*=E,y.p2w*=E,y.p3w*=E,y.p3bw*=E,y.p4w*=E}let a=0,c=0,u=0,p=t.appSpecificScore(s);a+=p*t.appSpecificWeight,e.knownIPs.forEach(E=>{if(t.IPColocationFactorWhitelist.has(E))return;let y=r.get(E),f=y!=null?y.size:0;if(f>t.IPColocationFactorThreshold){let g=f-t.IPColocationFactorThreshold,w=g*g;c+=w*t.IPColocationFactorWeight}});let m=e.behaviourPenalty*e.behaviourPenalty;return u+=m*t.behaviourPenaltyWeight,i+=a+c+u,{byTopic:o,p5w:a,p6w:c,p7w:u,score:i}}function il(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 c=Gf(o,a,t,r,n);for(let[u,p]of c.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(c.p5w),i.p6w.push(c.p6w),i.p7w.push(c.p7w),i.score.push(c.score)}else i.p5w.push(0),i.p6w.push(0),i.p7w.push(0),i.score.push(0)}return i}function Vi(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 ol(s){let e=Vi(s);if(e==null)throw new oe(`Multiaddr ${s} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function al(s){return Vi(s)!==null}var $i=class s extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,s)}},cl=s=>s.reason??new DOMException("This operation was aborted.","AbortError");function ji(s,e){let{milliseconds:t,fallback:r,message:n,customTimers:i={setTimeout,clearTimeout},signal:o}=e,a,c,p=new Promise((m,E)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(o?.aborted){E(cl(o)),s.then(m,E);return}if(o&&(c=()=>{E(cl(o))},o.addEventListener("abort",c,{once:!0})),s.then(m,E),t===Number.POSITIVE_INFINITY)return;let y=new $i;a=i.setTimeout.call(void 0,()=>{if(r){try{m(r())}catch(f){E(f)}return}typeof s.cancel=="function"&&s.cancel(),n===!1?m():n instanceof Error?E(n):(y.message=n??`Promise timed out after ${t} milliseconds`,E(y))},t)}).finally(()=>{p.clear(),c&&o&&o.removeEventListener("abort",c)});return p.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},p}var Hf=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 Wf(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(),c=[],{addListener:u,removeListener:p}=Hf(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}c.push(f),t.count===c.length&&(r(),i(c))},E=(...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,E)};for(let y of a)u(y,m);for(let y of t.rejectionEvents)a.includes(y)||u(y,E);t.signal&&t.signal.addEventListener("abort",()=>{E(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(n.cancel=r,typeof t.timeout=="number"){let i=ji(n,{milliseconds:t.timeout});return i.cancel=()=>{r(),i.clear()},i}return n}function ll(s,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let r=Wf(s,e,t),n=r.then(i=>i[0]);return n.cancel=r.cancel,n}function Vf(s){return s?.addEventListener!=null}function $f(s){let e=Nt(),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 c=a();for(;;){t=Promise.withResolvers();let{done:u,value:p}=await Promise.race([c.next(),t.promise]);if(s.writeStatus==="closing"||s.writeStatus==="closed"||(p!=null&&(s.send(p)||await Promise.race([ll(s,"drain",{rejectionEvents:["close"]})])),u===!0))break}await s.close()}}}function ul(...s){let e=s.map(t=>Vf(t)?$f(t):t);return Us(...e)}var Gr=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(as.single(e))}pushPrefixed(e){this.rawStream.send(e)}async close(e){await this.rawStream.close(e).catch(t=>{this.rawStream.abort(t)})}},Hr=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=ul(this.rawStream,r=>Ns(r,t))}async close(){this.closeController.abort()}};var Wr=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!==Te.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 hl=Y("libp2p-pubsub:"),jf=BigInt(Date.now())*1000000n;function Zf(){let s=++jf,e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,s,!1),e}async function fl(s,e,t,r){switch(s.type){case vt.Signing:{let n={from:s.author.toMultihash().bytes,data:r,seqno:Zf(),topic:e,signature:void 0,key:void 0},i=It([hl,ct.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${j(n.seqno??new Uint8Array(0),"base16")}`),topic:e,signature:n.signature,key:Ui(n.key)};return{raw:n,msg:o}}case vt.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 dl(s,e){switch(s){case Ut:return e.signature!=null?{valid:!1,error:me.SignaturePresent}:e.seqno!=null?{valid:!1,error:me.SeqnoPresent}:e.from!=null||e.key!=null?{valid:!1,error:me.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case Et:{if(e.seqno==null)return{valid:!1,error:me.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:me.InvalidSeqno};if(e.signature==null)return{valid:!1,error:me.InvalidSignature};if(e.from==null)return{valid:!1,error:me.InvalidPeerId};let t;try{t=is(et(e.from))}catch{return{valid:!1,error:me.InvalidPeerId}}let r;if(e.key!=null){try{r=Ui(e.key)}catch{return{valid:!1,error:me.InvalidPeerId}}if(!t.equals(r.toMultihash().bytes))return{valid:!1,error:me.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:me.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=It([hl,ct.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${j(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:r}}:{valid:!1,error:me.InvalidSignature}}default:throw new Error("Unreachable")}}function Ve(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 Zi(s){return s.control===void 0&&(s.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),s}function Je(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 pl(s){return j(s,"base64")}function ml(s,e,t){switch(s){case Et:return{type:vt.Signing,author:e,key:je(t.publicKey),privateKey:t};case Ut:return{type:vt.Anonymous};default:throw new Error(`Unknown signature policy "${s}"`)}}var Yf=(s,e)=>{let t=Y(e.toString(16).padStart(16,"0"),"base16"),r=je(s),n=new Uint8Array(r.byteLength+t.length);return n.set(r,0),n.set(t,r.byteLength),n};function gl(s){if(s.type!=="signed")throw new Error("expected signed message type");if(s.sequenceNumber==null)throw Error("missing seqno field");return Yf(s.from.publicKey??s.key,s.sequenceNumber)}async function bl(s){return Tt.encode(s.data)}function yl(s){if(al(s)){let e=ol(s);switch(e.type){case"ip4":case"ip6":return e.host;default:break}}return null}var fs=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 Le;(function(s){s[s.started=0]="started",s[s.stopped=1]="stopped"})(Le||(Le={}));var Vr=class extends Ws{globalSignaturePolicy;protocols=[...qs].reverse();publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=Nt({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=Kt;opts;decodeRpcLimits;metrics;status={code:Le.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:Qi,Dlo:eo,Dhi:to,Dscore:so,Dout:ro,Dlazy:oo,heartbeatInterval:lo,fanoutTTL:uo,mcacheLength:no,mcacheGossip:io,seenTTL:_o,gossipsubIWantFollowupMs:So,prunePeers:ho,pruneBackoff:fo,unsubcribeBackoff:po,graftFloodThreshold:xo,opportunisticGraftPeers:wo,opportunisticGraftTicks:yo,directConnectTicks:go,gossipFactor:ao,idontwantMinDataSize:Ro,idontwantMaxMessages:Lo,...t,scoreParams:Xc(t.scoreParams),scoreThresholds:Qc(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=r.decodeRpcLimits??$c,this.globalSignaturePolicy=r.globalSignaturePolicy??Et,r.fallbackToFloodsub&&this.protocols.push(jr),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 fs({validityMs:r.seenTTL}),this.publishedMessageIds=new fs({validityMs:r.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case Et:this.msgIdFn=gl;break;case Ut:this.msgIdFn=bl;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new fs({validityMs:r.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??pl,this.mcache=t.messageCache??new Nr(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),Bo),i=Yc(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 Wr(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new qr(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??Co}[Symbol.toStringTag]="@libp2p/gossipsub";[Uo]=["@libp2p/pubsub"];[Ko]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===Le.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=ml(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=Nt({objectMode:!0}),Us(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,Yr);this.status={code:Le.started,registrarTopologyIds:r,heartbeatTimeout:n,hearbeatStartMs:Date.now()+Yr},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)})},bo),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!==Le.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:Le.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 Gr(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===jr&&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 Hr(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=yl(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,We.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===Le.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)??Ot(r))}getTopics(){return Array.from(this.subscriptions)}decodeRpc(e){return ct.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 Us(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,c=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&&(c=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${r} messages ${n} ihave ${i} iwant ${o} graft ${a} prune ${c}`),t.subscriptions!=null&&t.subscriptions.length>0){let u=[],p=e.toString(),m=[];t.subscriptions.forEach(E=>{let y=E.topic,f=E.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+Oo;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 we.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 we.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 we.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:we.duplicate,msgIdStr:n};let i=await dl(this.globalSignaturePolicy,t);if(!i.valid)return{code:we.invalid,reason:Te.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:we.invalid,reason:Te.Error,error:me.TransformFailed}}let a=await this.msgIdFn(o),c=this.msgIdToStrFn(a),u={msgId:a,msgIdStr:c};if(r!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(r,c)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(c))return{code:we.duplicate,msgIdStr:c};this.seenCache.put(c),(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(E){let y=E.code;y===Do&&(m=xe.Ignore),y===To?m=xe.Reject:m=xe.Ignore}if(m!==xe.Accept)return{code:we.invalid,reason:Wi(m),msgIdStr:c}}return{code:we.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,Ve(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<Mo&&r.acceptUntil>=t)return r.messagesAccepted+=1,!0;let n=this.score.score(e);return n>=Ao?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+Po}):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:hs.LowScore}),[];let n=(this.peerhave.get(e)??0)+1;if(this.peerhave.set(e,n),n>vo)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:hs.MaxIhave}),[];let i=this.iasked.get(e)??0;if(i>=Qe)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,i),this.metrics?.ihaveRcvIgnored.inc({reason:hs.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 E=0;for(let y of m){if(a>=Qe)break e;a++;let f=this.msgIdToStrFn(y);this.seenCache.has(f)||(o.set(f,y),E++)}this.metrics?.onIhaveRcv(p,m.length,E)}if(o.size===0)return[];let c=o.size;c+i>Qe&&(c=Qe-i),this.log("IHAVE: Asking for %d out of %d messages from %s",c,o.size,e);let u=Array.from(o.values());return Je(u),u=u.slice(0,c),this.iasked.set(e,i+c),[{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>Eo)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,c=0;e:for(let{messageIDs:u}of t)if(u!=null)for(let p of u){if(c>=Qe)break e;c++;let m=this.msgIdToStrFn(p),E=this.mcache.getWithIWantCount(m,e);if(E==null){a++;continue}if(this.idontwants.get(e)?.has(m)===!0){this.metrics?.onIdontwantSkippedSend(Ks.iwant);continue}if(o.set(E.msg.topic,1+(o.get(E.msg.topic)??0)),E.count>co){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,p);continue}i.set(m,E.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:c})=>{if(c==null)return;let u=this.mesh.get(c);if(u==null){o=!1;return}if(u.has(e))return;let p=this.backoff.get(c)?.get(e);if(this.direct.has(e))this.log("GRAFT: ignoring request from direct peer %s",e),r.push(c),o=!1;else if(typeof p=="number"&&i<p){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,us.GraftBackoff),o=!1;let m=p+this.opts.graftFloodThreshold-this.opts.pruneBackoff;i<m&&this.score.addPenalty(e,1,us.GraftBackoff),this.addBackoff(e,c),r.push(c)}else n<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,n,c),r.push(c),o=!1,this.addBackoff(e,c)):u.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(r.push(c),this.addBackoff(e,c)):(this.log("GRAFT: Add mesh link from %s in %s",e,c),this.addToMesh(e,c,ve.Subscribed));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:c,direction:"inbound"}})}),r.length===0)return[];let a=!1;return Promise.all(r.map(async c=>this.makePrune(e,c,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,We.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:c}of t)for(let u of c){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,us.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%mo!==0)return;let e=Date.now();this.backoff.forEach((t,r)=>{t.forEach((n,i)=>{n+ko*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&&(Je(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async r=>{if(r.peerID==null)return;let n=is(et(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=Ot(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!==Le.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!==Le.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!==Le.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,ve.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,ve.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!==Le.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,t){let r=new Set,n={direct:0,floodsub:0,mesh:0,fanout:0},i=this.topics.get(e);if(i!=null)if(t??this.opts.floodPublish)i.forEach(o=>{this.direct.has(o)?(r.add(o),n.direct++):this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(r.add(o),n.floodsub++)});else{this.direct.forEach(a=>{i.has(a)&&(r.add(a),n.direct++)}),this.floodsubPeers.forEach(a=>{i.has(a)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&(r.add(a),n.floodsub++)});let o=this.mesh.get(e);if(o!=null&&o.size>0)o.forEach(a=>{r.add(a),n.mesh++}),o.size<this.opts.D&&this.getRandomGossipPeers(e,this.opts.D-o.size,c=>!o.has(c)&&!this.direct.has(c)&&!this.floodsubPeers.has(c)&&this.score.score(c)>=this.opts.scoreThresholds.publishThreshold).forEach(c=>{r.add(c),n.mesh++});else{let a=this.fanout.get(e);if(a!=null&&a.size>0)a.forEach(c=>{r.add(c),n.fanout++});else{let c=this.getRandomGossipPeers(e,this.opts.D,u=>this.score.score(u)>=this.opts.scoreThresholds.publishThreshold);c.size>0&&(this.fanout.set(e,c),c.forEach(u=>{r.add(u),n.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:r,tosendCount:n}}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=>{if(this.idontwants.get(o)?.has(e)===!0){i.delete(o),this.metrics?.onIdontwantSkippedSend(Ks.forward);return}this.sendRpc(o,Ve([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 fl(this.publishConfig,e,t,i),c=await this.msgIdFn(a),u=this.msgIdToStrFn(c),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:E}=this.selectPeersToPublish(e,r?.floodPublish),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:c,msgIdStr:u},o,!0),this.gossipTracer.deliverMessage(u),this.publishedMessageIds.put(u);let g=r?.batchPublish??this.opts.batchPublish,w=Ve([o]);if(g)this.sendRpcInBatch(m,w);else for(let _ of m)this.sendRpc(_,w)||m.delete(_);let S=Date.now()-n;return this.metrics?.onPublishMsg(e,E,m.size,o.data!=null?o.data.length:0,S),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(_=>this.peers.get(_)??Ot(_))}}sendRpcInBatch(e,t){let r=ct.encode(t),n=as.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===xe.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=Wi(r),{message:a,originatingPeers:c}=n;this.score.rejectMessage(t,e,a.topic,o);for(let u of c)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=Ve([],{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,ve.Subscribed),!0)}async sendPrune(e,t){let n=[await this.makePrune(e,t,this.opts.doPX,!0)],i=Ve([],{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)Zr(this.streamsOutbound.get(a)?.protocol,St.IDontWant)||i.delete(a);let o=Ve([],{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=ct.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=Zi(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=Zi(t);n.control.ihave=r}async sendGraftPrune(e,t,r){let n=this.opts.doPX,i=!1;for(let[o,a]of e){let c=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,Ve([],{graft:c,prune:u}))}for(let[o,a]of t){let c=await Promise.all(a.map(async u=>this.makePrune(o,u,n&&!(r.get(o)??!1),i)));this.sendRpc(o,Ve([],{prune:c}))}}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||(Je(r),r.length>Qe&&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=Je(Array.from(a)).slice(0,n),a.forEach(c=>{let u=r;r.length>Qe&&(u=Je(u.slice()).slice(0,Qe)),this.pushGossip(c,{topicID:e,messageIDs:u})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,Ve([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let r=Ve([],{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),!Zr(this.streamsOutbound.get(e)?.protocol,St.Backoff))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),c=await Promise.all(Array.from(a).map(async u=>{let p=this.peers.get(u)??Ot(u),m;try{m=await this.components.peerStore.get(p)}catch(E){if(E.name!=="NotFoundError")throw E}return{peerID:p.toMultihash().bytes,signedPeerRecord:m?.peerRecordEnvelope}}));return{topicID:t,peers:c,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===Le.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,c=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 E=new Map;this.mesh.forEach((f,g)=>{let w=this.topics.get(g),S=new Set,_=new Set;if(E.set(g,_),w!=null){let d=Je(Array.from(w)),b=this.backoff.get(g);for(let v of d){let I=this.streamsOutbound.get(v);if(I!=null&&this.protocols.includes(I.protocol)&&!f.has(v)&&!this.direct.has(v)){let D=c(v);b?.has(v)!==!0&&D>=0&&S.add(v),D>=this.opts.scoreThresholds.gossipThreshold&&_.add(v)}}}let l=(d,b)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",d,g),this.addBackoff(d,g),f.delete(d),c(d)>=this.opts.scoreThresholds.gossipThreshold&&_.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),_.delete(d);let v=u.get(d);v==null?u.set(d,[g]):v.push(g)};if(f.forEach(d=>{let b=c(d);b<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",d,b,g),l(d,We.BadScore),m.set(d,!0))}),f.size<t){let d=e-f.size;el(S,d).forEach(v=>{h(v,ve.NotEnough)})}if(f.size>r){let d=Array.from(f);d.sort((v,I)=>c(I)-c(v)),d=d.slice(0,n).concat(Je(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 M=d[D];for(let U=D;U>0;U--)d[U]=d[U-1];d[0]=M};if(b>0){let D=b;for(let M=1;M<e&&D>0;M++)(this.outbound.get(d[M])??!1)&&(v(M),D--)}let I=e-b;for(let D=e;D<d.length&&I>0;D++)(this.outbound.get(d[D])??!1)&&(v(D),I--)}d.slice(e).forEach(v=>{l(v,We.Excess)})}if(f.size>=t){let d=0;if(f.forEach(b=>{(this.outbound.get(b)??!1)&&d++}),d<i){let b=i-d;Kr(S,b,I=>this.outbound.get(I)===!0).forEach(I=>{h(I,ve.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&f.size>1){let d=Array.from(f).sort((I,D)=>c(I)-c(D)),b=Math.floor(f.size/2),v=c(d[b]);if(v<this.opts.scoreThresholds.opportunisticGraftThreshold){let I=this.opts.opportunisticGraftPeers,D=Kr(S,I,M=>c(M)>v);for(let M of D)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",M,g),h(M,ve.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)||c(h)<this.opts.scoreThresholds.publishThreshold)&&f.delete(h)});let S=this.topics.get(g),_=[],l=new Set;if(E.set(g,l),S!=null){let h=Je(Array.from(S));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=c(d);v>=this.opts.scoreThresholds.publishThreshold&&_.push(d),v>=this.opts.scoreThresholds.gossipThreshold&&l.add(d)}}}if(f.size<e){let h=e-f.size;_.slice(0,h).forEach(d=>{f.add(d),l?.delete(d)})}}),this.emitGossip(E),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=Je(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 c of this.backoff.values()){t+=c.size;for(let[u,p]of c.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 c of this.idontwants.values())n+=c.size;e.cacheSize.set({cache:"idontwants"},n);for(let[c,u]of this.topics)e.topicPeersCount.set({topicStr:c},u.size);for(let[c,u]of this.mesh)e.meshPeerCounts.set({topicStr:c},u.size);let i=[],o=new Map;e.behaviourPenalty.reset();for(let c of this.peers.keys()){let u=this.score.score(c);i.push(u),o.set(c,u),e.behaviourPenalty.observe(this.score.peerStats.get(c)?.behaviourPenalty??0)}e.registerScores(i,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,o);let a=il(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)??Ot(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)??Ot(t),{tags:{[r]:void 0}}).catch(n=>{this.log.error("Error untagging peer %s with topic %s",t,r,n)})}};var Et="StrictSign",Ut="StrictNoSign",xe;(function(s){s.Accept="accept",s.Ignore="ignore",s.Reject="reject"})(xe||(xe={}));var Xf=Kt;function Jf(s={}){return e=>new Vr(e,s)}return Ml(Qf);})();
3
3
  /*! Bundled license information:
4
4
 
5
5
  @noble/curves/utils.js: