@libp2p/gossipsub 16.1.1 → 17.0.0-4dae661b4

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 Mc=Object.create;var Vs=Object.defineProperty;var Pc=Object.getOwnPropertyDescriptor;var kc=Object.getOwnPropertyNames;var Bc=Object.getPrototypeOf,Rc=Object.prototype.hasOwnProperty;var Lc=(s,e)=>()=>{try{return e||s((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Ie=(s,e)=>{for(var t in e)Vs(s,t,{get:e[t],enumerable:!0})},ji=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of kc(e))!Rc.call(s,n)&&n!==t&&Vs(s,n,{get:()=>e[n],enumerable:!(r=Pc(e,n))||r.enumerable});return s};var Cc=(s,e,t)=>(t=s!=null?Mc(Bc(s)):{},ji(e||!s||!s.__esModule?Vs(t,"default",{value:s,enumerable:!0}):t,s)),Fc=s=>ji(Vs({},"__esModule",{value:!0}),s);var fc=Lc((Rb,hc)=>{"use strict";function Z(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))}Z.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]}};Z.prototype.get=function(e){return this.peekAt(e)};Z.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};Z.prototype.peekFront=function(){return this.peek()};Z.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(Z.prototype,"length",{get:function(){return this.size()}});Z.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};Z.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)};Z.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}};Z.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)};Z.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}};Z.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}}};Z.prototype.remove=function(e,t){var r=e,n,i=t;if(r===(r|0)&&this._head!==this._tail){var o=this.size(),a=this._list.length;if(!(r>=o||r<-o||t<1)){if(r<0&&(r+=o),t===1||!t)return n=new Array(1),n[0]=this.removeOne(r),n;if(r===0&&r+t>=o)return n=this.toArray(),this.clear(),n;r+t>o&&(t=o-r);var l;for(n=new Array(t),l=0;l<t;l++)n[l]=this._list[this._head+r+l&this._capacityMask];if(r=this._head+r&this._capacityMask,e+t===o){for(this._tail=this._tail-t+a&this._capacityMask,l=t;l>0;l--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(e===0){for(this._head=this._head+t+a&this._capacityMask,l=t-1;l>0;l--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(r<o/2){for(this._head=this._head+e+t+a&this._capacityMask,l=e;l>0;l--)this.unshift(this._list[r=r-1+a&this._capacityMask]);for(r=this._head-1+a&this._capacityMask;i>0;)this._list[r=r-1+a&this._capacityMask]=void 0,i--;e<0&&(this._tail=r)}else{for(this._tail=r,r=r+t+a&this._capacityMask,l=o-(t+e);l>0;l--)this.push(this._list[r++]);for(r=this._tail;i>0;)this._list[r=r+1+a&this._capacityMask]=void 0,i--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),n}}};Z.prototype.splice=function(e,t){var r=e;if(r===(r|0)){var n=this.size();if(r<0&&(r+=n),!(r>n))if(arguments.length>2){var i,o,a,l=arguments.length,u=this._list.length,d=2;if(!n||r<n/2){for(o=new Array(r),i=0;i<r;i++)o[i]=this._list[this._head+i&this._capacityMask];for(t===0?(a=[],r>0&&(this._head=this._head+r+u&this._capacityMask)):(a=this.remove(r,t),this._head=this._head+r+u&this._capacityMask);l>d;)this.unshift(arguments[--l]);for(i=r;i>0;i--)this.unshift(o[i-1])}else{o=new Array(n-(r+t));var m=o.length;for(i=0;i<m;i++)o[i]=this._list[this._head+r+t+i&this._capacityMask];for(t===0?(a=[],r!=n&&(this._tail=this._head+r+u&this._capacityMask)):(a=this.remove(r,t),this._tail=this._tail-m+u&this._capacityMask);d<l;)this.push(arguments[d++]);for(i=0;i<m;i++)this.push(o[i])}return a}else return this.remove(r,t)}};Z.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0};Z.prototype.isEmpty=function(){return this._head===this._tail};Z.prototype.toArray=function(){return this._copyArray(!1)};Z.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]};Z.prototype._copyArray=function(e,t){var r=this._list,n=r.length,i=this.length;if(t=t|i,t==i&&this._head<this._tail)return this._list.slice(this._head,this._tail);var o=new Array(t),a=0,l;if(e||this._head>this._tail){for(l=this._head;l<n;l++)o[a++]=r[l];for(l=0;l<this._tail;l++)o[a++]=r[l]}else for(l=this._head;l<this._tail;l++)o[a++]=r[l];return o};Z.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};Z.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1};Z.prototype._nextPowerOf2=function(e){var t=Math.log(e)/Math.log(2),r=1<<t+1;return Math.max(r,4)};hc.exports=Z});var Ef={};Ie(Ef,{StrictNoSign:()=>Ot,StrictSign:()=>vt,TopicValidatorResult:()=>ge,gossipsub:()=>vf,multicodec:()=>xf});var Gr="/floodsub/1.0.0",qr="/meshsub/1.0.0",Zi="/meshsub/1.1.0",Kt="/meshsub/1.2.0";var Yi="ERR_TOPIC_VALIDATOR_REJECT",Xi="ERR_TOPIC_VALIDATOR_IGNORE";var Y=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 Ws=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},$s=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Ht=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Vr=Symbol.for("@libp2p/peer-id");function Nc(s){return typeof s?.handleEvent=="function"}function Oc(s){return(s!==!0&&s!==!1&&s?.once)??!1}var js=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=Oc(r);super.addEventListener(e,o=>{if(n){let a=this.#e.get(o.type);a!=null&&(a=a.filter(({callback:l})=>l!==t),this.#e.set(o.type,a))}Nc(t)?t.handleEvent(o):t(o)},r);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:t,once:n})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),t??null,r);let n=this.#e.get(e);n!=null&&(n=n.filter(({callback:i})=>i!==t),this.#e.set(e,n))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Qi=Symbol.for("@libp2p/service-capabilities"),eo=Symbol.for("@libp2p/service-dependencies");var Yr={};Ie(Yr,{base58btc:()=>J,base58flickr:()=>Wc});var Jf=new Uint8Array(0);function so(s,e){if(s===e)return!0;if(s.byteLength!==e.byteLength)return!1;for(let t=0;t<s.byteLength;t++)if(s[t]!==e[t])return!1;return!0}function ke(s){if(s instanceof Uint8Array&&s.constructor.name==="Uint8Array")return St(s);if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return St(new Uint8Array(s.buffer,s.byteOffset,s.byteLength));throw new Error("Unknown type, must be binary type")}function ro(s){let e=new Uint8Array(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}var to=4096;function no(s){let e=s.length;if(e<=to)return String.fromCharCode.apply(String,s);let t="",r=0;for(;r<e;)t+=String.fromCharCode.apply(String,s.subarray(r,r+=to));return t}function Uc(s){return s?.buffer instanceof ArrayBuffer}function St(s){return Uc(s)?s:s.slice()}function Kc(s,e,t){if(s.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<s.length;i++){var o=s.charAt(i),a=o.charCodeAt(0);if(r[a]!==255)throw new TypeError(o+" is ambiguous");if(r[a]=i,t){var l=o.toLowerCase().charCodeAt(0),u=o.toUpperCase().charCodeAt(0);l!==a&&(r[l]=i),u!==a&&(r[u]=i)}}var d=s.length,m=s.charAt(0),E=Math.log(d)/Math.log(256),y=Math.log(256)/Math.log(d);function f(x){if(x instanceof Uint8Array||(ArrayBuffer.isView(x)?x=new Uint8Array(x.buffer,x.byteOffset,x.byteLength):Array.isArray(x)&&(x=Uint8Array.from(x))),!(x instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(x.length===0)return"";for(var I=0,c=0,h=0,p=x.length;h!==p&&x[h]===0;)h++,I++;for(var w=(p-h)*y+1>>>0,v=new Uint8Array(w);h!==p;){for(var S=x[h],M=0,R=w-1;(S!==0||M<c)&&R!==-1;R--,M++)S+=256*v[R]>>>0,v[R]=S%d>>>0,S=S/d>>>0;if(S!==0)throw new Error("Non-zero carry");c=M,h++}for(var F=w-c;F!==w&&v[F]===0;)F++;for(var _=m.repeat(I);F<w;++F)_+=s.charAt(v[F]);return _}function b(x){if(typeof x!="string")throw new TypeError("Expected String");if(x.length===0)return new Uint8Array;var I=0;if(x[I]!==" "){for(var c=0,h=0;x[I]===m;)c++,I++;for(var p=(x.length-I)*E+1>>>0,w=new Uint8Array(p);x[I];){var v=r[x.charCodeAt(I)];if(v===255)return;for(var S=0,M=p-1;(v!==0||S<h)&&M!==-1;M--,S++)v+=d*w[M]>>>0,w[M]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");h=S,I++}if(x[I]!==" "){for(var R=p-h;R!==p&&w[R]===0;)R++;for(var F=new Uint8Array(c+(p-R)),_=c;R!==p;)F[_++]=w[R++];return F}}}function g(x){var I=b(x);if(I)return I;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:b,decode:g}}var zc=Kc,Hc=zc,oo=Hc;var Wr=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")}},$r=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,r){this.name=e,this.prefix=t;let n=t.codePointAt(0);if(n===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ao(this,e)}},jr=class{decoders;constructor(e){this.decoders=e}or(e){return ao(this,e)}decode(e){let t=e[0],r=this.decoders[t];if(r!=null)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ao(s,e){return new jr({...s.decoders??{[s.prefix]:s},...e.decoders??{[e.prefix]:e}})}var Zr=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 Wr(e,t,r),this.decoder=new $r(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 Zr(s,e,t,r)}function at({name:s,prefix:e,alphabet:t,caseInsensitive:r=!1}){let{encode:n,decode:i}=oo(t,s,r);return Gt({prefix:e,name:s,encode:n,decode:o=>ke(i(o))})}function Gc(s,e,t,r){let n=s.length;for(;s[n-1]==="=";)--n;let i=new Uint8Array(n*t/8|0),o=0,a=0,l=0;for(let u=0;u<n;++u){let d=e[s[u]];if(d===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<t|d,o+=t,o>=8&&(o-=8,i[l++]=255&a>>o)}if(o>=t||(255&a<<8-o)!==0)throw new SyntaxError("Unexpected end of data");return i}function qc(s,e,t){let r=e[e.length-1]==="=",n=(1<<t)-1,i="",o=0,a=0;for(let l=0;l<s.length;++l)for(a=a<<8|s[l],o+=8;o>t;)o-=t,i+=e[n&a>>o];if(o!==0&&(i+=e[n&a<<t-o]),r)for(;(i.length*t&7)!==0;)i+="=";return i}function Vc(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 X({name:s,prefix:e,bitsPerChar:t,alphabet:r,caseInsensitive:n=!1}){let i=Vc(r,n);return Gt({prefix:e,name:s,encode(o){return qc(o,r,t)},decode(o){return Gc(o,i,t,s)}})}var J=at({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Wc=at({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Xr={};Ie(Xr,{base32:()=>qt,base32hex:()=>Yc,base32hexpad:()=>Jc,base32hexpadupper:()=>Qc,base32hexupper:()=>Xc,base32pad:()=>jc,base32padupper:()=>Zc,base32upper:()=>$c,base32z:()=>el});var qt=X({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),$c=X({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),jc=X({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),Zc=X({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),Yc=X({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),Xc=X({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),Jc=X({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),Qc=X({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),el=X({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Jr={};Ie(Jr,{base36:()=>gs,base36upper:()=>tl});var gs=at({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),tl=at({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var sl=uo,co=128,rl=127,nl=~rl,il=Math.pow(2,31);function uo(s,e,t){e=e||[],t=t||0;for(var r=t;s>=il;)e[t++]=s&255|co,s/=128;for(;s&nl;)e[t++]=s&255|co,s>>>=7;return e[t]=s|0,uo.bytes=t-r+1,e}var ol=Qr,al=128,lo=127;function Qr(s,r){var t=0,r=r||0,n=0,i=r,o,a=s.length;do{if(i>=a)throw Qr.bytes=0,new RangeError("Could not decode varint");o=s[i++],t+=n<28?(o&lo)<<n:(o&lo)*Math.pow(2,n),n+=7}while(o>=al);return Qr.bytes=i-r,t}var cl=Math.pow(2,7),ll=Math.pow(2,14),ul=Math.pow(2,21),hl=Math.pow(2,28),fl=Math.pow(2,35),dl=Math.pow(2,42),pl=Math.pow(2,49),ml=Math.pow(2,56),gl=Math.pow(2,63),bl=function(s){return s<cl?1:s<ll?2:s<ul?3:s<hl?4:s<fl?5:s<dl?6:s<pl?7:s<ml?8:s<gl?9:10},yl={encode:sl,decode:ol,encodingLength:bl},wl=yl,bs=wl;function ys(s,e=0){let t=bs.decode(s,e),r=bs.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 Vt(s,e,t=0){return bs.encode(s,e,t),e}function Wt(s){return bs.encodingLength(s)}function qe(s,e){let t=e.byteLength,r=Wt(s),n=r+Wt(t),i=new Uint8Array(n+t);return Vt(s,i,0),Vt(t,i,r),i.set(e,n),new $t(s,t,e,i)}function Xe(s){let e=ke(s),[t,r]=ys(e),[n,i]=ys(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 ho(s,e){if(s===e)return!0;{let t=e;return s.code===t.code&&s.size===t.size&&t.bytes instanceof Uint8Array&&so(s.bytes,t.bytes)}}var $t=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=St(r),this.bytes=St(n)}};function fo(s,e){let{bytes:t,version:r}=s;return r===0?vl(t,en(s),e??J.encoder):El(t,en(s),e??qt.encoder)}var po=new WeakMap;function en(s){let e=po.get(s);if(e==null){let t=new Map;return po.set(s,t),t}return e}var ce=class s{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=St(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!==ws)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Sl)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=qe(e,t);return s.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return s.equals(this,e)}static equals(e,t){let r=t;return r!=null&&e.code===r.code&&e.version===r.version&&ho(e.multihash,r.multihash)}toString(e){return fo(this,e)}toJSON(){return{"/":fo(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof s)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:r,code:n,multihash:i,bytes:o}=t;return new s(r,n,i,o??mo(r,n,i.bytes))}else if(t[_l]===!0){let{version:r,multihash:n,code:i}=t,o=Xe(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!==ws)throw new Error(`Version 0 CID must use dag-pb (code: ${ws}) block encoding`);return new s(e,t,r,r.bytes)}case 1:{let n=mo(e,t,r.bytes);return new s(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return s.create(0,ws,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=ke(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]=ys(e.subarray(t));return t+=E,m},n=r(),i=ws;if(n===18?(n=0,t=0):i=r(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let o=t,a=r(),l=r(),u=t+l,d=u-o;return{version:n,codec:i,multihashCode:a,digestSize:l,multihashSize:d,size:u}}static parse(e,t){let[r,n]=xl(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 en(i).set(r,e),i}};function xl(s,e){switch(s[0]){case"Q":{let t=e??J;return[J.prefix,t.decode(`${J.prefix}${s}`)]}case J.prefix:{let t=e??J;return[J.prefix,t.decode(s)]}case qt.prefix:{let t=e??qt;return[qt.prefix,t.decode(s)]}case gs.prefix:{let t=e??gs;return[gs.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 vl(s,e,t){let{prefix:r}=t;if(r!==J.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 El(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 ws=112,Sl=18;function mo(s,e,t){let r=Wt(s),n=r+Wt(e),i=new Uint8Array(n+t.byteLength);return Vt(s,i,0),Vt(e,i,r),i.set(t,n),i}var _l=Symbol.for("@ipld/js-cid/CID");var tn={};Ie(tn,{identity:()=>Ce});var go=0,Il="identity",bo=ke;function Tl(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 qe(go,bo(s))}var Ce={code:go,name:Il,encode:bo,digest:Tl};function Te(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 Dl(s){return s.buffer instanceof ArrayBuffer}function Be(s){return Dl(s)?s:s.slice()}async function yo(s,e,t,r){let n=await crypto.subtle.importKey("jwk",s,{name:"ECDSA",namedCurve:s.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();let i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,Be(e),Be(t.subarray()));return r?.signal?.throwIfAborted(),i}function Je(s=0){return new Uint8Array(s)}function fe(s=0){return new Uint8Array(s)}function Al(s){return s?.buffer instanceof ArrayBuffer}function wo(s){if(Al(s))return s;let e=s.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function _t(s,e){e==null&&(e=s.reduce((n,i)=>n+i.length,0));let t=fe(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return wo(t)}var vo=Symbol.for("@achingbrain/uint8arraylist");function xo(s,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let r of s){let n=t+r.byteLength;if(e<n)return{buf:r,index:e-t};t=n}throw new RangeError("index is out of bounds")}function Ys(s){return!!s?.[vo]}var oe=class s{bufs;length;[vo]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else if(Ys(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(Ys(r))t+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=xo(this.bufs,e);return t.buf[t.index]}set(e,t){let r=xo(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(t+r,e[r]);else if(Ys(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 _t(r,n)}subarray(e,t){let{bufs:r,length:n}=this._subList(e,t);return r.length===1?r[0]:_t(r,n)}sublist(e,t){let{bufs:r,length:n}=this._subList(e,t),i=new s;return i.length=n,i.bufs=r,i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let r=[],n=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],a=n,l=a+o.byteLength;if(n=l,e>=l)continue;let u=e>=a&&e<l,d=t>a&&t<=l;if(u&&d){if(e===a&&t===l){r.push(o);break}let m=e-a;r.push(o.subarray(m,m+(t-e)));break}if(u){if(e===0){r.push(o);continue}r.push(o.subarray(e-a));continue}if(d){if(t===l){r.push(o);break}r.push(o.subarray(0,t-a));break}r.push(o)}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!Ys(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let r=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let n=r.byteLength;if(n===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let m=0;m<i;m++)o[m]=-1;for(let m=0;m<n;m++)o[r[m]]=m;let a=o,l=this.byteLength-r.byteLength,u=r.byteLength-1,d;for(let m=t;m<=l;m+=d){d=0;for(let E=u;E>=0;E--){let y=this.get(m+E);if(r[E]!==y){d=Math.max(1,E-a[y]);break}}if(d===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=fe(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=Je(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=Je(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=Je(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=fe(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=Je(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=Je(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=Je(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=Je(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=Je(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(!Te(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 sn={};Ie(sn,{base10:()=>Ml});var Ml=at({prefix:"9",name:"base10",alphabet:"0123456789"});var rn={};Ie(rn,{base16:()=>Pl,base16upper:()=>kl});var Pl=X({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),kl=X({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var nn={};Ie(nn,{base2:()=>Bl});var Bl=X({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var on={};Ie(on,{base256emoji:()=>Nl});var Eo=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Rl=Eo.reduce((s,e,t)=>(s[t]=e,s),[]),Ll=Eo.reduce((s,e,t)=>{let r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return s[r]=t,s},[]);function Cl(s){return s.reduce((e,t)=>(e+=Rl[t],e),"")}function Fl(s){let e=[];for(let t of s){let r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);let n=Ll[r];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Nl=Gt({prefix:"\u{1F680}",name:"base256emoji",encode:Cl,decode:Fl});var an={};Ie(an,{base64:()=>Ol,base64pad:()=>Ul,base64url:()=>Kl,base64urlpad:()=>zl});var Ol=X({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ul=X({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Kl=X({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zl=X({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var cn={};Ie(cn,{base8:()=>Hl});var Hl=X({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ln={};Ie(ln,{identity:()=>Gl});var Gl=Gt({prefix:"\0",name:"identity",encode:s=>no(ke(s)),decode:s=>ke(ro(s))});var Nd=new TextEncoder,Od=new TextDecoder;var fn={};Ie(fn,{sha256:()=>It,sha512:()=>$l});var Wl=20;function hn({name:s,code:e,encode:t,minDigestLength:r,maxDigestLength:n}){return new un(s,e,t,r,n)}var un=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,r,n,i){this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??Wl,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?So(r,this.code,t?.truncate):r.then(n=>So(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function So(s,e,t){if(t!=null&&t!==s.byteLength){if(t>s.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${s.byteLength}`);s=s.subarray(0,t)}return qe(e,s)}function Io(s){return async e=>new Uint8Array(await crypto.subtle.digest(s,e))}var It=hn({name:"sha2-256",code:18,encode:Io("SHA-256")}),$l=hn({name:"sha2-512",code:19,encode:Io("SHA-512")});var dn={...ln,...nn,...cn,...sn,...rn,...Xr,...Jr,...Yr,...an,...on},Yd={...fn,...tn};function Do(s,e,t,r){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:r}}}var To=Do("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),pn=Do("ascii","a",s=>{let e="a";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return e},s=>{s=s.substring(1);let e=fe(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),jl={utf8:To,"utf-8":To,hex:dn.base16,latin1:pn,ascii:pn,binary:pn,...dn},Xs=jl;function V(s,e="utf8"){let t=Xs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${s}`)}function q(s,e="utf8"){let t=Xs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(s).substring(1)}var Zl=parseInt("11111",2),mn=parseInt("10000000",2),Yl=parseInt("01111111",2),Ao={0:xs,1:xs,2:Xl,3:eu,4:tu,5:Ql,6:Jl,16:xs,22:xs,48:xs};function Qe(s,e={offset:0}){let t=s[e.offset]&Zl;if(e.offset++,Ao[t]!=null)return Ao[t](s,e);throw new Error("No decoder for tag "+t)}function vs(s,e){let t=0;if((s[e.offset]&mn)===mn){let r=s[e.offset]&Yl,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 xs(s,e){vs(s,e);let t=[];for(;!(e.offset>=s.byteLength);){let r=Qe(s,e);if(r===null)break;t.push(r)}return t}function Xl(s,e){let t=vs(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 Jl(s,e){let t=vs(s,e),r=e.offset+t,n=s[e.offset];e.offset++;let i=0,o=0;n<40?(i=0,o=n):n<80?(i=1,o=n-40):(i=2,o=n-80);let a=`${i}.${o}`,l=[];for(;e.offset<r;){let u=s[e.offset];if(e.offset++,l.push(u&127),u<128){l.reverse();let d=0;for(let m=0;m<l.length;m++)d+=l[m]<<m*7;a+=`.${d}`,l=[]}}return a}function Ql(s,e){return e.offset++,null}function eu(s,e){let t=vs(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 tu(s,e){let t=vs(s,e),r=s.subarray(e.offset,e.offset+t);return e.offset+=t,r}function su(s){let e=s.toString(16);e.length%2===1&&(e="0"+e);let t=new oe;for(let r=0;r<e.length;r+=2)t.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return t}function gn(s){if(s.byteLength<128)return Uint8Array.from([s.byteLength]);let e=su(s.byteLength);return new oe(Uint8Array.from([e.byteLength|mn]),e)}function De(s){let e=new oe,t=128;return(s.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(s),new oe(Uint8Array.from([2]),gn(e),e)}function Js(s){let e=Uint8Array.from([0]),t=new oe(e,s);return new oe(Uint8Array.from([3]),gn(t),t)}function lt(s,e=48){let t=new oe;for(let r of s)t.append(r);return new oe(Uint8Array.from([e]),gn(t),t)}var ru=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),nu=Uint8Array.from([6,5,43,129,4,0,34]),iu=Uint8Array.from([6,5,43,129,4,0,35]),ou={ext:!0,kty:"EC",crv:"P-256"},au={ext:!0,kty:"EC",crv:"P-384"},cu={ext:!0,kty:"EC",crv:"P-521"},bn=32,yn=48,wn=66;function xn(s){let e=Qe(s);return Mo(e)}function Mo(s){let e=s[1][1][0],t=1,r,n;if(e.byteLength===bn*2+1)return r=q(e.subarray(t,t+bn),"base64url"),n=q(e.subarray(t+bn),"base64url"),new jt({...ou,key_ops:["verify"],x:r,y:n});if(e.byteLength===yn*2+1)return r=q(e.subarray(t,t+yn),"base64url"),n=q(e.subarray(t+yn),"base64url"),new jt({...au,key_ops:["verify"],x:r,y:n});if(e.byteLength===wn*2+1)return r=q(e.subarray(t,t+wn),"base64url"),n=q(e.subarray(t+wn),"base64url"),new jt({...cu,key_ops:["verify"],x:r,y:n});throw new Y(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Po(s){return lt([De(Uint8Array.from([1])),lt([lu(s.crv)],160),lt([Js(new oe(Uint8Array.from([4]),V(s.x??"","base64url"),V(s.y??"","base64url")))],161)]).subarray()}function lu(s){if(s==="P-256")return ru;if(s==="P-384")return nu;if(s==="P-521")return iu;throw new Y(`Invalid curve ${s}`)}var jt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Po(this.jwk)),this._raw}toMultihash(){return Ce.digest(Ve(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Te(this.raw,e.raw)}async verify(e,t,r){return yo(this.jwk,t,e,r)}};function vn(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in s&&s.BYTES_PER_ELEMENT===1}function ut(s,e=""){if(typeof s!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof s}`)}if(!Number.isSafeInteger(s)||s<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${s}`)}}function Ae(s,e,t=""){let r=vn(s),n=s?.length,i=e!==void 0;if(!r||i&&n!==e){let o=t&&`"${t}" `,a=i?` of length ${e}`:"",l=r?`length=${n}`:`type=${typeof s}`,u=o+"expected Uint8Array"+a+", got "+l;throw r?new RangeError(u):new TypeError(u)}return s}function Qs(s){if(typeof s!="function"||typeof s.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(ut(s.outputLen),ut(s.blockLen),s.outputLen<1)throw new Error('"outputLen" must be >= 1');if(s.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Zt(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function er(s,e){Ae(s,void 0,"digestInto() output");let t=e.outputLen;if(s.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function tt(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function tr(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Fe(s,e){return s<<32-e|s>>>e}var Bo=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",uu=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function sr(s){if(Ae(s),Bo)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=uu[s[t]];return e}var et={_0:48,_9:57,A:65,F:70,a:97,f:102};function ko(s){if(s>=et._0&&s<=et._9)return s-et._0;if(s>=et.A&&s<=et.F)return s-(et.A-10);if(s>=et.a&&s<=et.f)return s-(et.a-10)}function Es(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);if(Bo)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=ko(s.charCodeAt(i)),a=ko(s.charCodeAt(i+1));if(o===void 0||a===void 0){let l=s[i]+s[i+1];throw new RangeError('hex string expected, got non-hex character "'+l+'" at index '+i)}r[n]=o*16+a}return r}function En(...s){let e=0;for(let r=0;r<s.length;r++){let n=s[r];Ae(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 Sn(s,e={}){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 Ro(s=32){ut(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 _n=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function Lo(s,e,t){return s&e^~s&t}function Co(s,e,t){return s&e^s&t^e&t}var Ss=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=tr(this.buffer)}update(e){Zt(this),Ae(e);let{view:t,buffer:r,blockLen:n}=this,i=e.length;for(let o=0;o<i;){let a=Math.min(n-this.pos,i-o);if(a===n){let l=tr(e);for(;n<=i-o;o+=n)this.process(l,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Zt(this),er(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,tt(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(r,0),o=0);for(let m=o;m<n;m++)t[m]=0;r.setBigUint64(n-8,BigInt(this.length*8),i),this.process(r,0);let a=tr(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=l/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let m=0;m<u;m++)a.setUint32(4*m,d[m],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}},st=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var le=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var rr=BigInt(4294967295),Fo=BigInt(32);function hu(s,e=!1){return e?{h:Number(s&rr),l:Number(s>>Fo&rr)}:{h:Number(s>>Fo&rr)|0,l:Number(s&rr)|0}}function No(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}=hu(s[i],e);[r[i],n[i]]=[o,a]}return[r,n]}var In=(s,e,t)=>s>>>t,Tn=(s,e,t)=>s<<32-t|e>>>t,Tt=(s,e,t)=>s>>>t|e<<32-t,Dt=(s,e,t)=>s<<32-t|e>>>t,_s=(s,e,t)=>s<<64-t|e>>>t-32,Is=(s,e,t)=>s>>>t-32|e<<64-t;function We(s,e,t,r){let n=(e>>>0)+(r>>>0);return{h:s+t+(n/2**32|0)|0,l:n|0}}var Oo=(s,e,t)=>(s>>>0)+(e>>>0)+(t>>>0),Uo=(s,e,t,r)=>e+t+r+(s/2**32|0)|0,Ko=(s,e,t,r)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0),zo=(s,e,t,r,n)=>e+t+r+n+(s/2**32|0)|0,Ho=(s,e,t,r,n)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Go=(s,e,t,r,n,i)=>e+t+r+n+i+(s/2**32|0)|0;var du=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]),ht=new Uint32Array(64),Dn=class extends Ss{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:n,E:i,F:o,G:a,H:l}=this;return[e,t,r,n,i,o,a,l]}set(e,t,r,n,i,o,a,l){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=l|0}process(e,t){for(let m=0;m<16;m++,t+=4)ht[m]=e.getUint32(t,!1);for(let m=16;m<64;m++){let E=ht[m-15],y=ht[m-2],f=Fe(E,7)^Fe(E,18)^E>>>3,b=Fe(y,17)^Fe(y,19)^y>>>10;ht[m]=b+ht[m-7]+f+ht[m-16]|0}let{A:r,B:n,C:i,D:o,E:a,F:l,G:u,H:d}=this;for(let m=0;m<64;m++){let E=Fe(a,6)^Fe(a,11)^Fe(a,25),y=d+E+Lo(a,l,u)+du[m]+ht[m]|0,b=(Fe(r,2)^Fe(r,13)^Fe(r,22))+Co(r,n,i)|0;d=u,u=l,l=a,a=o+y|0,o=i,i=n,n=r,r=y+b|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,l=l+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(r,n,i,o,a,l,u,d)}roundClean(){tt(ht)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),tt(this.buffer)}},An=class extends Dn{A=st[0]|0;B=st[1]|0;C=st[2]|0;D=st[3]|0;E=st[4]|0;F=st[5]|0;G=st[6]|0;H=st[7]|0;constructor(){super(32)}};var qo=No(["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))),pu=qo[0],mu=qo[1],ft=new Uint32Array(80),dt=new Uint32Array(80),Mn=class extends Ss{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:o,Dh:a,Dl:l,Eh:u,El:d,Fh:m,Fl:E,Gh:y,Gl:f,Hh:b,Hl:g}=this;return[e,t,r,n,i,o,a,l,u,d,m,E,y,f,b,g]}set(e,t,r,n,i,o,a,l,u,d,m,E,y,f,b,g){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=n|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=l|0,this.Eh=u|0,this.El=d|0,this.Fh=m|0,this.Fl=E|0,this.Gh=y|0,this.Gl=f|0,this.Hh=b|0,this.Hl=g|0}process(e,t){for(let c=0;c<16;c++,t+=4)ft[c]=e.getUint32(t),dt[c]=e.getUint32(t+=4);for(let c=16;c<80;c++){let h=ft[c-15]|0,p=dt[c-15]|0,w=Tt(h,p,1)^Tt(h,p,8)^In(h,p,7),v=Dt(h,p,1)^Dt(h,p,8)^Tn(h,p,7),S=ft[c-2]|0,M=dt[c-2]|0,R=Tt(S,M,19)^_s(S,M,61)^In(S,M,6),F=Dt(S,M,19)^Is(S,M,61)^Tn(S,M,6),_=Ko(v,F,dt[c-7],dt[c-16]),T=zo(_,w,R,ft[c-7],ft[c-16]);ft[c]=T|0,dt[c]=_|0}let{Ah:r,Al:n,Bh:i,Bl:o,Ch:a,Cl:l,Dh:u,Dl:d,Eh:m,El:E,Fh:y,Fl:f,Gh:b,Gl:g,Hh:x,Hl:I}=this;for(let c=0;c<80;c++){let h=Tt(m,E,14)^Tt(m,E,18)^_s(m,E,41),p=Dt(m,E,14)^Dt(m,E,18)^Is(m,E,41),w=m&y^~m&b,v=E&f^~E&g,S=Ho(I,p,v,mu[c],dt[c]),M=Go(S,x,h,w,pu[c],ft[c]),R=S|0,F=Tt(r,n,28)^_s(r,n,34)^_s(r,n,39),_=Dt(r,n,28)^Is(r,n,34)^Is(r,n,39),T=r&i^r&a^i&a,P=n&o^n&l^o&l;x=b|0,I=g|0,b=y|0,g=f|0,y=m|0,f=E|0,{h:m,l:E}=We(u|0,d|0,M|0,R|0),u=a|0,d=l|0,a=i|0,l=o|0,i=r|0,o=n|0;let A=Oo(R,_,P);r=Uo(A,M,F,T),n=A|0}({h:r,l:n}=We(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=We(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l}=We(this.Ch|0,this.Cl|0,a|0,l|0),{h:u,l:d}=We(this.Dh|0,this.Dl|0,u|0,d|0),{h:m,l:E}=We(this.Eh|0,this.El|0,m|0,E|0),{h:y,l:f}=We(this.Fh|0,this.Fl|0,y|0,f|0),{h:b,l:g}=We(this.Gh|0,this.Gl|0,b|0,g|0),{h:x,l:I}=We(this.Hh|0,this.Hl|0,x|0,I|0),this.set(r,n,i,o,a,l,u,d,m,E,y,f,b,g,x,I)}roundClean(){tt(ft,dt)}destroy(){this.destroyed=!0,tt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Pn=class extends Mn{Ah=le[0]|0;Al=le[1]|0;Bh=le[2]|0;Bl=le[3]|0;Ch=le[4]|0;Cl=le[5]|0;Dh=le[6]|0;Dl=le[7]|0;Eh=le[8]|0;El=le[9]|0;Fh=le[10]|0;Fl=le[11]|0;Gh=le[12]|0;Gl=le[13]|0;Hh=le[14]|0;Hl=le[15]|0;constructor(){super(64)}};var Yt=Sn(()=>new An,_n(1));var nr=Sn(()=>new Pn,_n(3));var K=(s,e,t)=>Ae(s,e,t),Bn=ut,Xt=sr,re=(...s)=>En(...s),Jt=s=>Es(s),At=vn,Ts=s=>Ro(s),or=BigInt(0),kn=BigInt(1);function Ne(s,e=""){if(typeof s!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof s)}return s}function ar(s){if(typeof s=="bigint"){if(!ir(s))throw new RangeError("positive bigint expected, got "+s)}else Bn(s);return s}function Oe(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 Ds(s){let e=ar(s).toString(16);return e.length&1?"0"+e:e}function Vo(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);return s===""?or:BigInt("0x"+s)}function Mt(s){return Vo(sr(s))}function $e(s){return Vo(sr(As(Ae(s)).reverse()))}function cr(s,e){if(ut(e),e===0)throw new RangeError("zero length");s=ar(s);let t=s.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Es(t.padStart(e*2,"0"))}function Rn(s,e){return cr(s,e).reverse()}function Wo(s,e){if(s=K(s),e=K(e),s.length!==e.length)return!1;let t=0;for(let r=0;r<s.length;r++)t|=s[r]^e[r];return t===0}function As(s){return Uint8Array.from(K(s))}function lr(s){if(typeof s!="string")throw new TypeError("ascii string expected, got "+typeof s);return Uint8Array.from(s,(e,t)=>{let r=e.charCodeAt(0);if(e.length!==1||r>127)throw new RangeError(`string contains non-ASCII character "${s[t]}" with code ${r} at position ${t}`);return r})}var ir=s=>typeof s=="bigint"&&or<=s;function gu(s,e,t){return ir(s)&&ir(e)&&ir(t)&&e<=s&&s<t}function Qt(s,e,t,r){if(!gu(e,t,r))throw new RangeError("expected valid "+s+": "+t+" <= n < "+r+", got "+e)}function es(s){if(s<or)throw new Error("expected non-negative bigint, got "+s);let e;for(e=0;s>or;s>>=kn,e+=1);return e}var Ms=s=>(kn<<BigInt(s))-kn;function $o(s,e,t){if(ut(s,"hashLen"),ut(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let r=g=>new Uint8Array(g),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3,l=r(s),u=r(s),d=0,m=()=>{l.fill(1),u.fill(0),d=0},E=(...g)=>t(u,re(l,...g)),y=(g=n)=>{u=E(i,g),l=E(),g.length!==0&&(u=E(o,g),l=E())},f=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let g=0,x=[];for(;g<e;){l=E();let I=l.slice();x.push(I),g+=l.length}return re(...x)};return(g,x)=>{m(),y(g);let I;for(;(I=x(f()))===void 0;)y();return m(),I}}function Ue(s,e={},t={}){if(Object.prototype.toString.call(s)!=="[object Object]")throw new TypeError("expected valid options object");function r(i,o,a){if(!a&&o!=="function"&&!Object.hasOwn(s,i))throw new TypeError(`param "${i}" is invalid: expected own property`);let l=s[i];if(a&&l===void 0)return;let u=typeof l;if(u!==o||l===null)throw new TypeError(`param "${i}" is invalid: expected ${o}, got ${u}`)}let n=(i,o)=>Object.entries(i).forEach(([a,l])=>r(a,l,o));n(e,!1),n(t,!0)}var Ln=()=>{throw new Error("not implemented")};var ue=BigInt(0),Q=BigInt(1),Pt=BigInt(2),Xo=BigInt(3),Jo=BigInt(4),Qo=BigInt(5),bu=BigInt(7),ea=BigInt(8),yu=BigInt(9),ta=BigInt(16);function te(s,e){if(e<=ue)throw new Error("mod: expected positive modulus, got "+e);let t=s%e;return t>=ue?t:e+t}function $(s,e,t){if(e<ue)throw new Error("pow2: expected non-negative exponent, got "+e);let r=s;for(;e-- >ue;)r*=r,r%=t;return r}function jo(s,e){if(s===ue)throw new Error("invert: expected non-zero number");if(e<=ue)throw new Error("invert: expected positive modulus, got "+e);let t=te(s,e),r=e,n=ue,i=Q,o=Q,a=ue;for(;t!==ue;){let u=r/t,d=r-t*u,m=n-o*u,E=i-a*u;r=t,t=d,n=o,i=a,o=m,a=E}if(r!==Q)throw new Error("invert: does not exist");return te(n,e)}function Cn(s,e,t){let r=s;if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function sa(s,e){let t=s,r=(t.ORDER+Q)/Jo,n=t.pow(e,r);return Cn(t,n,e),n}function wu(s,e){let t=s,r=(t.ORDER-Qo)/ea,n=t.mul(e,Pt),i=t.pow(n,r),o=t.mul(e,i),a=t.mul(t.mul(o,Pt),i),l=t.mul(o,t.sub(a,t.ONE));return Cn(t,l,e),l}function xu(s){let e=ts(s),t=ra(s),r=t(e,e.neg(e.ONE)),n=t(e,r),i=t(e,e.neg(r)),o=(s+bu)/ta;return((a,l)=>{let u=a,d=u.pow(l,o),m=u.mul(d,r),E=u.mul(d,n),y=u.mul(d,i),f=u.eql(u.sqr(m),l),b=u.eql(u.sqr(E),l);d=u.cmov(d,m,f),m=u.cmov(y,E,b);let g=u.eql(u.sqr(m),l),x=u.cmov(d,m,g);return Cn(u,x,l),x})}function ra(s){if(s<Xo)throw new Error("sqrt is not defined for small field");let e=s-Q,t=0;for(;e%Pt===ue;)e/=Pt,t++;let r=Pt,n=ts(s);for(;Zo(n,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return sa;let i=n.pow(r,e),o=(e+Q)/Pt;return function(l,u){let d=l;if(d.is0(u))return u;if(Zo(d,u)!==1)throw new Error("Cannot find square root");let m=t,E=d.mul(d.ONE,i),y=d.pow(u,e),f=d.pow(u,o);for(;!d.eql(y,d.ONE);){if(d.is0(y))return d.ZERO;let b=1,g=d.sqr(y);for(;!d.eql(g,d.ONE);)if(b++,g=d.sqr(g),b===m)throw new Error("Cannot find square root");let x=Q<<BigInt(m-b-1),I=d.pow(E,x);m=b,E=d.sqr(I),y=d.mul(y,E),f=d.mul(f,I)}return f}}function vu(s){return s%Jo===Xo?sa:s%ea===Qo?wu:s%ta===yu?xu(s):ra(s)}var rt=(s,e)=>(te(s,e)&Q)===Q,Eu=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Fn(s){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=Eu.reduce((r,n)=>(r[n]="function",r),e);if(Ue(s,t),Oe(s.BYTES,"BYTES"),Oe(s.BITS,"BITS"),s.BYTES<1||s.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(s.ORDER<=Q)throw new Error("invalid field: expected ORDER > 1, got "+s.ORDER);return s}function Su(s,e,t){let r=s;if(t<ue)throw new Error("invalid exponent, negatives unsupported");if(t===ue)return r.ONE;if(t===Q)return e;let n=r.ONE,i=e;for(;t>ue;)t&Q&&(n=r.mul(n,i)),i=r.sqr(i),t>>=Q;return n}function Ps(s,e,t=!1){let r=s,n=new Array(e.length).fill(t?r.ZERO:void 0),i=e.reduce((a,l,u)=>r.is0(l)?a:(n[u]=a,r.mul(a,l)),r.ONE),o=r.inv(i);return e.reduceRight((a,l,u)=>r.is0(l)?a:(n[u]=r.mul(a,n[u]),r.mul(a,l)),o),n}function Zo(s,e){let t=s,r=(t.ORDER-Q)/Pt,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 _u(s,e){if(e!==void 0&&Bn(e),s<=ue)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=es(s);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let r=e!==void 0?e:t,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var Yo=new WeakMap,ur=class{ORDER;BITS;BYTES;isLE;ZERO=ue;ONE=Q;_lengths;_mod;constructor(e,t={}){if(e<=Q)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}=_u(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 te(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return ue<=e&&e<this.ORDER}is0(e){return e===ue}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Q)===Q}neg(e){return te(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return te(e*e,this.ORDER)}add(e,t){return te(e+t,this.ORDER)}sub(e,t){return te(e-t,this.ORDER)}mul(e,t){return te(e*t,this.ORDER)}pow(e,t){return Su(this,e,t)}div(e,t){return te(e*jo(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 jo(e,this.ORDER)}sqrt(e){let t=Yo.get(this);return t||Yo.set(this,t=vu(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Rn(e,this.BYTES):cr(e,this.BYTES)}fromBytes(e,t=!1){K(e);let{_lengths:r,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let u=new Uint8Array(n);u.set(e,i?0:u.length-e.length),e=u}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=i?$e(e):Mt(e);if(a&&(l=te(l,o)),!t&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return Ps(this,e)}cmov(e,t,r){return Ne(r,"condition"),r?t:e}};Object.freeze(ur.prototype);function ts(s,e={}){return new ur(s,e)}function na(s){if(typeof s!="bigint")throw new Error("field order must be bigint");if(s<=Q)throw new Error("field order must be greater than 1");let e=es(s-Q);return Math.ceil(e/8)}function Nn(s){let e=na(s);return e+Math.ceil(e/2)}function On(s,e,t=!1){K(s);let r=s.length,n=na(e),i=Math.max(Nn(e),16);if(r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let o=t?$e(s):Mt(s),a=te(o,e-Q)+Q;return t?Rn(a,n):cr(a,n)}var ss=BigInt(0),kt=BigInt(1);function ks(s,e){let t=e.negate();return s?t:e}function Bt(s,e){let t=Ps(s.Fp,e.map(r=>r.Z));return e.map((r,n)=>s.fromAffine(r.toAffine(t[n])))}function ca(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function Un(s,e){ca(s,e);let t=Math.ceil(e/s)+1,r=2**(s-1),n=2**s,i=Ms(s),o=BigInt(s);return{windows:t,windowSize:r,mask:i,maxNumber:n,shiftBy:o}}function ia(s,e,t){let{windowSize:r,mask:n,maxNumber:i,shiftBy:o}=t,a=Number(s&n),l=s>>o;a>r&&(a-=i,l+=kt);let u=e*r,d=u+Math.abs(a)-1,m=a===0,E=a<0,y=e%2!==0;return{nextN:l,offset:d,isZero:m,isNeg:E,isNegF:y,offsetF:u}}var Kn=new WeakMap,la=new WeakMap;function zn(s){return la.get(s)||1}function oa(s){if(s!==ss)throw new Error("invalid wNAF")}var rs=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let n=e;for(;t>ss;)t&kt&&(r=r.add(n)),n=n.double(),t>>=kt;return r}precomputeWindow(e,t){let{windows:r,windowSize:n}=Un(t,this.bits),i=[],o=e,a=o;for(let l=0;l<r;l++){a=o,i.push(a);for(let u=1;u<n;u++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE,o=Un(e,this.bits);for(let a=0;a<o.windows;a++){let{nextN:l,offset:u,isZero:d,isNeg:m,isNegF:E,offsetF:y}=ia(r,a,o);r=l,d?i=i.add(ks(E,t[y])):n=n.add(ks(m,t[u]))}return oa(r),{p:n,f:i}}wNAFUnsafe(e,t,r,n=this.ZERO){let i=Un(e,this.bits);for(let o=0;o<i.windows&&r!==ss;o++){let{nextN:a,offset:l,isZero:u,isNeg:d}=ia(r,o,i);if(r=a,!u){let m=t[l];n=n.add(d?m.negate():m)}}return oa(r),n}getPrecomputes(e,t,r){let n=Kn.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(n=r(n)),Kn.set(t,n))),n}cached(e,t,r){let n=zn(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){let i=zn(e);return i===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),t,n)}createCache(e,t){ca(t,this.bits),la.set(e,t),Kn.delete(e)}hasCache(e){return zn(e)!==1}};function ua(s,e,t,r){let n=e,i=s.ZERO,o=s.ZERO;for(;t>ss||r>ss;)t&kt&&(i=i.add(n)),r&kt&&(o=o.add(n)),n=n.double(),t>>=kt,r>>=kt;return{p1:i,p2:o}}function aa(s,e,t){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Fn(e),e}else return ts(s,{isLE:t})}function hr(s,e,t={},r){if(r===void 0&&(r=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(let l of["p","n","h"]){let u=e[l];if(!(typeof u=="bigint"&&u>ss))throw new Error(`CURVE.${l} must be positive bigint`)}let n=aa(e.p,t.Fp,r),i=aa(e.n,t.Fn,r),a=["Gx","Gy","a",s==="weierstrass"?"b":"d"];for(let l of a)if(!n.isValid(e[l]))throw new Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function fr(s,e){return function(r){let n=s(r);return{secretKey:n,publicKey:e(n)}}}var pt=BigInt(0),ae=BigInt(1),Hn=BigInt(2),Iu=BigInt(8);function Tu(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 ha(s,e={}){let t=e,r=hr("edwards",s,t,t.FpFnLE),{Fp:n,Fn:i}=r,o=r.CURVE,{h:a}=o;Ue(t,{},{uvRatio:"function"});let l=Hn<<BigInt(i.BYTES*8)-ae,u=b=>n.create(b),d=t.uvRatio===void 0?(b,g)=>{try{return{isValid:!0,value:n.sqrt(n.div(b,g))}}catch{return{isValid:!1,value:pt}}}:t.uvRatio;if(!Tu(n,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function m(b,g,x=!1){let I=x?ae:pt;return Qt("coordinate "+b,g,I,l),g}function E(b){if(!(b instanceof y))throw new Error("EdwardsPoint expected")}class y{static BASE=new y(o.Gx,o.Gy,ae,u(o.Gx*o.Gy));static ZERO=new y(pt,ae,ae,pt);static Fp=n;static Fn=i;X;Y;Z;T;constructor(g,x,I,c){this.X=m("x",g),this.Y=m("y",x),this.Z=m("z",I,!0),this.T=m("t",c),Object.freeze(this)}static CURVE(){return o}static fromAffine(g){if(g instanceof y)throw new Error("extended point not allowed");let{x,y:I}=g||{};return m("x",x),m("y",I),new y(x,I,ae,u(x*I))}static fromBytes(g,x=!1){let I=n.BYTES,{a:c,d:h}=o;g=As(K(g,I,"point")),Ne(x,"zip215");let p=As(g),w=g[I-1];p[I-1]=w&-129;let v=$e(p),S=x?l:n.ORDER;Qt("point.y",v,pt,S);let M=u(v*v),R=u(M-ae),F=u(h*M-c),{isValid:_,value:T}=d(R,F);if(!_)throw new Error("bad point: invalid y coordinate");let P=(T&ae)===ae,A=(w&128)!==0;if(!x&&T===pt&&A)throw new Error("bad point: x=0 and x_0=1");return A!==P&&(T=u(-T)),y.fromAffine({x:T,y:v})}static fromHex(g,x=!1){return y.fromBytes(Jt(g),x)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,x=!0){return f.createCache(this,g),x||this.multiply(Hn),this}assertValidity(){let g=this,{a:x,d:I}=o;if(g.is0())throw new Error("bad point: ZERO");let{X:c,Y:h,Z:p,T:w}=g,v=u(c*c),S=u(h*h),M=u(p*p),R=u(M*M),F=u(v*x),_=u(M*u(F+S)),T=u(R+u(I*u(v*S)));if(_!==T)throw new Error("bad point: equation left != right (1)");let P=u(c*h),A=u(p*w);if(P!==A)throw new Error("bad point: equation left != right (2)")}equals(g){E(g);let{X:x,Y:I,Z:c}=this,{X:h,Y:p,Z:w}=g,v=u(x*w),S=u(h*c),M=u(I*w),R=u(p*c);return v===S&&M===R}is0(){return this.equals(y.ZERO)}negate(){return new y(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:g}=o,{X:x,Y:I,Z:c}=this,h=u(x*x),p=u(I*I),w=u(Hn*u(c*c)),v=u(g*h),S=x+I,M=u(u(S*S)-h-p),R=v+p,F=R-w,_=v-p,T=u(M*F),P=u(R*_),A=u(M*_),D=u(F*R);return new y(T,P,D,A)}add(g){E(g);let{a:x,d:I}=o,{X:c,Y:h,Z:p,T:w}=this,{X:v,Y:S,Z:M,T:R}=g,F=u(c*v),_=u(h*S),T=u(w*I*R),P=u(p*M),A=u((c+h)*(v+S)-F-_),D=P-T,k=P+T,L=u(_-x*F),B=u(A*D),C=u(k*L),N=u(A*L),U=u(D*k);return new y(B,C,U,N)}subtract(g){return E(g),this.add(g.negate())}multiply(g){if(!i.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:x,f:I}=f.cached(this,g,c=>Bt(y,c));return Bt(y,[x,I])[0]}multiplyUnsafe(g){if(!i.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===pt?y.ZERO:this.is0()||g===ae?this:f.unsafe(this,g,x=>Bt(y,x))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return f.unsafe(this,o.n).is0()}toAffine(g){let x=this,I=g,{X:c,Y:h,Z:p}=x,w=x.is0();I==null&&(I=w?Iu:n.inv(p));let v=u(c*I),S=u(h*I),M=n.mul(p,I);if(w)return{x:pt,y:ae};if(M!==ae)throw new Error("invZ was invalid");return{x:v,y:S}}clearCofactor(){return a===ae?this:this.multiplyUnsafe(a)}toBytes(){let{x:g,y:x}=this.toAffine(),I=n.toBytes(x);return I[I.length-1]|=g&ae?128:0,I}toHex(){return Xt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let f=new rs(y,i.BITS);return i.BITS>=8&&y.BASE.precompute(8),Object.freeze(y.prototype),Object.freeze(y),y}var dr=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Ln()}static fromHex(e){Ln()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Xt(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function fa(s,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let r=e,n=t;Ue(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:i}=n,{BASE:o,Fp:a,Fn:l}=s,u=r.outputLen,d=2*a.BYTES;if(u!==void 0&&(Oe(u,"hash.outputLen"),u!==d))throw new Error(`hash.outputLen must be ${d}, got ${u}`);let m=n.randomBytes===void 0?Ts:n.randomBytes,E=n.adjustScalarBytes===void 0?_=>_:n.adjustScalarBytes,y=n.domain===void 0?(_,T,P)=>{if(Ne(P,"phflag"),T.length||P)throw new Error("Contexts/pre-hash are not supported");return _}:n.domain;function f(_){return l.create($e(_))}function b(_){let T=v.secretKey;K(_,v.secretKey,"secretKey");let P=K(r(_),2*T,"hashedSecretKey"),A=E(P.slice(0,T)),D=P.slice(T,2*T),k=f(A);return{head:A,prefix:D,scalar:k}}function g(_){let{head:T,prefix:P,scalar:A}=b(_),D=o.multiply(A),k=D.toBytes();return{head:T,prefix:P,scalar:A,point:D,pointBytes:k}}function x(_){return g(_).pointBytes}function I(_=Uint8Array.of(),...T){let P=re(...T);return f(r(y(P,K(_,void 0,"context"),!!i)))}function c(_,T,P={}){_=K(_,void 0,"message"),i&&(_=i(_));let{prefix:A,scalar:D,pointBytes:k}=g(T),L=I(P.context,A,_),B=o.multiply(L).toBytes(),C=I(P.context,B,k,_),N=l.create(L+C*D);if(!l.isValid(N))throw new Error("sign failed: invalid s");let U=re(B,l.toBytes(N));return K(U,v.signature,"result")}let h={zip215:n.zip215};function p(_,T,P,A=h){let{context:D}=A,k=A.zip215===void 0?!!h.zip215:A.zip215,L=v.signature;_=K(_,L,"signature"),T=K(T,void 0,"message"),P=K(P,v.publicKey,"publicKey"),k!==void 0&&Ne(k,"zip215"),i&&(T=i(T));let B=L/2,C=_.subarray(0,B),N=$e(_.subarray(B,L)),U,z,O;try{U=s.fromBytes(P,k),z=s.fromBytes(C,k),O=o.multiplyUnsafe(N)}catch{return!1}if(!k&&U.isSmallOrder())return!1;let se=I(D,C,P,T);return z.add(U.multiplyUnsafe(se)).subtract(O).clearCofactor().is0()}let w=a.BYTES,v={secretKey:w,publicKey:w,signature:2*w,seed:w};function S(_){return _=_===void 0?m(v.seed):_,K(_,v.seed,"seed")}function M(_){return At(_)&&_.length===v.secretKey}function R(_,T){try{return!!s.fromBytes(_,T===void 0?h.zip215:T)}catch{return!1}}let F={getExtendedPublicKey:g,randomSecretKey:S,isValidSecretKey:M,isValidPublicKey:R,toMontgomery(_){let{y:T}=s.fromBytes(_),P=v.publicKey,A=P===32;if(!A&&P!==57)throw new Error("only defined for 25519 and 448");let D=A?a.div(ae+T,ae-T):a.div(T-ae,T+ae);return a.toBytes(D)},toMontgomerySecret(_){let T=v.secretKey;K(_,T);let P=r(_.subarray(0,T));return E(P).subarray(0,T)}};return Object.freeze(v),Object.freeze(F),Object.freeze({keygen:fr(S,x),getPublicKey:x,sign:c,verify:p,utils:F,Point:s,lengths:v})}function Bs(s,e){if(Oe(s),Oe(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(s<0||s>2**(8*e)-1)throw new Error("invalid I2OSP input: "+s);let t=Array.from({length:e}).fill(0);for(let r=e-1;r>=0;r--)t[r]=s&255,s>>>=8;return new Uint8Array(t)}function Du(s,e){let t=new Uint8Array(s.length);for(let r=0;r<s.length;r++)t[r]=s[r]^e[r];return t}function Au(s){if(!At(s)&&typeof s!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof s=="string"?lr(s):s;if(e.length===0)throw new Error("DST must be non-empty");return e}function Gn(s,e,t,r){K(s),Oe(t),e=Au(e),e.length>255&&(e=r(re(lr("H2C-OVERSIZE-DST-"),e)));let{outputLen:n,blockLen:i}=r,o=Math.ceil(t/n);if(t>65535||o>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=re(e,Bs(e.length,1)),l=new Uint8Array(i),u=Bs(t,2),d=new Array(o),m=r(re(l,s,u,Bs(0,1),a));d[0]=r(re(m,Bs(1,1),a));for(let y=1;y<o;y++){let f=[Du(m,d[y-1]),Bs(y+1,1),a];d[y]=r(re(...f))}return re(...d).slice(0,t)}var da="HashToScalar-";var Mu=BigInt(0),nt=BigInt(1),pa=BigInt(2);var Pu=BigInt(5),ku=BigInt(8),ns=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),$n={p:ns,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ku,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Bu(s){let e=BigInt(10),t=BigInt(20),r=BigInt(40),n=BigInt(80),i=ns,a=s*s%i*s%i,l=$(a,pa,i)*a%i,u=$(l,nt,i)*s%i,d=$(u,Pu,i)*u%i,m=$(d,e,i)*d%i,E=$(m,t,i)*m%i,y=$(E,r,i)*E%i,f=$(y,n,i)*y%i,b=$(f,n,i)*y%i,g=$(b,e,i)*d%i;return{pow_p_5_8:$(g,pa,i)*s%i,b2:a}}function Ru(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}var qn=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function jn(s,e){let t=ns,r=te(e*e*e,t),n=te(r*r*e,t),i=Bu(s*n).pow_p_5_8,o=te(s*r*i,t),a=te(e*o*o,t),l=o,u=te(o*qn,t),d=a===s,m=a===te(-s,t),E=a===te(-s*qn,t);return d&&(o=l),(m||E)&&(o=u),rt(o,t)&&(o=te(-o,t)),{isValid:d||m,value:o}}var gt=ha($n,{uvRatio:jn}),mt=gt.Fp,ba=gt.Fn;function Lu(s){return fa(gt,nr,Object.assign({adjustScalarBytes:Ru,zip215:!0},s))}var ya=Lu({});var Vn=qn,Cu=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Fu=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Nu=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Ou=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),ma=s=>jn(nt,s),Uu=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Wn=s=>mt.create($e(s)&Uu);function ga(s){let{d:e}=$n,t=ns,r=x=>mt.create(x),n=r(Vn*s*s),i=r((n+nt)*Nu),o=BigInt(-1),a=r((o-e*n)*r(n+e)),{isValid:l,value:u}=jn(i,a),d=r(u*s);rt(d,t)||(d=r(-d)),l||(u=d),l||(o=n);let m=r(o*(n-nt)*Ou-a),E=u*u,y=r((u+u)*a),f=r(m*Cu),b=r(nt-E),g=r(nt+E);return new gt(r(y*g),r(b*f),r(f*g),r(y*b))}var bt=class s extends dr{static BASE=new s(gt.BASE);static ZERO=new s(gt.ZERO);static Fp=mt;static Fn=ba;constructor(e){super(e)}static fromAffine(e){return new s(gt.fromAffine(e))}assertSame(e){if(!(e instanceof s))throw new Error("RistrettoPoint expected")}init(e){return new s(e)}static fromBytes(e){Ae(e,32);let{a:t,d:r}=$n,n=ns,i=h=>mt.create(h),o=Wn(e);if(!Wo(mt.toBytes(o),e)||rt(o,n))throw new Error("invalid ristretto255 encoding 1");let a=i(o*o),l=i(nt+t*a),u=i(nt-t*a),d=i(l*l),m=i(u*u),E=i(t*r*d-m),{isValid:y,value:f}=ma(i(E*m)),b=i(f*u),g=i(f*b*E),x=i((o+o)*b);rt(x,n)&&(x=i(-x));let I=i(l*g),c=i(x*I);if(!y||rt(c,n)||I===Mu)throw new Error("invalid ristretto255 encoding 2");return new s(new gt(x,I,nt,c))}static fromHex(e){return s.fromBytes(Es(e))}toBytes(){let{X:e,Y:t,Z:r,T:n}=this.ep,i=ns,o=g=>mt.create(g),a=o(o(r+t)*o(r-t)),l=o(e*t),u=o(l*l),{value:d}=ma(o(a*u)),m=o(d*a),E=o(d*l),y=o(m*E*n),f;if(rt(n*y,i)){let g=o(t*Vn),x=o(e*Vn);e=g,t=x,f=o(m*Fu)}else f=E;rt(e*y,i)&&(t=o(-t));let b=o((r-t)*f);return rt(b,i)&&(b=o(-b)),mt.toBytes(b)}equals(e){this.assertSame(e);let{X:t,Y:r}=this.ep,{X:n,Y:i}=e.ep,o=u=>mt.create(u),a=o(t*i)===o(r*n),l=o(r*i)===o(t*n);return a||l}is0(){return this.equals(s.ZERO)}};Object.freeze(bt.BASE);Object.freeze(bt.ZERO);Object.freeze(bt.prototype);Object.freeze(bt);var Ku=Object.freeze({Point:bt,hashToCurve(s,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,r=Gn(s,t,64,nr);return Ku.deriveToCurve(r)},hashToScalar(s,e={DST:da}){let t=Gn(s,e.DST,64,nr);return ba.create($e(t))},deriveToCurve(s){Ae(s,64);let e=Wn(s.subarray(0,32)),t=ga(e),r=Wn(s.subarray(32,64)),n=ga(r);return new bt(t.add(n))}});var Rs=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},pr=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Re={get(s=globalThis){let e=s.crypto;if(e?.subtle==null)throw new pr("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 mr=32;var Zn,zu=(async()=>{try{return await Re.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Hu(s,e,t){if(s.buffer instanceof ArrayBuffer){let r=await Re.get().subtle.importKey("raw",s.buffer,{name:"Ed25519"},!1,["verify"]);return await Re.get().subtle.verify({name:"Ed25519"},r,Be(e),Be(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Gu(s,e,t){return ya.verify(e,t instanceof Uint8Array?t:t.subarray(),s)}async function wa(s,e,t){return Zn==null&&(Zn=await zu),Zn?Hu(s,e,t):Gu(s,e,t)}function gr(s){return s==null?!1:typeof s.then=="function"&&typeof s.catch=="function"&&typeof s.finally=="function"}var br=class{type="Ed25519";raw;constructor(e){this.raw=Yn(e,mr)}toMultihash(){return Ce.digest(Ve(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Te(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();let n=wa(this.raw,t,e);return gr(n)?n.then(i=>(r?.signal?.throwIfAborted(),i)):n}};function Xn(s){return s=Yn(s,mr),new br(s)}function Yn(s,e){if(s=Uint8Array.from(s??[]),s.length!==e)throw new Y(`Key must be a Uint8Array of length ${e}, got ${s.length}`);return s}var Vu=Math.pow(2,7),Wu=Math.pow(2,14),$u=Math.pow(2,21),Jn=Math.pow(2,28),Qn=Math.pow(2,35),ei=Math.pow(2,42),ti=Math.pow(2,49),H=128,de=127;function Le(s){if(s<Vu)return 1;if(s<Wu)return 2;if(s<$u)return 3;if(s<Jn)return 4;if(s<Qn)return 5;if(s<ei)return 6;if(s<ti)return 7;if(Number.MAX_SAFE_INTEGER!=null&&s>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function si(s,e,t=0){switch(Le(s)){case 8:e[t++]=s&255|H,s/=128;case 7:e[t++]=s&255|H,s/=128;case 6:e[t++]=s&255|H,s/=128;case 5:e[t++]=s&255|H,s/=128;case 4:e[t++]=s&255|H,s>>>=7;case 3:e[t++]=s&255|H,s>>>=7;case 2:e[t++]=s&255|H,s>>>=7;case 1:{e[t++]=s&255,s>>>=7;break}default:throw new Error("unreachable")}return e}function ju(s,e,t=0){switch(Le(s)){case 8:e.set(t++,s&255|H),s/=128;case 7:e.set(t++,s&255|H),s/=128;case 6:e.set(t++,s&255|H),s/=128;case 5:e.set(t++,s&255|H),s/=128;case 4:e.set(t++,s&255|H),s>>>=7;case 3:e.set(t++,s&255|H),s>>>=7;case 2:e.set(t++,s&255|H),s>>>=7;case 1:{e.set(t++,s&255),s>>>=7;break}default:throw new Error("unreachable")}return e}function ri(s,e){let t=s[e],r=0;if(r+=t&de,t<H||(t=s[e+1],r+=(t&de)<<7,t<H)||(t=s[e+2],r+=(t&de)<<14,t<H)||(t=s[e+3],r+=(t&de)<<21,t<H)||(t=s[e+4],r+=(t&de)*Jn,t<H)||(t=s[e+5],r+=(t&de)*Qn,t<H)||(t=s[e+6],r+=(t&de)*ei,t<H)||(t=s[e+7],r+=(t&de)*ti,t<H))return r;throw new RangeError("Could not decode varint")}function Zu(s,e){let t=s.get(e),r=0;if(r+=t&de,t<H||(t=s.get(e+1),r+=(t&de)<<7,t<H)||(t=s.get(e+2),r+=(t&de)<<14,t<H)||(t=s.get(e+3),r+=(t&de)<<21,t<H)||(t=s.get(e+4),r+=(t&de)*Jn,t<H)||(t=s.get(e+5),r+=(t&de)*Qn,t<H)||(t=s.get(e+6),r+=(t&de)*ei,t<H)||(t=s.get(e+7),r+=(t&de)*ti,t<H))return r;throw new RangeError("Could not decode varint")}function ni(s,e,t=0){return e==null&&(e=fe(Le(s))),e instanceof Uint8Array?si(s,e,t):ju(s,e,t)}function ii(s,e=0){return s instanceof Uint8Array?ri(s,e):Zu(s,e)}var ai=new Float32Array([-0]),yt=new Uint8Array(ai.buffer);function va(s,e,t){ai[0]=s,e[t]=yt[0],e[t+1]=yt[1],e[t+2]=yt[2],e[t+3]=yt[3]}function Ea(s,e){return yt[0]=s[e],yt[1]=s[e+1],yt[2]=s[e+2],yt[3]=s[e+3],ai[0]}var ci=new Float64Array([-0]),pe=new Uint8Array(ci.buffer);function Sa(s,e,t){ci[0]=s,e[t]=pe[0],e[t+1]=pe[1],e[t+2]=pe[2],e[t+3]=pe[3],e[t+4]=pe[4],e[t+5]=pe[5],e[t+6]=pe[6],e[t+7]=pe[7]}function _a(s,e){return pe[0]=s[e],pe[1]=s[e+1],pe[2]=s[e+2],pe[3]=s[e+3],pe[4]=s[e+4],pe[5]=s[e+5],pe[6]=s[e+6],pe[7]=s[e+7],ci[0]}var Yu=BigInt(Number.MAX_SAFE_INTEGER),Xu=BigInt(Number.MIN_SAFE_INTEGER),Me=class s{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,r=~this.hi>>>0;return t===0&&(r=r+1>>>0),-(t+r*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,r=~this.hi>>>0;return t===0&&(r=r+1>>>0),-(BigInt(t)+(BigInt(r)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(e===0n)return Rt;if(e<Yu&&e>Xu)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>Ia&&(n=0n,++r>Ia&&(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 Me(0,0);Rt.toBigInt=function(){return 0n};Rt.zzEncode=Rt.zzDecode=function(){return this};Rt.length=function(){return 1};var Ia=4294967296n;function Ta(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 Da(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 li(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 Ke(s,e){return RangeError(`index out of range: ${s.pos} + ${e??1} > ${s.len}`)}function yr(s,e){return(s[e-4]|s[e-3]<<8|s[e-2]<<16|s[e-1]<<24)>>>0}var ui=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Be(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,Ke(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 Ke(this,4);return yr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ke(this,4);return yr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ke(this,4);let e=Ea(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ke(this,4);let e=_a(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 Ke(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){let e=this.bytes();return Da(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Ke(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Ke(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Me(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Ke(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 Ke(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 Ke(this,8);let e=yr(this.buf,this.pos+=4),t=yr(this.buf,this.pos+=4);return new Me(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=ri(this.buf,this.pos);return this.pos+=Le(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 Ls(s){return new ui(s instanceof Uint8Array?s:s.subarray())}function ye(s,e,t){let r=Ls(s);return e.decode(r,void 0,t)}function hi(s){let e=s??8192,t=e>>>1,r,n=e;return function(o){if(o<1||o>t)return fe(o);n+o>e&&(r=fe(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 fi(){}var pi=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Ju=hi();function Qu(s){return globalThis.Buffer!=null?fe(s):Ju(s)}var Fs=class{len;head;tail;states;constructor(){this.len=0,this.head=new Lt(fi,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 mi((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(wr,10,Me.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Me.fromBigInt(e);return this._push(wr,t.length(),t)}uint64Number(e){return this._push(si,Le(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Me.fromBigInt(e).zzEncode();return this._push(wr,t.length(),t)}sint64Number(e){let t=Me.fromNumber(e).zzEncode();return this._push(wr,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(di,1,e?1:0)}fixed32(e){return this._push(Cs,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Me.fromBigInt(e);return this._push(Cs,4,t.lo)._push(Cs,4,t.hi)}fixed64Number(e){let t=Me.fromNumber(e);return this._push(Cs,4,t.lo)._push(Cs,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(va,4,e)}double(e){return this._push(Sa,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(di,1,0):this.uint32(t)._push(th,t,e)}string(e){let t=Ta(e);return t!==0?this.uint32(t)._push(li,t,e):this._push(di,1,0)}fork(){return this.states=new pi(this),this.head=this.tail=new Lt(fi,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(fi,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=Qu(this.len),r=0;for(;e!=null;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}};function di(s,e,t){e[t]=s&255}function eh(s,e,t){for(;s>127;)e[t++]=s&127|128,s>>>=7;e[t]=s}var mi=class extends Lt{next;constructor(e,t){super(eh,e,t),this.next=void 0}};function wr(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 Cs(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 th(s,e,t){e.set(s,t)}globalThis.Buffer!=null&&(Fs.prototype.bytes=function(s){let e=s.length>>>0;return this.uint32(e),e>0&&this._push(sh,e,s),this},Fs.prototype.string=function(s){let e=globalThis.Buffer.byteLength(s);return this.uint32(e),e>0&&this._push(rh,e,s),this});function sh(s,e,t){e.set(s,t)}function rh(s,e,t){s.length<40?li(s,e,t):e.utf8Write!=null?e.utf8Write(s,t):e.set(V(s),t)}function gi(){return new Fs}function we(s,e){let t=gi();return e.encode(s,t,{lengthDelimited:!1}),t.finish()}function*xe(s,e,t){let r=Ls(s);yield*e.stream(r,void 0,"$",t)}var xr={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function vr(s,e,t,r,n){return{name:s,type:e,encode:t,decode:r,stream:n}}function bi(s){function e(i){if(s[i.toString()]==null)throw new Error("Invalid enum value");return s[i]}let t=function(o,a){let l=e(o);a.int32(l)},r=function(o){let a=o.int32();return e(a)},n=function*(o){let a=o.int32();yield e(a)};return vr("enum",xr.VARINT,t,r,n)}function ve(s,e,t){return vr("message",xr.LENGTH_DELIMITED,s,e,t)}var W=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var j;(function(s){s.RSA="RSA",s.Ed25519="Ed25519",s.secp256k1="secp256k1",s.ECDSA="ECDSA"})(j||(j={}));var yi;(function(s){s[s.RSA=0]="RSA",s[s.Ed25519=1]="Ed25519",s[s.secp256k1=2]="secp256k1",s[s.ECDSA=3]="ECDSA"})(yi||(yi={}));(function(s){s.codec=()=>bi(yi)})(j||(j={}));var je;(function(s){let e;s.codec=()=>(e==null&&(e=ve((i,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),i.Type!=null&&(o.uint32(8),j.codec().encode(i.Type,o)),i.Data!=null&&(o.uint32(18),o.bytes(i.Data)),a.lengthDelimited!==!1&&o.ldelim()},(i,o,a={})=>{let l={},u=o==null?i.len:i.pos+o;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{l.Type=j.codec().decode(i);break}case 2:{l.Data=i.bytes();break}default:{i.skipType(d&7);break}}}return l},function*(i,o,a,l={}){let u=o==null?i.len:i.pos+o;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${a}.Type`,value:j.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(d&7);break}}}})),e);function t(i){return we(i,s.codec())}s.encode=t;function r(i,o){return ye(i,s.codec(),o)}s.decode=r;function n(i,o){return xe(i,s.codec(),o)}s.stream=n})(je||(je={}));var wi;(function(s){let e;s.codec=()=>(e==null&&(e=ve((i,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),i.Type!=null&&(o.uint32(8),j.codec().encode(i.Type,o)),i.Data!=null&&(o.uint32(18),o.bytes(i.Data)),a.lengthDelimited!==!1&&o.ldelim()},(i,o,a={})=>{let l={},u=o==null?i.len:i.pos+o;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{l.Type=j.codec().decode(i);break}case 2:{l.Data=i.bytes();break}default:{i.skipType(d&7);break}}}return l},function*(i,o,a,l={}){let u=o==null?i.len:i.pos+o;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${a}.Type`,value:j.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(d&7);break}}}})),e);function t(i){return we(i,s.codec())}s.encode=t;function r(i,o){return ye(i,s.codec(),o)}s.decode=r;function n(i,o){return xe(i,s.codec(),o)}s.stream=n})(wi||(wi={}));var Os={};Ie(Os,{MAX_RSA_KEY_SIZE:()=>xi,generateRSAKeyPair:()=>Ra,jwkToJWKKeyPair:()=>La,jwkToPkcs1:()=>ah,jwkToPkix:()=>_i,jwkToRSAPrivateKey:()=>Ai,pkcs1MessageToJwk:()=>Ei,pkcs1MessageToRSAPrivateKey:()=>Ii,pkcs1ToJwk:()=>oh,pkcs1ToRSAPrivateKey:()=>Ba,pkixMessageToJwk:()=>Si,pkixMessageToRSAPublicKey:()=>Di,pkixToJwk:()=>ch,pkixToRSAPublicKey:()=>Ti});var is=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Os.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ce.createV1(114,this._multihash)}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Te(this.raw,e.raw)}verify(e,t,r){return ka(this.jwk,t,e,r)}},Ns=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Os.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Te(this.raw,e.raw)}sign(e,t){return Pa(this.jwk,e,t)}};var xi=8192,vi=18,nh=1062,ih=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function oh(s){let e=Qe(s);return Ei(e)}function Ei(s){return{n:q(s[1],"base64url"),e:q(s[2],"base64url"),d:q(s[3],"base64url"),p:q(s[4],"base64url"),q:q(s[5],"base64url"),dp:q(s[6],"base64url"),dq:q(s[7],"base64url"),qi:q(s[8],"base64url"),kty:"RSA"}}function ah(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 Y("JWK was missing components");return lt([De(Uint8Array.from([0])),De(V(s.n,"base64url")),De(V(s.e,"base64url")),De(V(s.d,"base64url")),De(V(s.p,"base64url")),De(V(s.q,"base64url")),De(V(s.dp,"base64url")),De(V(s.dq,"base64url")),De(V(s.qi,"base64url"))]).subarray()}function ch(s){let e=Qe(s,{offset:0});return Si(e)}function Si(s){let e=Qe(s[1],{offset:0});return{kty:"RSA",n:q(e[0],"base64url"),e:q(e[1],"base64url")}}function _i(s){if(s.n==null||s.e==null)throw new Y("JWK was missing components");return lt([ih,Js(lt([De(V(s.n,"base64url")),De(V(s.e,"base64url"))]))]).subarray()}function Ba(s){let e=Qe(s);return Ii(e)}function Ii(s){let e=Ei(s);return Ai(e)}function Ti(s,e){if(s.byteLength>=nh)throw new zt("Key size is too large");let t=Qe(s,{offset:0});return Di(t,s,e)}function Di(s,e,t){let r=Si(s);if(t==null){let n=Yt(je.encode({Type:j.RSA,Data:e}));t=qe(vi,n)}return new is(r,t)}function Ai(s){if(Fa(s)>xi)throw new Y("Key size is too large");let e=La(s),t=Yt(je.encode({Type:j.RSA,Data:_i(e.publicKey)})),r=qe(vi,t);return new Ns(e.privateKey,new is(e.publicKey,r))}async function Ra(s){if(s>xi)throw new Y("Key size is too large");let e=await Ca(s),t=Yt(je.encode({Type:j.RSA,Data:_i(e.publicKey)})),r=qe(vi,t);return new Ns(e.privateKey,new is(e.publicKey,r))}function La(s){if(s==null)throw new Y("Missing key parameter");return{privateKey:s,publicKey:{kty:s.kty,n:s.n,e:s.e}}}async function Ca(s,e){let t=await Re.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 lh(t,e);return{privateKey:r[0],publicKey:r[1]}}async function Pa(s,e,t){let r=await Re.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let n=await Re.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,Be(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(n,0,n.byteLength)}async function ka(s,e,t,r){let n=await Re.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();let i=await Re.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,Be(e),Be(t instanceof Uint8Array?t:t.subarray()));return r?.signal?.throwIfAborted(),i}async function lh(s,e){if(s.privateKey==null||s.publicKey==null)throw new Y("Private and public key are required");let t=await Promise.all([Re.get().subtle.exportKey("jwk",s.privateKey),Re.get().subtle.exportKey("jwk",s.publicKey)]);return e?.signal?.throwIfAborted(),t}function Fa(s){if(s.kty!=="RSA")throw new Y("invalid key type");if(s.n==null)throw new Y("invalid key modulus");return V(s.n,"base64url").length*8}var Er=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Qs(e),Ae(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,n=new Uint8Array(r);n.set(t.length>r?e.create().update(t).digest():t);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),tt(n)}update(e){return Zt(this),this.iHash.update(e),this}digestInto(e){Zt(this),er(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}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,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()}},Na=(()=>{let s=((e,t,r)=>new Er(e,t).update(r).digest());return s.create=(e,t)=>new Er(e,t),s})();var Oa=(s,e)=>(s+(s>=0?e:-e)/Ua)/e;function uh(s,e,t){Qt("scalar",s,Ze,t);let[[r,n],[i,o]]=e,a=Oa(o*s,t),l=Oa(-n*s,t),u=s-a*r-l*i,d=-a*n-l*o,m=u<Ze,E=d<Ze;m&&(u=-u),E&&(d=-d);let y=Ms(Math.ceil(es(t)/2))+wt;if(u<Ze||u>=y||d<Ze||d>=y)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:m,k1:u,k2neg:E,k2:d}}function Pi(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function Mi(s,e){Ue(s);let t={};for(let r of Object.keys(e))t[r]=s[r]===void 0?e[r]:s[r];return Ne(t.lowS,"lowS"),Ne(t.prehash,"prehash"),t.format!==void 0&&Pi(t.format),t}var ki=class extends Error{constructor(e=""){super(e)}},ze={Err:ki,_tlv:{encode:(s,e)=>{let{Err:t}=ze;if(Oe(s,"tag"),s<0||s>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let r=e.length/2,n=Ds(r);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let i=r>127?Ds(n.length/2|128):"";return Ds(s)+i+n+e},decode(s,e){let{Err:t}=ze;e=K(e,void 0,"DER data");let r=0;if(s<0||s>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[r++]!==s)throw new t("tlv.decode: wrong tlv");let n=e[r++],i=!!(n&128),o=0;if(!i)o=n;else{let l=n&127;if(!l)throw new t("tlv.decode(long): indefinite length not supported");if(l>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(r,r+l);if(u.length!==l)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let d of u)o=o<<8|d;if(r+=l,o<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(s){let{Err:e}=ze;if(ar(s),s<Ze)throw new e("integer: negative integers are not allowed");let t=Ds(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}=ze;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 Mt(s)}},toSig(s){let{Err:e,_int:t,_tlv:r}=ze,n=K(s,void 0,"signature"),{v:i,l:o}=r.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l}=r.decode(2,i),{v:u,l:d}=r.decode(2,l);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(s){let{_tlv:e,_int:t}=ze,r=e.encode(2,t.encode(s.r)),n=e.encode(2,t.encode(s.s)),i=r+n;return e.encode(48,i)}};Object.freeze(ze._tlv);Object.freeze(ze._int);Object.freeze(ze);var Ze=BigInt(0),wt=BigInt(1),Ua=BigInt(2),Sr=BigInt(3),hh=BigInt(4);function Ka(s,e={}){let t=hr("weierstrass",s,e),r=t.Fp,n=t.Fn,i=t.CURVE,{h:o,n:a}=i;Ue(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:l,allowInfinityPoint:u}=e;if(l&&(!r.is0(i.a)||typeof l.beta!="bigint"||!Array.isArray(l.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let d=Ha(r,n);function m(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function E(F,_,T){if(u&&_.is0())return Uint8Array.of(0);let{x:P,y:A}=_.toAffine(),D=r.toBytes(P);if(Ne(T,"isCompressed"),T){m();let k=!r.isOdd(A);return re(za(k),D)}else return re(Uint8Array.of(4),D,r.toBytes(A))}function y(F){K(F,void 0,"Point");let{publicKey:_,publicKeyUncompressed:T}=d,P=F.length,A=F[0],D=F.subarray(1);if(u&&P===1&&A===0)return{x:r.ZERO,y:r.ZERO};if(P===_&&(A===2||A===3)){let k=r.fromBytes(D);if(!r.isValid(k))throw new Error("bad point: is not on curve, wrong x");let L=g(k),B;try{B=r.sqrt(L)}catch(U){let z=U instanceof Error?": "+U.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}m();let C=r.isOdd(B);return(A&1)===1!==C&&(B=r.neg(B)),{x:k,y:B}}else if(P===T&&A===4){let k=r.BYTES,L=r.fromBytes(D.subarray(0,k)),B=r.fromBytes(D.subarray(k,k*2));if(!x(L,B))throw new Error("bad point: is not on curve");return{x:L,y:B}}else throw new Error(`bad point: got length ${P}, expected compressed=${_} or uncompressed=${T}`)}let f=e.toBytes===void 0?E:e.toBytes,b=e.fromBytes===void 0?y:e.fromBytes;function g(F){let _=r.sqr(F),T=r.mul(_,F);return r.add(r.add(T,r.mul(F,i.a)),i.b)}function x(F,_){let T=r.sqr(_),P=g(F);return r.eql(T,P)}if(!x(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let I=r.mul(r.pow(i.a,Sr),hh),c=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(I,c)))throw new Error("bad curve params: a or b");function h(F,_,T=!1){if(!r.isValid(_)||T&&r.is0(_))throw new Error(`bad point coordinate ${F}`);return _}function p(F){if(!(F instanceof S))throw new Error("Weierstrass Point expected")}function w(F){if(!l||!l.basises)throw new Error("no endo");return uh(F,l.basises,n.ORDER)}function v(F,_,T,P,A){return T=new S(r.mul(T.X,F),T.Y,T.Z),_=ks(P,_),T=ks(A,T),_.add(T)}class S{static BASE=new S(i.Gx,i.Gy,r.ONE);static ZERO=new S(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=n;X;Y;Z;constructor(_,T,P){this.X=h("x",_),this.Y=h("y",T,!0),this.Z=h("z",P),Object.freeze(this)}static CURVE(){return i}static fromAffine(_){let{x:T,y:P}=_||{};if(!_||!r.isValid(T)||!r.isValid(P))throw new Error("invalid affine point");if(_ instanceof S)throw new Error("projective point not allowed");return r.is0(T)&&r.is0(P)?S.ZERO:new S(T,P,r.ONE)}static fromBytes(_){let T=S.fromAffine(b(K(_,void 0,"point")));return T.assertValidity(),T}static fromHex(_){return S.fromBytes(Jt(_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,T=!0){return R.createCache(this,_),T||this.multiply(Sr),this}assertValidity(){let _=this;if(_.is0()){if(e.allowInfinityPoint&&r.is0(_.X)&&r.eql(_.Y,r.ONE)&&r.is0(_.Z))return;throw new Error("bad point: ZERO")}let{x:T,y:P}=_.toAffine();if(!r.isValid(T)||!r.isValid(P))throw new Error("bad point: x or y not field elements");if(!x(T,P))throw new Error("bad point: equation left != right");if(!_.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:_}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(_)}equals(_){p(_);let{X:T,Y:P,Z:A}=this,{X:D,Y:k,Z:L}=_,B=r.eql(r.mul(T,L),r.mul(D,A)),C=r.eql(r.mul(P,L),r.mul(k,A));return B&&C}negate(){return new S(this.X,r.neg(this.Y),this.Z)}double(){let{a:_,b:T}=i,P=r.mul(T,Sr),{X:A,Y:D,Z:k}=this,L=r.ZERO,B=r.ZERO,C=r.ZERO,N=r.mul(A,A),U=r.mul(D,D),z=r.mul(k,k),O=r.mul(A,D);return O=r.add(O,O),C=r.mul(A,k),C=r.add(C,C),L=r.mul(_,C),B=r.mul(P,z),B=r.add(L,B),L=r.sub(U,B),B=r.add(U,B),B=r.mul(L,B),L=r.mul(O,L),C=r.mul(P,C),z=r.mul(_,z),O=r.sub(N,z),O=r.mul(_,O),O=r.add(O,C),C=r.add(N,N),N=r.add(C,N),N=r.add(N,z),N=r.mul(N,O),B=r.add(B,N),z=r.mul(D,k),z=r.add(z,z),N=r.mul(z,O),L=r.sub(L,N),C=r.mul(z,U),C=r.add(C,C),C=r.add(C,C),new S(L,B,C)}add(_){p(_);let{X:T,Y:P,Z:A}=this,{X:D,Y:k,Z:L}=_,B=r.ZERO,C=r.ZERO,N=r.ZERO,U=i.a,z=r.mul(i.b,Sr),O=r.mul(T,D),se=r.mul(P,k),ne=r.mul(A,L),ie=r.add(T,P),ee=r.add(D,k);ie=r.mul(ie,ee),ee=r.add(O,se),ie=r.sub(ie,ee),ee=r.add(T,A);let _e=r.add(D,L);return ee=r.mul(ee,_e),_e=r.add(O,ne),ee=r.sub(ee,_e),_e=r.add(P,A),B=r.add(k,L),_e=r.mul(_e,B),B=r.add(se,ne),_e=r.sub(_e,B),N=r.mul(U,ee),B=r.mul(z,ne),N=r.add(B,N),B=r.sub(se,N),N=r.add(se,N),C=r.mul(B,N),se=r.add(O,O),se=r.add(se,O),ne=r.mul(U,ne),ee=r.mul(z,ee),se=r.add(se,ne),ne=r.sub(O,ne),ne=r.mul(U,ne),ee=r.add(ee,ne),O=r.mul(se,ee),C=r.add(C,O),O=r.mul(_e,ee),B=r.mul(ie,B),B=r.sub(B,O),O=r.mul(ie,se),N=r.mul(_e,N),N=r.add(N,O),new S(B,C,N)}subtract(_){return p(_),this.add(_.negate())}is0(){return this.equals(S.ZERO)}multiply(_){let{endo:T}=e;if(!n.isValidNot0(_))throw new RangeError("invalid scalar: out of range");let P,A,D=k=>R.cached(this,k,L=>Bt(S,L));if(T){let{k1neg:k,k1:L,k2neg:B,k2:C}=w(_),{p:N,f:U}=D(L),{p:z,f:O}=D(C);A=U.add(O),P=v(T.beta,N,z,k,B)}else{let{p:k,f:L}=D(_);P=k,A=L}return Bt(S,[P,A])[0]}multiplyUnsafe(_){let{endo:T}=e,P=this,A=_;if(!n.isValid(A))throw new RangeError("invalid scalar: out of range");if(A===Ze||P.is0())return S.ZERO;if(A===wt)return P;if(R.hasCache(this))return this.multiply(A);if(T){let{k1neg:D,k1:k,k2neg:L,k2:B}=w(A),{p1:C,p2:N}=ua(S,P,k,B);return v(T.beta,C,N,D,L)}else return R.unsafe(P,A)}toAffine(_){let T=this,P=_,{X:A,Y:D,Z:k}=T;if(r.eql(k,r.ONE))return{x:A,y:D};let L=T.is0();P==null&&(P=L?r.ONE:r.inv(k));let B=r.mul(A,P),C=r.mul(D,P),N=r.mul(k,P);if(L)return{x:r.ZERO,y:r.ZERO};if(!r.eql(N,r.ONE))throw new Error("invZ was invalid");return{x:B,y:C}}isTorsionFree(){let{isTorsionFree:_}=e;return o===wt?!0:_?_(S,this):R.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:_}=e;return o===wt?this:_?_(S,this):this.multiplyUnsafe(o)}isSmallOrder(){return o===wt?this.is0():this.clearCofactor().is0()}toBytes(_=!0){return Ne(_,"isCompressed"),this.assertValidity(),f(S,this,_)}toHex(_=!0){return Xt(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let M=n.BITS,R=new rs(S,e.endo?Math.ceil(M/2):M);return M>=8&&S.BASE.precompute(8),Object.freeze(S.prototype),Object.freeze(S),S}function za(s){return Uint8Array.of(s?2:3)}function Ha(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function fh(s,e={}){let{Fn:t}=s,r=e.randomBytes===void 0?Ts:e.randomBytes,n=Object.assign(Ha(s.Fp,t),{seed:Math.max(Nn(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:b,publicKeyUncompressed:g}=n;try{let x=y.length;return f===!0&&x!==b||f===!1&&x!==g?!1:!!s.fromBytes(y)}catch{return!1}}function a(y){return y=y===void 0?r(n.seed):y,On(K(y,n.seed,"seed"),t.ORDER)}function l(y,f=!0){return s.BASE.multiply(t.fromBytes(y)).toBytes(f)}function u(y){let{secretKey:f,publicKey:b,publicKeyUncompressed:g}=n,x=t._lengths;if(!At(y))return;let I=K(y,void 0,"key").length,c=I===b||I===g,h=I===f||!!x?.includes(I);if(!(c&&h))return c}function d(y,f,b=!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 g=t.fromBytes(y);return s.fromBytes(f).multiply(g).toBytes(b)}let m={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},E=fr(a,l);return Object.freeze(m),Object.freeze(n),Object.freeze({getPublicKey:l,getSharedSecret:d,keygen:E,Point:s,utils:m,lengths:n})}function Ga(s,e,t={}){let r=e;Qs(r),Ue(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes===void 0?Ts:t.randomBytes,i=t.hmac===void 0?(A,D)=>Na(r,A,D):t.hmac,{Fp:o,Fn:a}=s,{ORDER:l,BITS:u}=a,{keygen:d,getPublicKey:m,getSharedSecret:E,utils:y,lengths:f}=fh(s,t),b={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},g=l*Ua+wt<o.ORDER;function x(A){let D=l>>wt;return A>D}function I(A,D){if(!a.isValidNot0(D))throw new Error(`invalid signature ${A}: out of range 1..Point.Fn.ORDER`);return D}function c(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function h(A,D){Pi(D);let k=f.signature,L=D==="compact"?k:D==="recovered"?k+1:void 0;return K(A,L)}class p{r;s;recovery;constructor(D,k,L){if(this.r=I("r",D),this.s=I("s",k),L!=null){if(c(),![0,1,2,3].includes(L))throw new Error("invalid recovery id");this.recovery=L}Object.freeze(this)}static fromBytes(D,k=b.format){h(D,k);let L;if(k==="der"){let{r:U,s:z}=ze.toSig(K(D));return new p(U,z)}k==="recovered"&&(L=D[0],k="compact",D=D.subarray(1));let B=f.signature/2,C=D.subarray(0,B),N=D.subarray(B,B*2);return new p(a.fromBytes(C),a.fromBytes(N),L)}static fromHex(D,k){return this.fromBytes(Jt(D),k)}assertRecovery(){let{recovery:D}=this;if(D==null)throw new Error("invalid recovery id: must be present");return D}addRecoveryBit(D){return new p(this.r,this.s,D)}recoverPublicKey(D){let{r:k,s:L}=this,B=this.assertRecovery(),C=B===2||B===3?k+l:k;if(!o.isValid(C))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let N=o.toBytes(C),U=s.fromBytes(re(za((B&1)===0),N)),z=a.inv(C),O=v(K(D,void 0,"msgHash")),se=a.create(-O*z),ne=a.create(L*z),ie=s.BASE.multiplyUnsafe(se).add(U.multiplyUnsafe(ne));if(ie.is0())throw new Error("invalid recovery: point at infinify");return ie.assertValidity(),ie}hasHighS(){return x(this.s)}toBytes(D=b.format){if(Pi(D),D==="der")return Jt(ze.hexFromSig(this));let{r:k,s:L}=this,B=a.toBytes(k),C=a.toBytes(L);return D==="recovered"?(c(),re(Uint8Array.of(this.assertRecovery()),B,C)):re(B,C)}toHex(D){return Xt(this.toBytes(D))}}Object.freeze(p.prototype),Object.freeze(p);let w=t.bits2int===void 0?function(D){if(D.length>8192)throw new Error("input is too large");let k=Mt(D),L=D.length*8-u;return L>0?k>>BigInt(L):k}:t.bits2int,v=t.bits2int_modN===void 0?function(D){return a.create(w(D))}:t.bits2int_modN,S=Ms(u);function M(A){return Qt("num < 2^"+u,A,Ze,S),a.toBytes(A)}function R(A,D){return K(A,void 0,"message"),D?K(r(A),void 0,"prehashed message"):A}function F(A,D,k){let{lowS:L,prehash:B,extraEntropy:C}=Mi(k,b);A=R(A,B);let N=v(A),U=a.fromBytes(D);if(!a.isValidNot0(U))throw new Error("invalid private key");let z=[M(U),M(N)];if(C!=null&&C!==!1){let ie=C===!0?n(f.secretKey):C;z.push(K(ie,void 0,"extraEntropy"))}let O=re(...z),se=N;function ne(ie){let ee=w(ie);if(!a.isValidNot0(ee))return;let _e=a.inv(ee),Ut=s.BASE.multiply(ee).toAffine(),ms=a.create(Ut.x);if(ms===Ze)return;let qs=a.create(_e*a.create(se+ms*U));if(qs===Ze)return;let Wi=(Ut.x===ms?0:2)|Number(Ut.y&wt),$i=qs;return L&&x(qs)&&($i=a.neg(qs),Wi^=1),new p(ms,$i,g?void 0:Wi)}return{seed:O,k2sig:ne}}function _(A,D,k={}){let{seed:L,k2sig:B}=F(A,D,k);return $o(r.outputLen,a.BYTES,i)(L,B).toBytes(k.format)}function T(A,D,k,L={}){let{lowS:B,prehash:C,format:N}=Mi(L,b);if(k=K(k,void 0,"publicKey"),D=R(D,C),!At(A)){let U=A instanceof p?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+U)}h(A,N);try{let U=p.fromBytes(A,N),z=s.fromBytes(k);if(B&&U.hasHighS())return!1;let{r:O,s:se}=U,ne=v(D),ie=a.inv(se),ee=a.create(ne*ie),_e=a.create(O*ie),Ut=s.BASE.multiplyUnsafe(ee).add(z.multiplyUnsafe(_e));return Ut.is0()?!1:a.create(Ut.x)===O}catch{return!1}}function P(A,D,k={}){let{prehash:L}=Mi(k,b);return D=R(D,L),p.fromBytes(A,"recovered").recoverPublicKey(D).toBytes()}return Object.freeze({keygen:d,getPublicKey:m,getSharedSecret:E,utils:y,lengths:f,Point:s,sign:_,verify:T,recoverPublicKey:P,Signature:p,hash:r})}var Ri={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},dh={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var qa=BigInt(2);function ph(s){let e=Ri.p,t=BigInt(3),r=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),l=BigInt(88),u=s*s*s%e,d=u*u*s%e,m=$(d,t,e)*d%e,E=$(m,t,e)*d%e,y=$(E,qa,e)*u%e,f=$(y,n,e)*y%e,b=$(f,i,e)*f%e,g=$(b,a,e)*b%e,x=$(g,l,e)*g%e,I=$(x,a,e)*b%e,c=$(I,t,e)*d%e,h=$(c,o,e)*f%e,p=$(h,r,e)*u%e,w=$(p,qa,e);if(!Bi.eql(Bi.sqr(w),s))throw new Error("Cannot find square root");return w}var Bi=ts(Ri.p,{sqrt:ph}),mh=Ka(Ri,{Fp:Bi,endo:dh}),os=Ga(mh,Yt);function Va(s,e,t,r){let n=It.digest(t instanceof Uint8Array?t:t.subarray());if(gr(n))return n.then(({digest:i})=>(r?.signal?.throwIfAborted(),os.verify(e,i,s,{prehash:!1,format:"der"}))).catch(i=>{throw i.name==="AbortError"?i:new Rs(String(i))});try{return r?.signal?.throwIfAborted(),os.verify(e,n.digest,s,{prehash:!1,format:"der"})}catch(i){throw new Rs(String(i))}}var _r=class{type="secp256k1";raw;_key;constructor(e){this._key=$a(e),this.raw=Wa(this._key)}toMultihash(){return Ce.digest(Ve(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Te(this.raw,e.raw)}verify(e,t,r){return Va(this._key,t,e,r)}};function Li(s){return new _r(s)}function Wa(s){return os.Point.fromBytes(s).toBytes()}function $a(s){try{return os.Point.fromBytes(s),s}catch(e){throw new zt(String(e))}}function Ci(s,e){let{Type:t,Data:r}=je.decode(s),n=r??new Uint8Array;switch(t){case j.RSA:return Ti(n,e);case j.Ed25519:return Xn(n);case j.secp256k1:return Li(n);case j.ECDSA:return xn(n);default:throw new Ht}}function ja(s){let{Type:e,Data:t}=je.decode(s.digest),r=t??new Uint8Array;switch(e){case j.Ed25519:return Xn(r);case j.secp256k1:return Li(r);case j.ECDSA:return xn(r);default:throw new Ht}}function Ve(s){return je.encode({Type:j[s.type],Data:s.raw})}var Za=Symbol.for("nodejs.util.inspect.custom"),gh=114,Us=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Vr]=!0;toString(){return this.string==null&&(this.string=J.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ce.createV1(gh,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Te(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Te(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Za](){return`PeerId(${this.toString()})`}},Ir=class extends Us{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Tr=class extends Us{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Dr=class extends Us{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},bh=2336,Ks=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ce.digest(V(this.url))}[Za](){return`PeerId(${this.url})`}[Vr]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ce.createV1(bh,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=q(e)),e.toString()===this.toString())}};var yh=114,Ya=2336;function Ct(s,e){let t;if(s.charAt(0)==="1"||s.charAt(0)==="Q")t=Xe(J.decode(`z${s}`));else{if(s.startsWith("k51qzi5uqu5")||s.startsWith("kzwfwjn5ji4")||s.startsWith("k2k4r8")||s.startsWith("bafz"))return wh(ce.parse(s));if(e==null)throw new Y('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Xe(e.decode(s))}return as(t)}function as(s){if(vh(s))return new Ir({multihash:s});if(xh(s))try{let e=ja(s);if(e.type==="Ed25519")return new Tr({multihash:s,publicKey:e});if(e.type==="secp256k1")return new Dr({multihash:s,publicKey:e})}catch{let t=q(s.digest);return new Ks(new URL(t))}throw new $s("Supplied PeerID Multihash is invalid")}function wh(s){if(s?.multihash==null||s.version==null||s.version===1&&s.code!==yh&&s.code!==Ya)throw new Ws("Supplied PeerID CID is invalid");if(s.code===Ya){let e=q(s.multihash.digest);return new Ks(new URL(e))}return as(s.multihash)}function xh(s){return s.code===Ce.code}function vh(s){return s.code===It.code}var Ar=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},cs=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Mr=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},zs=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Pr(s){return s[Symbol.asyncIterator]!=null}function Xa(s,e){if(s.byteLength>e)throw new cs("Message length too long")}var Br=s=>{let e=Le(s),t=fe(e);return ni(s,t),Br.bytes=e,t};Br.bytes=0;function ls(s,e){e=e??{};let t=e.lengthEncoder??Br,r=e?.maxDataLength??4194304;function*n(i){Xa(i,r);let o=t(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return Pr(s)?(async function*(){for await(let i of s)yield*n(i)})():(function*(){for(let i of s)yield*n(i)})()}ls.single=(s,e)=>{e=e??{};let t=e.lengthEncoder??Br,r=e?.maxDataLength??4194304;return Xa(s,r),new oe(t(s.byteLength),s)};var Ft;(function(s){s[s.LENGTH=0]="LENGTH",s[s.DATA=1]="DATA"})(Ft||(Ft={}));var Fi=s=>{let e=ii(s);return Fi.bytes=Le(e),e};Fi.bytes=0;function Hs(s,e){let t=new oe,r=Ft.LENGTH,n=-1,i=e?.lengthDecoder??Fi,o=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*l(){for(;t.byteLength>0;){if(r===Ft.LENGTH)try{if(n=i(t),n<0)throw new Ar("Invalid message length");if(n>a)throw new cs("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 Mr("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 Pr(s)?(async function*(){for await(let u of s)t.append(u),yield*l();if(t.byteLength>0)throw new zs("Unexpected end of input")})():(function*(){for(let u of s)t.append(u),yield*l();if(t.byteLength>0)throw new zs("Unexpected end of input")})()}Hs.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 Hs(r,{...e??{},onLength:i=>{t=i}})};function it(){let s={};return s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),s}var Rr=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},us=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Rr(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Rr(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Ni=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Nt(s={}){return Sh(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 Sh(s,e){e=e??{};let t=e.onEnd,r=new us,n,i,o,a=it(),l=async()=>{try{return r.isEmpty()?o?{done:!0}:await new Promise((g,x)=>{i=I=>{i=null,r.push(I);try{g(s(r))}catch(c){x(c)}return n}}):s(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=it()})}},u=g=>i!=null?i(g):(r.push(g),n),d=g=>(r=new us,i!=null?i({error:g}):(r.push({error:g}),n)),m=g=>{if(o)return n;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:g})},E=g=>o?n:(o=!0,g!=null?d(g):u({done:!0})),y=()=>(r=new us,E(),{done:!0}),f=g=>(E(g),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:l,return:y,throw:f,push:m,end:E,get readableLength(){return r.size},onEmpty:async g=>{let x=g?.signal;if(x?.throwIfAborted(),r.isEmpty())return;let I,c;x!=null&&(I=new Promise((h,p)=>{c=()=>{p(new Ni)},x.addEventListener("abort",c)}));try{await Promise.race([a.promise,I])}finally{c!=null&&x!=null&&x?.removeEventListener("abort",c)}}},t==null)return n;let b=n;return n={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(g){return b.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return b.return(),t!=null&&(t(),t=void 0),{done:!0}},push:m,end(g){return b.end(g),t!=null&&(t(g),t=void 0),n},get readableLength(){return b.readableLength},onEmpty:g=>b.onEmpty(g)},n}function _h(s){return s.reason}async function Oi(s,e,t){if(e==null)return s;let r=t?.translateError??_h;if(e.aborted)return s.catch(()=>{}),Promise.reject(r(e));let n;try{return await Promise.race([s,new Promise((i,o)=>{n=()=>{o(r(e))},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Ui=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=it(),this.haveNext=it()}[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=it(),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=it(),await Oi(this.readNext.promise,t?.signal,t)}};function Ja(){return new Ui}function Ih(s){return s[Symbol.asyncIterator]!=null}async function Th(s,e,t){try{await Promise.all(s.map(async r=>{for await(let n of r)await e.push(n,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(r){await e.end(r,{signal:t}).catch(()=>{})}}async function*Dh(s){let e=new AbortController,t=Ja();Th(s,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Ah(s){for(let e of s)yield*e}function Mh(...s){let e=[];for(let t of s)Ih(t)||e.push(t);return e.length===s.length?Ah(e):Dh(s)}var Qa=Mh;function Gs(s,...e){if(s==null)throw new Error("Empty pipeline");if(Ki(s)){let r=s;s=()=>r.source}else if(tc(s)||ec(s)){let r=s;s=()=>r}let t=[s,...e];if(t.length>1&&Ki(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let r=1;r<t.length-1;r++)Ki(t[r])&&(t[r]=kh(t[r]));return Ph(...t)}var Ph=(...s)=>{let e;for(;s.length>0;)e=s.shift()(e);return e},ec=s=>s?.[Symbol.asyncIterator]!=null,tc=s=>s?.[Symbol.iterator]!=null,Ki=s=>s==null?!1:s.sink!=null&&s.source!=null,kh=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(ec(i))n=async function*(){yield*i,r.end()};else if(tc(i))n=function*(){yield*i,r.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Qa(r,n())}return s.source};var sc={maxSubscriptions:5e3,maxMessages:5e3,maxIhaveMessageIDs:5e3,maxIwantMessageIDs:5e3,maxControlMessages:5e3,maxIdontwantMessageIDs:512,maxPeerInfos:16};var ot;(function(s){let e;(function(f){let b;f.codec=()=>(b==null&&(b=ve((c,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),c.subscribe!=null&&(h.uint32(8),h.bool(c.subscribe)),c.topic!=null&&(h.uint32(18),h.string(c.topic)),p.lengthDelimited!==!1&&h.ldelim()},(c,h,p={})=>{let w={},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{w.subscribe=c.bool();break}case 2:{w.topic=c.string();break}default:{c.skipType(S&7);break}}}return w},function*(c,h,p,w={}){let v=h==null?c.len:c.pos+h;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{yield{field:`${p}.subscribe`,value:c.bool()};break}case 2:{yield{field:`${p}.topic`,value:c.string()};break}default:{c.skipType(S&7);break}}}})),b);function g(c){return we(c,f.codec())}f.encode=g;function x(c,h){return ye(c,f.codec(),h)}f.decode=x;function I(c,h){return xe(c,f.codec(),h)}f.stream=I})(e=s.SubOpts||(s.SubOpts={}));let t;(function(f){let b;f.codec=()=>(b==null&&(b=ve((c,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),c.from!=null&&(h.uint32(10),h.bytes(c.from)),c.data!=null&&(h.uint32(18),h.bytes(c.data)),c.seqno!=null&&(h.uint32(26),h.bytes(c.seqno)),c.topic!=null&&c.topic!==""&&(h.uint32(34),h.string(c.topic)),c.signature!=null&&(h.uint32(42),h.bytes(c.signature)),c.key!=null&&(h.uint32(50),h.bytes(c.key)),p.lengthDelimited!==!1&&h.ldelim()},(c,h,p={})=>{let w={topic:""},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{w.from=c.bytes();break}case 2:{w.data=c.bytes();break}case 3:{w.seqno=c.bytes();break}case 4:{w.topic=c.string();break}case 5:{w.signature=c.bytes();break}case 6:{w.key=c.bytes();break}default:{c.skipType(S&7);break}}}return w},function*(c,h,p,w={}){let v=h==null?c.len:c.pos+h;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{yield{field:`${p}.from`,value:c.bytes()};break}case 2:{yield{field:`${p}.data`,value:c.bytes()};break}case 3:{yield{field:`${p}.seqno`,value:c.bytes()};break}case 4:{yield{field:`${p}.topic`,value:c.string()};break}case 5:{yield{field:`${p}.signature`,value:c.bytes()};break}case 6:{yield{field:`${p}.key`,value:c.bytes()};break}default:{c.skipType(S&7);break}}}})),b);function g(c){return we(c,f.codec())}f.encode=g;function x(c,h){return ye(c,f.codec(),h)}f.decode=x;function I(c,h){return xe(c,f.codec(),h)}f.stream=I})(t=s.Message||(s.Message={}));let r;(function(f){let b;f.codec=()=>(b==null&&(b=ve((c,h,p={})=>{if(p.lengthDelimited!==!1&&h.fork(),c.ihave!=null&&c.ihave.length>0)for(let w of c.ihave)h.uint32(10),s.ControlIHave.codec().encode(w,h);if(c.iwant!=null&&c.iwant.length>0)for(let w of c.iwant)h.uint32(18),s.ControlIWant.codec().encode(w,h);if(c.graft!=null&&c.graft.length>0)for(let w of c.graft)h.uint32(26),s.ControlGraft.codec().encode(w,h);if(c.prune!=null&&c.prune.length>0)for(let w of c.prune)h.uint32(34),s.ControlPrune.codec().encode(w,h);if(c.idontwant!=null&&c.idontwant.length>0)for(let w of c.idontwant)h.uint32(42),s.ControlIDontWant.codec().encode(w,h);p.lengthDelimited!==!1&&h.ldelim()},(c,h,p={})=>{let w={ihave:[],iwant:[],graft:[],prune:[],idontwant:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{if(p.limits?.ihave!=null&&w.ihave.length===p.limits.ihave)throw new W('Decode error - repeated field "ihave" had too many elements');w.ihave.push(s.ControlIHave.codec().decode(c,c.uint32(),{limits:p.limits?.ihave$}));break}case 2:{if(p.limits?.iwant!=null&&w.iwant.length===p.limits.iwant)throw new W('Decode error - repeated field "iwant" had too many elements');w.iwant.push(s.ControlIWant.codec().decode(c,c.uint32(),{limits:p.limits?.iwant$}));break}case 3:{if(p.limits?.graft!=null&&w.graft.length===p.limits.graft)throw new W('Decode error - repeated field "graft" had too many elements');w.graft.push(s.ControlGraft.codec().decode(c,c.uint32(),{limits:p.limits?.graft$}));break}case 4:{if(p.limits?.prune!=null&&w.prune.length===p.limits.prune)throw new W('Decode error - repeated field "prune" had too many elements');w.prune.push(s.ControlPrune.codec().decode(c,c.uint32(),{limits:p.limits?.prune$}));break}case 5:{if(p.limits?.idontwant!=null&&w.idontwant.length===p.limits.idontwant)throw new W('Decode error - repeated field "idontwant" had too many elements');w.idontwant.push(s.ControlIDontWant.codec().decode(c,c.uint32(),{limits:p.limits?.idontwant$}));break}default:{c.skipType(S&7);break}}}return w},function*(c,h,p,w={}){let v={ihave:0,iwant:0,graft:0,prune:0,idontwant:0},S=h==null?c.len:c.pos+h;for(;c.pos<S;){let M=c.uint32();switch(M>>>3){case 1:{if(w.limits?.ihave!=null&&v.ihave===w.limits.ihave)throw new W('Streaming decode error - repeated field "ihave" had too many elements');for(let R of s.ControlIHave.codec().stream(c,c.uint32(),`${p}.ihave[]`,{limits:w.limits?.ihave$}))yield{...R,index:v.ihave};v.ihave++;break}case 2:{if(w.limits?.iwant!=null&&v.iwant===w.limits.iwant)throw new W('Streaming decode error - repeated field "iwant" had too many elements');for(let R of s.ControlIWant.codec().stream(c,c.uint32(),`${p}.iwant[]`,{limits:w.limits?.iwant$}))yield{...R,index:v.iwant};v.iwant++;break}case 3:{if(w.limits?.graft!=null&&v.graft===w.limits.graft)throw new W('Streaming decode error - repeated field "graft" had too many elements');for(let R of s.ControlGraft.codec().stream(c,c.uint32(),`${p}.graft[]`,{limits:w.limits?.graft$}))yield{...R,index:v.graft};v.graft++;break}case 4:{if(w.limits?.prune!=null&&v.prune===w.limits.prune)throw new W('Streaming decode error - repeated field "prune" had too many elements');for(let R of s.ControlPrune.codec().stream(c,c.uint32(),`${p}.prune[]`,{limits:w.limits?.prune$}))yield{...R,index:v.prune};v.prune++;break}case 5:{if(w.limits?.idontwant!=null&&v.idontwant===w.limits.idontwant)throw new W('Streaming decode error - repeated field "idontwant" had too many elements');for(let R of s.ControlIDontWant.codec().stream(c,c.uint32(),`${p}.idontwant[]`,{limits:w.limits?.idontwant$}))yield{...R,index:v.idontwant};v.idontwant++;break}default:{c.skipType(M&7);break}}}})),b);function g(c){return we(c,f.codec())}f.encode=g;function x(c,h){return ye(c,f.codec(),h)}f.decode=x;function I(c,h){return xe(c,f.codec(),h)}f.stream=I})(r=s.ControlMessage||(s.ControlMessage={}));let n;(function(f){let b;f.codec=()=>(b==null&&(b=ve((c,h,p={})=>{if(p.lengthDelimited!==!1&&h.fork(),c.topicID!=null&&(h.uint32(10),h.string(c.topicID)),c.messageIDs!=null&&c.messageIDs.length>0)for(let w of c.messageIDs)h.uint32(18),h.bytes(w);p.lengthDelimited!==!1&&h.ldelim()},(c,h,p={})=>{let w={messageIDs:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{w.topicID=c.string();break}case 2:{if(p.limits?.messageIDs!=null&&w.messageIDs.length===p.limits.messageIDs)throw new W('Decode error - repeated field "messageIDs" had too many elements');w.messageIDs.push(c.bytes());break}default:{c.skipType(S&7);break}}}return w},function*(c,h,p,w={}){let v={messageIDs:0},S=h==null?c.len:c.pos+h;for(;c.pos<S;){let M=c.uint32();switch(M>>>3){case 1:{yield{field:`${p}.topicID`,value:c.string()};break}case 2:{if(w.limits?.messageIDs!=null&&v.messageIDs===w.limits.messageIDs)throw new W('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${p}.messageIDs[]`,index:v.messageIDs,value:c.bytes()},v.messageIDs++;break}default:{c.skipType(M&7);break}}}})),b);function g(c){return we(c,f.codec())}f.encode=g;function x(c,h){return ye(c,f.codec(),h)}f.decode=x;function I(c,h){return xe(c,f.codec(),h)}f.stream=I})(n=s.ControlIHave||(s.ControlIHave={}));let i;(function(f){let b;f.codec=()=>(b==null&&(b=ve((c,h,p={})=>{if(p.lengthDelimited!==!1&&h.fork(),c.messageIDs!=null&&c.messageIDs.length>0)for(let w of c.messageIDs)h.uint32(10),h.bytes(w);p.lengthDelimited!==!1&&h.ldelim()},(c,h,p={})=>{let w={messageIDs:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{if(p.limits?.messageIDs!=null&&w.messageIDs.length===p.limits.messageIDs)throw new W('Decode error - repeated field "messageIDs" had too many elements');w.messageIDs.push(c.bytes());break}default:{c.skipType(S&7);break}}}return w},function*(c,h,p,w={}){let v={messageIDs:0},S=h==null?c.len:c.pos+h;for(;c.pos<S;){let M=c.uint32();switch(M>>>3){case 1:{if(w.limits?.messageIDs!=null&&v.messageIDs===w.limits.messageIDs)throw new W('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${p}.messageIDs[]`,index:v.messageIDs,value:c.bytes()},v.messageIDs++;break}default:{c.skipType(M&7);break}}}})),b);function g(c){return we(c,f.codec())}f.encode=g;function x(c,h){return ye(c,f.codec(),h)}f.decode=x;function I(c,h){return xe(c,f.codec(),h)}f.stream=I})(i=s.ControlIWant||(s.ControlIWant={}));let o;(function(f){let b;f.codec=()=>(b==null&&(b=ve((c,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),c.topicID!=null&&(h.uint32(10),h.string(c.topicID)),p.lengthDelimited!==!1&&h.ldelim()},(c,h,p={})=>{let w={},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let S=c.uint32();S>>>3===1?w.topicID=c.string():c.skipType(S&7)}return w},function*(c,h,p,w={}){let v=h==null?c.len:c.pos+h;for(;c.pos<v;){let S=c.uint32();S>>>3===1?yield{field:`${p}.topicID`,value:c.string()}:c.skipType(S&7)}})),b);function g(c){return we(c,f.codec())}f.encode=g;function x(c,h){return ye(c,f.codec(),h)}f.decode=x;function I(c,h){return xe(c,f.codec(),h)}f.stream=I})(o=s.ControlGraft||(s.ControlGraft={}));let a;(function(f){let b;f.codec=()=>(b==null&&(b=ve((c,h,p={})=>{if(p.lengthDelimited!==!1&&h.fork(),c.topicID!=null&&(h.uint32(10),h.string(c.topicID)),c.peers!=null&&c.peers.length>0)for(let w of c.peers)h.uint32(18),s.PeerInfo.codec().encode(w,h);c.backoff!=null&&(h.uint32(24),h.uint64Number(c.backoff)),p.lengthDelimited!==!1&&h.ldelim()},(c,h,p={})=>{let w={peers:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{w.topicID=c.string();break}case 2:{if(p.limits?.peers!=null&&w.peers.length===p.limits.peers)throw new W('Decode error - repeated field "peers" had too many elements');w.peers.push(s.PeerInfo.codec().decode(c,c.uint32(),{limits:p.limits?.peers$}));break}case 3:{w.backoff=c.uint64Number();break}default:{c.skipType(S&7);break}}}return w},function*(c,h,p,w={}){let v={peers:0},S=h==null?c.len:c.pos+h;for(;c.pos<S;){let M=c.uint32();switch(M>>>3){case 1:{yield{field:`${p}.topicID`,value:c.string()};break}case 2:{if(w.limits?.peers!=null&&v.peers===w.limits.peers)throw new W('Streaming decode error - repeated field "peers" had too many elements');for(let R of s.PeerInfo.codec().stream(c,c.uint32(),`${p}.peers[]`,{limits:w.limits?.peers$}))yield{...R,index:v.peers};v.peers++;break}case 3:{yield{field:`${p}.backoff`,value:c.uint64Number()};break}default:{c.skipType(M&7);break}}}})),b);function g(c){return we(c,f.codec())}f.encode=g;function x(c,h){return ye(c,f.codec(),h)}f.decode=x;function I(c,h){return xe(c,f.codec(),h)}f.stream=I})(a=s.ControlPrune||(s.ControlPrune={}));let l;(function(f){let b;f.codec=()=>(b==null&&(b=ve((c,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),c.peerID!=null&&(h.uint32(10),h.bytes(c.peerID)),c.signedPeerRecord!=null&&(h.uint32(18),h.bytes(c.signedPeerRecord)),p.lengthDelimited!==!1&&h.ldelim()},(c,h,p={})=>{let w={},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{w.peerID=c.bytes();break}case 2:{w.signedPeerRecord=c.bytes();break}default:{c.skipType(S&7);break}}}return w},function*(c,h,p,w={}){let v=h==null?c.len:c.pos+h;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{yield{field:`${p}.peerID`,value:c.bytes()};break}case 2:{yield{field:`${p}.signedPeerRecord`,value:c.bytes()};break}default:{c.skipType(S&7);break}}}})),b);function g(c){return we(c,f.codec())}f.encode=g;function x(c,h){return ye(c,f.codec(),h)}f.decode=x;function I(c,h){return xe(c,f.codec(),h)}f.stream=I})(l=s.PeerInfo||(s.PeerInfo={}));let u;(function(f){let b;f.codec=()=>(b==null&&(b=ve((c,h,p={})=>{if(p.lengthDelimited!==!1&&h.fork(),c.messageIDs!=null&&c.messageIDs.length>0)for(let w of c.messageIDs)h.uint32(10),h.bytes(w);p.lengthDelimited!==!1&&h.ldelim()},(c,h,p={})=>{let w={messageIDs:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{if(p.limits?.messageIDs!=null&&w.messageIDs.length===p.limits.messageIDs)throw new W('Decode error - repeated field "messageIDs" had too many elements');w.messageIDs.push(c.bytes());break}default:{c.skipType(S&7);break}}}return w},function*(c,h,p,w={}){let v={messageIDs:0},S=h==null?c.len:c.pos+h;for(;c.pos<S;){let M=c.uint32();switch(M>>>3){case 1:{if(w.limits?.messageIDs!=null&&v.messageIDs===w.limits.messageIDs)throw new W('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${p}.messageIDs[]`,index:v.messageIDs,value:c.bytes()},v.messageIDs++;break}default:{c.skipType(M&7);break}}}})),b);function g(c){return we(c,f.codec())}f.encode=g;function x(c,h){return ye(c,f.codec(),h)}f.decode=x;function I(c,h){return xe(c,f.codec(),h)}f.stream=I})(u=s.ControlIDontWant||(s.ControlIDontWant={}));let d;s.codec=()=>(d==null&&(d=ve((f,b,g={})=>{if(g.lengthDelimited!==!1&&b.fork(),f.subscriptions!=null&&f.subscriptions.length>0)for(let x of f.subscriptions)b.uint32(10),s.SubOpts.codec().encode(x,b);if(f.messages!=null&&f.messages.length>0)for(let x of f.messages)b.uint32(18),s.Message.codec().encode(x,b);f.control!=null&&(b.uint32(26),s.ControlMessage.codec().encode(f.control,b)),g.lengthDelimited!==!1&&b.ldelim()},(f,b,g={})=>{let x={subscriptions:[],messages:[]},I=b==null?f.len:f.pos+b;for(;f.pos<I;){let c=f.uint32();switch(c>>>3){case 1:{if(g.limits?.subscriptions!=null&&x.subscriptions.length===g.limits.subscriptions)throw new W('Decode error - repeated field "subscriptions" had too many elements');x.subscriptions.push(s.SubOpts.codec().decode(f,f.uint32(),{limits:g.limits?.subscriptions$}));break}case 2:{if(g.limits?.messages!=null&&x.messages.length===g.limits.messages)throw new W('Decode error - repeated field "messages" had too many elements');x.messages.push(s.Message.codec().decode(f,f.uint32(),{limits:g.limits?.messages$}));break}case 3:{x.control=s.ControlMessage.codec().decode(f,f.uint32(),{limits:g.limits?.control});break}default:{f.skipType(c&7);break}}}return x},function*(f,b,g,x={}){let I={subscriptions:0,messages:0},c=b==null?f.len:f.pos+b;for(;f.pos<c;){let h=f.uint32();switch(h>>>3){case 1:{if(x.limits?.subscriptions!=null&&I.subscriptions===x.limits.subscriptions)throw new W('Streaming decode error - repeated field "subscriptions" had too many elements');for(let p of s.SubOpts.codec().stream(f,f.uint32(),`${g}.subscriptions[]`,{limits:x.limits?.subscriptions$}))yield{...p,index:I.subscriptions};I.subscriptions++;break}case 2:{if(x.limits?.messages!=null&&I.messages===x.limits.messages)throw new W('Streaming decode error - repeated field "messages" had too many elements');for(let p of s.Message.codec().stream(f,f.uint32(),`${g}.messages[]`,{limits:x.limits?.messages$}))yield{...p,index:I.messages};I.messages++;break}case 3:{yield*s.ControlMessage.codec().stream(f,f.uint32(),`${g}.control`,{limits:x.limits?.control});break}default:{f.skipType(h&7);break}}}})),d);function m(f){return we(f,s.codec())}s.encode=m;function E(f,b){return ye(f,s.codec(),b)}s.decode=E;function y(f,b){return xe(f,s.codec(),b)}s.stream=y})(ot||(ot={}));var Lr=class{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,r){this.gossip=e,this.msgIdToStrFn=r;for(let n=0;n<t;n++)this.history[n]=[]}get size(){return this.msgs.size}put(e,t,r=!1){let{msgIdStr:n}=e;return this.msgs.has(n)?!1:(this.msgs.set(n,{message:t,validated:r,originatingPeers:new Set,iwantCounts:new Map}),this.history[0].push({...e,topic:t.topic}),r||this.notValidatedCount++,!0)}observeDuplicate(e,t){let r=this.msgs.get(e);r!=null&&!r.validated&&r.originatingPeers.add(t)}get(e){return this.msgs.get(this.msgIdToStrFn(e))?.message}getWithIWantCount(e,t){let r=this.msgs.get(e);if(r==null)return null;let n=(r.iwantCounts.get(t)??0)+1;return r.iwantCounts.set(t,n),{msg:r.message,count:n}}getGossipIDs(e){let t=new Map;for(let r=0;r<this.gossip;r++)this.history[r].forEach(n=>{if((this.msgs.get(n.msgIdStr)?.validated??!1)&&e.has(n.topic)){let o=t.get(n.topic);o==null&&(o=[],t.set(n.topic,o)),o.push(n.msgId)}});return t}validate(e){let t=this.msgs.get(e);if(t==null)return null;t.validated||this.notValidatedCount--;let{message:r,originatingPeers:n}=t;return t.validated=!0,t.originatingPeers=new Set,{message:r,originatingPeers:n}}shift(){this.history[this.history.length-1].forEach(t=>{let r=this.msgs.get(t.msgIdStr);r!=null&&(this.msgs.delete(t.msgIdStr),r.validated||this.notValidatedCount--)}),this.history.pop(),this.history.unshift([])}remove(e){let t=this.msgs.get(e);return t==null?null:(this.msgs.delete(e),t)}};var rc;(function(s){s.StrictSign="StrictSign",s.StrictNoSign="StrictNoSign"})(rc||(rc={}));var xt;(function(s){s[s.Signing=0]="Signing",s[s.Anonymous=1]="Anonymous"})(xt||(xt={}));var Ee;(function(s){s.Error="error",s.Ignore="ignore",s.Reject="reject",s.Blacklisted="blacklisted"})(Ee||(Ee={}));var he;(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"})(he||(he={}));var me;(function(s){s.duplicate="duplicate",s.invalid="invalid",s.valid="valid"})(me||(me={}));function zi(s){switch(s){case ge.Ignore:return Ee.Ignore;case ge.Reject:return Ee.Reject;default:throw new Error("Unreachable")}}var nc;(function(s){s.forward="forward",s.publish="publish"})(nc||(nc={}));var be;(function(s){s.Fanout="fanout",s.Random="random",s.Subscribed="subscribed",s.Outbound="outbound",s.NotEnough="not_enough",s.Opportunistic="opportunistic"})(be||(be={}));var He;(function(s){s.Dc="disconnected",s.BadScore="bad_score",s.Prune="prune",s.Excess="excess"})(He||(He={}));var fs;(function(s){s.GraftBackoff="graft_backoff",s.BrokenPromise="broken_promise",s.MessageDeficit="message_deficit",s.IPColocation="IP_colocation"})(fs||(fs={}));var ds;(function(s){s.LowScore="low_score",s.MaxIhave="max_ihave",s.MaxIasked="max_iasked"})(ds||(ds={}));var hs;(function(s){s.graylist="graylist",s.publish="publish",s.gossip="gossip",s.mesh="mesh"})(hs||(hs={}));function ic(s,e,t){return{protocolsEnabled:s.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:s.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:s.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:s.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEventsFanout:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_fanout_total",help:"Number of times we include peers in a topic mesh for fanout reasons",labelNames:["topic"]}),meshPeerInclusionEventsRandom:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_random_total",help:"Number of times we include peers in a topic mesh for random reasons",labelNames:["topic"]}),meshPeerInclusionEventsSubscribed:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_subscribed_total",help:"Number of times we include peers in a topic mesh for subscribed reasons",labelNames:["topic"]}),meshPeerInclusionEventsOutbound:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_outbound_total",help:"Number of times we include peers in a topic mesh for outbound reasons",labelNames:["topic"]}),meshPeerInclusionEventsNotEnough:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_not_enough_total",help:"Number of times we include peers in a topic mesh for not_enough reasons",labelNames:["topic"]}),meshPeerInclusionEventsOpportunistic:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_opportunistic_total",help:"Number of times we include peers in a topic mesh for opportunistic reasons",labelNames:["topic"]}),meshPeerInclusionEventsUnknown:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_unknown_total",help:"Number of times we include peers in a topic mesh for unknown reasons",labelNames:["topic"]}),meshPeerChurnEventsDisconnected:s.gauge({name:"gossipsub_peer_churn_events_disconnected_total",help:"Number of times we remove peers in a topic mesh for disconnected reasons",labelNames:["topic"]}),meshPeerChurnEventsBadScore:s.gauge({name:"gossipsub_peer_churn_events_bad_score_total",help:"Number of times we remove peers in a topic mesh for bad_score reasons",labelNames:["topic"]}),meshPeerChurnEventsPrune:s.gauge({name:"gossipsub_peer_churn_events_prune_total",help:"Number of times we remove peers in a topic mesh for prune reasons",labelNames:["topic"]}),meshPeerChurnEventsExcess:s.gauge({name:"gossipsub_peer_churn_events_excess_total",help:"Number of times we remove peers in a topic mesh for excess reasons",labelNames:["topic"]}),meshPeerChurnEventsUnknown:s.gauge({name:"gossipsub_peer_churn_events_unknown_total",help:"Number of times we remove peers in a topic mesh for unknown reasons",labelNames:["topic"]}),peersPerProtocol:s.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:s.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:s.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),acceptedMessagesTotal:s.gauge({name:"gossipsub_accepted_messages_total",help:"Total accepted messages for each topic",labelNames:["topic"]}),ignoredMessagesTotal:s.gauge({name:"gossipsub_ignored_messages_total",help:"Total ignored messages for each topic",labelNames:["topic"]}),rejectedMessagesTotal:s.gauge({name:"gossipsub_rejected_messages_total",help:"Total rejected messages for each topic",labelNames:["topic"]}),unknownValidationResultsTotal:s.gauge({name:"gossipsub_unknown_validation_results_total",help:"Total unknown validation results for each topic",labelNames:["topic"]}),asyncValidationMcacheHit:s.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),asyncValidationDelayFromFirstSeenSec:s.histogram({name:"gossipsub_async_validation_delay_from_first_seen",help:"Async validation report delay from first seen in second",buckets:[.01,.03,.1,.3,1,3,10]}),asyncValidationUnknownFirstSeen:s.gauge({name:"gossipsub_async_validation_unknown_first_seen_count_total",help:"Async validation report unknown first seen value for message"}),peerReadStreamError:s.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:s.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:s.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:s.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:s.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:s.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:s.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:s.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:s.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:s.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:s.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:s.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:s.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:s.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:s.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:s.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:s.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:s.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:s.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:s.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:s.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:s.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),rpcSentIDontWant:s.gauge({name:"gossipsub_rpc_sent_idontwant_total",help:"RPC sent"}),msgPublishCount:s.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeersByTopic:s.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),directPeersPublishedTotal:s.gauge({name:"gossipsub_direct_peers_published_total",help:"Total direct peers that we publish a msg to",labelNames:["topic"]}),floodsubPeersPublishedTotal:s.gauge({name:"gossipsub_floodsub_peers_published_total",help:"Total floodsub peers that we publish a msg to",labelNames:["topic"]}),meshPeersPublishedTotal:s.gauge({name:"gossipsub_mesh_peers_published_total",help:"Total mesh peers that we publish a msg to",labelNames:["topic"]}),fanoutPeersPublishedTotal:s.gauge({name:"gossipsub_fanout_peers_published_total",help:"Total fanout peers that we publish a msg to",labelNames:["topic"]}),msgPublishBytes:s.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgPublishTime:s.histogram({name:"gossipsub_msg_publish_seconds",help:"Total time in seconds to publish a message",buckets:[.001,.002,.005,.01,.1,.5,1],labelNames:["topic"]}),msgForwardCount:s.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:s.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:s.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:s.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),prevalidationInvalidTotal:s.gauge({name:"gossipsub_pre_validation_invalid_total",help:"Total count of invalid messages received",labelNames:["topic"]}),prevalidationValidTotal:s.gauge({name:"gossipsub_pre_validation_valid_total",help:"Total count of valid messages received",labelNames:["topic"]}),prevalidationDuplicateTotal:s.gauge({name:"gossipsub_pre_validation_duplicate_total",help:"Total count of duplicate messages received",labelNames:["topic"]}),prevalidationUnknownTotal:s.gauge({name:"gossipsub_pre_validation_unknown_status_total",help:"Total count of unknown_status messages received",labelNames:["topic"]}),msgReceivedInvalid:s.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["error"]}),msgReceivedInvalidByTopic:s.gauge({name:"gossipsub_msg_received_invalid_by_topic_total",help:"Tracks specific invalid message by topic",labelNames:["topic"]}),duplicateMsgDeliveryDelay:s.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*t.maxMeshMessageDeliveriesWindowSec,.5*t.maxMeshMessageDeliveriesWindowSec,Number(t.maxMeshMessageDeliveriesWindowSec),2*t.maxMeshMessageDeliveriesWindowSec,4*t.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:s.gauge({name:"gossisub_duplicate_msg_late_delivery_total",help:"Total count of late duplicate message delivery by topic, which triggers P3 penalty",labelNames:["topic"]}),duplicateMsgIgnored:s.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:s.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:s.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:s.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:s.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:s.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores"}),scoreWeights:s.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:s.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:s.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:s.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*t.behaviourPenaltyThreshold,.5*t.behaviourPenaltyThreshold,Number(t.behaviourPenaltyThreshold),2*t.behaviourPenaltyThreshold,4*t.behaviourPenaltyThreshold]}),ihaveRcvIgnored:s.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:s.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:s.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:s.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:s.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),idontwantRcvMsgids:s.gauge({name:"gossipsub_idontwant_rcv_msgids_total",help:"Total received IDONTWANT messages"}),idontwantRcvDonthaveMsgids:s.gauge({name:"gossipsub_idontwant_rcv_dont_have_msgids_total",help:"Total received IDONTWANT messageIDs that we do not have in mcache"}),iwantPromiseStarted:s.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:s.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:s.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:s.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:s.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:s.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:s.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*t.gossipPromiseExpireSec,Number(t.gossipPromiseExpireSec),2*t.gossipPromiseExpireSec,4*t.gossipPromiseExpireSec]}),iwantPromiseUntracked:s.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),connectedPeersBackoffSec:s.histogram({name:"gossipsub_connected_peers_backoff_seconds",help:"Backoff time in seconds",buckets:[1,2,4,10,20,60,120]}),cacheSize:s.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:s.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:s.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:s.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:s.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:e,toTopic(r){return this.topicStrToLabel.get(r)??r},onJoin(r){this.topicSubscriptionStatus.set({topicStr:r},1),this.meshPeerCounts.set({topicStr:r},0)},onLeave(r){this.topicSubscriptionStatus.set({topicStr:r},0),this.meshPeerCounts.set({topicStr:r},0)},onAddToMesh(r,n,i){let o=this.toTopic(r);switch(n){case be.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:o},i);break;case be.Random:this.meshPeerInclusionEventsRandom.inc({topic:o},i);break;case be.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:o},i);break;case be.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:o},i);break;case be.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:o},i);break;case be.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 He.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:o},i);break;case He.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:o},i);break;case He.Prune:this.meshPeerChurnEventsPrune.inc({topic:o},i);break;case He.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 ge.Accept:this.acceptedMessagesTotal.inc({topic:o});break;case ge.Ignore:this.ignoredMessagesTotal.inc({topic:o});break;case ge.Reject:this.rejectedMessagesTotal.inc({topic:o});break;default:this.unknownValidationResultsTotal.inc({topic:o});break}}i!=null?this.asyncValidationDelayFromFirstSeenSec.observe((Date.now()-i)/1e3):this.asyncValidationUnknownFirstSeen.inc()},onScorePenalty(r){this.scoringPenalties.inc({penalty:r},1)},onIhaveRcv(r,n,i){let o=this.toTopic(r);this.ihaveRcvMsgids.inc({topic:o},n),this.ihaveRcvNotSeenMsgids.inc({topic:o},i)},onIwantRcv(r,n){for(let[i,o]of r){let a=this.toTopic(i);this.iwantRcvMsgids.inc({topic:a},o)}this.iwantRcvDonthaveMsgids.inc(n)},onIdontwantRcv(r,n){this.idontwantRcvMsgids.inc(r),this.idontwantRcvDonthaveMsgids.inc(n)},onForwardMsg(r,n){let i=this.toTopic(r);this.msgForwardCount.inc({topic:i},1),this.msgForwardPeers.inc({topic:i},n)},onPublishMsg(r,n,i,o,a){let l=this.toTopic(r);this.msgPublishCount.inc({topic:l},1),this.msgPublishBytes.inc({topic:l},i*o),this.msgPublishPeersByTopic.inc({topic:l},i),this.directPeersPublishedTotal.inc({topic:l},n.direct),this.floodsubPeersPublishedTotal.inc({topic:l},n.floodsub),this.meshPeersPublishedTotal.inc({topic:l},n.mesh),this.fanoutPeersPublishedTotal.inc({topic:l},n.fanout),this.msgPublishTime.observe({topic:l},a/1e3)},onMsgRecvPreValidation(r){let n=this.toTopic(r);this.msgReceivedPreValidation.inc({topic:n},1)},onMsgRecvError(r){let n=this.toTopic(r);this.msgReceivedError.inc({topic:n},1)},onPrevalidationResult(r,n){let i=this.toTopic(r);switch(n){case me.duplicate:this.prevalidationDuplicateTotal.inc({topic:i});break;case me.invalid:this.prevalidationInvalidTotal.inc({topic:i});break;case me.valid:this.prevalidationValidTotal.inc({topic:i});break;default:this.prevalidationUnknownTotal.inc({topic:i});break}},onMsgRecvInvalid(r,n){let i=this.toTopic(r),o=n.reason===Ee.Error?n.error:n.reason;this.msgReceivedInvalid.inc({error:o},1),this.msgReceivedInvalidByTopic.inc({topic:i},1)},onDuplicateMsgDelivery(r,n,i){let o=this.toTopic(r);this.duplicateMsgDeliveryDelay.observe({topic:o},n/1e3),i&&this.duplicateMsgLateDelivery.inc({topic:o},1)},onPublishDuplicateMsg(r){let n=this.toTopic(r);this.duplicateMsgIgnored.inc({topic:n},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(r,n){this.rpcRecvBytes.inc(n),this.rpcRecvCount.inc(1),r.subscriptions!=null&&this.rpcRecvSubscription.inc(r.subscriptions.length),r.messages!=null&&this.rpcRecvMessage.inc(r.messages.length),r.control!=null&&(this.rpcRecvControl.inc(1),r.control.ihave!=null&&this.rpcRecvIHave.inc(r.control.ihave.length),r.control.iwant!=null&&this.rpcRecvIWant.inc(r.control.iwant.length),r.control.graft!=null&&this.rpcRecvGraft.inc(r.control.graft.length),r.control.prune!=null&&this.rpcRecvPrune.inc(r.control.prune.length))},onRpcSent(r,n){if(this.rpcSentBytes.inc(n),this.rpcSentCount.inc(1),r.subscriptions!=null&&this.rpcSentSubscription.inc(r.subscriptions.length),r.messages!=null&&this.rpcSentMessage.inc(r.messages.length),r.control!=null){let i=r.control.ihave?.length??0,o=r.control.iwant?.length??0,a=r.control.graft?.length??0,l=r.control.prune?.length??0,u=r.control.idontwant?.length??0;i>0&&this.rpcSentIHave.inc(i),o>0&&this.rpcSentIWant.inc(o),a>0&&this.rpcSentGraft.inc(a),l>0&&this.rpcSentPrune.inc(l),u>0&&this.rpcSentIDontWant.inc(u),(i>0||o>0||a>0||l>0||u>0)&&this.rpcSentControl.inc(1)}},registerScores(r,n){let i=0,o=0,a=0,l=0;for(let u of r)u>=n.graylistThreshold&&i++,u>=n.publishThreshold&&o++,u>=n.gossipThreshold&&a++,u>=0&&l++;this.peersByScoreThreshold.set({threshold:hs.graylist},i),this.peersByScoreThreshold.set({threshold:hs.publish},o),this.peersByScoreThreshold.set({threshold:hs.gossip},a),this.peersByScoreThreshold.set({threshold:hs.mesh},l),this.score.set(r)},registerScoreWeights(r){for(let[n,i]of r.byTopic)this.scoreWeights.set({topic:n,p:"p1"},i.p1w),this.scoreWeights.set({topic:n,p:"p2"},i.p2w),this.scoreWeights.set({topic:n,p:"p3"},i.p3w),this.scoreWeights.set({topic:n,p:"p3b"},i.p3bw),this.scoreWeights.set({topic:n,p:"p4"},i.p4w);this.scoreWeights.set({p:"p5"},r.p5w),this.scoreWeights.set({p:"p6"},r.p6w),this.scoreWeights.set({p:"p7"},r.p7w)},registerScorePerMesh(r,n){let i=new Map;r.forEach((o,a)=>{let l=this.topicStrToLabel.get(a)??"unknown",u=i.get(l);u==null&&(u=new Set,i.set(l,u)),o.forEach(d=>u?.add(d))});for(let[o,a]of i){let l=[];a.forEach(u=>{l.push(n.get(u)??0)}),this.scorePerMesh.set({topic:o},l)}}}}var G=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var Bh={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},Rh={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 oc(s={}){return{...Bh,...s,topics:s.topics!=null?Object.entries(s.topics).reduce((e,[t,r])=>(e[t]=Lh(r),e),{}):{}}}function Lh(s={}){return{...Rh,...s}}function ac(s){for(let[e,t]of Object.entries(s.topics))try{Ch(t)}catch(r){throw new G(`invalid score parameters for topic ${e}: ${r.message}`)}if(s.topicScoreCap<0)throw new G("invalid topic score cap; must be positive (or 0 for no cap)");if(s.appSpecificScore===null||s.appSpecificScore===void 0)throw new G("missing application specific score function");if(s.IPColocationFactorWeight>0)throw new G("invalid IPColocationFactorWeight; must be negative (or 0 to disable)");if(s.IPColocationFactorWeight!==0&&s.IPColocationFactorThreshold<1)throw new G("invalid IPColocationFactorThreshold; must be at least 1");if(s.behaviourPenaltyWeight>0)throw new G("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)");if(s.behaviourPenaltyWeight!==0&&(s.behaviourPenaltyDecay<=0||s.behaviourPenaltyDecay>=1))throw new G("invalid BehaviourPenaltyDecay; must be between 0 and 1");if(s.decayInterval<1e3)throw new G("invalid DecayInterval; must be at least 1s");if(s.decayToZero<=0||s.decayToZero>=1)throw new G("invalid DecayToZero; must be between 0 and 1")}function Ch(s){if(s.topicWeight<0)throw new G("invalid topic weight; must be >= 0");if(s.timeInMeshQuantum===0)throw new G("invalid TimeInMeshQuantum; must be non zero");if(s.timeInMeshWeight<0)throw new G("invalid TimeInMeshWeight; must be positive (or 0 to disable)");if(s.timeInMeshWeight!==0&&s.timeInMeshQuantum<=0)throw new G("invalid TimeInMeshQuantum; must be positive");if(s.timeInMeshWeight!==0&&s.timeInMeshCap<=0)throw new G("invalid TimeInMeshCap; must be positive");if(s.firstMessageDeliveriesWeight<0)throw new G("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)");if(s.firstMessageDeliveriesWeight!==0&&(s.firstMessageDeliveriesDecay<=0||s.firstMessageDeliveriesDecay>=1))throw new G("invalid FirstMessageDeliveriesDecay; must be between 0 and 1");if(s.firstMessageDeliveriesWeight!==0&&s.firstMessageDeliveriesCap<=0)throw new G("invalid FirstMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight>0)throw new G("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.meshMessageDeliveriesWeight!==0&&(s.meshMessageDeliveriesDecay<=0||s.meshMessageDeliveriesDecay>=1))throw new G("invalid MeshMessageDeliveriesDecay; must be between 0 and 1");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesCap<=0)throw new G("invalid MeshMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesThreshold<=0)throw new G("invalid MeshMessageDeliveriesThreshold; must be positive");if(s.meshMessageDeliveriesWindow<0)throw new G("invalid MeshMessageDeliveriesWindow; must be non-negative");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesActivation<1e3)throw new G("invalid MeshMessageDeliveriesActivation; must be at least 1s");if(s.meshFailurePenaltyWeight>0)throw new G("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)");if(s.meshFailurePenaltyWeight!==0&&(s.meshFailurePenaltyDecay<=0||s.meshFailurePenaltyDecay>=1))throw new G("invalid MeshFailurePenaltyDecay; must be between 0 and 1");if(s.invalidMessageDeliveriesWeight>0)throw new G("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.invalidMessageDeliveriesDecay<=0||s.invalidMessageDeliveriesDecay>=1)throw new G("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1")}var Fh={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function cc(s={}){return{...Fh,...s}}function Fr(s,e,t=()=>!0){let r=new Set;if(e<=0)return r;for(let n of s){if(r.size>=e)break;t(n)&&(r.add(n),s.delete(n))}return r}function lc(s,e){return Fr(s,e,()=>!0)}var Cr=class extends Map{getDefault;constructor(e){super(),this.getDefault=e}getOrDefault(e){let t=super.get(e);return t===void 0&&(t=this.getDefault(),this.set(e,t)),t}};function uc(s,e,t,r){let n=0;Object.entries(e.topics).forEach(([o,a])=>{let l=t.topics[o];if(l===void 0)return;let u=0;if(a.inMesh){let y=a.meshTime/l.timeInMeshQuantum;y>l.timeInMeshCap&&(y=l.timeInMeshCap),u+=y*l.timeInMeshWeight}let d=a.firstMessageDeliveries;if(d>l.firstMessageDeliveriesCap&&(d=l.firstMessageDeliveriesCap),u+=d*l.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries<l.meshMessageDeliveriesThreshold){let y=l.meshMessageDeliveriesThreshold-a.meshMessageDeliveries,f=y*y;u+=f*l.meshMessageDeliveriesWeight}let m=a.meshFailurePenalty;u+=m*l.meshFailurePenaltyWeight;let E=a.invalidMessageDeliveries*a.invalidMessageDeliveries;u+=E*l.invalidMessageDeliveriesWeight,n+=u*l.topicWeight}),t.topicScoreCap>0&&n>t.topicScoreCap&&(n=t.topicScoreCap);let i=t.appSpecificScore(s);if(n+=i*t.appSpecificWeight,e.knownIPs.forEach(o=>{if(t.IPColocationFactorWhitelist.has(o))return;let a=r.get(o),l=a!=null?a.size:0;if(l>t.IPColocationFactorThreshold){let u=l-t.IPColocationFactorThreshold,d=u*u;n+=d*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let o=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=o*o;n+=a*t.behaviourPenaltyWeight}return n}var dc=Cc(fc(),1);var Se;(function(s){s[s.unknown=0]="unknown",s[s.valid=1]="valid",s[s.invalid=2]="invalid",s[s.ignored=3]="ignored"})(Se||(Se={}));var Nr=class{records;queue;constructor(){this.records=new Map,this.queue=new dc.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:Se.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let r={msgId:e,expire:Date.now()+12e4};return this.queue.push(r),t}gc(){let e=Date.now(),t=this.queue.peekFront();for(;t!=null&&t.expire<e;)this.records.delete(t.msgId),this.queue.shift(),t=this.queue.peekFront()}clear(){this.records.clear(),this.queue.clear()}};var Or=class{params;metrics;peerStats=new Map;peerIPs=new Cr(()=>new Set);scoreCache=new Map;deliveryRecords=new Nr;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,r,n){this.params=e,this.metrics=t,ac(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??uc,this.log=r.forComponent("libp2p:gossipsub:score")}get size(){return this.peerStats.size}start(){if(this._backgroundInterval!=null){this.log("Peer score already running");return}this._backgroundInterval=setInterval(()=>{this.background()},this.params.decayInterval),this.log("started")}stop(){if(this._backgroundInterval==null){this.log("Peer score already stopped");return}clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),this.log("stopped")}background(){this.refreshScores(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map(([e,t])=>[e,t]))}messageFirstSeenTimestampMs(e){let t=this.deliveryRecords.getRecord(e);return t!=null?t.firstSeenTsMs:null}refreshScores(){let e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach((r,n)=>{if(!r.connected){e>r.expire&&(this.removeIPsForPeer(n,r.knownIPs),this.peerStats.delete(n),this.scoreCache.delete(n));return}Object.entries(r.topics).forEach(([i,o])=>{let a=this.params.topics[i];a!==void 0&&(o.firstMessageDeliveries*=a.firstMessageDeliveriesDecay,o.firstMessageDeliveries<t&&(o.firstMessageDeliveries=0),o.meshMessageDeliveries*=a.meshMessageDeliveriesDecay,o.meshMessageDeliveries<t&&(o.meshMessageDeliveries=0),o.meshFailurePenalty*=a.meshFailurePenaltyDecay,o.meshFailurePenalty<t&&(o.meshFailurePenalty=0),o.invalidMessageDeliveries*=a.invalidMessageDeliveriesDecay,o.invalidMessageDeliveries<t&&(o.invalidMessageDeliveries=0),o.inMesh&&(o.meshTime=e-o.graftTime,o.meshTime>a.meshMessageDeliveriesActivation&&(o.meshMessageDeliveriesActive=!0)))}),r.behaviourPenalty*=this.params.behaviourPenaltyDecay,r.behaviourPenalty<t&&(r.behaviourPenalty=0)})}score(e){this.metrics?.scoreFnCalls.inc();let t=this.peerStats.get(e);if(t==null)return 0;let r=Date.now(),n=this.scoreCache.get(e);if(n!=null&&n.cacheUntil>r)return n.score;this.metrics?.scoreFnRuns.inc();let i=this.computeScore(e,t,this.params,this.peerIPs),o=r+this.scoreCacheValidityMs;return n!=null?(this.metrics?.scoreCachedDelta.observe(Math.abs(i-n.score)),n.score=i,n.cacheUntil=o):this.scoreCache.set(e,{score:i,cacheUntil:o}),i}addPenalty(e,t,r){let n=this.peerStats.get(e);n!=null&&(n.behaviourPenalty+=t,this.metrics?.onScorePenalty(r))}addPeer(e){let t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){let r=this.peerStats.get(e);r?.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){let r=this.peerStats.get(e);r?.knownIPs.delete(t);let n=this.peerIPs.get(t);n!=null&&(n.delete(e),n.size===0&&this.peerIPs.delete(t))}removePeer(e){let t=this.peerStats.get(e);if(t!=null){if(this.score(e)>0){this.removeIPsForPeer(e,t.knownIPs),this.peerStats.delete(e);return}Object.entries(t.topics).forEach(([r,n])=>{n.firstMessageDeliveries=0;let i=this.params.topics[r].meshMessageDeliveriesThreshold;if(n.inMesh&&n.meshMessageDeliveriesActive&&n.meshMessageDeliveries<i){let o=i-n.meshMessageDeliveries;n.meshFailurePenalty+=o*o}n.inMesh=!1,n.meshMessageDeliveriesActive=!1}),t.connected=!1,t.expire=Date.now()+this.params.retainScore}}graft(e,t){let r=this.peerStats.get(e);if(r!=null){let n=this.getPtopicStats(r,t);n!=null&&(n.inMesh=!0,n.graftTime=Date.now(),n.meshTime=0,n.meshMessageDeliveriesActive=!1)}}prune(e,t){let r=this.peerStats.get(e);if(r!=null){let n=this.getPtopicStats(r,t);if(n!=null){let i=this.params.topics[t].meshMessageDeliveriesThreshold;if(n.meshMessageDeliveriesActive&&n.meshMessageDeliveries<i){let o=i-n.meshMessageDeliveries;n.meshFailurePenalty+=o*o}n.meshMessageDeliveriesActive=!1,n.inMesh=!1}}}validateMessage(e){this.deliveryRecords.ensureRecord(e)}deliverMessage(e,t,r){this.markFirstMessageDelivery(e,r);let n=this.deliveryRecords.ensureRecord(t),i=Date.now();if(n.status!==Se.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,i-n.firstSeenTsMs,Se[n.status]);return}n.status=Se.valid,n.validated=i,n.peers.forEach(o=>{o!==e.toString()&&this.markDuplicateMessageDelivery(o,r)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,r,n){switch(n){case Ee.Error:this.markInvalidMessageDelivery(e,r);return;case Ee.Blacklisted:return}let i=this.deliveryRecords.ensureRecord(t);if(i.status!==Se.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-i.firstSeenTsMs,Se[i.status]);return}if(n===Ee.Ignore){i.status=Se.ignored,i.peers.clear();return}i.status=Se.invalid,this.markInvalidMessageDelivery(e,r),i.peers.forEach(o=>{this.markInvalidMessageDelivery(o,r)}),i.peers.clear()}duplicateMessage(e,t,r){let n=this.deliveryRecords.ensureRecord(t);if(!n.peers.has(e))switch(n.status){case Se.unknown:n.peers.add(e);break;case Se.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,r,n.validated);break;case Se.invalid:this.markInvalidMessageDelivery(e,r);break;case Se.ignored:break}}markInvalidMessageDelivery(e,t){let r=this.peerStats.get(e);if(r!=null){let n=this.getPtopicStats(r,t);n!=null&&(n.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){let r=this.peerStats.get(e);if(r!=null){let n=this.getPtopicStats(r,t);if(n!=null){let i=this.params.topics[t].firstMessageDeliveriesCap;n.firstMessageDeliveries=Math.min(i,n.firstMessageDeliveries+1),n.inMesh&&(i=this.params.topics[t].meshMessageDeliveriesCap,n.meshMessageDeliveries=Math.min(i,n.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,r){let n=this.peerStats.get(e);if(n!=null){let i=r!==void 0?Date.now():0,o=this.getPtopicStats(n,t);if(o!=null&&o.inMesh){let a=this.params.topics[t];if(r!==void 0){let u=i-r,d=u>a.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,u,d),d)return}let l=a.meshMessageDeliveriesCap;o.meshMessageDeliveries=Math.min(l,o.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(let r of t){let n=this.peerIPs.get(r);n!=null&&(n.delete(e),n.size===0&&this.peerIPs.delete(r))}}getPtopicStats(e,t){let r=e.topics[t];return r!==void 0?r:this.params.topics[t]!==void 0?(r={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=r,r):null}};function Nh(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",b=t.topics[E];if(b===void 0)return;let g=o.get(f);g==null&&(g={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},o.set(f,g));let x=0,I=0,c=0,h=0,p=0;if(y.inMesh){let M=Math.max(y.meshTime/b.timeInMeshQuantum,b.timeInMeshCap);x+=M*b.timeInMeshWeight}let w=y.firstMessageDeliveries;if(w>b.firstMessageDeliveriesCap&&(w=b.firstMessageDeliveriesCap),I+=w*b.firstMessageDeliveriesWeight,y.meshMessageDeliveriesActive&&y.meshMessageDeliveries<b.meshMessageDeliveriesThreshold){let M=b.meshMessageDeliveriesThreshold-y.meshMessageDeliveries,R=M*M;c+=R*b.meshMessageDeliveriesWeight}let v=y.meshFailurePenalty;h+=v*b.meshFailurePenaltyWeight;let S=y.invalidMessageDeliveries*y.invalidMessageDeliveries;p+=S*b.invalidMessageDeliveriesWeight,i+=(x+I+c+h+p)*b.topicWeight,g.p1w+=x,g.p2w+=I,g.p3w+=c,g.p3bw+=h,g.p4w+=p}),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,l=0,u=0,d=t.appSpecificScore(s);a+=d*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 b=f-t.IPColocationFactorThreshold,g=b*b;l+=g*t.IPColocationFactorWeight}});let m=e.behaviourPenalty*e.behaviourPenalty;return u+=m*t.behaviourPenaltyWeight,i+=a+l+u,{byTopic:o,p5w:a,p6w:l,p7w:u,score:i}}function pc(s,e,t,r,n){let i={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let o of s){let a=e.get(o);if(a!=null){let l=Nh(o,a,t,r,n);for(let[u,d]of l.byTopic){let m=i.byTopic.get(u);m==null&&(m={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},i.byTopic.set(u,m)),m.p1w.push(d.p1w),m.p2w.push(d.p2w),m.p3w.push(d.p3w),m.p3bw.push(d.p3bw),m.p4w.push(d.p4w)}i.p5w.push(l.p5w),i.p6w.push(l.p6w),i.p7w.push(l.p7w),i.score.push(l.score)}else i.p5w.push(0),i.p6w.push(0),i.p7w.push(0),i.score.push(0)}return i}function Hi(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 mc(s){let e=Hi(s);if(e==null)throw new Y(`Multiaddr ${s} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function gc(s){return Hi(s)!==null}var Gi=class s extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,s)}},bc=s=>s.reason??new DOMException("This operation was aborted.","AbortError");function qi(s,e){let{milliseconds:t,fallback:r,message:n,customTimers:i={setTimeout,clearTimeout},signal:o}=e,a,l,d=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(bc(o));return}if(o&&(l=()=>{E(bc(o))},o.addEventListener("abort",l,{once:!0})),s.then(m,E),t===Number.POSITIVE_INFINITY)return;let y=new Gi;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(()=>{d.clear(),l&&o&&o.removeEventListener("abort",l)});return d.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},d}var Oh=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 Uh(s,e,t){let r,n=new Promise((i,o)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),l=[],{addListener:u,removeListener:d}=Oh(s),m=async(...y)=>{let f=t.multiArgs?y:y[0];if(t.filter)try{if(!await t.filter(f))return}catch(b){r(),o(b);return}l.push(f),t.count===l.length&&(r(),i(l))},E=(...y)=>{r(),o(t.rejectionMultiArgs?y:y[0])};r=()=>{for(let y of a)d(y,m);for(let y of t.rejectionEvents)a.includes(y)||d(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(l)});if(n.cancel=r,typeof t.timeout=="number"){let i=qi(n,{milliseconds:t.timeout});return i.cancel=()=>{r(),i.clear()},i}return n}function yc(s,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let r=Uh(s,e,t),n=r.then(i=>i[0]);return n.cancel=r.cancel,n}function Kh(s){return s?.addEventListener!=null}function zh(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 l=a();for(;;){t=Promise.withResolvers();let{done:u,value:d}=await Promise.race([l.next(),t.promise]);if(s.writeStatus==="closing"||s.writeStatus==="closed"||(d!=null&&(s.send(d)||await Promise.race([yc(s,"drain",{rejectionEvents:["close"]})])),u===!0))break}await s.close()}}}function wc(...s){let e=s.map(t=>Kh(t)?zh(t):t);return Gs(...e)}var Ur=class{rawStream;constructor(e,t,r){this.rawStream=e,r.maxBufferSize!=null&&(e.maxWriteBufferLength=r.maxBufferSize),e.addEventListener("close",n=>{n.error!=null&&t(n.error)})}get protocol(){return this.rawStream.protocol}push(e){this.pushPrefixed(ls.single(e))}pushPrefixed(e){this.rawStream.send(e)}async close(e){await this.rawStream.close(e).catch(t=>{this.rawStream.abort(t)})}},Kr=class{source;rawStream;closeController;constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(r=>{e.abort(r)})}),this.source=wc(this.rawStream,r=>Hs(r,t))}async close(){this.closeController.abort()}};var zr=class{gossipsubIWantFollowupMs;msgIdToStrFn;metrics;promises=new Map;requestMsByMsg=new Map;requestMsByMsgExpire;constructor(e,t,r){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=r,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){let r=Math.floor(Math.random()*t.length),n=t[r],i=this.msgIdToStrFn(n),o=this.promises.get(i);o==null&&(o=new Map,this.promises.set(i,o));let a=Date.now();o.has(e)||(o.set(e,a+this.gossipsubIWantFollowupMs),this.metrics!=null&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(i)||this.requestMsByMsg.set(i,a)))}getBrokenPromises(){let e=Date.now(),t=new Map,r=0;return this.promises.forEach((n,i)=>{n.forEach((o,a)=>{o<e&&(t.set(a,(t.get(a)??0)+1),n.delete(a),r++)}),n.size===0&&this.promises.delete(i)}),this.metrics?.iwantPromiseBroken.inc(r),t}deliverMessage(e,t=!1){this.trackMessage(e);let r=this.promises.get(e);r!=null&&(this.promises.delete(e),this.metrics!=null&&(this.metrics.iwantPromiseResolved.inc(1),t&&this.metrics.iwantPromiseResolvedFromDuplicate.inc(1),this.metrics.iwantPromiseResolvedPeers.inc(r.size)))}rejectMessage(e,t){this.trackMessage(e),t!==Ee.Error&&this.promises.delete(e)}clear(){this.promises.clear()}prune(){let e=Date.now()-this.requestMsByMsgExpire,t=0;for(let[r,n]of this.requestMsByMsg.entries())if(n<e)this.requestMsByMsg.delete(r),t++;else break;this.metrics?.iwantMessagePruned.inc(t)}trackMessage(e){if(this.metrics!=null){let t=this.requestMsByMsg.get(e);t!==void 0&&(this.metrics.iwantPromiseDeliveryTime.observe((Date.now()-t)/1e3),this.requestMsByMsg.delete(e))}}};var xc=V("libp2p-pubsub:"),Hh=BigInt(Date.now())*1000000n;function Gh(){let s=++Hh,e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,s,!1),e}async function vc(s,e,t,r){switch(s.type){case xt.Signing:{let n={from:s.author.toMultihash().bytes,data:r,seqno:Gh(),topic:e,signature:void 0,key:void 0},i=_t([xc,ot.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${q(n.seqno??new Uint8Array(0),"base16")}`),topic:e,signature:n.signature,key:Ci(n.key)};return{raw:n,msg:o}}case xt.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 Ec(s,e){switch(s){case Ot:return e.signature!=null?{valid:!1,error:he.SignaturePresent}:e.seqno!=null?{valid:!1,error:he.SeqnoPresent}:e.key!=null?{valid:!1,error:he.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case vt:{if(e.seqno==null)return{valid:!1,error:he.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:he.InvalidSeqno};if(e.signature==null)return{valid:!1,error:he.InvalidSignature};if(e.from==null)return{valid:!1,error:he.InvalidPeerId};let t;try{t=as(Xe(e.from))}catch{return{valid:!1,error:he.InvalidPeerId}}let r;if(e.key!=null){try{r=Ci(e.key)}catch{return{valid:!1,error:he.InvalidPeerId}}if(!t.equals(r.toMultihash().bytes))return{valid:!1,error:he.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:he.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=_t([xc,ot.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${q(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:r}}:{valid:!1,error:he.InvalidSignature}}default:throw new Error("Unreachable")}}function Ge(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 Vi(s){return s.control===void 0&&(s.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),s}function Ye(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 Sc(s){return q(s,"base64")}function _c(s,e,t){switch(s){case vt:return{type:xt.Signing,author:e,key:Ve(t.publicKey),privateKey:t};case Ot:return{type:xt.Anonymous};default:throw new Error(`Unknown signature policy "${s}"`)}}var qh=(s,e)=>{let t=V(e.toString(16).padStart(16,"0"),"base16"),r=Ve(s),n=new Uint8Array(r.byteLength+t.length);return n.set(r,0),n.set(t,r.byteLength),n};function Ic(s){if(s.type!=="signed")throw new Error("expected signed message type");if(s.sequenceNumber==null)throw Error("missing seqno field");return qh(s.from.publicKey??s.key,s.sequenceNumber)}async function Tc(s){return It.encode(s.data)}function Dc(s){if(gc(s)){let e=mc(s);switch(e.type){case"ip4":case"ip6":return e.host;default:break}}return null}var ps=class{entries=new Map;validityMs;constructor(e){this.validityMs=e.validityMs}get size(){return this.entries.size}put(e,t){return this.entries.has(e)?!0:(this.entries.set(e,{value:t,validUntilMs:Date.now()+this.validityMs}),!1)}prune(){let e=Date.now();for(let[t,r]of this.entries.entries())if(r.validUntilMs<e)this.entries.delete(t);else break}has(e){return this.entries.has(e)}get(e){let t=this.entries.get(e);return t!=null&&t.validUntilMs>=Date.now()?t.value:void 0}clear(){this.entries.clear()}};var Pe;(function(s){s[s.started=0]="started",s[s.stopped=1]="stopped"})(Pe||(Pe={}));var Hr=class extends js{globalSignaturePolicy;protocols=[Kt,Zi,qr];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:Pe.stopped};maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;allowedTopics;heartbeatTimer=null;constructor(e,t={}){super();let r={fallbackToFloodsub:!0,floodPublish:!0,batchPublish:!1,tagMeshPeers:!0,doPX:!1,directPeers:[],D:6,Dlo:4,Dhi:12,Dscore:4,Dout:2,Dlazy:6,heartbeatInterval:1e3,fanoutTTL:6e4,mcacheLength:5,mcacheGossip:3,seenTTL:12e4,gossipsubIWantFollowupMs:3e3,prunePeers:16,pruneBackoff:6e4,unsubcribeBackoff:1e4,graftFloodThreshold:1e4,opportunisticGraftPeers:2,opportunisticGraftTicks:60,directConnectTicks:300,gossipFactor:.25,idontwantMinDataSize:512,idontwantMaxMessages:512,...t,scoreParams:oc(t.scoreParams),scoreThresholds:cc(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=r.decodeRpcLimits??sc,this.globalSignaturePolicy=r.globalSignaturePolicy??vt,r.fallbackToFloodsub&&this.protocols.push(Gr),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 ps({validityMs:r.seenTTL}),this.publishedMessageIds=new ps({validityMs:r.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case vt:this.msgIdFn=Ic;break;case Ot:this.msgIdFn=Tc;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new ps({validityMs:r.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??Sc,this.mcache=t.messageCache??new Lr(r.mcacheGossip,r.mcacheLength,this.msgIdToStrFn),t.dataTransform!=null&&(this.dataTransform=t.dataTransform),t.metricsRegister!=null){if(t.metricsTopicStrToLabel==null)throw Error("Must set metricsTopicStrToLabel with metrics");let n=Math.max(...Object.values(r.scoreParams.topics).map(o=>o.meshMessageDeliveriesWindow),1e3),i=ic(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:r.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:n/1e3});i.mcacheSize.addCollect(()=>{this.onScrapeMetrics(i)});for(let o of this.protocols)i.protocolsEnabled.set({protocol:o},1);this.metrics=i}else this.metrics=null;this.gossipTracer=new zr(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new Or(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:r.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnLimitedConnection=t.runOnLimitedConnection,this.allowedTopics=r.allowedTopics!=null?new Set(r.allowedTopics):null}[Symbol.toStringTag]="@libp2p/gossipsub";[Qi]=["@libp2p/pubsub"];[eo]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===Pe.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=_c(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=Nt({objectMode:!0}),Gs(this.outboundInflightQueue,async i=>{for await(let{peerId:o,connection:a}of i)await this.createOutboundStream(o,a)}).catch(i=>{this.log.error("outbound inflight queue error",i)}),await Promise.all(this.opts.directPeers.map(async i=>{await this.components.peerStore.merge(i.id,{multiaddrs:i.addrs})}));let e=this.components.registrar;await Promise.all(this.protocols.map(async i=>e.handle(i,this.onIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection})));let t={onConnect:this.onPeerConnected.bind(this),onDisconnect:this.onPeerDisconnected.bind(this),notifyOnLimitedConnection:this.runOnLimitedConnection},r=await Promise.all(this.protocols.map(async i=>e.register(i,t))),n=setTimeout(this.runHeartbeat,100);this.status={code:Pe.started,registrarTopologyIds:r,heartbeatTimeout:n,hearbeatStartMs:Date.now()+100},this.score.start(),this.directPeerInitial=setTimeout(()=>{Promise.resolve().then(async()=>{await Promise.all(Array.from(this.direct).map(async i=>this.connect(i)))}).catch(i=>{this.log(i)})},1e3),this.opts.tagMeshPeers&&(this.addEventListener("gossipsub:graft",this.tagMeshPeer),this.addEventListener("gossipsub:prune",this.untagMeshPeer)),this.log("started")}async stop(){if(this.log("stopping"),this.status.code!==Pe.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:Pe.stopped},this.opts.tagMeshPeers&&(this.removeEventListener("gossipsub:graft",this.tagMeshPeer),this.removeEventListener("gossipsub:prune",this.untagMeshPeer));let t=this.components.registrar;await Promise.all(this.protocols.map(async n=>t.unhandle(n))),e.forEach(n=>{t.unregister(n)}),this.outboundInflightQueue.end();let r=[];for(let n of this.streamsOutbound.values())r.push(n.close());this.streamsOutbound.clear();for(let n of this.streamsInbound.values())r.push(n.close());this.streamsInbound.clear(),await Promise.all(r),this.peers.clear(),this.subscriptions.clear(),this.topics.clear(),this.heartbeatTimer!=null&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.iwantCounts.clear(),this.backoff.clear(),this.outbound.clear(),this.gossipTracer.clear(),this.seenCache.clear(),this.fastMsgIdCache!=null&&this.fastMsgIdCache.clear(),this.directPeerInitial!=null&&clearTimeout(this.directPeerInitial),this.idontwantCounts.clear(),this.idontwants.clear(),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream(e,t){if(!this.isStarted())return;let r=t.remotePeer;this.addPeer(r,t.direction,t.remoteAddr),this.createInboundStream(r,e),this.outboundInflightQueue.push({peerId:r,connection:t})}onPeerConnected(e,t){this.metrics?.newConnectionCount.inc({status:t.status}),!(!this.isStarted()||t.status!=="open")&&(this.addPeer(e,t.direction,t.remoteAddr),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}async createOutboundStream(e,t){if(!this.isStarted())return;let r=e.toString();if(this.peers.has(r)&&!this.streamsOutbound.has(r))try{let n=await t.newStream(this.protocols,{runOnLimitedConnection:this.runOnLimitedConnection}),i=new Ur(n,a=>{this.log.error("outbound pipe error",a)},{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(r,i);let o=i.protocol;o===Gr&&this.floodsubPeers.add(r),this.metrics?.peersPerProtocol.inc({protocol:o},1),n.addEventListener("close",()=>{this.streamsOutbound.get(r)===i&&(this.streamsOutbound.delete(r),this.floodsubPeers.delete(r),this.metrics?.peersPerProtocol.inc({protocol:o},-1))},{once:!0}),this.subscriptions.size>0&&(this.log("send subscriptions to",r),this.sendSubscriptions(r,Array.from(this.subscriptions),!0))}catch(n){this.log.error("createOutboundStream error",n)}}createInboundStream(e,t){if(!this.isStarted())return;let r=e.toString();if(!this.peers.has(r))return;let n=this.streamsInbound.get(r);n!==void 0&&(this.log("replacing existing inbound steam %s",r),n.close().catch(o=>{this.log.error(o)})),this.log("create inbound stream %s",r);let i=new Kr(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(r,i),this.pipePeerReadStream(e,i.source).catch(o=>{this.log(o)})}addPeer(e,t,r){let n=e.toString();if(!this.peers.has(n)){this.peers.set(n,e),this.score.addPeer(n);let i=Dc(r);i!==null?this.score.addIP(n,i):this.log("Added peer has no IP in current address %s %s",n,r.toString()),this.outbound.has(n)||this.outbound.set(n,t==="outbound")}}removePeer(e){let t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);let r=this.streamsOutbound.get(t),n=this.streamsInbound.get(t);r!=null&&this.metrics?.peersPerProtocol.inc({protocol:r.protocol},-1),r?.close().catch(i=>{this.log.error(i)}),n?.close().catch(i=>{this.log.error(i)}),this.streamsOutbound.delete(t),this.streamsInbound.delete(t);for(let[i,o]of this.topics)o.delete(t),o.size===0&&this.topics.delete(i);for(let[i,o]of this.mesh)o.delete(t)&&this.metrics?.onRemoveFromMesh(i,He.Dc,1);for(let i of this.fanout.values())i.delete(t);this.floodsubPeers.delete(t),this.gossip.delete(t),this.control.delete(t),this.outbound.delete(t),this.idontwantCounts.delete(t),this.idontwants.delete(t),this.score.removePeer(t),this.acceptFromWhitelist.delete(t)}get started(){return this.status.code===Pe.started}getMeshPeers(e){let t=this.mesh.get(e);return t!=null?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(t!=null?Array.from(t):[]).map(r=>this.peers.get(r)??Ct(r))}getTopics(){return Array.from(this.subscriptions)}decodeRpc(e){return ot.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 Gs(t,async r=>{for await(let n of r)try{let i=n.subarray(),o=this.decodeRpc(i);if(this.metrics?.onRpcRecv(o,i.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,o)}catch(a){this.metrics?.onRpcRecvError(),this.log(a)}else this.handleReceivedRpc(e,o).catch(a=>{this.metrics?.onRpcRecvError(),this.log(a)})}catch(i){this.metrics?.onRpcDataError(),this.log(i)}})}catch(r){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(r,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){if(!this.acceptFrom(e.toString())){this.log("received message from unacceptable peer %p",e),this.metrics?.rpcRecvNotAccepted.inc();return}let r=t.subscriptions!=null?t.subscriptions.length:0,n=t.messages!=null?t.messages.length:0,i=0,o=0,a=0,l=0;if(t.control!=null&&(t.control.ihave!=null&&(i=t.control.ihave.length),t.control.iwant!=null&&(o=t.control.iwant.length),t.control.graft!=null&&(a=t.control.graft.length),t.control.prune!=null&&(l=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${r} messages ${n} ihave ${i} iwant ${o} graft ${a} prune ${l}`),t.subscriptions!=null&&t.subscriptions.length>0){let u=[],d=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))return;this.handleReceivedSubscription(e,y,f),f&&this.graftOnSubscribe(d,y)&&m.push(y),u.push({topic:y,subscribe:f})}}),m.length>0&&this.sendGraft(d,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 d=this.handleReceivedMessage(e,u).catch(m=>{this.metrics?.onMsgRecvError(u.topic),this.log(m)});this.opts.awaitRpcMessageHandler&&await d}t.control!=null&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,r){this.log("subscription update from %p topic %s",e,t);let n=this.topics.get(t);r?(n==null&&(n=new Set,this.topics.set(t,n)),n.add(e.toString())):n!=null&&(n.delete(e.toString()),n.size===0&&this.topics.delete(t))}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);let r=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,r.code);let n=r.code;switch(n){case me.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 me.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 me.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:me.duplicate,msgIdStr:n};let i=await Ec(this.globalSignaturePolicy,t);if(!i.valid)return{code:me.invalid,reason:Ee.Error,error:i.error};let o=i.message;try{this.dataTransform!=null&&(o.data=this.dataTransform.inboundTransform(t.topic,o.data))}catch(m){return this.log("Invalid message, transform failed",m),{code:me.invalid,reason:Ee.Error,error:he.TransformFailed}}let a=await this.msgIdFn(o),l=this.msgIdToStrFn(a),u={msgId:a,msgIdStr:l};if(r!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(r,l)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(l))return{code:me.duplicate,msgIdStr:l};this.seenCache.put(l),(t.data?.length??0)>=this.opts.idontwantMinDataSize&&this.sendIDontWants(a,t.topic,e.toString());let d=this.topicValidators.get(t.topic);if(d!=null){let m;try{m=await d(e,o)}catch(E){let y=E.code;y===Xi&&(m=ge.Ignore),y===Yi?m=ge.Reject:m=ge.Ignore}if(m!==ge.Accept)return{code:me.invalid,reason:zi(m),msgIdStr:l}}return{code:me.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,Ge(n,{iwant:r,prune:i})),a=r[0]?.messageIDs;a!=null&&(o?this.gossipTracer.addPromise(e,a):this.metrics?.iwantPromiseUntracked.inc(1))}acceptFrom(e){if(this.direct.has(e))return!0;let t=Date.now(),r=this.acceptFromWhitelist.get(e);if(r!=null&&r.messagesAccepted<128&&r.acceptUntil>=t)return r.messagesAccepted+=1,!0;let n=this.score.score(e);return n>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),n>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){if(t.length===0)return[];let r=this.score.score(e);if(r<this.opts.scoreThresholds.gossipThreshold)return this.log("IHAVE: ignoring peer %s with score below threshold [ score = %d ]",e,r),this.metrics?.ihaveRcvIgnored.inc({reason:ds.LowScore}),[];let n=(this.peerhave.get(e)??0)+1;if(this.peerhave.set(e,n),n>10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:ds.MaxIhave}),[];let i=this.iasked.get(e)??0;if(i>=5e3)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,i),this.metrics?.ihaveRcvIgnored.inc({reason:ds.MaxIasked}),[];let o=new Map,a=0;e:for(let{topicID:d,messageIDs:m}of t){if(d==null||m==null||!this.mesh.has(d))continue;let E=0;for(let y of m){if(a>=5e3)break e;a++;let f=this.msgIdToStrFn(y);this.seenCache.has(f)||(o.set(f,y),E++)}this.metrics?.onIhaveRcv(d,m.length,E)}if(o.size===0)return[];let l=o.size;l+i>5e3&&(l=5e3-i),this.log("IHAVE: Asking for %d out of %d messages from %s",l,o.size,e);let u=Array.from(o.values());return Ye(u),u=u.slice(0,l),this.iasked.set(e,i+l),[{messageIDs:u}]}handleIWant(e,t){if(t.length===0)return[];let r=this.score.score(e);if(r<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,r),[];let n=(this.iwantCounts.get(e)??0)+1;if(this.iwantCounts.set(e,n),n>10)return this.log("IWANT: peer %s has requested too many times within this heartbeat interval; ignoring",e),[];let i=new Map,o=new Map,a=0,l=0;e:for(let{messageIDs:u}of t)if(u!=null)for(let d of u){if(l>=5e3)break e;l++;let m=this.msgIdToStrFn(d),E=this.mcache.getWithIWantCount(m,e);if(E==null){a++;continue}if(o.set(E.msg.topic,1+(o.get(E.msg.topic)??0)),E.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,d);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:l})=>{if(l==null)return;let u=this.mesh.get(l);if(u==null){o=!1;return}if(u.has(e))return;let d=this.backoff.get(l)?.get(e);if(this.direct.has(e))this.log("GRAFT: ignoring request from direct peer %s",e),r.push(l),o=!1;else if(typeof d=="number"&&i<d){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,fs.GraftBackoff),o=!1;let m=d+this.opts.graftFloodThreshold-this.opts.pruneBackoff;i<m&&this.score.addPenalty(e,1,fs.GraftBackoff),this.addBackoff(e,l),r.push(l)}else n<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,n,l),r.push(l),o=!1,this.addBackoff(e,l)):u.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(r.push(l),this.addBackoff(e,l)):(this.log("GRAFT: Add mesh link from %s in %s",e,l),this.addToMesh(e,l,be.Subscribed));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:l,direction:"inbound"}})}),r.length===0)return[];let a=!1;return Promise.all(r.map(async l=>this.makePrune(e,l,o,a)))}async handlePrune(e,t){let r=this.score.score(e);for(let{topicID:n,backoff:i,peers:o}of t){if(n==null)continue;let a=this.mesh.get(n);if(a==null)return;this.log("PRUNE: Remove mesh link to %s in %s",e,n),this.score.prune(e,n),a.has(e)&&(a.delete(e),this.metrics?.onRemoveFromMesh(n,He.Prune,1)),typeof i=="number"&&i>0?this.doAddBackoff(e,n,i*1e3):this.addBackoff(e,n),o!=null&&o.length>0&&(r<this.opts.scoreThresholds.acceptPXThreshold?this.log("PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]",e,r,n):await this.pxConnect(o)),this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:n,direction:"inbound"}})}}handleIdontwant(e,t){let r=this.idontwantCounts.get(e)??0;if(r>=this.opts.idontwantMaxMessages)return;let n=r,i=this.idontwants.get(e);i==null&&(i=new Map,this.idontwants.set(e,i));let o=0;e:for(let{messageIDs:l}of t)for(let u of l){if(r>=this.opts.idontwantMaxMessages)break e;r++;let d=this.msgIdToStrFn(u);i.set(d,this.heartbeatTicks),this.mcache.msgs.has(d)||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,fs.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!==0)return;let e=Date.now();this.backoff.forEach((t,r)=>{t.forEach((n,i)=>{n+1*this.opts.heartbeatInterval<e&&t.delete(i)}),t.size===0&&this.backoff.delete(r)})}async directConnect(){let e=[];this.direct.forEach(t=>{this.streamsOutbound.has(t)||e.push(t)}),await Promise.all(e.map(async t=>this.connect(t)))}async pxConnect(e){e.length>this.opts.prunePeers&&(Ye(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async r=>{if(r.peerID==null)return;let n=as(Xe(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=Ct(e),r=await this.components.connectionManager.openConnection(t);for(let n of this.protocols)for(let i of this.components.registrar.getTopologies(n))i.onConnect?.(t,r)}subscribe(e){if(this.status.code!==Pe.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(let t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==Pe.started)throw new Error("Pubsub is not started");let t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(let r of this.peers.keys())this.sendSubscriptions(r,[e],!1);this.leave(e)}join(e){if(this.status.code!==Pe.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);let t=new Set,r=this.backoff.get(e),n=this.fanout.get(e);if(n!=null&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),n.forEach(i=>{!this.direct.has(i)&&this.score.score(i)>=0&&r?.has(i)!==!0&&t.add(i)}),this.metrics?.onAddToMesh(e,be.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,be.Random,t.size-i)}this.mesh.set(e,t),t.forEach(i=>{this.log("JOIN: Add mesh link to %s in %s",i,e),this.sendGraft(i,[e])})}leave(e){if(this.status.code!==Pe.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);let t=this.mesh.get(e);t!=null&&(Promise.all(Array.from(t).map(async r=>{this.log("LEAVE: Remove mesh link to %s in %s",r,e),await this.sendPrune(r,e)})).catch(r=>{this.log("Error sending prunes to mesh peers",r)}),this.mesh.delete(e))}selectPeersToForward(e,t,r){let n=new Set,i=this.topics.get(e);i!=null&&(this.direct.forEach(a=>{i.has(a)&&t!==a&&!(r?.has(a)??!1)&&n.add(a)}),this.floodsubPeers.forEach(a=>{i.has(a)&&t!==a&&!(r?.has(a)??!1)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&n.add(a)}));let o=this.mesh.get(e);return o!=null&&o.size>0&&o.forEach(a=>{t!==a&&!(r?.has(a)??!1)&&n.add(a)}),n}selectPeersToPublish(e){let t=new Set,r={direct:0,floodsub:0,mesh:0,fanout:0},n=this.topics.get(e);if(n!=null)if(this.opts.floodPublish)n.forEach(i=>{this.direct.has(i)?(t.add(i),r.direct++):this.score.score(i)>=this.opts.scoreThresholds.publishThreshold&&(t.add(i),r.floodsub++)});else{this.direct.forEach(o=>{n.has(o)&&(t.add(o),r.direct++)}),this.floodsubPeers.forEach(o=>{n.has(o)&&this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),r.floodsub++)});let i=this.mesh.get(e);if(i!=null&&i.size>0)i.forEach(o=>{t.add(o),r.mesh++}),i.size<this.opts.D&&this.getRandomGossipPeers(e,this.opts.D-i.size,a=>!i.has(a)&&!this.direct.has(a)&&!this.floodsubPeers.has(a)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold).forEach(a=>{t.add(a),r.mesh++});else{let o=this.fanout.get(e);if(o!=null&&o.size>0)o.forEach(a=>{t.add(a),r.fanout++});else{let a=this.getRandomGossipPeers(e,this.opts.D,l=>this.score.score(l)>=this.opts.scoreThresholds.publishThreshold);a.size>0&&(this.fanout.set(e,a),a.forEach(l=>{t.add(l),r.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:r}}forwardMessage(e,t,r,n){r!=null&&this.score.deliverMessage(r,e,t.topic);let i=this.selectPeersToForward(t.topic,r,n);i.forEach(o=>{this.sendRpc(o,Ge([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 vc(this.publishConfig,e,t,i),l=await this.msgIdFn(a),u=this.msgIdToStrFn(l),d=r?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(u)){if(d)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:m,tosendCount:E}=this.selectPeersToPublish(e),y=this.opts.emitSelf&&this.subscriptions.has(e),f=r?.allowPublishToZeroTopicPeers??this.opts.allowPublishToZeroTopicPeers;if(m.size===0&&!f&&!y)throw Error("PublishError.NoPeersSubscribedToTopic");this.seenCache.put(u),this.mcache.put({msgId:l,msgIdStr:u},o,!0),this.gossipTracer.deliverMessage(u),this.publishedMessageIds.put(u);let b=r?.batchPublish??this.opts.batchPublish,g=Ge([o]);if(b)this.sendRpcInBatch(m,g);else for(let I of m)this.sendRpc(I,g)||m.delete(I);let x=Date.now()-n;return this.metrics?.onPublishMsg(e,E,m.size,o.data!=null?o.data.length:0,x),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(I=>this.peers.get(I)??Ct(I))}}sendRpcInBatch(e,t){let r=ot.encode(t),n=ls.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===ge.Accept){if(n=this.mcache.validate(e),n!=null){let{message:o,originatingPeers:a}=n;this.score.deliverMessage(t,e,o.topic),this.forwardMessage(e,n.message,t,a)}}else if(n=this.mcache.remove(e),n!=null){let o=zi(r),{message:a,originatingPeers:l}=n;this.score.rejectMessage(t,e,a.topic,o);for(let u of l)this.score.rejectMessage(u,e,a.topic,o)}let i=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(n,r,i)}sendGraft(e,t){let r=t.map(i=>({topicID:i})),n=Ge([],{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,be.Subscribed),!0)}async sendPrune(e,t){let n=[await this.makePrune(e,t,this.opts.doPX,!0)],i=Ge([],{prune:n});this.sendRpc(e,i)}sendIDontWants(e,t,r){let n=this.mesh.get(t);if(n==null)return;let i=new Set(n);i.delete(r);for(let a of i)this.streamsOutbound.get(a)?.protocol!==Kt&&i.delete(a);let o=Ge([],{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=ot.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=Vi(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=Vi(t);n.control.ihave=r}async sendGraftPrune(e,t,r){let n=this.opts.doPX,i=!1;for(let[o,a]of e){let l=a.map(m=>({topicID:m})),u=[],d=t.get(o);d!=null&&(u=await Promise.all(d.map(async m=>this.makePrune(o,m,n&&!(r.get(o)??!1),i))),t.delete(o)),this.sendRpc(o,Ge([],{graft:l,prune:u}))}for(let[o,a]of t){let l=await Promise.all(a.map(async u=>this.makePrune(o,u,n&&!(r.get(o)??!1),i)));this.sendRpc(o,Ge([],{prune:l}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[r,n]of e)this.doEmitGossip(r,n,t.get(r)??[])}doEmitGossip(e,t,r){if(r.length===0||(Ye(r),r.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",r.length),t.size===0))return;let n=this.opts.Dlazy,o=this.opts.gossipFactor*t.size,a=t;o>n&&(n=o),n>a.size?n=a.size:a=Ye(Array.from(a)).slice(0,n),a.forEach(l=>{let u=r;r.length>5e3&&(u=Ye(u.slice()).slice(0,5e3)),this.pushGossip(l,{topicID:e,messageIDs:u})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,Ge([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let r=Ge([],{graft:t.graft,prune:t.prune});this.sendRpc(e,r)}}pushGossip(e,t){this.log("Add gossip to %s",e);let r=this.gossip.get(e)??[];this.gossip.set(e,r.concat(t))}async makePrune(e,t,r,n){if(this.score.prune(e,t),this.streamsOutbound.get(e)?.protocol===qr)return{topicID:t,peers:[]};let i=n?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,o=i/1e3;if(this.doAddBackoff(e,t,i),!r)return{topicID:t,peers:[],backoff:o};let a=this.getRandomGossipPeers(t,this.opts.prunePeers,u=>u!==e&&this.score.score(u)>=0),l=await Promise.all(Array.from(a).map(async u=>{let d=this.peers.get(u)??Ct(u),m;try{m=await this.components.peerStore.get(d)}catch(E){if(E.name!=="NotFoundError")throw E}return{peerID:d.toMultihash().bytes,signedPeerRecord:m?.peerRecordEnvelope}}));return{topicID:t,peers:l,backoff:o}}runHeartbeat=()=>{let e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch(t=>{this.log("Error running heartbeat",t)}).finally(()=>{if(e?.(),this.status.code===Pe.started){clearTimeout(this.status.heartbeatTimeout);let t=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;t<this.opts.heartbeatInterval*.25&&(t+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,t)}})};async heartbeat(){let{D:e,Dlo:t,Dhi:r,Dscore:n,Dout:i,fanoutTTL:o}=this.opts;this.heartbeatTicks++;let a=new Map,l=f=>{let b=a.get(f);return b===void 0&&(b=this.score.score(f),a.set(f,b)),b},u=new Map,d=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[b,g]of f)this.heartbeatTicks-g>=this.opts.mcacheLength&&f.delete(b);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,b)=>{let g=this.topics.get(b),x=new Set,I=new Set;if(E.set(b,I),g!=null){let p=Ye(Array.from(g)),w=this.backoff.get(b);for(let v of p){let S=this.streamsOutbound.get(v);if(S!=null&&this.protocols.includes(S.protocol)&&!f.has(v)&&!this.direct.has(v)){let M=l(v);w?.has(v)!==!0&&M>=0&&x.add(v),M>=this.opts.scoreThresholds.gossipThreshold&&I.add(v)}}}let c=(p,w)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",p,b),this.addBackoff(p,b),f.delete(p),l(p)>=this.opts.scoreThresholds.gossipThreshold&&I.add(p),this.metrics?.onRemoveFromMesh(b,w,1);let v=d.get(p);v==null?d.set(p,[b]):v.push(b)},h=(p,w)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",p,b),this.addToMesh(p,b,w),I.delete(p);let v=u.get(p);v==null?u.set(p,[b]):v.push(b)};if(f.forEach(p=>{let w=l(p);w<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",p,w,b),c(p,He.BadScore),m.set(p,!0))}),f.size<t){let p=e-f.size;lc(x,p).forEach(v=>{h(v,be.NotEnough)})}if(f.size>r){let p=Array.from(f);p.sort((v,S)=>l(S)-l(v)),p=p.slice(0,n).concat(Ye(p.slice(n)));let w=0;if(p.slice(0,e).forEach(v=>{(this.outbound.get(v)??!1)&&w++}),w<i){let v=M=>{let R=p[M];for(let F=M;F>0;F--)p[F]=p[F-1];p[0]=R};if(w>0){let M=w;for(let R=1;R<e&&M>0;R++)(this.outbound.get(p[R])??!1)&&(v(R),M--)}let S=e-w;for(let M=e;M<p.length&&S>0;M++)(this.outbound.get(p[M])??!1)&&(v(M),S--)}p.slice(e).forEach(v=>{c(v,He.Excess)})}if(f.size>=t){let p=0;if(f.forEach(w=>{(this.outbound.get(w)??!1)&&p++}),p<i){let w=i-p;Fr(x,w,S=>this.outbound.get(S)===!0).forEach(S=>{h(S,be.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&f.size>1){let p=Array.from(f).sort((S,M)=>l(S)-l(M)),w=Math.floor(f.size/2),v=l(p[w]);if(v<this.opts.scoreThresholds.opportunisticGraftThreshold){let S=this.opts.opportunisticGraftPeers,M=Fr(x,S,R=>l(R)>v);for(let R of M)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",R,b),h(R,be.Opportunistic)}}});let y=Date.now();this.fanoutLastpub.forEach((f,b)=>{f+o<y&&(this.fanout.delete(b),this.fanoutLastpub.delete(b))}),this.fanout.forEach((f,b)=>{let g=this.topics.get(b);f.forEach(h=>{(!(g?.has(h)??!1)||l(h)<this.opts.scoreThresholds.publishThreshold)&&f.delete(h)});let x=this.topics.get(b),I=[],c=new Set;if(E.set(b,c),x!=null){let h=Ye(Array.from(x));for(let p of h){let w=this.streamsOutbound.get(p);if(w!=null&&this.protocols.includes(w.protocol)&&!f.has(p)&&!this.direct.has(p)){let v=l(p);v>=this.opts.scoreThresholds.publishThreshold&&I.push(p),v>=this.opts.scoreThresholds.gossipThreshold&&c.add(p)}}}if(f.size<e){let h=e-f.size;I.slice(0,h).forEach(p=>{f.add(p),c?.delete(p)})}}),this.emitGossip(E),await this.sendGraftPrune(u,d,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=Ye(i),t>0&&i.length>t&&(i=i.slice(0,t)),new Set(i)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0,r=Date.now();e.connectedPeersBackoffSec.reset();for(let l of this.backoff.values()){t+=l.size;for(let[u,d]of l.entries())this.peers.has(u)&&e.connectedPeersBackoffSec.observe(Math.max(0,d-r)/1e3)}e.cacheSize.set({cache:"backoff"},t);let n=0;for(let l of this.idontwants.values())n+=l.size;e.cacheSize.set({cache:"idontwants"},n);for(let[l,u]of this.topics)e.topicPeersCount.set({topicStr:l},u.size);for(let[l,u]of this.mesh)e.meshPeerCounts.set({topicStr:l},u.size);let i=[],o=new Map;e.behaviourPenalty.reset();for(let l of this.peers.keys()){let u=this.score.score(l);i.push(u),o.set(l,u),e.behaviourPenalty.observe(this.score.peerStats.get(l)?.behaviourPenalty??0)}e.registerScores(i,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,o);let a=pc(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)??Ct(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)??Ct(t),{tags:{[r]:void 0}}).catch(n=>{this.log.error("Error untagging peer %s with topic %s",t,r,n)})}};var vt="StrictSign",Ot="StrictNoSign",ge;(function(s){s.Accept="accept",s.Ignore="ignore",s.Reject="reject"})(ge||(ge={}));var xf=Kt;function vf(s={}){return e=>new Hr(e,s)}return Fc(Ef);})();
2
+ "use strict";var Libp2PGossipsub=(()=>{var Oc=Object.create;var Os=Object.defineProperty;var Uc=Object.getOwnPropertyDescriptor;var Kc=Object.getOwnPropertyNames;var zc=Object.getPrototypeOf,qc=Object.prototype.hasOwnProperty;var Gc=(s,e)=>()=>{try{return e||s((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},_e=(s,e)=>{for(var t in e)Os(s,t,{get:e[t],enumerable:!0})},$i=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Kc(e))!qc.call(s,n)&&n!==t&&Os(s,n,{get:()=>e[n],enumerable:!(r=Uc(e,n))||r.enumerable});return s};var Hc=(s,e,t)=>(t=s!=null?Oc(zc(s)):{},$i(e||!s||!s.__esModule?Os(t,"default",{value:s,enumerable:!0}):t,s)),Wc=s=>$i(Os({},"__esModule",{value:!0}),s);var yc=Gc((J0,bc)=>{"use strict";function ee(s,t){var t=t||{};this._capacity=t.capacity,this._head=0,this._tail=0,Array.isArray(s)?this._fromArray(s):(this._capacityMask=3,this._list=new Array(4))}ee.prototype.peekAt=function(e){var t=e;if(t===(t|0)){var r=this.size();if(!(t>=r||t<-r))return t<0&&(t+=r),t=this._head+t&this._capacityMask,this._list[t]}};ee.prototype.get=function(e){return this.peekAt(e)};ee.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};ee.prototype.peekFront=function(){return this.peek()};ee.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(ee.prototype,"length",{get:function(){return this.size()}});ee.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ee.prototype.unshift=function(e){if(arguments.length===0)return this.size();var t=this._list.length;return this._head=this._head-1+t&this._capacityMask,this._list[this._head]=e,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.pop(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ee.prototype.shift=function(){var e=this._head;if(e!==this._tail){var t=this._list[e];return this._list[e]=void 0,this._head=e+1&this._capacityMask,e<2&&this._tail>1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}};ee.prototype.push=function(e){if(arguments.length===0)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};ee.prototype.pop=function(){var e=this._tail;if(e!==this._head){var t=this._list.length;this._tail=e-1+t&this._capacityMask;var r=this._list[this._tail];return this._list[this._tail]=void 0,this._head<2&&e>1e4&&e<=t>>>2&&this._shrinkArray(),r}};ee.prototype.removeOne=function(e){var t=e;if(t===(t|0)&&this._head!==this._tail){var r=this.size(),n=this._list.length;if(!(t>=r||t<-r)){t<0&&(t+=r),t=this._head+t&this._capacityMask;var i=this._list[t],o;if(e<r/2){for(o=e;o>0;o--)this._list[t]=this._list[t=t-1+n&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+n&this._capacityMask}else{for(o=r-1-e;o>0;o--)this._list[t]=this._list[t=t+1+n&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+n&this._capacityMask}return i}}};ee.prototype.remove=function(e,t){var r=e,n,i=t;if(r===(r|0)&&this._head!==this._tail){var o=this.size(),a=this._list.length;if(!(r>=o||r<-o||t<1)){if(r<0&&(r+=o),t===1||!t)return n=new Array(1),n[0]=this.removeOne(r),n;if(r===0&&r+t>=o)return n=this.toArray(),this.clear(),n;r+t>o&&(t=o-r);var l;for(n=new Array(t),l=0;l<t;l++)n[l]=this._list[this._head+r+l&this._capacityMask];if(r=this._head+r&this._capacityMask,e+t===o){for(this._tail=this._tail-t+a&this._capacityMask,l=t;l>0;l--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(e===0){for(this._head=this._head+t+a&this._capacityMask,l=t-1;l>0;l--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(r<o/2){for(this._head=this._head+e+t+a&this._capacityMask,l=e;l>0;l--)this.unshift(this._list[r=r-1+a&this._capacityMask]);for(r=this._head-1+a&this._capacityMask;i>0;)this._list[r=r-1+a&this._capacityMask]=void 0,i--;e<0&&(this._tail=r)}else{for(this._tail=r,r=r+t+a&this._capacityMask,l=o-(t+e);l>0;l--)this.push(this._list[r++]);for(r=this._tail;i>0;)this._list[r=r+1+a&this._capacityMask]=void 0,i--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),n}}};ee.prototype.splice=function(e,t){var r=e;if(r===(r|0)){var n=this.size();if(r<0&&(r+=n),!(r>n))if(arguments.length>2){var i,o,a,l=arguments.length,u=this._list.length,p=2;if(!n||r<n/2){for(o=new Array(r),i=0;i<r;i++)o[i]=this._list[this._head+i&this._capacityMask];for(t===0?(a=[],r>0&&(this._head=this._head+r+u&this._capacityMask)):(a=this.remove(r,t),this._head=this._head+r+u&this._capacityMask);l>p;)this.unshift(arguments[--l]);for(i=r;i>0;i--)this.unshift(o[i-1])}else{o=new Array(n-(r+t));var m=o.length;for(i=0;i<m;i++)o[i]=this._list[this._head+r+t+i&this._capacityMask];for(t===0?(a=[],r!=n&&(this._tail=this._head+r+u&this._capacityMask)):(a=this.remove(r,t),this._tail=this._tail-m+u&this._capacityMask);p<l;)this.push(arguments[p++]);for(i=0;i<m;i++)this.push(o[i])}return a}else return this.remove(r,t)}};ee.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0};ee.prototype.isEmpty=function(){return this._head===this._tail};ee.prototype.toArray=function(){return this._copyArray(!1)};ee.prototype._fromArray=function(e){var t=e.length,r=this._nextPowerOf2(t);this._list=new Array(r),this._capacityMask=r-1,this._tail=t;for(var n=0;n<t;n++)this._list[n]=e[n]};ee.prototype._copyArray=function(e,t){var r=this._list,n=r.length,i=this.length;if(t=t|i,t==i&&this._head<this._tail)return this._list.slice(this._head,this._tail);var o=new Array(t),a=0,l;if(e||this._head>this._tail){for(l=this._head;l<n;l++)o[a++]=r[l];for(l=0;l<this._tail;l++)o[a++]=r[l]}else for(l=this._head;l<this._tail;l++)o[a++]=r[l];return o};ee.prototype._growArray=function(){if(this._head!=0){var e=this._copyArray(!0,this._list.length<<1);this._tail=this._list.length,this._head=0,this._list=e}else this._tail=this._list.length,this._list.length<<=1;this._capacityMask=this._capacityMask<<1|1};ee.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1};ee.prototype._nextPowerOf2=function(e){var t=Math.log(e)/Math.log(2),r=1<<t+1;return Math.max(r,4)};bc.exports=ee});var zf={};_e(zf,{StrictNoSign:()=>Ft,StrictSign:()=>wt,TopicValidatorResult:()=>me,gossipsub:()=>Kf,multicodec:()=>Uf});var Hr="/floodsub/1.0.0",Wr="/meshsub/1.0.0",ji="/meshsub/1.1.0",Ot="/meshsub/1.2.0";var Zi="ERR_TOPIC_VALIDATOR_REJECT",Yi="ERR_TOPIC_VALIDATOR_IGNORE";var re=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Ut=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Us=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Ks=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Kt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Vr=Symbol.for("@libp2p/peer-id");function Vc(s){return typeof s?.handleEvent=="function"}function $c(s){return s===!0||s===!1}function jc(s){return $c(s)?s:s?.capture??!1}function $r(s){let e={capture:jc(s),once:!!s?.once};return s?.passive!=null&&(e.passive=s?.passive),s?.signal!=null&&(e.signal=s?.signal),e}function Ji(s,e){return $r(s).capture===$r(e).capture}var zs=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,r){let n=$r(r);if(n?.signal?.aborted===!0)return;let i=u=>{n.once&&this.removeEventListener(e,t,n),Vc(t)?t.handleEvent(u):t(u)},o=this.#e.get(e);if(o==null&&(o=[],this.#e.set(e,o)),o.some(u=>u.callback!==t?!1:Ji(u.options,n)))return;super.addEventListener(e,i,n);let l=()=>{this.removeEventListener(e,t,n)};n.signal?.addEventListener("abort",l),o.push({callback:t,wrapper:i,options:n,onAbort:l})}removeEventListener(e,t,r){let n=this.#e.get(e);if(n==null){super.removeEventListener(e,t??null,r);return}this.#e.set(e,n.filter(i=>i.callback===t&&Ji(i.options,r)?(super.removeEventListener(e,i.wrapper,r),i.options?.signal?.removeEventListener("abort",i.onAbort),!1):!0))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Qi=Symbol.for("@libp2p/service-capabilities"),eo=Symbol.for("@libp2p/service-dependencies");var Jr={};_e(Jr,{base58btc:()=>ie,base58flickr:()=>sl});var bd=new Uint8Array(0);function so(s,e){if(s===e)return!0;if(s.byteLength!==e.byteLength)return!1;for(let t=0;t<s.byteLength;t++)if(s[t]!==e[t])return!1;return!0}function Be(s){if(s instanceof Uint8Array&&s.constructor.name==="Uint8Array")return vt(s);if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return vt(new Uint8Array(s.buffer,s.byteOffset,s.byteLength));throw new Error("Unknown type, must be binary type")}function ro(s){let e=new Uint8Array(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}var to=4096;function no(s){let e=s.length;if(e<=to)return String.fromCharCode.apply(String,s);let t="",r=0;for(;r<e;)t+=String.fromCharCode.apply(String,s.subarray(r,r+=to));return t}function Zc(s){return s?.buffer instanceof ArrayBuffer}function vt(s){return Zc(s)?s:s.slice()}function Yc(s,e,t){if(s.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<s.length;i++){var o=s.charAt(i),a=o.charCodeAt(0);if(r[a]!==255)throw new TypeError(o+" is ambiguous");if(r[a]=i,t){var l=o.toLowerCase().charCodeAt(0),u=o.toUpperCase().charCodeAt(0);l!==a&&(r[l]=i),u!==a&&(r[u]=i)}}var p=s.length,m=s.charAt(0),x=Math.log(p)/Math.log(256),y=Math.log(256)/Math.log(p);function f(E){if(E instanceof Uint8Array||(ArrayBuffer.isView(E)?E=new Uint8Array(E.buffer,E.byteOffset,E.byteLength):Array.isArray(E)&&(E=Uint8Array.from(E))),!(E instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(E.length===0)return"";for(var S=0,c=0,h=0,d=E.length;h!==d&&E[h]===0;)h++,S++;for(var b=(d-h)*y+1>>>0,v=new Uint8Array(b);h!==d;){for(var _=E[h],D=0,P=b-1;(_!==0||D<c)&&P!==-1;P--,D++)_+=256*v[P]>>>0,v[P]=_%p>>>0,_=_/p>>>0;if(_!==0)throw new Error("Non-zero carry");c=D,h++}for(var K=b-c;K!==b&&v[K]===0;)K++;for(var F=m.repeat(S);K<b;++K)F+=s.charAt(v[K]);return F}function g(E){if(typeof E!="string")throw new TypeError("Expected String");if(E.length===0)return new Uint8Array;var S=0;if(E[S]!==" "){for(var c=0,h=0;E[S]===m;)c++,S++;for(var d=(E.length-S)*x+1>>>0,b=new Uint8Array(d);E[S];){var v=r[E.charCodeAt(S)];if(v===255)return;for(var _=0,D=d-1;(v!==0||_<h)&&D!==-1;D--,_++)v+=p*b[D]>>>0,b[D]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");h=_,S++}if(E[S]!==" "){for(var P=d-h;P!==d&&b[P]===0;)P++;for(var K=new Uint8Array(c+(d-P)),F=c;P!==d;)K[F++]=b[P++];return K}}}function w(E){var S=g(E);if(S)return S;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:g,decode:w}}var Xc=Yc,Jc=Xc,oo=Jc;var jr=class{name;prefix;baseEncode;constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Zr=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,r){this.name=e,this.prefix=t;let n=t.codePointAt(0);if(n===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ao(this,e)}},Yr=class{decoders;constructor(e){this.decoders=e}or(e){return ao(this,e)}decode(e){let t=e[0],r=this.decoders[t];if(r!=null)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ao(s,e){return new Yr({...s.decoders??{[s.prefix]:s},...e.decoders??{[e.prefix]:e}})}var Xr=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,r,n){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new jr(e,t,r),this.decoder=new Zr(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function zt({name:s,prefix:e,encode:t,decode:r}){return new Xr(s,e,t,r)}function it({name:s,prefix:e,alphabet:t,caseInsensitive:r=!1}){let{encode:n,decode:i}=oo(t,s,r);return zt({prefix:e,name:s,encode:n,decode:o=>Be(i(o))})}function Qc(s,e,t,r){let n=s.length;for(;s[n-1]==="=";)--n;let i=new Uint8Array(n*t/8|0),o=0,a=0,l=0;for(let u=0;u<n;++u){let p=e[s[u]];if(p===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<t|p,o+=t,o>=8&&(o-=8,i[l++]=255&a>>o)}if(o>=t||(255&a<<8-o)!==0)throw new SyntaxError("Unexpected end of data");return i}function el(s,e,t){let r=e[e.length-1]==="=",n=(1<<t)-1,i="",o=0,a=0;for(let l=0;l<s.length;++l)for(a=a<<8|s[l],o+=8;o>t;)o-=t,i+=e[n&a>>o];if(o!==0&&(i+=e[n&a<<t-o]),r)for(;(i.length*t&7)!==0;)i+="=";return i}function tl(s,e){let t={};for(let r=0;r<s.length;++r)if(t[s[r]]=r,e){let n=s[r].toLowerCase(),i=s[r].toUpperCase();n!==s[r]&&(t[n]=r),i!==s[r]&&(t[i]=r)}return t}function ne({name:s,prefix:e,bitsPerChar:t,alphabet:r,caseInsensitive:n=!1}){let i=tl(r,n);return zt({prefix:e,name:s,encode(o){return el(o,r,t)},decode(o){return Qc(o,i,t,s)}})}var ie=it({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),sl=it({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Qr={};_e(Qr,{base32:()=>qt,base32hex:()=>ol,base32hexpad:()=>cl,base32hexpadupper:()=>ll,base32hexupper:()=>al,base32pad:()=>nl,base32padupper:()=>il,base32upper:()=>rl,base32z:()=>ul});var qt=ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),rl=ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),nl=ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),il=ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),ol=ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),al=ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),cl=ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),ll=ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),ul=ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var en={};_e(en,{base36:()=>ds,base36upper:()=>hl});var ds=it({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),hl=it({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var fl=uo,co=128,dl=127,pl=~dl,ml=Math.pow(2,31);function uo(s,e,t){e=e||[],t=t||0;for(var r=t;s>=ml;)e[t++]=s&255|co,s/=128;for(;s&pl;)e[t++]=s&255|co,s>>>=7;return e[t]=s|0,uo.bytes=t-r+1,e}var gl=tn,bl=128,lo=127;function tn(s,r){var t=0,r=r||0,n=0,i=r,o,a=s.length;do{if(i>=a)throw tn.bytes=0,new RangeError("Could not decode varint");o=s[i++],t+=n<28?(o&lo)<<n:(o&lo)*Math.pow(2,n),n+=7}while(o>=bl);return tn.bytes=i-r,t}var yl=Math.pow(2,7),wl=Math.pow(2,14),xl=Math.pow(2,21),vl=Math.pow(2,28),El=Math.pow(2,35),Sl=Math.pow(2,42),_l=Math.pow(2,49),Il=Math.pow(2,56),Tl=Math.pow(2,63),Dl=function(s){return s<yl?1:s<wl?2:s<xl?3:s<vl?4:s<El?5:s<Sl?6:s<_l?7:s<Il?8:s<Tl?9:10},Al={encode:fl,decode:gl,encodingLength:Dl},Ml=Al,ps=Ml;function ms(s,e=0){let t=ps.decode(s,e),r=ps.decode.bytes;if(r>9)throw new RangeError("Invalid varint: too long");if(r>1&&s[e+r-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[t,r]}function Gt(s,e,t=0){return ps.encode(s,e,t),e}function Ht(s){return ps.encodingLength(s)}function He(s,e){let t=e.byteLength,r=Ht(s),n=r+Ht(t),i=new Uint8Array(n+t);return Gt(s,i,0),Gt(t,i,r),i.set(e,n),new Wt(s,t,e,i)}function Ye(s){let e=Be(s),[t,r]=ms(e),[n,i]=ms(e.subarray(r)),o=e.subarray(r+i);if(o.byteLength!==n)throw new Error("Incorrect length");return new Wt(t,n,o,e)}function ho(s,e){if(s===e)return!0;{let t=e;return s.code===t.code&&s.size===t.size&&t.bytes instanceof Uint8Array&&so(s.bytes,t.bytes)}}var Wt=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=vt(r),this.bytes=vt(n)}};function fo(s,e){let{bytes:t,version:r}=s;return r===0?Bl(t,sn(s),e??ie.encoder):kl(t,sn(s),e??qt.encoder)}var po=new WeakMap;function sn(s){let e=po.get(s);if(e==null){let t=new Map;return po.set(s,t),t}return e}var ce=class s{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=vt(n),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==gs)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Rl)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return s.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,r=He(e,t);return s.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return s.equals(this,e)}static equals(e,t){let r=t;return r!=null&&e.code===r.code&&e.version===r.version&&ho(e.multihash,r.multihash)}toString(e){return fo(this,e)}toJSON(){return{"/":fo(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof s)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:r,code:n,multihash:i,bytes:o}=t;return new s(r,n,i,o??mo(r,n,i.bytes))}else if(t[Ll]===!0){let{version:r,multihash:n,code:i}=t,o=Ye(n);return s.create(r,i,o)}else return null}static create(e,t,r){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==gs)throw new Error(`Version 0 CID must use dag-pb (code: ${gs}) block encoding`);return new s(e,t,r,r.bytes)}case 1:{let n=mo(e,t,r.bytes);return new s(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return s.create(0,gs,e)}static createV1(e,t){return s.create(1,e,t)}static decode(e){let[t,r]=s.decodeFirst(e);if(r.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=s.inspectBytes(e),r=t.size-t.multihashSize,n=Be(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=n.subarray(t.multihashSize-t.digestSize),o=new Wt(t.multihashCode,t.digestSize,i,n);return[t.version===0?s.createV0(o):s.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,r=()=>{let[m,x]=ms(e.subarray(t));return t+=x,m},n=r(),i=gs;if(n===18?(n=0,t=0):i=r(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let o=t,a=r(),l=r(),u=t+l,p=u-o;return{version:n,codec:i,multihashCode:a,digestSize:l,multihashSize:p,size:u}}static parse(e,t){let[r,n]=Pl(e,t),i=s.decode(n);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return sn(i).set(r,e),i}};function Pl(s,e){switch(s[0]){case"Q":{let t=e??ie;return[ie.prefix,t.decode(`${ie.prefix}${s}`)]}case ie.prefix:{let t=e??ie;return[ie.prefix,t.decode(s)]}case qt.prefix:{let t=e??qt;return[qt.prefix,t.decode(s)]}case ds.prefix:{let t=e??ds;return[ds.prefix,t.decode(s)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[s[0],e.decode(s)]}}}function Bl(s,e,t){let{prefix:r}=t;if(r!==ie.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let n=e.get(r);if(n==null){let i=t.encode(s).slice(1);return e.set(r,i),i}else return n}function kl(s,e,t){let{prefix:r}=t,n=e.get(r);if(n==null){let i=t.encode(s);return e.set(r,i),i}else return n}var gs=112,Rl=18;function mo(s,e,t){let r=Ht(s),n=r+Ht(e),i=new Uint8Array(n+t.byteLength);return Gt(s,i,0),Gt(e,i,r),i.set(t,n),i}var Ll=Symbol.for("@ipld/js-cid/CID");var rn={};_e(rn,{identity:()=>Ne});var go=0,Cl="identity",bo=Be;function Fl(s,e){if(e?.truncate!=null&&e.truncate!==s.byteLength){if(e.truncate<0||e.truncate>s.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${s.byteLength}`);s=s.subarray(0,e.truncate)}return He(go,bo(s))}var Ne={code:go,name:Cl,encode:bo,digest:Fl};function Ie(s,e){if(s===e)return!0;if(s.byteLength!==e.byteLength)return!1;for(let t=0;t<s.byteLength;t++)if(s[t]!==e[t])return!1;return!0}function Nl(s){return s.buffer instanceof ArrayBuffer}function ke(s){return Nl(s)?s:s.slice()}async function yo(s,e,t,r){let n=await crypto.subtle.importKey("jwk",s,{name:"ECDSA",namedCurve:s.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();let i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,ke(e),ke(t.subarray()));return r?.signal?.throwIfAborted(),i}function Xe(s=0){return new Uint8Array(s)}function he(s=0){return new Uint8Array(s)}function Ol(s){return s?.buffer instanceof ArrayBuffer}function wo(s){if(Ol(s))return s;let e=s.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Et(s,e){e==null&&(e=s.reduce((n,i)=>n+i.length,0));let t=he(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return wo(t)}var vo=Symbol.for("@achingbrain/uint8arraylist");function xo(s,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let r of s){let n=t+r.byteLength;if(e<n)return{buf:r,index:e-t};t=n}throw new RangeError("index is out of bounds")}function Gs(s){return!!s?.[vo]}var ae=class s{bufs;length;[vo]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else if(Gs(r)){t+=r.byteLength;for(let n of r.bufs)this.bufs.push(n)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else if(Gs(r))t+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=xo(this.bufs,e);return t.buf[t.index]}set(e,t){let r=xo(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(t+r,e[r]);else if(Gs(e))for(let r=0;r<e.length;r++)this.set(t+r,e.get(r));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:r,length:n}=this._subList(e,t);return Et(r,n)}subarray(e,t){let{bufs:r,length:n}=this._subList(e,t);return r.length===1?r[0]:Et(r,n)}sublist(e,t){let{bufs:r,length:n}=this._subList(e,t),i=new s;return i.length=n,i.bufs=r,i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let r=[],n=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],a=n,l=a+o.byteLength;if(n=l,e>=l)continue;let u=e>=a&&e<l,p=t>a&&t<=l;if(u&&p){if(e===a&&t===l){r.push(o);break}let m=e-a;r.push(o.subarray(m,m+(t-e)));break}if(u){if(e===0){r.push(o);continue}r.push(o.subarray(e-a));continue}if(p){if(t===l){r.push(o);break}r.push(o.subarray(0,t-a));break}r.push(o)}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!Gs(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let r=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let n=r.byteLength;if(n===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let m=0;m<i;m++)o[m]=-1;for(let m=0;m<n;m++)o[r[m]]=m;let a=o,l=this.byteLength-r.byteLength,u=r.byteLength-1,p;for(let m=t;m<=l;m+=p){p=0;for(let x=u;x>=0;x--){let y=this.get(m+x);if(r[x]!==y){p=Math.max(1,x-a[y]);break}}if(p===0)return m}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let r=he(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){let n=Xe(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){let n=Xe(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){let n=Xe(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let r=he(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){let n=Xe(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){let n=Xe(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){let n=Xe(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){let n=Xe(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){let n=Xe(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(e==null||!(e instanceof s)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Ie(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let r=new s;return r.bufs=e,t==null&&(t=e.reduce((n,i)=>n+i.byteLength,0)),r.length=t,r}};var nn={};_e(nn,{base10:()=>Ul});var Ul=it({prefix:"9",name:"base10",alphabet:"0123456789"});var on={};_e(on,{base16:()=>Kl,base16upper:()=>zl});var Kl=ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),zl=ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var an={};_e(an,{base2:()=>ql});var ql=ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var cn={};_e(cn,{base256emoji:()=>$l});var Eo=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Gl=Eo.reduce((s,e,t)=>(s[t]=e,s),[]),Hl=Eo.reduce((s,e,t)=>{let r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return s[r]=t,s},[]);function Wl(s){return s.reduce((e,t)=>(e+=Gl[t],e),"")}function Vl(s){let e=[];for(let t of s){let r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);let n=Hl[r];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var $l=zt({prefix:"\u{1F680}",name:"base256emoji",encode:Wl,decode:Vl});var ln={};_e(ln,{base64:()=>jl,base64pad:()=>Zl,base64url:()=>Yl,base64urlpad:()=>Xl});var jl=ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Zl=ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Yl=ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Xl=ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var un={};_e(un,{base8:()=>Jl});var Jl=ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var hn={};_e(hn,{identity:()=>Ql});var Ql=zt({prefix:"\0",name:"identity",encode:s=>no(Be(s)),decode:s=>Be(ro(s))});var sp=new TextEncoder,rp=new TextDecoder;var pn={};_e(pn,{sha256:()=>St,sha512:()=>ru});var su=20;function dn({name:s,code:e,encode:t,minDigestLength:r,maxDigestLength:n}){return new fn(s,e,t,r,n)}var fn=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,r,n,i){this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??su,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?So(r,this.code,t?.truncate):r.then(n=>So(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function So(s,e,t){if(t!=null&&t!==s.byteLength){if(t>s.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${s.byteLength}`);s=s.subarray(0,t)}return He(e,s)}function Io(s){return async e=>new Uint8Array(await crypto.subtle.digest(s,e))}var St=dn({name:"sha2-256",code:18,encode:Io("SHA-256")}),ru=dn({name:"sha2-512",code:19,encode:Io("SHA-512")});var mn={...hn,...an,...un,...nn,...on,...Qr,...en,...Jr,...ln,...cn},mp={...pn,...rn};function Do(s,e,t,r){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:r}}}var To=Do("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),gn=Do("ascii","a",s=>{let e="a";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return e},s=>{s=s.substring(1);let e=he(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),nu={utf8:To,"utf-8":To,hex:mn.base16,latin1:gn,ascii:gn,binary:gn,...mn},Hs=nu;function j(s,e="utf8"){let t=Hs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${s}`)}function $(s,e="utf8"){let t=Hs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(s).substring(1)}var iu=parseInt("11111",2),bn=parseInt("10000000",2),ou=parseInt("01111111",2),Ao={0:bs,1:bs,2:au,3:uu,4:hu,5:lu,6:cu,16:bs,22:bs,48:bs};function Je(s,e={offset:0}){let t=s[e.offset]&iu;if(e.offset++,Ao[t]!=null)return Ao[t](s,e);throw new Error("No decoder for tag "+t)}function ys(s,e){let t=0;if((s[e.offset]&bn)===bn){let r=s[e.offset]&ou,n="0x";e.offset++;for(let i=0;i<r;i++,e.offset++){if(e.offset>=s.byteLength)throw new Error("invalid DER element length");n+=s[e.offset].toString(16).padStart(2,"0")}t=parseInt(n,16)}else t=s[e.offset],e.offset++;if(!Number.isInteger(t)||t<0||t>s.byteLength-e.offset)throw new Error("invalid DER element length");return t}function bs(s,e){ys(s,e);let t=[];for(;!(e.offset>=s.byteLength);){let r=Je(s,e);if(r===null)break;t.push(r)}return t}function au(s,e){let t=ys(s,e),r=e.offset,n=e.offset+t,i=[];for(let o=r;o<n;o++)o===r&&s[o]===0||i.push(s[o]);return e.offset+=t,Uint8Array.from(i)}function cu(s,e){let t=ys(s,e),r=e.offset+t,n=s[e.offset];e.offset++;let i=0,o=0;n<40?(i=0,o=n):n<80?(i=1,o=n-40):(i=2,o=n-80);let a=`${i}.${o}`,l=[];for(;e.offset<r;){let u=s[e.offset];if(e.offset++,l.push(u&127),u<128){l.reverse();let p=0;for(let m=0;m<l.length;m++)p+=l[m]<<m*7;a+=`.${p}`,l=[]}}return a}function lu(s,e){return e.offset++,null}function uu(s,e){let t=ys(s,e),r=s[e.offset];e.offset++;let n=s.subarray(e.offset,e.offset+t-1);if(e.offset+=t,r!==0)throw new Error("Unused bits in bit string is unimplemented");return n}function hu(s,e){let t=ys(s,e),r=s.subarray(e.offset,e.offset+t);return e.offset+=t,r}function fu(s){let e=s.toString(16);e.length%2===1&&(e="0"+e);let t=new ae;for(let r=0;r<e.length;r+=2)t.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return t}function yn(s){if(s.byteLength<128)return Uint8Array.from([s.byteLength]);let e=fu(s.byteLength);return new ae(Uint8Array.from([e.byteLength|bn]),e)}function Te(s){let e=new ae,t=128;return(s.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(s),new ae(Uint8Array.from([2]),yn(e),e)}function Ws(s){let e=Uint8Array.from([0]),t=new ae(e,s);return new ae(Uint8Array.from([3]),yn(t),t)}function at(s,e=48){let t=new ae;for(let r of s)t.append(r);return new ae(Uint8Array.from([e]),yn(t),t)}var du=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),pu=Uint8Array.from([6,5,43,129,4,0,34]),mu=Uint8Array.from([6,5,43,129,4,0,35]),gu={ext:!0,kty:"EC",crv:"P-256"},bu={ext:!0,kty:"EC",crv:"P-384"},yu={ext:!0,kty:"EC",crv:"P-521"},wn=32,xn=48,vn=66;function En(s){let e=Je(s);return Mo(e)}function Mo(s){let e=s[1][1][0],t=1,r,n;if(e.byteLength===wn*2+1)return r=$(e.subarray(t,t+wn),"base64url"),n=$(e.subarray(t+wn),"base64url"),new Vt({...gu,key_ops:["verify"],x:r,y:n});if(e.byteLength===xn*2+1)return r=$(e.subarray(t,t+xn),"base64url"),n=$(e.subarray(t+xn),"base64url"),new Vt({...bu,key_ops:["verify"],x:r,y:n});if(e.byteLength===vn*2+1)return r=$(e.subarray(t,t+vn),"base64url"),n=$(e.subarray(t+vn),"base64url"),new Vt({...yu,key_ops:["verify"],x:r,y:n});throw new re(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Po(s){return at([Te(Uint8Array.from([1])),at([wu(s.crv)],160),at([Ws(new ae(Uint8Array.from([4]),j(s.x??"","base64url"),j(s.y??"","base64url")))],161)]).subarray()}function wu(s){if(s==="P-256")return du;if(s==="P-384")return pu;if(s==="P-521")return mu;throw new re(`Invalid curve ${s}`)}var Vt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Po(this.jwk)),this._raw}toMultihash(){return Ne.digest(We(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}async verify(e,t,r){return yo(this.jwk,t,e,r)}};var Vs=BigInt(4294967295),Bo=BigInt(32);function xu(s,e=!1){return e?{h:Number(s&Vs),l:Number(s>>Bo&Vs)}:{h:Number(s>>Bo&Vs)|0,l:Number(s&Vs)|0}}function ko(s,e=!1){let t=s.length,r=new Uint32Array(t),n=new Uint32Array(t);for(let i=0;i<t;i++){let{h:o,l:a}=xu(s[i],e);[r[i],n[i]]=[o,a]}return[r,n]}var vu=s=>s/2**32|0,Eu=s=>s>>>0;function Ro(s,e,t,r){let n=vu(t),i=Eu(t);s.setUint32(e,r?i:n,r),s.setUint32(e+4,r?n:i,r)}var Sn=(s,e,t)=>s>>>t,_n=(s,e,t)=>s<<32-t|e>>>t,_t=(s,e,t)=>s>>>t|e<<32-t,It=(s,e,t)=>s<<32-t|e>>>t,ws=(s,e,t)=>s<<64-t|e>>>t-32,xs=(s,e,t)=>s>>>t-32|e<<64-t;function Ve(s,e,t,r){let n=(e>>>0)+(r>>>0);return{h:s+t+(n/2**32|0)|0,l:n|0}}var Lo=(s,e,t)=>(s>>>0)+(e>>>0)+(t>>>0),Co=(s,e,t,r)=>e+t+r+(s/2**32|0)|0,Fo=(s,e,t,r)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0),No=(s,e,t,r,n)=>e+t+r+n+(s/2**32|0)|0,Oo=(s,e,t,r,n)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Uo=(s,e,t,r,n,i)=>e+t+r+n+i+(s/2**32|0)|0;function $s(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in s&&s.BYTES_PER_ELEMENT===1}var In=s=>s?`"${s}" `:"";function Qe(s,e=""){if(typeof s!="number")throw new TypeError(In(e)+"expected number, got "+typeof s);if(!Number.isSafeInteger(s)||s<0)throw new RangeError(In(e)+"expected integer >= 0, got "+s);return s}function Re(s,e,t=""){if($s(s)&&(e===void 0||s.length===e))return s;e!==void 0&&Qe(e,"length");let r=$s(s),n=e!==void 0?` of length ${e}`:"",i=r?`length=${s.length}`:`type=${typeof s}`,o=In(t)+"expected Uint8Array"+n+", got "+i;throw r?new RangeError(o):new TypeError(o)}function js(s){if(typeof s!="function"||typeof s.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Qe(s.outputLen),Qe(s.blockLen),s.outputLen<1||s.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var Ko=(s,e)=>{if(s===null||typeof s!="object"||Array.isArray(s))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof s)};function $t(s,e=!0){if(s.destroyed)throw new Error("hash was destroyed");if(e&&s.finished)throw new Error("digest() was already called")}function Zs(s,e){Re(s,void 0,"output");let t=e.outputLen;if(!(s.length>=t))throw new RangeError('"output" expected length >= '+t)}function Tt(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Ys(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Oe(s,e){return s<<32-e|s>>>e}var qo=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",_u=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Xs(s){if(Re(s),qo)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=_u[s[t]];return e}function zo(s){return s>=48&&s<=57?s-48:s>=65&&s<=70?s-55:s>=97&&s<=102?s-87:void 0}function Js(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);if(qo)try{return Uint8Array.fromHex(s)}catch(n){throw n instanceof SyntaxError?new RangeError(n.message):n}let e=s.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let n=0,i=0;n<t;n++,i+=2){let o=zo(s.charCodeAt(i)),a=zo(s.charCodeAt(i+1));if(o===void 0||a===void 0){let l=s[i]+s[i+1];throw new RangeError('hex string expected, got non-hex character "'+l+'" at index '+i)}r[n]=o*16+a}return r}function Tn(...s){let e=0;for(let r=0;r<s.length;r++){let n=s[r];Re(n),e+=n.length}let t=new Uint8Array(e);for(let r=0,n=0;r<s.length;r++){let i=s[r];t.set(i,n),n+=i.length}return t}function Iu(s,e,t="opts"){return Ko(s,"defaults"),e!==void 0&&Ko(e,t),Object.assign(s,e)}function Dn(s,e={}){if(typeof s!="function")throw new TypeError('"hashCons" expected function, got type='+typeof s);e=Iu({},e,"info");let t=(n,i)=>s(i).update(n).digest(),r=s(void 0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.canXOF=r.canXOF,t.create=n=>s(n),Object.assign(t,e),Object.freeze(t)}function Go(s=32){Qe(s,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(s>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${s}`);return e.getRandomValues(new Uint8Array(s))}var An=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function Ho(s,e,t){return s&e^~s&t}function Wo(s,e,t){return s&e^s&t^e&t}var vs=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Ys(this.buffer)}update(e){$t(this),Re(e);let{view:t,buffer:r,blockLen:n}=this,i=e.length,o=!1;for(let a=0;a<i;){let l=Math.min(n-this.pos,i-a);if(l===n){let u=Ys(e);for(;n<=i-a;a+=n)this.process(u,a);o=!0;continue}r.set(a===0&&l===i?e:e.subarray(a,a+l),this.pos),this.pos+=l,a+=l,this.pos===n&&(this.process(t,0),this.pos=0,o=!0)}return this.length+=e.length,o&&this.roundClean(),this}digestInto(e){$t(this),Zs(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,t.fill(0,o),this.padOffset>n-o&&(this.process(r,0),t.fill(0)),Ro(r,n-8,this.length*8,i),this.process(r,0),this.roundClean();let a=e===t?r:Ys(e),l=this.outputLen,u=l/4,p=this.get();if(l%4||u>p.length)throw new Error("invalid outputLen");for(let m=0;m<u;m++)a.setUint32(4*m,p[m],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:i,pos:o}=this;return e.destroyed=i,e.finished=n,e.length=r,e.pos=o,o&&e.buffer.set(t),e}clone(){return this._cloneInto()}},Vo=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var $o=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Tu=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ct=new Uint32Array(64),Mn=class extends vs{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:i,F:o,G:a,H:l}=this;return[e,t,r,n,i,o,a,l]}set(e,t,r,n,i,o,a,l){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=l|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let m=0;m<16;m++,t+=4)ct[m]=e.getUint32(t,!1);for(let m=16;m<64;m++){let x=ct[m-15],y=ct[m-2],f=Oe(x,7)^Oe(x,18)^x>>>3,g=Oe(y,17)^Oe(y,19)^y>>>10;ct[m]=g+ct[m-7]+f+ct[m-16]|0}let{A:r,B:n,C:i,D:o,E:a,F:l,G:u,H:p}=this;for(let m=0;m<64;m++){let x=Oe(a,6)^Oe(a,11)^Oe(a,25),y=p+x+Ho(a,l,u)+Tu[m]+ct[m]|0,g=(Oe(r,2)^Oe(r,13)^Oe(r,22))+Wo(r,n,i)|0;p=u,u=l,l=a,a=o+y|0,o=i,i=n,n=r,r=y+g|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,l=l+this.F|0,u=u+this.G|0,p=p+this.H|0,this.set(r,n,i,o,a,l,u,p)}roundClean(){Tt(ct)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Tt(this.buffer)}},Pn=class extends Mn{constructor(){super(32,Vo)}};var jo=ko(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(s=>BigInt(s))),Du=jo[0],Au=jo[1],lt=new Uint32Array(80),ut=new Uint32Array(80),Bn=class extends vs{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:o,Dh:a,Dl:l,Eh:u,El:p,Fh:m,Fl:x,Gh:y,Gl:f,Hh:g,Hl:w}=this;return[e,t,r,n,i,o,a,l,u,p,m,x,y,f,g,w]}set(e,t,r,n,i,o,a,l,u,p,m,x,y,f,g,w){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=n|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=l|0,this.Eh=u|0,this.El=p|0,this.Fh=m|0,this.Fl=x|0,this.Gh=y|0,this.Gl=f|0,this.Hh=g|0,this.Hl=w|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let c=0;c<16;c++,t+=4)lt[c]=e.getUint32(t),ut[c]=e.getUint32(t+=4);for(let c=16;c<80;c++){let h=lt[c-15]|0,d=ut[c-15]|0,b=_t(h,d,1)^_t(h,d,8)^Sn(h,d,7),v=It(h,d,1)^It(h,d,8)^_n(h,d,7),_=lt[c-2]|0,D=ut[c-2]|0,P=_t(_,D,19)^ws(_,D,61)^Sn(_,D,6),K=It(_,D,19)^xs(_,D,61)^_n(_,D,6),F=Fo(v,K,ut[c-7],ut[c-16]),Y=No(F,b,P,lt[c-7],lt[c-16]);lt[c]=Y|0,ut[c]=F|0}let{Ah:r,Al:n,Bh:i,Bl:o,Ch:a,Cl:l,Dh:u,Dl:p,Eh:m,El:x,Fh:y,Fl:f,Gh:g,Gl:w,Hh:E,Hl:S}=this;for(let c=0;c<80;c++){let h=_t(m,x,14)^_t(m,x,18)^ws(m,x,41),d=It(m,x,14)^It(m,x,18)^xs(m,x,41),b=m&y^~m&g,v=x&f^~x&w,_=Oo(S,d,v,Au[c],ut[c]),D=Uo(_,E,h,b,Du[c],lt[c]),P=_|0,K=_t(r,n,28)^ws(r,n,34)^ws(r,n,39),F=It(r,n,28)^xs(r,n,34)^xs(r,n,39),Y=r&i^r&a^i&a,C=n&o^n&l^o&l;E=g|0,S=w|0,g=y|0,w=f|0,y=m|0,f=x|0,{h:m,l:x}=Ve(u|0,p|0,D|0,P|0),u=a|0,p=l|0,a=i|0,l=o|0,i=r|0,o=n|0;let L=Lo(P,F,C);r=Co(L,D,K,Y),n=L|0}({h:r,l:n}=Ve(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=Ve(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l}=Ve(this.Ch|0,this.Cl|0,a|0,l|0),{h:u,l:p}=Ve(this.Dh|0,this.Dl|0,u|0,p|0),{h:m,l:x}=Ve(this.Eh|0,this.El|0,m|0,x|0),{h:y,l:f}=Ve(this.Fh|0,this.Fl|0,y|0,f|0),{h:g,l:w}=Ve(this.Gh|0,this.Gl|0,g|0,w|0),{h:E,l:S}=Ve(this.Hh|0,this.Hl|0,E|0,S|0),this.set(r,n,i,o,a,l,u,p,m,x,y,f,g,w,E,S)}roundClean(){Tt(lt,ut)}destroy(){this.destroyed=!0,Tt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},kn=class extends Bn{constructor(){super(64,$o)}};var jt=Dn(()=>new Pn,An(1));var Rn=Dn(()=>new kn,An(3));function er(s,e,t=()=>{}){if(!Array.isArray(s))throw new TypeError(`"${e}" expected array, got type=${typeof s}`);for(let r=0;r<s.length;r++)t(s[r],`${e}[${r}]`);return s}var G=(s,e,t)=>Re(s,e,t),Ln=Qe;function Yo(s,e=""){if(typeof s!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof s)}return s}function ht(s,e="object"){if(s===null||typeof s!="object"||Array.isArray(s))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof s}`);return s}function Dt(s,e){if(typeof s!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof s}`);return s}var Es=Xs,Le=(...s)=>Tn(...s),Zt=s=>Js(s),dt=$s,At=s=>Go(s),Qs=BigInt(0),Zo=BigInt(1),Mu=s=>s?`"${s}" `:"";function De(s,e=""){if(typeof s!="boolean")throw new TypeError(Mu(e)+"expected boolean, got type="+typeof s);return s}function tr(s){if(typeof s=="bigint"){if(!ft(s))throw new RangeError("positive bigint expected, got "+s)}else Ln(s);return s}function pt(s,e=""){if(typeof s!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof s)}if(!Number.isSafeInteger(s)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+s)}}function Ss(s){let e=tr(s).toString(16);return e.length&1?"0"+e:e}function Xo(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);return s===""?Qs:BigInt("0x"+s)}function $e(s){return Xo(Xs(s))}function Mt(s){return Xo(Xs(rr(Re(s)).reverse()))}function sr(s,e){if(Qe(e),e===0)throw new Error("zero output length is invalid");s=tr(s);let t=e*2,r=s.toString(16);if(r.length>t)throw new RangeError("number is too large");return Js(r.padStart(t,"0"))}function Cn(s,e){return sr(s,e).reverse()}function rr(s){return Uint8Array.from(G(s))}function ft(s){return typeof s=="bigint"&&Qs<=s}function Fn(s,e,t){return ft(s)&&ft(e)&&ft(t)&&e<=s&&s<t}function Yt(s,e,t,r){if(!Fn(e,t,r))throw new RangeError("expected valid "+s+": "+t+" <= n < "+r+", got "+e)}function Xt(s){if(s<Qs)throw new Error("expected non-negative bigint, got "+s);return s===Qs?0:s.toString(2).length}var _s=s=>(pt(s,"n"),(Zo<<BigInt(s))-Zo);function Jo(s,e,t){if(Qe(s,"hashLen"),Qe(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let r=w=>new Uint8Array(w),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3,l=r(s),u=r(s),p=0,m=()=>{l.fill(1),u.fill(0),p=0},x=(...w)=>t(u,Le(l,...w)),y=(w=n)=>{u=x(i,w),l=x(),w.length!==0&&(u=x(o,w),l=x())},f=()=>{if(p++>=a)throw new Error("drbg: tried max amount of iterations");let w=0,E=[];for(;w<e;){l=x();let S=l.slice();E.push(S),w+=l.length}return Le(...E)};return(w,E)=>{m(),y(w);let S;for(;(S=E(f()))===void 0;)y();return m(),S}}function Ae(s,e={},t={},r="object"){ht(s,r),ht(e,"fields"),ht(t,"optFields");function n(o,a,l){let u=r==="object"?`param "${String(o)}"`:`"${r}.${String(o)}"`,p=s[o];if(!Object.hasOwn(s,o)&&(l?p!==void 0:a!=="function"))throw new TypeError(`${u} is invalid: expected own property`);if(l&&p===void 0)return;let m=typeof p;if(m!==a||p===null)throw new TypeError(`${u} is invalid: expected ${a}, got ${m}`)}let i=(o,a)=>Object.entries(o).forEach(([l,u])=>n(l,u,a));i(e,!1),i(t,!0)}var oe=BigInt(0),H=BigInt(1),mt=BigInt(2),ta=BigInt(3),Nn=BigInt(4),sa=BigInt(5),Pu=BigInt(7),ra=BigInt(8),Bu=BigInt(9),ku=BigInt(15),na=BigInt(16),Ru=BigInt("0x10000000000000000");function J(s,e){if(e<=oe)throw new Error("mod: expected positive modulus, got "+e);let t=s%e;return t>=oe?t:e+t}function ia(s,e,t){if(t<=H)throw new Error("pow: expected modulus > 1, got "+t);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<oe)throw new Error("invalid exponent, negatives unsupported");if(e===oe)return H;if(e===H)return s;let r=s%t;if(r<oe&&(r+=t),e<Ru){let a=H;for(;e>oe;)e&H&&(a=a*r%t),r=r*r%t,e>>=H;return a}let n=[];for(;e>oe;)n.push(Number(e&ku)),e>>=Nn;let i=new Array(16);i[0]=H,i[1]=r;for(let a=2;a<16;a++)i[a]=i[a-1]*r%t;let o=i[n[n.length-1]];for(let a=n.length-2;a>=0;a--){o=o*o%t,o=o*o%t,o=o*o%t,o=o*o%t;let l=n[a];l!==0&&(o=o*i[l]%t)}return o}function X(s,e,t){if(t<=H)throw new Error("pow2: expected modulus > 1, got "+t);if(e<oe)throw new Error("pow2: expected non-negative exponent, got "+e);let r=s;for(;e-- >oe;)r*=r,r%=t;return r}function Qo(s,e){if(s===oe)throw new Error("invert: expected non-zero number");if(e<=H)throw new Error("invert: expected modulus > 1, got "+e);let t=J(s,e),r=e,n=oe,i=H;for(;t!==oe;){let a=r/t,l=r-t*a,u=n-i*a;r=t,t=l,n=i,i=u}if(r!==H)throw new Error("invert: does not exist");return J(n,e)}function oa(s,e){if(e<=H)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=J(s,e);if(t===oe)throw new Error("invertCt: expected non-zero number");let r=ia(t,e-mt,e);if(J(t*r,e)!==H)throw new Error("invertCt: does not exist");return r}function On(s,e,t){let r=s;if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function Un(s,e){if((s&H)===oe)throw new Error(e+": expected odd modulus, got "+s)}function aa(s,e){let t=s,r=(t.ORDER+H)/Nn,n=t.pow(e,r);return On(t,n,e),n}function Lu(s,e){let t=s,r=(t.ORDER-sa)/ra,n=t.mul(e,mt),i=t.pow(n,r),o=t.mul(e,i),a=t.mul(t.mul(o,mt),i),l=t.mul(o,t.sub(a,t.ONE));return On(t,l,e),l}function Cu(s){let e=Qt(s),t=ca(s),r=t(e,e.neg(e.ONE)),n=t(e,r),i=t(e,e.neg(r)),o=(s+Pu)/na;return((a,l)=>{let u=a,p=u.pow(l,o),m=u.mul(p,r),x=u.mul(p,n),y=u.mul(p,i),f=u.eql(u.sqr(m),l),g=u.eql(u.sqr(x),l);p=u.cmov(p,m,f),m=u.cmov(y,x,g);let w=u.eql(u.sqr(m),l),E=u.cmov(p,m,w);return On(u,E,l),E})}function ca(s){if(s<ta)throw new Error("sqrt is not defined for small field");Un(s,"tonelliShanks");let e=s-H,t=0;for(;e%mt===oe;)e/=mt,t++;let r=mt,n=Qt(s);for(;Is(n,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return aa;let i=n.pow(r,e),o=(e+H)/mt;return function(l,u){let p=l;if(p.is0(u))return u;if(Is(p,u)!==1)throw new Error("Cannot find square root");let m=t,x=p.mul(p.ONE,i),y=p.pow(u,e),f=p.pow(u,o);for(;!p.eql(y,p.ONE);){if(p.is0(y))throw new Error("Cannot find square root: probably non-prime P");let g=1,w=p.sqr(y);for(;!p.eql(w,p.ONE);)if(g++,w=p.sqr(w),g===m)throw new Error("Cannot find square root");let E=H<<BigInt(m-g-1),S=p.pow(x,E);m=g,x=p.sqr(S),y=p.mul(y,x),f=p.mul(f,S)}return f}}function Fu(s){return Un(s,"Fp.sqrt"),s%Nn===ta?aa:s%ra===sa?Lu:s%na===Bu?Cu(s):ca(s)}var la=(s,e)=>(J(s,e)&H)===H,Nu=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Jt(s){if(ht(s,"field"),typeof s.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof s.ORDER);pt(s.BYTES,"BYTES"),pt(s.BITS,"BITS");for(let e of Nu)Dt(s[e],"field."+e);if(s.BYTES<1||s.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(s.ORDER<=H)throw new Error("invalid field: expected ORDER > 1, got "+s.ORDER);return s}function ir(s,e,t=!1){Jt(s),er(e,"nums"),De(t,"passZero");let r=s,n=new Array(e.length).fill(t?r.ZERO:void 0),i=e.reduce((a,l,u)=>r.is0(l)?a:(n[u]=a,r.mul(a,l)),r.ONE),o=r.inv(i);return e.reduceRight((a,l,u)=>r.is0(l)?a:(n[u]=r.mul(a,n[u]),r.mul(a,l)),o),n}function Is(s,e){Jt(s);let t=s;Un(t.ORDER,"FpLegendre");let r=(t.ORDER-H)/mt,n=t.pow(e,r),i=t.eql(n,t.ONE),o=t.eql(n,t.ZERO),a=t.eql(n,t.neg(t.ONE));if(!i&&!o&&!a)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function Ou(s,e){if(e!==void 0&&Ln(e),s<=oe)throw new Error("invalid n length: expected positive n, got "+s);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Xt(s);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let r=e!==void 0?e:t,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var ea=new WeakMap,nr=class{ORDER;BITS;BYTES;isLE;ZERO=oe;ONE=H;_lengths;_mod;constructor(e,t={}){if(e<=H)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:n,nByteLength:i}=Ou(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,Object.freeze(this)}create(e){return J(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return oe<=e&&e<this.ORDER}is0(e){return e===oe}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&H)===H}neg(e){return J(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return J(e*e,this.ORDER)}add(e,t){return J(e+t,this.ORDER)}sub(e,t){return J(e-t,this.ORDER)}mul(e,t){return J(e*t,this.ORDER)}pow(e,t){return ia(e,t,this.ORDER)}div(e,t){return J(e*Qo(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Qo(e,this.ORDER)}sqrt(e){let t=ea.get(this);return t||ea.set(this,t=Fu(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Cn(e,this.BYTES):sr(e,this.BYTES)}fromBytes(e,t=!1){G(e);let{_lengths:r,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let u=new Uint8Array(n);u.set(e,i?0:u.length-e.length),e=u}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=i?Mt(e):$e(e);if(a&&(l=J(l,o)),!t&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return ir(this,e,!0)}cmov(e,t,r){return De(r,"condition"),r?t:e}};function Qt(s,e={}){return Object.freeze(nr.prototype),new nr(s,e)}function ua(s){if(typeof s!="bigint")throw new Error("field order must be bigint");if(s<=H)throw new Error("field order must be greater than 1");let e=Xt(s-H);return Math.ceil(e/8)}function or(s){let e=ua(s);return e+Math.ceil(e/2)}function ar(s,e,t=!1){G(s);let r=s.length,n=ua(e),i=Math.max(or(e),16);if(r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let o=t?Mt(s):$e(s),a=J(o,e-H)+H;return t?Cn(a,n):sr(a,n)}var qn=BigInt(0),Ts=BigInt(1),Uu=BigInt(4),Kn=16,ha=128,Ku=5,fa=2**31;function gt(s){let e=s;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof s);Dt(e.fromAffine,"Point.fromAffine"),Dt(e.fromBytes,"Point.fromBytes"),Dt(e.fromHex,"Point.fromHex"),ht(e.BASE,"Point.BASE"),ht(e.ZERO,"Point.ZERO"),Jt(e.Fp),Jt(e.Fn)}function cr(s,e){gt(s),pa(e,s);let t=ir(s.Fp,e.map(r=>r.Z));return e.map((r,n)=>s.fromAffine(r.toAffine(t[n])))}function zu(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 qu(s,e){let t=s*(4*e+128);if(t>fa)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+fa/2**20+" MiB")}function Gn(s,e){if(s!==void 0){Dt(s,"randomBytes");try{let t=s(e);if(!dt(t)||t.length!==e)return}catch{return}return s}}function pa(s,e){er(s,"points"),s.forEach((t,r)=>{if(!(t instanceof e))throw new Error("invalid point at index "+r)})}function Gu(s,e,t){if(!Array.isArray(s))throw new Error("array of scalars expected");s.forEach((r,n)=>{if(!(t===void 0?e.isValid(r):ft(r)&&r<t))throw new Error("invalid scalar at index "+n)})}var ma=new WeakMap;function zn(s){return ma.get(s)||1}function Hu(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 Wu(s,e){let t=2**e,r=t/2,n=BigInt(t-1),i=[];for(;s>qn;){let o=0;s&Ts&&(o=Number(s&n),o>=r&&(o-=t),s-=BigInt(o)),i.push(o),s>>=Ts}return i}function Vu(s,e,t){let r=2**e,n=r/2,i=BigInt(r-1),o=BigInt(e),a=[];for(let l=0;l<t;l++){let u=Number(s&i);s>>=o,u>n&&(u-=r,s+=Ts),a.push(u)}if(s!==qn)throw new Error("invalid wnaf");return a}function $u(s,e,t){let r=0;for(let i of t)r=Math.max(r,i.length);let n=s;for(let i=r-1;i>=0;i--){i!==r-1&&(n=n.double());for(let o=0;o<t.length;o++){let a=t[o][i];if(a){let l=e[o][Math.abs(a)-1>>1];n=n.add(a<0?l.negate():l)}}}return n}var es=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){gt(e),this.randomBytes=Gn(t,Kn),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,r){let n=Math.ceil(r/t)+1,i=2**(t-1),o=[],a=e;for(let l=0;l<n;l++){let u=a;for(let p=0;p<i;p++)o.push(u),u=u.add(a);a=o[o.length-1].double()}return{W:t,bits:r,windows:n,comp:o}}wnafCachedCT(e,t){let{W:r,windows:n,comp:i}=e,o=2**(r-1),a=Vu(t,r,n),l=this.ZERO,u=this.BASE;for(let p=0;p<n;p++){let m=a[p],x=p*o,y=Math.abs(m)-1,f=i[x];for(let w=1;w<o;w++)f=w===y?i[x+w]:f;let g=f.negate();m===0?u=u.add(i[x]):l=l.add(m<0?g:f)}return{p:l,f:u}}getWnafPrecomputes(e,t,r,n){let i=this.wnafPrecomputes.get(t),o=i?.find(a=>a.W===e&&a.bits===r);return o||(o=this.buildWnafTable(t,e,r),typeof n=="function"&&(o={...o,comp:n(o.comp)}),i||(i=[],this.wnafPrecomputes.set(t,i)),i.push(o)),o}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!Fn(t,Ts,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,r,n){let i=zn(e);return i===1?this.fixedWindowCT(e,t,r):this.wnafCachedCT(this.getWnafPrecomputes(i,e,r,n),t)}mulCT(e,t,r){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,r)}mulCTBlinded(e,t,r){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let n=this.Point.Fn.BITS+ha,i=this.randomBytes(Kn);if(!dt(i)||i.length!==Kn)throw new Error("randomBytes returned invalid byte array");i[0]=i[0]&63|128;let o=t+$e(i)*this.Point.Fn.ORDER;return this.runCT(e,o,n,r)}fixedWindowCT(e,t,r){let n=Ku,i=1<<n,o=_s(n),a=new Array(i);a[0]=this.ZERO;for(let p=1;p<i;p++)a[p]=a[p-1].add(e);let l=Math.ceil(r/n),u=this.ZERO;for(let p=l-1;p>=0;p--){if(p!==l-1)for(let y=0;y<n;y++)u=u.double();let m=Number(t>>BigInt(p*n)&o),x=a[0];for(let y=1;y<i;y++)x=y===m?a[y]:x;u=u.add(x)}return{p:u,f:u}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===Ts?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,r,n){return this.shouldBlind(e,r)?this.mulCTBlinded(e,t,n):this.mulCT(e,t,n)}mulUnsafe(e,t,r){if(this.assertPoint(e),!ft(t))throw new Error("invalid scalar");let n=zn(e);if(n===1||t>=this.Point.Fn.ORDER)return lr(this.Point,[e],[t],!0);let i=this.getWnafPrecomputes(n,e,this.bits,r);return this.wnafCachedCT(i,t).p}setWindowSize(e,t){this.assertPoint(e),zu(t,this.bits);let r=Math.ceil((this.bits+ha)/t)+1;qu(r*2**(t-1),this.Point.Fp.BYTES),ma.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return zn(e)!==1}};function lr(s,e,t,r=!1){if(gt(s),pa(e,s),De(r,"allowOversized"),Gu(t,s.Fn,r?s.Fn.ORDER**Uu:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let n=e.map(o=>Hu(o,4)),i=t.map(o=>Wu(o,4));return $u(s.ZERO,n,i)}function da(s,e,t){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Jt(e),e}else return Qt(s,{isLE:t})}function ur(s,e,t={},r){if(s!=="weierstrass"&&s!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(r===void 0&&(r=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);Ae(t);for(let l of["p","n","h"]){let u=e[l];if(!(ft(u)&&u!==qn))throw new Error(`CURVE.${l} must be positive bigint`)}let n=da(e.p,t.Fp,r),i=da(e.n,t.Fn,r),a=["Gx","Gy","a",s==="weierstrass"?"b":"d"];for(let l of a)if(!n.isValid(e[l]))throw new Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function hr(s,e){return function(r){let n=s(r);return{secretKey:n,publicKey:e(n)}}}var fr=BigInt(0),dr=BigInt(1),pr=BigInt(2),ju=BigInt(4),ga=BigInt(8);function Zu(s,e,t,r){let n=s.sqr(t),i=s.sqr(r),o=s.add(s.mul(e.a,n),i),a=s.add(s.ONE,s.mul(e.d,s.mul(n,i)));return s.eql(o,a)}function ba(s,e={}){Ae(e,{},{},"extraOpts");let t=e,r=ur("edwards",s,t,t.FpFnLE),{Fp:n,Fn:i}=r,o=r.CURVE,{h:a}=o;if(Is(n,o.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Is(n,o.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Ae(t,{},{uvRatio:"function",randomBytes:"function"});let l=t.randomBytes===void 0?At:t.randomBytes,u=pr<<BigInt(n.BYTES*8)-dr;function p(S){if(!n.isOdd)throw new Error("Field does not have .isOdd()");return n.isOdd(S)}let m=t.uvRatio===void 0?(S,c)=>{try{return{isValid:!0,value:n.sqrt(n.div(S,c))}}catch{return{isValid:!1,value:fr}}}:t.uvRatio;if(!Zu(n,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");let x=n.eql(o.a,n.neg(n.ONE))?S=>n.neg(S):n.eql(o.a,n.ONE)?S=>S:S=>n.mul(o.a,S);function y(S,c,h=!1){let d=h?dr:fr;return Yt("coordinate "+S,c,d,u),c}function f(S){if(!(S instanceof g))throw new Error("EdwardsPoint expected")}class g{static BASE=new g(o.Gx,o.Gy,n.ONE,n.mul(o.Gx,o.Gy));static ZERO=new g(n.ZERO,n.ONE,n.ONE,n.ZERO);static Fp=n;static Fn=i;X;Y;Z;T;constructor(c,h,d,b){this.X=y("x",c),this.Y=y("y",h),this.Z=y("z",d,!0),this.T=y("t",b),Object.freeze(this)}static CURVE(){return o}static fromAffine(c){if(c instanceof g)throw new Error("extended point not allowed");let{x:h,y:d}=c||{};return y("x",h),y("y",d),new g(h,d,n.ONE,n.mul(h,d))}static fromBytes(c,h=!1){let d=n.BYTES,{a:b,d:v}=o;c=rr(G(c,d,"point")),De(h,"zip215");let _=rr(c),D=c[d-1];_[d-1]=D&-129;let P=Mt(_),K=h?u:n.ORDER;Yt("point.y",P,fr,K);let F=n.sqr(P),Y=n.sub(F,n.ONE),C=n.sub(n.mulN(v,F),b),{isValid:L,value:I}=m(Y,C);if(!L)throw new Error("bad point: invalid y coordinate");let A=p(I),B=(D&128)!==0;if(!h&&n.is0(I)&&B)throw new Error("bad point: x=0 and x_0=1");return B!==A&&(I=n.neg(I)),g.fromAffine({x:I,y:P})}static fromHex(c,h=!1){return g.fromBytes(Zt(c),h)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(c=6,h=!0){return E.setWindowSize(this,c),h||this.multiply(pr),this}assertValidity(){let c=this,{a:h,d}=o;if(c.is0())throw new Error("bad point: ZERO");let{X:b,Y:v,Z:_,T:D}=c,P=n.sqr(b),K=n.sqr(v),F=n.sqr(_),Y=n.sqr(F),C=n.mul(P,h),L=n.mul(n.add(C,K),F),I=n.add(Y,n.mul(d,n.mul(P,K)));if(!n.eql(L,I))throw new Error("bad point: equation left != right (1)");let A=n.mul(b,v),B=n.mul(_,D);if(!n.eql(A,B))throw new Error("bad point: equation left != right (2)")}equals(c){f(c);let{X:h,Y:d,Z:b}=this,{X:v,Y:_,Z:D}=c,P=n.mul(h,D),K=n.mul(v,b),F=n.mul(d,D),Y=n.mul(_,b);return n.eql(P,K)&&n.eql(F,Y)}is0(){return this.equals(g.ZERO)}negate(){return new g(n.neg(this.X),this.Y,this.Z,n.neg(this.T))}double(){let{X:c,Y:h,Z:d}=this,b=n.sqr(c),v=n.sqr(h),_=n.mul(n.sqr(d),pr),D=x(b),P=n.addN(c,h),K=n.sub(n.subN(n.sqr(P),b),v),F=n.addN(D,v),Y=n.subN(F,_),C=n.subN(D,v),L=n.mul(K,Y),I=n.mul(F,C),A=n.mul(K,C),B=n.mul(Y,F);return new g(L,I,B,A)}add(c){f(c);let{d:h}=o,{X:d,Y:b,Z:v,T:_}=this,{X:D,Y:P,Z:K,T:F}=c,Y=n.mul(d,D),C=n.mul(b,P),L=n.mul(n.mulN(_,h),F),I=n.mul(v,K),A=n.sub(n.subN(n.mulN(n.addN(d,b),n.addN(D,P)),Y),C),B=n.subN(I,L),N=n.addN(I,L),M=n.sub(C,x(Y)),T=n.mul(A,B),k=n.mul(N,M),R=n.mul(A,M),O=n.mul(B,N);return new g(T,k,O,R)}subtract(c){return f(c),this.add(c.negate())}multiply(c){if(!i.isValidNot0(c))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:h,f:d}=E.mulSecret(this,c,a,w);return w([h,d])[0]}multiplyUnsafe(c){if(!i.isValid(c))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return c===fr?g.ZERO:this.is0()||c===dr?this:E.mulUnsafe(this,c,w)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return E.mulUnsafe(this,o.n).is0()}toAffine(c){let h=this,d=c;if(d!=null&&typeof d!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof d);let{X:b,Y:v,Z:_}=h,D=h.is0();d==null&&(d=D?n.create(ga):n.inv(_));let P=n.mul(b,d),K=n.mul(v,d),F=n.mul(_,d);if(D)return{x:n.ZERO,y:n.ONE};if(!n.eql(F,n.ONE))throw new Error("invZ was invalid");return{x:P,y:K}}clearCofactor(){return a===dr?this:a===pr?this.double():a===ju?this.double().double():a===ga?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:c,y:h}=this.toAffine(),d=n.toBytes(h);return d[d.length-1]|=p(c)?128:0,d}toHex(){return Es(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let w=S=>cr(g,S),E=new es(g,l);return E.bits>=6&&g.BASE.precompute(6),Object.freeze(g.prototype),Object.freeze(g),g}function ya(s,e,t={}){if(gt(s),typeof e!="function")throw new Error('"hash" function param is required');let r=e,n=t;Ae(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:i}=n,{BASE:o,Fp:a,Fn:l}=s,u=r.outputLen,p=2*a.BYTES;if(u!==void 0&&(pt(u,"hash.outputLen"),u!==p))throw new Error(`hash.outputLen must be ${p}, got ${u}`);let m=n.randomBytes===void 0?At:n.randomBytes,x=n.toMontgomery,y=n.toMontgomerySecret,f=n.adjustScalarBytes===void 0?C=>C:n.adjustScalarBytes,g=n.domain===void 0?(C,L,I)=>{if(De(I,"phflag"),L.length||I)throw new Error("Contexts/pre-hash are not supported");return C}:n.domain;function w(C){return l.create(Mt(C))}function E(C){let L=D.secretKey;G(C,D.secretKey,"secretKey");let I=G(r(C),2*L,"hashedSecretKey"),A=f(I.slice(0,L)),B=I.slice(L,2*L),N=w(A);return{head:A,prefix:B,scalar:N}}function S(C){let{head:L,prefix:I,scalar:A}=E(C),B=o.multiply(A),N=B.toBytes();return{head:L,prefix:I,scalar:A,point:B,pointBytes:N}}function c(C){return S(C).pointBytes}function h(C=Uint8Array.of(),...L){let I=Le(...L);return w(r(g(I,G(C,void 0,"context"),!!i)))}function d(C,L,I={}){Ae(I,{},{},"options"),C=G(C,void 0,"message"),i&&(C=i(C));let{prefix:A,scalar:B,pointBytes:N}=S(L),M=h(I.context,A,C),T=o.multiply(M).toBytes(),k=h(I.context,T,N,C),R=l.create(M+k*B);if(!l.isValid(R))throw new Error("sign failed: invalid s");let O=Le(T,l.toBytes(R));return G(O,D.signature,"result")}let b={zip215:n.zip215};function v(C,L,I,A=b){Ae(A);let{context:B}=A,N=A.zip215===void 0?!!b.zip215:A.zip215,M=D.signature;C=G(C,M,"signature"),L=G(L,void 0,"message"),I=G(I,D.publicKey,"publicKey"),N!==void 0&&De(N,"zip215"),i&&(L=i(L));let T=M/2,k=C.subarray(0,T),R=Mt(C.subarray(T,M)),O,U,q;try{O=s.fromBytes(I,N),U=s.fromBytes(k,N),q=o.multiplyUnsafe(R)}catch{return!1}if(!N&&O.isSmallOrder())return!1;let z=h(B,k,I,L);return U.add(O.multiplyUnsafe(z)).subtract(q).clearCofactor().is0()}let _=a.BYTES,D={secretKey:_,publicKey:_,signature:2*_,seed:_};function P(C){return C=C===void 0?m(D.seed):C,G(C,D.seed,"seed")}function K(C){return dt(C)&&C.length===D.secretKey}function F(C,L){try{return!!s.fromBytes(C,L===void 0?b.zip215:L)}catch{return!1}}let Y={getExtendedPublicKey:S,randomSecretKey:P,isValidSecretKey:K,isValidPublicKey:F,toMontgomery(C){if(x===void 0)throw new Error("Montgomery conversion is not supported for this curve");return x(s.fromBytes(C))},toMontgomerySecret(C){if(y===void 0)throw new Error("Montgomery conversion is not supported for this curve");return y(C)}};return Object.freeze(D),Object.freeze(Y),Object.freeze({keygen:hr(P,c),getPublicKey:c,sign:d,verify:v,utils:Y,Point:s,lengths:D})}var Hn=BigInt(1),wa=BigInt(2);var Yu=BigInt(5),Xu=BigInt(8),Wn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ju={p:Wn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Xu,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Qu(s){let e=BigInt(10),t=BigInt(20),r=BigInt(40),n=BigInt(80),i=Wn,a=s*s%i*s%i,l=X(a,wa,i)*a%i,u=X(l,Hn,i)*s%i,p=X(u,Yu,i)*u%i,m=X(p,e,i)*p%i,x=X(m,t,i)*m%i,y=X(x,r,i)*x%i,f=X(y,n,i)*y%i,g=X(f,n,i)*y%i,w=X(g,e,i)*p%i;return{pow_p_5_8:X(w,wa,i)*s%i,b2:a}}function Ea(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}var xa=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function eh(s,e){let t=Wn,r=J(e*e*e,t),n=J(r*r*e,t),i=Qu(s*n).pow_p_5_8,o=J(s*r*i,t),a=J(e*o*o,t),l=o,u=J(o*xa,t),p=a===s,m=a===J(-s,t),x=a===J(-s*xa,t);return p&&(o=l),(m||x)&&(o=u),la(o,t)&&(o=J(-o,t)),{isValid:p||m,value:o}}var Vn=ba(Ju,{uvRatio:eh}),va=Vn.Fp;function th(s){let{y:e}=s;return va.toBytes(va.div(Hn+e,Hn-e))}function sh(s){let e=Vn.Fp.BYTES;return Re(s,e),Ea(Rn(s.subarray(0,e))).subarray(0,e)}function rh(s){return ya(Vn,Rn,Object.assign({adjustScalarBytes:Ea,toMontgomery:th,toMontgomerySecret:sh,zip215:!0},s))}var Sa=rh({});var Ds=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},mr=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ce={get(s=globalThis){let e=s.crypto;if(e?.subtle==null)throw new mr("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var gr=32;var $n,nh=(async()=>{try{return await Ce.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function ih(s,e,t){if(s.buffer instanceof ArrayBuffer){let r=await Ce.get().subtle.importKey("raw",s.buffer,{name:"Ed25519"},!1,["verify"]);return await Ce.get().subtle.verify({name:"Ed25519"},r,ke(e),ke(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function oh(s,e,t){return Sa.verify(e,t instanceof Uint8Array?t:t.subarray(),s)}async function _a(s,e,t){return $n==null&&($n=await nh),$n?ih(s,e,t):oh(s,e,t)}function br(s){return s==null?!1:typeof s.then=="function"&&typeof s.catch=="function"&&typeof s.finally=="function"}var yr=class{type="Ed25519";raw;constructor(e){this.raw=jn(e,gr)}toMultihash(){return Ne.digest(We(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();let n=_a(this.raw,t,e);return br(n)?n.then(i=>(r?.signal?.throwIfAborted(),i)):n}};function Zn(s){return s=jn(s,gr),new yr(s)}function jn(s,e){if(s=Uint8Array.from(s??[]),s.length!==e)throw new re(`Key must be a Uint8Array of length ${e}, got ${s.length}`);return s}var ch=Math.pow(2,7),lh=Math.pow(2,14),uh=Math.pow(2,21),Yn=Math.pow(2,28),Xn=Math.pow(2,35),Jn=Math.pow(2,42),Qn=Math.pow(2,49),W=128,fe=127;function Fe(s){if(s<ch)return 1;if(s<lh)return 2;if(s<uh)return 3;if(s<Yn)return 4;if(s<Xn)return 5;if(s<Jn)return 6;if(s<Qn)return 7;if(Number.MAX_SAFE_INTEGER!=null&&s>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ei(s,e,t=0){switch(Fe(s)){case 8:e[t++]=s&255|W,s/=128;case 7:e[t++]=s&255|W,s/=128;case 6:e[t++]=s&255|W,s/=128;case 5:e[t++]=s&255|W,s/=128;case 4:e[t++]=s&255|W,s>>>=7;case 3:e[t++]=s&255|W,s>>>=7;case 2:e[t++]=s&255|W,s>>>=7;case 1:{e[t++]=s&255,s>>>=7;break}default:throw new Error("unreachable")}return e}function hh(s,e,t=0){switch(Fe(s)){case 8:e.set(t++,s&255|W),s/=128;case 7:e.set(t++,s&255|W),s/=128;case 6:e.set(t++,s&255|W),s/=128;case 5:e.set(t++,s&255|W),s/=128;case 4:e.set(t++,s&255|W),s>>>=7;case 3:e.set(t++,s&255|W),s>>>=7;case 2:e.set(t++,s&255|W),s>>>=7;case 1:{e.set(t++,s&255),s>>>=7;break}default:throw new Error("unreachable")}return e}function ti(s,e){let t=s[e],r=0;if(r+=t&fe,t<W||(t=s[e+1],r+=(t&fe)<<7,t<W)||(t=s[e+2],r+=(t&fe)<<14,t<W)||(t=s[e+3],r+=(t&fe)<<21,t<W)||(t=s[e+4],r+=(t&fe)*Yn,t<W)||(t=s[e+5],r+=(t&fe)*Xn,t<W)||(t=s[e+6],r+=(t&fe)*Jn,t<W)||(t=s[e+7],r+=(t&fe)*Qn,t<W))return r;throw new RangeError("Could not decode varint")}function fh(s,e){let t=s.get(e),r=0;if(r+=t&fe,t<W||(t=s.get(e+1),r+=(t&fe)<<7,t<W)||(t=s.get(e+2),r+=(t&fe)<<14,t<W)||(t=s.get(e+3),r+=(t&fe)<<21,t<W)||(t=s.get(e+4),r+=(t&fe)*Yn,t<W)||(t=s.get(e+5),r+=(t&fe)*Xn,t<W)||(t=s.get(e+6),r+=(t&fe)*Jn,t<W)||(t=s.get(e+7),r+=(t&fe)*Qn,t<W))return r;throw new RangeError("Could not decode varint")}function si(s,e,t=0){return e==null&&(e=he(Fe(s))),e instanceof Uint8Array?ei(s,e,t):hh(s,e,t)}function ri(s,e=0){return s instanceof Uint8Array?ti(s,e):fh(s,e)}var ii=new Float32Array([-0]),bt=new Uint8Array(ii.buffer);function Ta(s,e,t){ii[0]=s,e[t]=bt[0],e[t+1]=bt[1],e[t+2]=bt[2],e[t+3]=bt[3]}function Da(s,e){return bt[0]=s[e],bt[1]=s[e+1],bt[2]=s[e+2],bt[3]=s[e+3],ii[0]}var oi=new Float64Array([-0]),de=new Uint8Array(oi.buffer);function Aa(s,e,t){oi[0]=s,e[t]=de[0],e[t+1]=de[1],e[t+2]=de[2],e[t+3]=de[3],e[t+4]=de[4],e[t+5]=de[5],e[t+6]=de[6],e[t+7]=de[7]}function Ma(s,e){return de[0]=s[e],de[1]=s[e+1],de[2]=s[e+2],de[3]=s[e+3],de[4]=s[e+4],de[5]=s[e+5],de[6]=s[e+6],de[7]=s[e+7],oi[0]}var dh=BigInt(Number.MAX_SAFE_INTEGER),ph=BigInt(Number.MIN_SAFE_INTEGER),Me=class s{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,r=~this.hi>>>0;return t===0&&(r=r+1>>>0),-(t+r*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,r=~this.hi>>>0;return t===0&&(r=r+1>>>0),-(BigInt(t)+(BigInt(r)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(e===0n)return Pt;if(e<dh&&e>ph)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let r=e>>32n,n=e-(r<<32n);return t&&(r=~r|0n,n=~n|0n,++n>Pa&&(n=0n,++r>Pa&&(r=0n))),new s(Number(n),Number(r))}static fromNumber(e){if(e===0)return Pt;let t=e<0;t&&(e=-e);let r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new s(r,n)}static from(e){return typeof e=="number"?s.fromNumber(e):typeof e=="bigint"?s.fromBigInt(e):typeof e=="string"?s.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new s(e.low>>>0,e.high>>>0):Pt}},Pt=new Me(0,0);Pt.toBigInt=function(){return 0n};Pt.zzEncode=Pt.zzDecode=function(){return this};Pt.length=function(){return 1};var Pa=4294967296n;function Ba(s){let e=0,t=0;for(let r=0;r<s.length;++r)t=s.charCodeAt(r),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(s.charCodeAt(r+1)&64512)===56320?(++r,e+=4):e+=3;return e}function ka(s,e,t){if(t-e<1)return"";let n,i=[],o=0,a;for(;e<t;)a=s[e++],a<128?i[o++]=a:a>191&&a<224?i[o++]=(a&31)<<6|s[e++]&63:a>239&&a<365?(a=((a&7)<<18|(s[e++]&63)<<12|(s[e++]&63)<<6|s[e++]&63)-65536,i[o++]=55296+(a>>10),i[o++]=56320+(a&1023)):i[o++]=(a&15)<<12|(s[e++]&63)<<6|s[e++]&63,o>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,i)),o=0);return n!=null?(o>0&&n.push(String.fromCharCode.apply(String,i.slice(0,o))),n.join("")):String.fromCharCode.apply(String,i.slice(0,o))}function ai(s,e,t){let r=t,n,i;for(let o=0;o<s.length;++o)n=s.charCodeAt(o),n<128?e[t++]=n:n<2048?(e[t++]=n>>6|192,e[t++]=n&63|128):(n&64512)===55296&&((i=s.charCodeAt(o+1))&64512)===56320?(n=65536+((n&1023)<<10)+(i&1023),++o,e[t++]=n>>18|240,e[t++]=n>>12&63|128,e[t++]=n>>6&63|128,e[t++]=n&63|128):(e[t++]=n>>12|224,e[t++]=n>>6&63|128,e[t++]=n&63|128);return t-r}function Ue(s,e){return RangeError(`index out of range: ${s.pos} + ${e??1} > ${s.len}`)}function wr(s,e){return(s[e-4]|s[e-3]<<8|s[e-2]<<16|s[e-1]<<24)>>>0}var ci=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=ke(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Ue(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Ue(this,4);return wr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ue(this,4);return wr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ue(this,4);let e=Da(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ue(this,4);let e=Ma(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw Ue(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){let e=this.bytes();return ka(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Ue(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Ue(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Me(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Ue(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Ue(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Ue(this,8);let e=wr(this.buf,this.pos+=4),t=wr(this.buf,this.pos+=4);return new Me(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=ti(this.buf,this.pos);return this.pos+=Fe(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function As(s){return new ci(s instanceof Uint8Array?s:s.subarray())}function ye(s,e,t){let r=As(s);return e.decode(r,void 0,t)}function li(s){let e=s??8192,t=e>>>1,r,n=e;return function(o){if(o<1||o>t)return he(o);n+o>e&&(r=he(e),n=0);let a=r.subarray(n,n+=o);return(n&7)!==0&&(n=(n|7)+1),a}}var Bt=class{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}};function ui(){}var fi=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},mh=li();function gh(s){return globalThis.Buffer!=null?he(s):mh(s)}var Ps=class{len;head;tail;states;constructor(){this.len=0,this.head=new Bt(ui,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new Bt(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new di((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(xr,10,Me.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Me.fromBigInt(e);return this._push(xr,t.length(),t)}uint64Number(e){return this._push(ei,Fe(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Me.fromBigInt(e).zzEncode();return this._push(xr,t.length(),t)}sint64Number(e){let t=Me.fromNumber(e).zzEncode();return this._push(xr,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(hi,1,e?1:0)}fixed32(e){return this._push(Ms,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Me.fromBigInt(e);return this._push(Ms,4,t.lo)._push(Ms,4,t.hi)}fixed64Number(e){let t=Me.fromNumber(e);return this._push(Ms,4,t.lo)._push(Ms,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Ta,4,e)}double(e){return this._push(Aa,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(hi,1,0):this.uint32(t)._push(yh,t,e)}string(e){let t=Ba(e);return t!==0?this.uint32(t)._push(ai,t,e):this._push(hi,1,0)}fork(){return this.states=new fi(this),this.head=this.tail=new Bt(ui,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Bt(ui,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r!==0&&(this.tail.next=e.next,this.tail=t,this.len+=r),this}finish(){let e=this.head.next,t=gh(this.len),r=0;for(;e!=null;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}};function hi(s,e,t){e[t]=s&255}function bh(s,e,t){for(;s>127;)e[t++]=s&127|128,s>>>=7;e[t]=s}var di=class extends Bt{next;constructor(e,t){super(bh,e,t),this.next=void 0}};function xr(s,e,t){for(;s.hi!==0;)e[t++]=s.lo&127|128,s.lo=(s.lo>>>7|s.hi<<25)>>>0,s.hi>>>=7;for(;s.lo>127;)e[t++]=s.lo&127|128,s.lo=s.lo>>>7;e[t++]=s.lo}function Ms(s,e,t){e[t]=s&255,e[t+1]=s>>>8&255,e[t+2]=s>>>16&255,e[t+3]=s>>>24}function yh(s,e,t){e.set(s,t)}globalThis.Buffer!=null&&(Ps.prototype.bytes=function(s){let e=s.length>>>0;return this.uint32(e),e>0&&this._push(wh,e,s),this},Ps.prototype.string=function(s){let e=globalThis.Buffer.byteLength(s);return this.uint32(e),e>0&&this._push(xh,e,s),this});function wh(s,e,t){e.set(s,t)}function xh(s,e,t){s.length<40?ai(s,e,t):e.utf8Write!=null?e.utf8Write(s,t):e.set(j(s),t)}function pi(){return new Ps}function we(s,e){let t=pi();return e.encode(s,t,{lengthDelimited:!1}),t.finish()}function*xe(s,e,t){let r=As(s);yield*e.stream(r,void 0,"$",t)}var vr={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Er(s,e,t,r,n){return{name:s,type:e,encode:t,decode:r,stream:n}}function mi(s){function e(i){if(s[i.toString()]==null)throw new Error("Invalid enum value");return s[i]}let t=function(o,a){let l=e(o);a.int32(l)},r=function(o){let a=o.int32();return e(a)},n=function*(o){let a=o.int32();yield e(a)};return Er("enum",vr.VARINT,t,r,n)}function ve(s,e,t){return Er("message",vr.LENGTH_DELIMITED,s,e,t)}var Z=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var Q;(function(s){s.RSA="RSA",s.Ed25519="Ed25519",s.secp256k1="secp256k1",s.ECDSA="ECDSA"})(Q||(Q={}));var gi;(function(s){s[s.RSA=0]="RSA",s[s.Ed25519=1]="Ed25519",s[s.secp256k1=2]="secp256k1",s[s.ECDSA=3]="ECDSA"})(gi||(gi={}));(function(s){s.codec=()=>mi(gi)})(Q||(Q={}));var je;(function(s){let e;s.codec=()=>(e==null&&(e=ve((i,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),i.Type!=null&&(o.uint32(8),Q.codec().encode(i.Type,o)),i.Data!=null&&(o.uint32(18),o.bytes(i.Data)),a.lengthDelimited!==!1&&o.ldelim()},(i,o,a={})=>{let l={},u=o==null?i.len:i.pos+o;for(;i.pos<u;){let p=i.uint32();switch(p>>>3){case 1:{l.Type=Q.codec().decode(i);break}case 2:{l.Data=i.bytes();break}default:{i.skipType(p&7);break}}}return l},function*(i,o,a,l={}){let u=o==null?i.len:i.pos+o;for(;i.pos<u;){let p=i.uint32();switch(p>>>3){case 1:{yield{field:`${a}.Type`,value:Q.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(p&7);break}}}})),e);function t(i){return we(i,s.codec())}s.encode=t;function r(i,o){return ye(i,s.codec(),o)}s.decode=r;function n(i,o){return xe(i,s.codec(),o)}s.stream=n})(je||(je={}));var bi;(function(s){let e;s.codec=()=>(e==null&&(e=ve((i,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),i.Type!=null&&(o.uint32(8),Q.codec().encode(i.Type,o)),i.Data!=null&&(o.uint32(18),o.bytes(i.Data)),a.lengthDelimited!==!1&&o.ldelim()},(i,o,a={})=>{let l={},u=o==null?i.len:i.pos+o;for(;i.pos<u;){let p=i.uint32();switch(p>>>3){case 1:{l.Type=Q.codec().decode(i);break}case 2:{l.Data=i.bytes();break}default:{i.skipType(p&7);break}}}return l},function*(i,o,a,l={}){let u=o==null?i.len:i.pos+o;for(;i.pos<u;){let p=i.uint32();switch(p>>>3){case 1:{yield{field:`${a}.Type`,value:Q.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(p&7);break}}}})),e);function t(i){return we(i,s.codec())}s.encode=t;function r(i,o){return ye(i,s.codec(),o)}s.decode=r;function n(i,o){return xe(i,s.codec(),o)}s.stream=n})(bi||(bi={}));var ks={};_e(ks,{MAX_RSA_KEY_SIZE:()=>yi,generateRSAKeyPair:()=>Oa,jwkToJWKKeyPair:()=>Ua,jwkToPkcs1:()=>_h,jwkToPkix:()=>Ei,jwkToRSAPrivateKey:()=>Ti,pkcs1MessageToJwk:()=>xi,pkcs1MessageToRSAPrivateKey:()=>Si,pkcs1ToJwk:()=>Sh,pkcs1ToRSAPrivateKey:()=>Na,pkixMessageToJwk:()=>vi,pkixMessageToRSAPublicKey:()=>Ii,pkixToJwk:()=>Ih,pkixToRSAPublicKey:()=>_i});var ts=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=ks.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ce.createV1(114,this._multihash)}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}verify(e,t,r){return Fa(this.jwk,t,e,r)}},Bs=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=ks.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}sign(e,t){return Ca(this.jwk,e,t)}};var yi=8192,wi=18,vh=1062,Eh=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Sh(s){let e=Je(s);return xi(e)}function xi(s){return{n:$(s[1],"base64url"),e:$(s[2],"base64url"),d:$(s[3],"base64url"),p:$(s[4],"base64url"),q:$(s[5],"base64url"),dp:$(s[6],"base64url"),dq:$(s[7],"base64url"),qi:$(s[8],"base64url"),kty:"RSA"}}function _h(s){if(s.n==null||s.e==null||s.d==null||s.p==null||s.q==null||s.dp==null||s.dq==null||s.qi==null)throw new re("JWK was missing components");return at([Te(Uint8Array.from([0])),Te(j(s.n,"base64url")),Te(j(s.e,"base64url")),Te(j(s.d,"base64url")),Te(j(s.p,"base64url")),Te(j(s.q,"base64url")),Te(j(s.dp,"base64url")),Te(j(s.dq,"base64url")),Te(j(s.qi,"base64url"))]).subarray()}function Ih(s){let e=Je(s,{offset:0});return vi(e)}function vi(s){let e=Je(s[1],{offset:0});return{kty:"RSA",n:$(e[0],"base64url"),e:$(e[1],"base64url")}}function Ei(s){if(s.n==null||s.e==null)throw new re("JWK was missing components");return at([Eh,Ws(at([Te(j(s.n,"base64url")),Te(j(s.e,"base64url"))]))]).subarray()}function Na(s){let e=Je(s);return Si(e)}function Si(s){let e=xi(s);return Ti(e)}function _i(s,e){if(s.byteLength>=vh)throw new Ut("Key size is too large");let t=Je(s,{offset:0});return Ii(t,s,e)}function Ii(s,e,t){let r=vi(s);if(t==null){let n=jt(je.encode({Type:Q.RSA,Data:e}));t=He(wi,n)}return new ts(r,t)}function Ti(s){if(za(s)>yi)throw new re("Key size is too large");let e=Ua(s),t=jt(je.encode({Type:Q.RSA,Data:Ei(e.publicKey)})),r=He(wi,t);return new Bs(e.privateKey,new ts(e.publicKey,r))}async function Oa(s){if(s>yi)throw new re("Key size is too large");let e=await Ka(s),t=jt(je.encode({Type:Q.RSA,Data:Ei(e.publicKey)})),r=He(wi,t);return new Bs(e.privateKey,new ts(e.publicKey,r))}function Ua(s){if(s==null)throw new re("Missing key parameter");return{privateKey:s,publicKey:{kty:s.kty,n:s.n,e:s.e}}}async function Ka(s,e){let t=await Ce.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:s,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let r=await Th(t,e);return{privateKey:r[0],publicKey:r[1]}}async function Ca(s,e,t){let r=await Ce.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let n=await Ce.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,ke(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(n,0,n.byteLength)}async function Fa(s,e,t,r){let n=await Ce.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();let i=await Ce.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,ke(e),ke(t instanceof Uint8Array?t:t.subarray()));return r?.signal?.throwIfAborted(),i}async function Th(s,e){if(s.privateKey==null||s.publicKey==null)throw new re("Private and public key are required");let t=await Promise.all([Ce.get().subtle.exportKey("jwk",s.privateKey),Ce.get().subtle.exportKey("jwk",s.publicKey)]);return e?.signal?.throwIfAborted(),t}function za(s){if(s.kty!=="RSA")throw new re("invalid key type");if(s.n==null)throw new re("invalid key modulus");return j(s.n,"base64url").length*8}var Sr=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(js(e),Re(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,n=new Uint8Array(r);n.set(t.length>r?e.create().update(t).digest():t);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),Tt(n)}update(e){return $t(this),this.iHash.update(e),this}digestInto(e){$t(this),Zs(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:n,destroyed:i,blockLen:o,outputLen:a,canXOF:l}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.canXOF=l,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},qa=(()=>{let s=((e,t,r)=>new Sr(e,t).update(r).digest());return s.create=(e,t)=>new Sr(e,t),s})();var Dh=BigInt(0),Di=class extends Error{constructor(e=""){super(e)}},et={Err:Di,_tlv:{encode:(s,e)=>{let{Err:t}=et;if(pt(s,"tag"),s<0||s>255)throw new t("tlv.encode: wrong tag");if(Yo(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let r=e.length/2,n=Ss(r);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let i=r>127?Ss(n.length/2|128):"";return Ss(s)+i+n+e},decode(s,e){let{Err:t}=et;e=G(e,void 0,"DER data");let r=0;if(s<0||s>255)throw new t("tlv.decode: wrong tag");if(e.length<2||e[r++]!==s)throw new t("tlv.decode: wrong tlv");let n=e[r++],i=!!(n&128),o=0;if(!i)o=n;else{let l=n&127;if(!l)throw new t("tlv.decode(long): indefinite length not supported");if(l>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(r,r+l);if(u.length!==l)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let p of u)o=o<<8|p;if(r+=l,o<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(s){let{Err:e}=et;if(tr(s),s<Dh)throw new e("integer: negative integers are not allowed");let t=Ss(s);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(s){let{Err:e}=et;if(s.length<1)throw new e("invalid signature integer: empty");if(s[0]&128)throw new e("invalid signature integer: negative");if(s.length>1&&s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return $e(s)}},toSig(s){let{Err:e,_int:t,_tlv:r}=et,n=G(s,void 0,"signature"),{v:i,l:o}=r.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l}=r.decode(2,i),{v:u,l:p}=r.decode(2,l);if(p.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(s){let{_tlv:e,_int:t}=et;Ae(s,{r:"bigint",s:"bigint"},{},"sig");let r=e.encode(2,t.encode(s.r)),n=e.encode(2,t.encode(s.s)),i=r+n;return e.encode(48,i)}},Ai=(Object.freeze(et._tlv),Object.freeze(et._int),Object.freeze(et));var Ga=(s,e)=>(s+(s>=0?e:-e)/Ha)/e;function Ah(s,e,t){Yt("scalar",s,tt,t);let[[r,n],[i,o]]=e,a=Ga(o*s,t),l=Ga(-n*s,t),u=s-a*r-l*i,p=-a*n-l*o,m=u<tt,x=p<tt;m&&(u=-u),x&&(p=-p);let y=_s(Math.ceil(Xt(t)/2))+kt;if(u<tt||u>=y||p<tt||p>=y)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:m,k1:u,k2neg:x,k2:p}}function Bi(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function Mi(s,e){Ae(s);let t={};for(let r of Object.keys(e))t[r]=s[r]===void 0?e[r]:s[r];return De(t.lowS,"lowS"),De(t.prehash,"prehash"),t.format!==void 0&&Bi(t.format),t}var tt=BigInt(0),kt=BigInt(1),Ha=BigInt(2),Pi=BigInt(3),Mh=BigInt(4);function Wa(s,e={}){let t=ur("weierstrass",s,e),r=t.Fp,n=t.Fn,i=t.CURVE,{h:o,n:a}=i;Ae(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:l,allowInfinityPoint:u}=e,p=e.randomBytes===void 0?At:e.randomBytes;if(l&&(!r.is0(i.a)||typeof l.beta!="bigint"||!Array.isArray(l.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let m=$a(r,n);function x(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function y(L,I,A){if(u&&I.is0())return Uint8Array.of(0);let{x:B,y:N}=I.toAffine(),M=r.toBytes(B);if(De(A,"isCompressed"),A){x();let T=!r.isOdd(N);return Le(Va(T),M)}else return Le(Uint8Array.of(4),M,r.toBytes(N))}function f(L){G(L,void 0,"Point");let{publicKey:I,publicKeyUncompressed:A}=m,B=L.length,N=L[0],M=L.subarray(1);if(u&&B===1&&N===0)return{x:r.ZERO,y:r.ZERO};if(B===I&&(N===2||N===3)){let T=r.fromBytes(M);if(!r.isValid(T))throw new Error("bad point: is not on curve, wrong x");let k=c(T),R;try{R=r.sqrt(k)}catch(q){let z=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}x();let O=r.isOdd(R);return(N&1)===1!==O&&(R=r.neg(R)),{x:T,y:R}}else if(B===A&&N===4){let T=r.BYTES,k=r.fromBytes(M.subarray(0,T)),R=r.fromBytes(M.subarray(T,T*2));if(!h(k,R))throw new Error("bad point: is not on curve");return{x:k,y:R}}else throw new Error(`bad point: got length ${B}, expected compressed=${I} or uncompressed=${A}`)}let g=e.toBytes===void 0?y:e.toBytes,w=e.fromBytes===void 0?f:e.fromBytes,E=r.mul(i.b,Pi),S=r.is0(i.a)?L=>r.ZERO:L=>r.mul(i.a,L);function c(L){let I=r.sqr(L),A=r.mul(I,L);return r.add(r.add(A,r.mul(L,i.a)),i.b)}function h(L,I){let A=r.sqr(I),B=c(L);return r.eql(A,B)}if(!h(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let d=r.mul(r.pow(i.a,Pi),Mh),b=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(d,b)))throw new Error("bad curve params: a or b");function v(L,I,A=!1){if(!r.isValid(I)||A&&r.is0(I))throw new Error(`bad point coordinate ${L}`);return I}function _(L){if(!(L instanceof F))throw new Error("Weierstrass Point expected")}function D(L){if(!l||!l.basises)throw new Error("no endo");return Ah(L,l.basises,n.ORDER)}function P(L,I,A,B){if(!n.isValid(B))throw new RangeError("invalid scalar: out of range");if(l){let{k1neg:N,k1:M,k2neg:T,k2:k}=D(B),R=new F(r.mul(A.X,l.beta),A.Y,A.Z);L.push(N?A.negate():A,T?R.negate():R),I.push(M,k)}else L.push(A),I.push(B)}let K=new WeakSet;class F{static BASE=new F(i.Gx,i.Gy,r.ONE);static ZERO=new F(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=n;X;Y;Z;constructor(I,A,B){this.X=v("x",I),this.Y=v("y",A,!0),this.Z=v("z",B),Object.freeze(this)}static CURVE(){return i}static fromAffine(I){let{x:A,y:B}=I||{};if(!I||!r.isValid(A)||!r.isValid(B))throw new Error("invalid affine point");if(I instanceof F)throw new Error("projective point not allowed");return r.is0(A)&&r.is0(B)?F.ZERO:new F(A,B,r.ONE)}static fromBytes(I){let A=F.fromAffine(w(G(I,void 0,"point")));return A.assertValidity(),A}static fromHex(I){return F.fromBytes(Zt(I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=6,A=!0){return C.setWindowSize(this,I),A||this.multiply(Pi),this}assertValidity(){let I=this;if(I.is0()){if(e.allowInfinityPoint&&r.is0(I.X)&&r.eql(I.Y,r.ONE)&&r.is0(I.Z))return;throw new Error("bad point: ZERO")}if(K.has(I))return;let{x:A,y:B}=I.toAffine();if(!r.isValid(A)||!r.isValid(B))throw new Error("bad point: x or y not field elements");if(!h(A,B))throw new Error("bad point: equation left != right");if(!I.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");K.add(I)}hasEvenY(){let{y:I}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(I)}equals(I){_(I);let{X:A,Y:B,Z:N}=this,{X:M,Y:T,Z:k}=I,R=r.eql(r.mul(A,k),r.mul(M,N)),O=r.eql(r.mul(B,k),r.mul(T,N));return R&&O}negate(){return new F(this.X,r.neg(this.Y),this.Z)}double(){let{X:I,Y:A,Z:B}=this,N=r.ZERO,M=r.ZERO,T=r.ZERO,k=r.mul(I,I),R=r.mul(A,A),O=r.mul(B,B),U=r.mul(I,A);return U=r.add(U,U),T=r.mul(I,B),T=r.add(T,T),N=S(T),M=r.mul(E,O),M=r.add(N,M),N=r.sub(R,M),M=r.add(R,M),M=r.mul(N,M),N=r.mul(U,N),T=r.mul(E,T),O=S(O),U=r.sub(k,O),U=S(U),U=r.add(U,T),T=r.add(k,k),k=r.add(T,k),k=r.add(k,O),k=r.mul(k,U),M=r.add(M,k),O=r.mul(A,B),O=r.add(O,O),k=r.mul(O,U),N=r.sub(N,k),T=r.mul(O,R),T=r.add(T,T),T=r.add(T,T),new F(N,M,T)}add(I){_(I);let{X:A,Y:B,Z:N}=this,{X:M,Y:T,Z:k}=I,R=r.ZERO,O=r.ZERO,U=r.ZERO,q=r.mul(A,M),z=r.mul(B,T),te=r.mul(N,k),be=r.add(A,B),se=r.add(M,T);be=r.mul(be,se),se=r.add(q,z),be=r.sub(be,se),se=r.add(A,N);let ue=r.add(M,k);return se=r.mul(se,ue),ue=r.add(q,te),se=r.sub(se,ue),ue=r.add(B,N),R=r.add(T,k),ue=r.mul(ue,R),R=r.add(z,te),ue=r.sub(ue,R),U=S(se),R=r.mul(E,te),U=r.add(R,U),R=r.sub(z,U),U=r.add(z,U),O=r.mul(R,U),z=r.add(q,q),z=r.add(z,q),te=S(te),se=r.mul(E,se),z=r.add(z,te),te=r.sub(q,te),te=S(te),se=r.add(se,te),q=r.mul(z,se),O=r.add(O,q),q=r.mul(ue,se),R=r.mul(be,R),R=r.sub(R,q),q=r.mul(be,z),U=r.mul(ue,U),U=r.add(U,q),new F(R,O,U)}subtract(I){return _(I),this.add(I.negate())}is0(){return this.equals(F.ZERO)}multiply(I){if(!n.isValidNot0(I))throw new RangeError("invalid scalar: out of range");let{p:A,f:B}=C.mulSecret(this,I,o,Y);return Y([A,B])[0]}multiplyUnsafe(I){let A=this,B=I;if(!n.isValid(B))throw new RangeError("invalid scalar: out of range");if(B===tt||A.is0())return F.ZERO;if(B===kt)return A;if(C.hasWindowSize(this))return C.mulUnsafe(A,B,Y);let N=[],M=[];return P(N,M,A,B),lr(F,N,M)}mulAddUnsafe(I,A,B){_(A);let N=[],M=[];return P(N,M,this,I),P(N,M,A,B),lr(F,N,M)}toAffine(I){let A=this,B=I;if(B!=null&&!r.isValid(B))throw new RangeError('"invertedZ" expected valid field element');let{X:N,Y:M,Z:T}=A;if(r.eql(T,r.ONE))return{x:N,y:M};let k=A.is0();B==null&&(B=k?r.ONE:r.inv(T));let R=r.mul(N,B),O=r.mul(M,B),U=r.mul(T,B);if(k)return{x:r.ZERO,y:r.ZERO};if(!r.eql(U,r.ONE))throw new Error("invZ was invalid");return{x:R,y:O}}isTorsionFree(){let{isTorsionFree:I}=e;return o===kt?!0:I?I(F,this):C.mulUnsafe(this,a).is0()}clearCofactor(){let{clearCofactor:I}=e;return o===kt?this:I?I(F,this):this.multiplyUnsafe(o)}isSmallOrder(){return o===kt?this.is0():this.clearCofactor().is0()}toBytes(I=!0){return De(I,"isCompressed"),this.assertValidity(),g(F,this,I)}toHex(I=!0){return Es(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let Y=L=>cr(F,L),C=new es(F,p);return C.bits>=6&&F.BASE.precompute(6),Object.freeze(F.prototype),Object.freeze(F),F}function Va(s){return Uint8Array.of(s?2:3)}function $a(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Ph(s,e={}){gt(s);let{Fn:t}=s,r=e.randomBytes===void 0?At:e.randomBytes,n=Object.assign($a(s.Fp,t),{seed:Math.max(or(t.ORDER),16)});function i(y){try{let f=t.fromBytes(y);return t.isValidNot0(f)}catch{return!1}}function o(y,f){let{publicKey:g,publicKeyUncompressed:w}=n;try{let E=y.length;return f===!0&&E!==g||f===!1&&E!==w?!1:!!s.fromBytes(y)}catch{return!1}}function a(y){return y=y===void 0?r(n.seed):y,ar(G(y,n.seed,"seed"),t.ORDER)}function l(y,f=!0){return s.BASE.multiply(t.fromBytes(y)).toBytes(f)}function u(y){let{secretKey:f,publicKey:g,publicKeyUncompressed:w}=n,E=t._lengths;if(!dt(y))return;let S=G(y,void 0,"key").length,c=S===g||S===w,h=S===f||!!E?.includes(S);if(!(c&&h))return c}function p(y,f,g=!0){if(u(y)===!0)throw new Error("first arg must be private key");if(u(f)===!1)throw new Error("second arg must be public key");let w=t.fromBytes(y);return s.fromBytes(f).multiply(w).toBytes(g)}let m={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},x=hr(a,l);return Object.freeze(m),Object.freeze(n),Object.freeze({getPublicKey:l,getSharedSecret:p,keygen:x,Point:s,utils:m,lengths:n})}function ja(s,e,t={}){gt(s);let r=e;js(r),Ae(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=Object.assign({},t),i=n.randomBytes===void 0?At:n.randomBytes,o=n.hmac===void 0?(M,T)=>qa(r,M,T):n.hmac,{Fp:a,Fn:l}=s,{ORDER:u,BITS:p}=l,m=or(u),x=Gn(i,m),{keygen:y,getPublicKey:f,getSharedSecret:g,utils:w,lengths:E}=Ph(s,n),S={prehash:!0,lowS:typeof n.lowS=="boolean"?n.lowS:!0,format:"compact",extraEntropy:!1},c=u*Ha+kt<a.ORDER;function h(M){let T=u>>kt;return M>T}function d(M,T){if(!l.isValidNot0(T))throw new Error(`invalid signature ${M}: out of range 1..Point.Fn.ORDER`);return T}function b(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function v(M,T,k){return b(),(M===k?0:2)|Number(a.isOdd(T))}function _(){if(c)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function D(M,T){Bi(T);let k=E.signature,R=T==="compact"?k:T==="recovered"?k+1:void 0;return G(M,R)}class P{r;s;recovery;constructor(T,k,R){if(this.r=d("r",T),this.s=d("s",k),R!=null){if(_(),![0,1,2,3].includes(R))throw new Error("invalid recovery id");this.recovery=R}Object.freeze(this)}static fromBytes(T,k=S.format){D(T,k);let R;if(k==="der"){let{r:z,s:te}=Ai.toSig(G(T));return new P(z,te)}k==="recovered"&&(R=T[0],k="compact",T=T.subarray(1));let O=E.signature/2,U=T.subarray(0,O),q=T.subarray(O,O*2);return new P(l.fromBytes(U),l.fromBytes(q),R)}static fromHex(T,k){return this.fromBytes(Zt(T),k)}assertRecovery(){let{recovery:T}=this;if(T==null)throw new Error("invalid recovery id: must be present");return T}addRecoveryBit(T){return new P(this.r,this.s,T)}recoverPublicKey(T){let{r:k,s:R}=this,O=this.assertRecovery(),U=O===2||O===3?k+u:k;if(!a.isValid(U))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let q=a.toBytes(U),z=s.fromBytes(Le(Va((O&1)===0),q)),te=l.inv(U),be=F(G(T,void 0,"msgHash")),se=l.create(-be*te),ue=l.create(R*te),qe=s.BASE.mulAddUnsafe(se,z,ue);if(qe.is0())throw new Error("invalid recovery: point at infinify");return qe.assertValidity(),qe}hasHighS(){return h(this.s)}toBytes(T=S.format){if(Bi(T),T==="der")return Zt(Ai.hexFromSig(this));let{r:k,s:R}=this,O=l.toBytes(k),U=l.toBytes(R);return T==="recovered"?(_(),Le(Uint8Array.of(this.assertRecovery()),O,U)):Le(O,U)}toHex(T){return Es(this.toBytes(T))}}Object.freeze(P.prototype),Object.freeze(P);let K=n.bits2int===void 0?function(T){if(T.length>8192)throw new Error("input is too large");let k=$e(T),R=T.length*8-p;return R>0?k>>BigInt(R):k}:n.bits2int,F=n.bits2int_modN===void 0?function(T){return l.create(K(T))}:n.bits2int_modN,Y=_s(p);function C(M){return Yt("num < 2^"+p,M,tt,Y),l.toBytes(M)}function L(M,T){return G(M,void 0,"message"),T?G(r(M),void 0,"prehashed message"):M}function I(M,T,k){let{lowS:R,prehash:O,extraEntropy:U}=Mi(k,S);M=L(M,O);let q=F(M),z=l.fromBytes(T);if(!l.isValidNot0(z))throw new Error("invalid private key");let te=[C(z),C(q)];if(U!=null&&U!==!1){let qe=U===!0?i(E.secretKey):U;te.push(G(qe,void 0,"extraEntropy"))}let be=Le(...te),se=q;function ue(qe){let Nt=K(qe);if(!l.isValidNot0(Nt))return;let hs=s.BASE.multiply(Nt).toAffine(),nt=l.create(hs.x);if(nt===tt)return;let Ge;if(x!==void 0){let fs=$e(ar(x(m),u)),Cc=l.inv(l.mul(fs,Nt)),Fc=l.mul(fs,se),Nc=l.mul(fs,z);Ge=l.create(Cc*l.create(Fc+Nc*nt))}else{let fs=oa(Nt,u);Ge=l.create(fs*l.create(se+nt*z))}if(Ge===tt)return;let Gr=v(hs.x,hs.y,nt),Vi=Ge;return R&&h(Ge)&&(Vi=l.neg(Ge),Gr^=1),new P(nt,Vi,c?void 0:Gr)}return{seed:be,k2sig:ue}}function A(M,T,k={}){let{seed:R,k2sig:O}=I(M,T,k);return Jo(r.outputLen,l.BYTES,o)(R,O).toBytes(k.format)}function B(M,T,k,R={}){let{lowS:O,prehash:U,format:q}=Mi(R,S);if(k=G(k,void 0,"publicKey"),T=L(T,U),!dt(M)){let z=M instanceof P?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+z)}D(M,q);try{let z=P.fromBytes(M,q),te=s.fromBytes(k);if(O&&z.hasHighS())return!1;let{r:be,s:se}=z,ue=F(T),qe=l.inv(se),Nt=l.create(ue*qe),hs=l.create(be*qe),nt=s.BASE.mulAddUnsafe(Nt,te,hs);if(nt.is0())return!1;let Ge=nt.toAffine();return!(l.create(Ge.x)!==be||q==="recovered"&&z.recovery!==v(Ge.x,Ge.y,be))}catch{return!1}}function N(M,T,k={}){let{prehash:R}=Mi(k,S);return T=L(T,R),P.fromBytes(M,"recovered").recoverPublicKey(T).toBytes()}return Object.freeze({keygen:y,getPublicKey:f,getSharedSecret:g,utils:w,lengths:E,Point:s,sign:A,verify:B,recoverPublicKey:N,Signature:P,hash:r})}var Ri={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Bh={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Za=BigInt(2);function kh(s){let e=Ri.p,t=BigInt(3),r=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),l=BigInt(88),u=s*s*s%e,p=u*u*s%e,m=X(p,t,e)*p%e,x=X(m,t,e)*p%e,y=X(x,Za,e)*u%e,f=X(y,n,e)*y%e,g=X(f,i,e)*f%e,w=X(g,a,e)*g%e,E=X(w,l,e)*w%e,S=X(E,a,e)*g%e,c=X(S,t,e)*p%e,h=X(c,o,e)*f%e,d=X(h,r,e)*u%e,b=X(d,Za,e);if(!ki.eql(ki.sqr(b),s))throw new Error("Cannot find square root");return b}var ki=Qt(Ri.p,{sqrt:kh}),Rh=Wa(Ri,{Fp:ki,endo:Bh}),ss=ja(Rh,jt);function Ya(s,e,t,r){let n=St.digest(t instanceof Uint8Array?t:t.subarray());if(br(n))return n.then(({digest:i})=>(r?.signal?.throwIfAborted(),ss.verify(e,i,s,{prehash:!1,format:"der"}))).catch(i=>{throw i.name==="AbortError"?i:new Ds(String(i))});try{return r?.signal?.throwIfAborted(),ss.verify(e,n.digest,s,{prehash:!1,format:"der"})}catch(i){throw new Ds(String(i))}}var _r=class{type="secp256k1";raw;_key;constructor(e){this._key=Ja(e),this.raw=Xa(this._key)}toMultihash(){return Ne.digest(We(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}verify(e,t,r){return Ya(this._key,t,e,r)}};function Li(s){return new _r(s)}function Xa(s){return ss.Point.fromBytes(s).toBytes()}function Ja(s){try{return ss.Point.fromBytes(s),s}catch(e){throw new Ut(String(e))}}function Ci(s,e){let{Type:t,Data:r}=je.decode(s),n=r??new Uint8Array;switch(t){case Q.RSA:return _i(n,e);case Q.Ed25519:return Zn(n);case Q.secp256k1:return Li(n);case Q.ECDSA:return En(n);default:throw new Kt}}function Qa(s){let{Type:e,Data:t}=je.decode(s.digest),r=t??new Uint8Array;switch(e){case Q.Ed25519:return Zn(r);case Q.secp256k1:return Li(r);case Q.ECDSA:return En(r);default:throw new Kt}}function We(s){return je.encode({Type:Q[s.type],Data:s.raw})}var ec=Symbol.for("nodejs.util.inspect.custom"),Lh=114,Rs=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Vr]=!0;toString(){return this.string==null&&(this.string=ie.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ce.createV1(Lh,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Ie(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Ie(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[ec](){return`PeerId(${this.toString()})`}},Ir=class extends Rs{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Tr=class extends Rs{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Dr=class extends Rs{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Ch=2336,Ls=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ne.digest(j(this.url))}[ec](){return`PeerId(${this.url})`}[Vr]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ce.createV1(Ch,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=$(e)),e.toString()===this.toString())}};var Fh=114,tc=2336;function Rt(s,e){let t;if(s.charAt(0)==="1"||s.charAt(0)==="Q")t=Ye(ie.decode(`z${s}`));else{if(s.startsWith("k51qzi5uqu5")||s.startsWith("kzwfwjn5ji4")||s.startsWith("k2k4r8")||s.startsWith("bafz"))return Nh(ce.parse(s));if(e==null)throw new re('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ye(e.decode(s))}return rs(t)}function rs(s){if(Uh(s))return new Ir({multihash:s});if(Oh(s))try{let e=Qa(s);if(e.type==="Ed25519")return new Tr({multihash:s,publicKey:e});if(e.type==="secp256k1")return new Dr({multihash:s,publicKey:e})}catch{let t=$(s.digest);return new Ls(new URL(t))}throw new Ks("Supplied PeerID Multihash is invalid")}function Nh(s){if(s?.multihash==null||s.version==null||s.version===1&&s.code!==Fh&&s.code!==tc)throw new Us("Supplied PeerID CID is invalid");if(s.code===tc){let e=$(s.multihash.digest);return new Ls(new URL(e))}return rs(s.multihash)}function Oh(s){return s.code===Ne.code}function Uh(s){return s.code===St.code}var Ar=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ns=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Mr=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Cs=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Pr(s){return s[Symbol.asyncIterator]!=null}function sc(s,e){if(s.byteLength>e)throw new ns("Message length too long")}var kr=s=>{let e=Fe(s),t=he(e);return si(s,t),kr.bytes=e,t};kr.bytes=0;function is(s,e){e=e??{};let t=e.lengthEncoder??kr,r=e?.maxDataLength??4194304;function*n(i){sc(i,r);let o=t(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return Pr(s)?(async function*(){for await(let i of s)yield*n(i)})():(function*(){for(let i of s)yield*n(i)})()}is.single=(s,e)=>{e=e??{};let t=e.lengthEncoder??kr,r=e?.maxDataLength??4194304;return sc(s,r),new ae(t(s.byteLength),s)};var Lt;(function(s){s[s.LENGTH=0]="LENGTH",s[s.DATA=1]="DATA"})(Lt||(Lt={}));var Fi=s=>{let e=ri(s);return Fi.bytes=Fe(e),e};Fi.bytes=0;function Fs(s,e){let t=new ae,r=Lt.LENGTH,n=-1,i=e?.lengthDecoder??Fi,o=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*l(){for(;t.byteLength>0;){if(r===Lt.LENGTH)try{if(n=i(t),n<0)throw new Ar("Invalid message length");if(n>a)throw new ns("Message length too long");let u=i.bytes;t.consume(u),e?.onLength!=null&&e.onLength(n),r=Lt.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>o)throw new Mr("Message length length too long");break}throw u}if(r===Lt.DATA){if(t.byteLength<n)break;let u=t.sublist(0,n);t.consume(n),e?.onData!=null&&e.onData(u),yield u,r=Lt.LENGTH}}}return Pr(s)?(async function*(){for await(let u of s)t.append(u),yield*l();if(t.byteLength>0)throw new Cs("Unexpected end of input")})():(function*(){for(let u of s)t.append(u),yield*l();if(t.byteLength>0)throw new Cs("Unexpected end of input")})()}Fs.fromReader=(s,e)=>{let t=1,r=(async function*(){for(;;)try{let{done:i,value:o}=await s.next(t);if(i===!0)return;o!=null&&(yield o)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{t=1}})();return Fs(r,{...e??{},onLength:i=>{t=i}})};function st(){let s={};return s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),s}var Rr=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},os=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Rr(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Rr(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Ni=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ct(s={}){return zh(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 zh(s,e){e=e??{};let t=e.onEnd,r=new os,n,i,o,a=st(),l=async()=>{try{return r.isEmpty()?o?{done:!0}:await new Promise((w,E)=>{i=S=>{i=null,r.push(S);try{w(s(r))}catch(c){E(c)}return n}}):s(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=st()})}},u=w=>i!=null?i(w):(r.push(w),n),p=w=>(r=new os,i!=null?i({error:w}):(r.push({error:w}),n)),m=w=>{if(o)return n;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:w})},x=w=>o?n:(o=!0,w!=null?p(w):u({done:!0})),y=()=>(r=new os,x(),{done:!0}),f=w=>(x(w),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:l,return:y,throw:f,push:m,end:x,get readableLength(){return r.size},onEmpty:async w=>{let E=w?.signal;if(E?.throwIfAborted(),r.isEmpty())return;let S,c;E!=null&&(S=new Promise((h,d)=>{c=()=>{d(new Ni)},E.addEventListener("abort",c)}));try{await Promise.race([a.promise,S])}finally{c!=null&&E!=null&&E?.removeEventListener("abort",c)}}},t==null)return n;let g=n;return n={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(w){return g.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:m,end(w){return g.end(w),t!=null&&(t(w),t=void 0),n},get readableLength(){return g.readableLength},onEmpty:w=>g.onEmpty(w)},n}function qh(s){return s.reason}function Oi(s,e,t){if(e==null||s==null)return s;let r=t?.translateError??qh;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 Ui=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=st(),this.haveNext=st()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=st(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=st(),await Oi(this.readNext.promise,t?.signal,t)}};function rc(){return new Ui}function nc(s){return s[Symbol.asyncIterator]!=null}async function Gh(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*Hh(s){let e=new AbortController,t=rc(),r=s.map(n=>nc(n)?n[Symbol.asyncIterator]():n[Symbol.iterator]());Gh(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort();for(let n of r)try{Promise.resolve(n.return?.()).catch(()=>{})}catch{}}}function*Wh(s){for(let e of s)yield*e}function Vh(...s){let e=[];for(let t of s)nc(t)||e.push(t);return e.length===s.length?Wh(e):Hh(s)}var ic=Vh;function Ns(s,...e){if(s==null)throw new Error("Empty pipeline");if(Ki(s)){let r=s;s=()=>r.source}else if(ac(s)||oc(s)){let r=s;s=()=>r}let t=[s,...e];if(t.length>1&&Ki(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let r=1;r<t.length-1;r++)Ki(t[r])&&(t[r]=jh(t[r]));return $h(...t)}var $h=(...s)=>{let e;for(;s.length>0;)e=s.shift()(e);return e},oc=s=>s?.[Symbol.asyncIterator]!=null,ac=s=>s?.[Symbol.iterator]!=null,Ki=s=>s==null?!1:s.sink!=null&&s.source!=null,jh=s=>e=>{let t=s.sink(e);if(t?.then!=null){let r=Ct({objectMode:!0});t.then(()=>{r.end()},o=>{r.end(o)});let n,i=s.source;if(oc(i))n=async function*(){yield*i,r.end()};else if(ac(i))n=function*(){yield*i,r.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return ic(r,n())}return s.source};var cc={maxSubscriptions:5e3,maxMessages:5e3,maxIhaveMessageIDs:5e3,maxIwantMessageIDs:5e3,maxControlMessages:5e3,maxIdontwantMessageIDs:512,maxPeerInfos:16};var rt;(function(s){let e;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),c.subscribe!=null&&(h.uint32(8),h.bool(c.subscribe)),c.topic!=null&&(h.uint32(18),h.string(c.topic)),d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{b.subscribe=c.bool();break}case 2:{b.topic=c.string();break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{yield{field:`${d}.subscribe`,value:c.bool()};break}case 2:{yield{field:`${d}.topic`,value:c.string()};break}default:{c.skipType(_&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(e=s.SubOpts||(s.SubOpts={}));let t;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),c.from!=null&&(h.uint32(10),h.bytes(c.from)),c.data!=null&&(h.uint32(18),h.bytes(c.data)),c.seqno!=null&&(h.uint32(26),h.bytes(c.seqno)),c.topic!=null&&c.topic!==""&&(h.uint32(34),h.string(c.topic)),c.signature!=null&&(h.uint32(42),h.bytes(c.signature)),c.key!=null&&(h.uint32(50),h.bytes(c.key)),d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={topic:""},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{b.from=c.bytes();break}case 2:{b.data=c.bytes();break}case 3:{b.seqno=c.bytes();break}case 4:{b.topic=c.string();break}case 5:{b.signature=c.bytes();break}case 6:{b.key=c.bytes();break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{yield{field:`${d}.from`,value:c.bytes()};break}case 2:{yield{field:`${d}.data`,value:c.bytes()};break}case 3:{yield{field:`${d}.seqno`,value:c.bytes()};break}case 4:{yield{field:`${d}.topic`,value:c.string()};break}case 5:{yield{field:`${d}.signature`,value:c.bytes()};break}case 6:{yield{field:`${d}.key`,value:c.bytes()};break}default:{c.skipType(_&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(t=s.Message||(s.Message={}));let r;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),c.ihave!=null&&c.ihave.length>0)for(let b of c.ihave)h.uint32(10),s.ControlIHave.codec().encode(b,h);if(c.iwant!=null&&c.iwant.length>0)for(let b of c.iwant)h.uint32(18),s.ControlIWant.codec().encode(b,h);if(c.graft!=null&&c.graft.length>0)for(let b of c.graft)h.uint32(26),s.ControlGraft.codec().encode(b,h);if(c.prune!=null&&c.prune.length>0)for(let b of c.prune)h.uint32(34),s.ControlPrune.codec().encode(b,h);if(c.idontwant!=null&&c.idontwant.length>0)for(let b of c.idontwant)h.uint32(42),s.ControlIDontWant.codec().encode(b,h);d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={ihave:[],iwant:[],graft:[],prune:[],idontwant:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{if(d.limits?.ihave!=null&&b.ihave.length===d.limits.ihave)throw new Z('Decode error - repeated field "ihave" had too many elements');b.ihave.push(s.ControlIHave.codec().decode(c,c.uint32(),{limits:d.limits?.ihave$}));break}case 2:{if(d.limits?.iwant!=null&&b.iwant.length===d.limits.iwant)throw new Z('Decode error - repeated field "iwant" had too many elements');b.iwant.push(s.ControlIWant.codec().decode(c,c.uint32(),{limits:d.limits?.iwant$}));break}case 3:{if(d.limits?.graft!=null&&b.graft.length===d.limits.graft)throw new Z('Decode error - repeated field "graft" had too many elements');b.graft.push(s.ControlGraft.codec().decode(c,c.uint32(),{limits:d.limits?.graft$}));break}case 4:{if(d.limits?.prune!=null&&b.prune.length===d.limits.prune)throw new Z('Decode error - repeated field "prune" had too many elements');b.prune.push(s.ControlPrune.codec().decode(c,c.uint32(),{limits:d.limits?.prune$}));break}case 5:{if(d.limits?.idontwant!=null&&b.idontwant.length===d.limits.idontwant)throw new Z('Decode error - repeated field "idontwant" had too many elements');b.idontwant.push(s.ControlIDontWant.codec().decode(c,c.uint32(),{limits:d.limits?.idontwant$}));break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v={ihave:0,iwant:0,graft:0,prune:0,idontwant:0},_=h==null?c.len:c.pos+h;for(;c.pos<_;){let D=c.uint32();switch(D>>>3){case 1:{if(b.limits?.ihave!=null&&v.ihave===b.limits.ihave)throw new Z('Streaming decode error - repeated field "ihave" had too many elements');for(let P of s.ControlIHave.codec().stream(c,c.uint32(),`${d}.ihave[]`,{limits:b.limits?.ihave$}))yield{...P,index:v.ihave};v.ihave++;break}case 2:{if(b.limits?.iwant!=null&&v.iwant===b.limits.iwant)throw new Z('Streaming decode error - repeated field "iwant" had too many elements');for(let P of s.ControlIWant.codec().stream(c,c.uint32(),`${d}.iwant[]`,{limits:b.limits?.iwant$}))yield{...P,index:v.iwant};v.iwant++;break}case 3:{if(b.limits?.graft!=null&&v.graft===b.limits.graft)throw new Z('Streaming decode error - repeated field "graft" had too many elements');for(let P of s.ControlGraft.codec().stream(c,c.uint32(),`${d}.graft[]`,{limits:b.limits?.graft$}))yield{...P,index:v.graft};v.graft++;break}case 4:{if(b.limits?.prune!=null&&v.prune===b.limits.prune)throw new Z('Streaming decode error - repeated field "prune" had too many elements');for(let P of s.ControlPrune.codec().stream(c,c.uint32(),`${d}.prune[]`,{limits:b.limits?.prune$}))yield{...P,index:v.prune};v.prune++;break}case 5:{if(b.limits?.idontwant!=null&&v.idontwant===b.limits.idontwant)throw new Z('Streaming decode error - repeated field "idontwant" had too many elements');for(let P of s.ControlIDontWant.codec().stream(c,c.uint32(),`${d}.idontwant[]`,{limits:b.limits?.idontwant$}))yield{...P,index:v.idontwant};v.idontwant++;break}default:{c.skipType(D&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(r=s.ControlMessage||(s.ControlMessage={}));let n;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),c.topicID!=null&&(h.uint32(10),h.string(c.topicID)),c.messageIDs!=null&&c.messageIDs.length>0)for(let b of c.messageIDs)h.uint32(18),h.bytes(b);d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={messageIDs:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{b.topicID=c.string();break}case 2:{if(d.limits?.messageIDs!=null&&b.messageIDs.length===d.limits.messageIDs)throw new Z('Decode error - repeated field "messageIDs" had too many elements');b.messageIDs.push(c.bytes());break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v={messageIDs:0},_=h==null?c.len:c.pos+h;for(;c.pos<_;){let D=c.uint32();switch(D>>>3){case 1:{yield{field:`${d}.topicID`,value:c.string()};break}case 2:{if(b.limits?.messageIDs!=null&&v.messageIDs===b.limits.messageIDs)throw new Z('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:c.bytes()},v.messageIDs++;break}default:{c.skipType(D&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(n=s.ControlIHave||(s.ControlIHave={}));let i;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),c.messageIDs!=null&&c.messageIDs.length>0)for(let b of c.messageIDs)h.uint32(10),h.bytes(b);d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={messageIDs:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{if(d.limits?.messageIDs!=null&&b.messageIDs.length===d.limits.messageIDs)throw new Z('Decode error - repeated field "messageIDs" had too many elements');b.messageIDs.push(c.bytes());break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v={messageIDs:0},_=h==null?c.len:c.pos+h;for(;c.pos<_;){let D=c.uint32();switch(D>>>3){case 1:{if(b.limits?.messageIDs!=null&&v.messageIDs===b.limits.messageIDs)throw new Z('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:c.bytes()},v.messageIDs++;break}default:{c.skipType(D&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(i=s.ControlIWant||(s.ControlIWant={}));let o;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),c.topicID!=null&&(h.uint32(10),h.string(c.topicID)),d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();_>>>3===1?b.topicID=c.string():c.skipType(_&7)}return b},function*(c,h,d,b={}){let v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();_>>>3===1?yield{field:`${d}.topicID`,value:c.string()}:c.skipType(_&7)}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(o=s.ControlGraft||(s.ControlGraft={}));let a;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),c.topicID!=null&&(h.uint32(10),h.string(c.topicID)),c.peers!=null&&c.peers.length>0)for(let b of c.peers)h.uint32(18),s.PeerInfo.codec().encode(b,h);c.backoff!=null&&(h.uint32(24),h.uint64Number(c.backoff)),d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={peers:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{b.topicID=c.string();break}case 2:{if(d.limits?.peers!=null&&b.peers.length===d.limits.peers)throw new Z('Decode error - repeated field "peers" had too many elements');b.peers.push(s.PeerInfo.codec().decode(c,c.uint32(),{limits:d.limits?.peers$}));break}case 3:{b.backoff=c.uint64Number();break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v={peers:0},_=h==null?c.len:c.pos+h;for(;c.pos<_;){let D=c.uint32();switch(D>>>3){case 1:{yield{field:`${d}.topicID`,value:c.string()};break}case 2:{if(b.limits?.peers!=null&&v.peers===b.limits.peers)throw new Z('Streaming decode error - repeated field "peers" had too many elements');for(let P of s.PeerInfo.codec().stream(c,c.uint32(),`${d}.peers[]`,{limits:b.limits?.peers$}))yield{...P,index:v.peers};v.peers++;break}case 3:{yield{field:`${d}.backoff`,value:c.uint64Number()};break}default:{c.skipType(D&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(a=s.ControlPrune||(s.ControlPrune={}));let l;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{d.lengthDelimited!==!1&&h.fork(),c.peerID!=null&&(h.uint32(10),h.bytes(c.peerID)),c.signedPeerRecord!=null&&(h.uint32(18),h.bytes(c.signedPeerRecord)),d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{b.peerID=c.bytes();break}case 2:{b.signedPeerRecord=c.bytes();break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{yield{field:`${d}.peerID`,value:c.bytes()};break}case 2:{yield{field:`${d}.signedPeerRecord`,value:c.bytes()};break}default:{c.skipType(_&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(l=s.PeerInfo||(s.PeerInfo={}));let u;(function(f){let g;f.codec=()=>(g==null&&(g=ve((c,h,d={})=>{if(d.lengthDelimited!==!1&&h.fork(),c.messageIDs!=null&&c.messageIDs.length>0)for(let b of c.messageIDs)h.uint32(10),h.bytes(b);d.lengthDelimited!==!1&&h.ldelim()},(c,h,d={})=>{let b={messageIDs:[]},v=h==null?c.len:c.pos+h;for(;c.pos<v;){let _=c.uint32();switch(_>>>3){case 1:{if(d.limits?.messageIDs!=null&&b.messageIDs.length===d.limits.messageIDs)throw new Z('Decode error - repeated field "messageIDs" had too many elements');b.messageIDs.push(c.bytes());break}default:{c.skipType(_&7);break}}}return b},function*(c,h,d,b={}){let v={messageIDs:0},_=h==null?c.len:c.pos+h;for(;c.pos<_;){let D=c.uint32();switch(D>>>3){case 1:{if(b.limits?.messageIDs!=null&&v.messageIDs===b.limits.messageIDs)throw new Z('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:c.bytes()},v.messageIDs++;break}default:{c.skipType(D&7);break}}}})),g);function w(c){return we(c,f.codec())}f.encode=w;function E(c,h){return ye(c,f.codec(),h)}f.decode=E;function S(c,h){return xe(c,f.codec(),h)}f.stream=S})(u=s.ControlIDontWant||(s.ControlIDontWant={}));let p;s.codec=()=>(p==null&&(p=ve((f,g,w={})=>{if(w.lengthDelimited!==!1&&g.fork(),f.subscriptions!=null&&f.subscriptions.length>0)for(let E of f.subscriptions)g.uint32(10),s.SubOpts.codec().encode(E,g);if(f.messages!=null&&f.messages.length>0)for(let E of f.messages)g.uint32(18),s.Message.codec().encode(E,g);f.control!=null&&(g.uint32(26),s.ControlMessage.codec().encode(f.control,g)),w.lengthDelimited!==!1&&g.ldelim()},(f,g,w={})=>{let E={subscriptions:[],messages:[]},S=g==null?f.len:f.pos+g;for(;f.pos<S;){let c=f.uint32();switch(c>>>3){case 1:{if(w.limits?.subscriptions!=null&&E.subscriptions.length===w.limits.subscriptions)throw new Z('Decode error - repeated field "subscriptions" had too many elements');E.subscriptions.push(s.SubOpts.codec().decode(f,f.uint32(),{limits:w.limits?.subscriptions$}));break}case 2:{if(w.limits?.messages!=null&&E.messages.length===w.limits.messages)throw new Z('Decode error - repeated field "messages" had too many elements');E.messages.push(s.Message.codec().decode(f,f.uint32(),{limits:w.limits?.messages$}));break}case 3:{E.control=s.ControlMessage.codec().decode(f,f.uint32(),{limits:w.limits?.control});break}default:{f.skipType(c&7);break}}}return E},function*(f,g,w,E={}){let S={subscriptions:0,messages:0},c=g==null?f.len:f.pos+g;for(;f.pos<c;){let h=f.uint32();switch(h>>>3){case 1:{if(E.limits?.subscriptions!=null&&S.subscriptions===E.limits.subscriptions)throw new Z('Streaming decode error - repeated field "subscriptions" had too many elements');for(let d of s.SubOpts.codec().stream(f,f.uint32(),`${w}.subscriptions[]`,{limits:E.limits?.subscriptions$}))yield{...d,index:S.subscriptions};S.subscriptions++;break}case 2:{if(E.limits?.messages!=null&&S.messages===E.limits.messages)throw new Z('Streaming decode error - repeated field "messages" had too many elements');for(let d of s.Message.codec().stream(f,f.uint32(),`${w}.messages[]`,{limits:E.limits?.messages$}))yield{...d,index:S.messages};S.messages++;break}case 3:{yield*s.ControlMessage.codec().stream(f,f.uint32(),`${w}.control`,{limits:E.limits?.control});break}default:{f.skipType(h&7);break}}}})),p);function m(f){return we(f,s.codec())}s.encode=m;function x(f,g){return ye(f,s.codec(),g)}s.decode=x;function y(f,g){return xe(f,s.codec(),g)}s.stream=y})(rt||(rt={}));var Lr=class{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,r){this.gossip=e,this.msgIdToStrFn=r;for(let n=0;n<t;n++)this.history[n]=[]}get size(){return this.msgs.size}put(e,t,r=!1){let{msgIdStr:n}=e;return this.msgs.has(n)?!1:(this.msgs.set(n,{message:t,validated:r,originatingPeers:new Set,iwantCounts:new Map}),this.history[0].push({...e,topic:t.topic}),r||this.notValidatedCount++,!0)}observeDuplicate(e,t){let r=this.msgs.get(e);r!=null&&!r.validated&&r.originatingPeers.add(t)}get(e){return this.msgs.get(this.msgIdToStrFn(e))?.message}getWithIWantCount(e,t){let r=this.msgs.get(e);if(r==null)return null;let n=(r.iwantCounts.get(t)??0)+1;return r.iwantCounts.set(t,n),{msg:r.message,count:n}}getGossipIDs(e){let t=new Map;for(let r=0;r<this.gossip;r++)this.history[r].forEach(n=>{if((this.msgs.get(n.msgIdStr)?.validated??!1)&&e.has(n.topic)){let o=t.get(n.topic);o==null&&(o=[],t.set(n.topic,o)),o.push(n.msgId)}});return t}validate(e){let t=this.msgs.get(e);if(t==null)return null;t.validated||this.notValidatedCount--;let{message:r,originatingPeers:n}=t;return t.validated=!0,t.originatingPeers=new Set,{message:r,originatingPeers:n}}shift(){this.history[this.history.length-1].forEach(t=>{let r=this.msgs.get(t.msgIdStr);r!=null&&(this.msgs.delete(t.msgIdStr),r.validated||this.notValidatedCount--)}),this.history.pop(),this.history.unshift([])}remove(e){let t=this.msgs.get(e);return t==null?null:(this.msgs.delete(e),t)}};var lc;(function(s){s.StrictSign="StrictSign",s.StrictNoSign="StrictNoSign"})(lc||(lc={}));var yt;(function(s){s[s.Signing=0]="Signing",s[s.Anonymous=1]="Anonymous"})(yt||(yt={}));var Ee;(function(s){s.Error="error",s.Ignore="ignore",s.Reject="reject",s.Blacklisted="blacklisted"})(Ee||(Ee={}));var le;(function(s){s.InvalidSignature="invalid_signature",s.InvalidSeqno="invalid_seqno",s.InvalidPeerId="invalid_peerid",s.SignaturePresent="signature_present",s.SeqnoPresent="seqno_present",s.FromPresent="from_present",s.TransformFailed="transform_failed"})(le||(le={}));var pe;(function(s){s.duplicate="duplicate",s.invalid="invalid",s.valid="valid"})(pe||(pe={}));function zi(s){switch(s){case me.Ignore:return Ee.Ignore;case me.Reject:return Ee.Reject;default:throw new Error("Unreachable")}}var uc;(function(s){s.forward="forward",s.publish="publish"})(uc||(uc={}));var ge;(function(s){s.Fanout="fanout",s.Random="random",s.Subscribed="subscribed",s.Outbound="outbound",s.NotEnough="not_enough",s.Opportunistic="opportunistic"})(ge||(ge={}));var Ke;(function(s){s.Dc="disconnected",s.BadScore="bad_score",s.Prune="prune",s.Excess="excess"})(Ke||(Ke={}));var cs;(function(s){s.GraftBackoff="graft_backoff",s.BrokenPromise="broken_promise",s.MessageDeficit="message_deficit",s.IPColocation="IP_colocation"})(cs||(cs={}));var ls;(function(s){s.LowScore="low_score",s.MaxIhave="max_ihave",s.MaxIasked="max_iasked"})(ls||(ls={}));var as;(function(s){s.graylist="graylist",s.publish="publish",s.gossip="gossip",s.mesh="mesh"})(as||(as={}));function hc(s,e,t){return{protocolsEnabled:s.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:s.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:s.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:s.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEventsFanout:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_fanout_total",help:"Number of times we include peers in a topic mesh for fanout reasons",labelNames:["topic"]}),meshPeerInclusionEventsRandom:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_random_total",help:"Number of times we include peers in a topic mesh for random reasons",labelNames:["topic"]}),meshPeerInclusionEventsSubscribed:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_subscribed_total",help:"Number of times we include peers in a topic mesh for subscribed reasons",labelNames:["topic"]}),meshPeerInclusionEventsOutbound:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_outbound_total",help:"Number of times we include peers in a topic mesh for outbound reasons",labelNames:["topic"]}),meshPeerInclusionEventsNotEnough:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_not_enough_total",help:"Number of times we include peers in a topic mesh for not_enough reasons",labelNames:["topic"]}),meshPeerInclusionEventsOpportunistic:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_opportunistic_total",help:"Number of times we include peers in a topic mesh for opportunistic reasons",labelNames:["topic"]}),meshPeerInclusionEventsUnknown:s.gauge({name:"gossipsub_mesh_peer_inclusion_events_unknown_total",help:"Number of times we include peers in a topic mesh for unknown reasons",labelNames:["topic"]}),meshPeerChurnEventsDisconnected:s.gauge({name:"gossipsub_peer_churn_events_disconnected_total",help:"Number of times we remove peers in a topic mesh for disconnected reasons",labelNames:["topic"]}),meshPeerChurnEventsBadScore:s.gauge({name:"gossipsub_peer_churn_events_bad_score_total",help:"Number of times we remove peers in a topic mesh for bad_score reasons",labelNames:["topic"]}),meshPeerChurnEventsPrune:s.gauge({name:"gossipsub_peer_churn_events_prune_total",help:"Number of times we remove peers in a topic mesh for prune reasons",labelNames:["topic"]}),meshPeerChurnEventsExcess:s.gauge({name:"gossipsub_peer_churn_events_excess_total",help:"Number of times we remove peers in a topic mesh for excess reasons",labelNames:["topic"]}),meshPeerChurnEventsUnknown:s.gauge({name:"gossipsub_peer_churn_events_unknown_total",help:"Number of times we remove peers in a topic mesh for unknown reasons",labelNames:["topic"]}),peersPerProtocol:s.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:s.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:s.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),acceptedMessagesTotal:s.gauge({name:"gossipsub_accepted_messages_total",help:"Total accepted messages for each topic",labelNames:["topic"]}),ignoredMessagesTotal:s.gauge({name:"gossipsub_ignored_messages_total",help:"Total ignored messages for each topic",labelNames:["topic"]}),rejectedMessagesTotal:s.gauge({name:"gossipsub_rejected_messages_total",help:"Total rejected messages for each topic",labelNames:["topic"]}),unknownValidationResultsTotal:s.gauge({name:"gossipsub_unknown_validation_results_total",help:"Total unknown validation results for each topic",labelNames:["topic"]}),asyncValidationMcacheHit:s.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),asyncValidationDelayFromFirstSeenSec:s.histogram({name:"gossipsub_async_validation_delay_from_first_seen",help:"Async validation report delay from first seen in second",buckets:[.01,.03,.1,.3,1,3,10]}),asyncValidationUnknownFirstSeen:s.gauge({name:"gossipsub_async_validation_unknown_first_seen_count_total",help:"Async validation report unknown first seen value for message"}),peerReadStreamError:s.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:s.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:s.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:s.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:s.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:s.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:s.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:s.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:s.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:s.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:s.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:s.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:s.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:s.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:s.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:s.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:s.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:s.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:s.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:s.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:s.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:s.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),rpcSentIDontWant:s.gauge({name:"gossipsub_rpc_sent_idontwant_total",help:"RPC sent"}),msgPublishCount:s.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeersByTopic:s.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),directPeersPublishedTotal:s.gauge({name:"gossipsub_direct_peers_published_total",help:"Total direct peers that we publish a msg to",labelNames:["topic"]}),floodsubPeersPublishedTotal:s.gauge({name:"gossipsub_floodsub_peers_published_total",help:"Total floodsub peers that we publish a msg to",labelNames:["topic"]}),meshPeersPublishedTotal:s.gauge({name:"gossipsub_mesh_peers_published_total",help:"Total mesh peers that we publish a msg to",labelNames:["topic"]}),fanoutPeersPublishedTotal:s.gauge({name:"gossipsub_fanout_peers_published_total",help:"Total fanout peers that we publish a msg to",labelNames:["topic"]}),msgPublishBytes:s.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgPublishTime:s.histogram({name:"gossipsub_msg_publish_seconds",help:"Total time in seconds to publish a message",buckets:[.001,.002,.005,.01,.1,.5,1],labelNames:["topic"]}),msgForwardCount:s.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:s.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:s.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:s.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),prevalidationInvalidTotal:s.gauge({name:"gossipsub_pre_validation_invalid_total",help:"Total count of invalid messages received",labelNames:["topic"]}),prevalidationValidTotal:s.gauge({name:"gossipsub_pre_validation_valid_total",help:"Total count of valid messages received",labelNames:["topic"]}),prevalidationDuplicateTotal:s.gauge({name:"gossipsub_pre_validation_duplicate_total",help:"Total count of duplicate messages received",labelNames:["topic"]}),prevalidationUnknownTotal:s.gauge({name:"gossipsub_pre_validation_unknown_status_total",help:"Total count of unknown_status messages received",labelNames:["topic"]}),msgReceivedInvalid:s.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["error"]}),msgReceivedInvalidByTopic:s.gauge({name:"gossipsub_msg_received_invalid_by_topic_total",help:"Tracks specific invalid message by topic",labelNames:["topic"]}),duplicateMsgDeliveryDelay:s.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*t.maxMeshMessageDeliveriesWindowSec,.5*t.maxMeshMessageDeliveriesWindowSec,Number(t.maxMeshMessageDeliveriesWindowSec),2*t.maxMeshMessageDeliveriesWindowSec,4*t.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:s.gauge({name:"gossisub_duplicate_msg_late_delivery_total",help:"Total count of late duplicate message delivery by topic, which triggers P3 penalty",labelNames:["topic"]}),duplicateMsgIgnored:s.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:s.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:s.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:s.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:s.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:s.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores"}),scoreWeights:s.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:s.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:s.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:s.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*t.behaviourPenaltyThreshold,.5*t.behaviourPenaltyThreshold,Number(t.behaviourPenaltyThreshold),2*t.behaviourPenaltyThreshold,4*t.behaviourPenaltyThreshold]}),ihaveRcvIgnored:s.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:s.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:s.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:s.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:s.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),idontwantRcvMsgids:s.gauge({name:"gossipsub_idontwant_rcv_msgids_total",help:"Total received IDONTWANT messages"}),idontwantRcvDonthaveMsgids:s.gauge({name:"gossipsub_idontwant_rcv_dont_have_msgids_total",help:"Total received IDONTWANT messageIDs that we do not have in mcache"}),iwantPromiseStarted:s.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:s.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:s.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:s.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:s.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:s.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:s.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*t.gossipPromiseExpireSec,Number(t.gossipPromiseExpireSec),2*t.gossipPromiseExpireSec,4*t.gossipPromiseExpireSec]}),iwantPromiseUntracked:s.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),connectedPeersBackoffSec:s.histogram({name:"gossipsub_connected_peers_backoff_seconds",help:"Backoff time in seconds",buckets:[1,2,4,10,20,60,120]}),cacheSize:s.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:s.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:s.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:s.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:s.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:e,toTopic(r){return this.topicStrToLabel.get(r)??r},onJoin(r){this.topicSubscriptionStatus.set({topicStr:r},1),this.meshPeerCounts.set({topicStr:r},0)},onLeave(r){this.topicSubscriptionStatus.set({topicStr:r},0),this.meshPeerCounts.set({topicStr:r},0)},onAddToMesh(r,n,i){let o=this.toTopic(r);switch(n){case ge.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:o},i);break;case ge.Random:this.meshPeerInclusionEventsRandom.inc({topic:o},i);break;case ge.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:o},i);break;case ge.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:o},i);break;case ge.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:o},i);break;case ge.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:o},i);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:o},i);break}},onRemoveFromMesh(r,n,i){let o=this.toTopic(r);switch(n){case Ke.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:o},i);break;case Ke.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:o},i);break;case Ke.Prune:this.meshPeerChurnEventsPrune.inc({topic:o},i);break;case Ke.Excess:this.meshPeerChurnEventsExcess.inc({topic:o},i);break;default:this.meshPeerChurnEventsUnknown.inc({topic:o},i);break}},onReportValidation(r,n,i){if(this.asyncValidationMcacheHit.inc({hit:r!=null?"hit":"miss"}),r!=null){let o=this.toTopic(r.message.topic);switch(n){case me.Accept:this.acceptedMessagesTotal.inc({topic:o});break;case me.Ignore:this.ignoredMessagesTotal.inc({topic:o});break;case me.Reject:this.rejectedMessagesTotal.inc({topic:o});break;default:this.unknownValidationResultsTotal.inc({topic:o});break}}i!=null?this.asyncValidationDelayFromFirstSeenSec.observe((Date.now()-i)/1e3):this.asyncValidationUnknownFirstSeen.inc()},onScorePenalty(r){this.scoringPenalties.inc({penalty:r},1)},onIhaveRcv(r,n,i){let o=this.toTopic(r);this.ihaveRcvMsgids.inc({topic:o},n),this.ihaveRcvNotSeenMsgids.inc({topic:o},i)},onIwantRcv(r,n){for(let[i,o]of r){let a=this.toTopic(i);this.iwantRcvMsgids.inc({topic:a},o)}this.iwantRcvDonthaveMsgids.inc(n)},onIdontwantRcv(r,n){this.idontwantRcvMsgids.inc(r),this.idontwantRcvDonthaveMsgids.inc(n)},onForwardMsg(r,n){let i=this.toTopic(r);this.msgForwardCount.inc({topic:i},1),this.msgForwardPeers.inc({topic:i},n)},onPublishMsg(r,n,i,o,a){let l=this.toTopic(r);this.msgPublishCount.inc({topic:l},1),this.msgPublishBytes.inc({topic:l},i*o),this.msgPublishPeersByTopic.inc({topic:l},i),this.directPeersPublishedTotal.inc({topic:l},n.direct),this.floodsubPeersPublishedTotal.inc({topic:l},n.floodsub),this.meshPeersPublishedTotal.inc({topic:l},n.mesh),this.fanoutPeersPublishedTotal.inc({topic:l},n.fanout),this.msgPublishTime.observe({topic:l},a/1e3)},onMsgRecvPreValidation(r){let n=this.toTopic(r);this.msgReceivedPreValidation.inc({topic:n},1)},onMsgRecvError(r){let n=this.toTopic(r);this.msgReceivedError.inc({topic:n},1)},onPrevalidationResult(r,n){let i=this.toTopic(r);switch(n){case pe.duplicate:this.prevalidationDuplicateTotal.inc({topic:i});break;case pe.invalid:this.prevalidationInvalidTotal.inc({topic:i});break;case pe.valid:this.prevalidationValidTotal.inc({topic:i});break;default:this.prevalidationUnknownTotal.inc({topic:i});break}},onMsgRecvInvalid(r,n){let i=this.toTopic(r),o=n.reason===Ee.Error?n.error:n.reason;this.msgReceivedInvalid.inc({error:o},1),this.msgReceivedInvalidByTopic.inc({topic:i},1)},onDuplicateMsgDelivery(r,n,i){let o=this.toTopic(r);this.duplicateMsgDeliveryDelay.observe({topic:o},n/1e3),i&&this.duplicateMsgLateDelivery.inc({topic:o},1)},onPublishDuplicateMsg(r){let n=this.toTopic(r);this.duplicateMsgIgnored.inc({topic:n},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(r,n){this.rpcRecvBytes.inc(n),this.rpcRecvCount.inc(1),r.subscriptions!=null&&this.rpcRecvSubscription.inc(r.subscriptions.length),r.messages!=null&&this.rpcRecvMessage.inc(r.messages.length),r.control!=null&&(this.rpcRecvControl.inc(1),r.control.ihave!=null&&this.rpcRecvIHave.inc(r.control.ihave.length),r.control.iwant!=null&&this.rpcRecvIWant.inc(r.control.iwant.length),r.control.graft!=null&&this.rpcRecvGraft.inc(r.control.graft.length),r.control.prune!=null&&this.rpcRecvPrune.inc(r.control.prune.length))},onRpcSent(r,n){if(this.rpcSentBytes.inc(n),this.rpcSentCount.inc(1),r.subscriptions!=null&&this.rpcSentSubscription.inc(r.subscriptions.length),r.messages!=null&&this.rpcSentMessage.inc(r.messages.length),r.control!=null){let i=r.control.ihave?.length??0,o=r.control.iwant?.length??0,a=r.control.graft?.length??0,l=r.control.prune?.length??0,u=r.control.idontwant?.length??0;i>0&&this.rpcSentIHave.inc(i),o>0&&this.rpcSentIWant.inc(o),a>0&&this.rpcSentGraft.inc(a),l>0&&this.rpcSentPrune.inc(l),u>0&&this.rpcSentIDontWant.inc(u),(i>0||o>0||a>0||l>0||u>0)&&this.rpcSentControl.inc(1)}},registerScores(r,n){let i=0,o=0,a=0,l=0;for(let u of r)u>=n.graylistThreshold&&i++,u>=n.publishThreshold&&o++,u>=n.gossipThreshold&&a++,u>=0&&l++;this.peersByScoreThreshold.set({threshold:as.graylist},i),this.peersByScoreThreshold.set({threshold:as.publish},o),this.peersByScoreThreshold.set({threshold:as.gossip},a),this.peersByScoreThreshold.set({threshold:as.mesh},l),this.score.set(r)},registerScoreWeights(r){for(let[n,i]of r.byTopic)this.scoreWeights.set({topic:n,p:"p1"},i.p1w),this.scoreWeights.set({topic:n,p:"p2"},i.p2w),this.scoreWeights.set({topic:n,p:"p3"},i.p3w),this.scoreWeights.set({topic:n,p:"p3b"},i.p3bw),this.scoreWeights.set({topic:n,p:"p4"},i.p4w);this.scoreWeights.set({p:"p5"},r.p5w),this.scoreWeights.set({p:"p6"},r.p6w),this.scoreWeights.set({p:"p7"},r.p7w)},registerScorePerMesh(r,n){let i=new Map;r.forEach((o,a)=>{let l=this.topicStrToLabel.get(a)??"unknown",u=i.get(l);u==null&&(u=new Set,i.set(l,u)),o.forEach(p=>u?.add(p))});for(let[o,a]of i){let l=[];a.forEach(u=>{l.push(n.get(u)??0)}),this.scorePerMesh.set({topic:o},l)}}}}var V=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var Zh={topics:{},topicScoreCap:10,appSpecificScore:()=>0,appSpecificWeight:10,IPColocationFactorWeight:-5,IPColocationFactorThreshold:10,IPColocationFactorWhitelist:new Set,behaviourPenaltyWeight:-10,behaviourPenaltyThreshold:0,behaviourPenaltyDecay:.2,decayInterval:1e3,decayToZero:.1,retainScore:3600*1e3},Yh={topicWeight:.5,timeInMeshWeight:1,timeInMeshQuantum:1,timeInMeshCap:3600,firstMessageDeliveriesWeight:1,firstMessageDeliveriesDecay:.5,firstMessageDeliveriesCap:2e3,meshMessageDeliveriesWeight:-1,meshMessageDeliveriesDecay:.5,meshMessageDeliveriesCap:100,meshMessageDeliveriesThreshold:20,meshMessageDeliveriesWindow:10,meshMessageDeliveriesActivation:5e3,meshFailurePenaltyWeight:-1,meshFailurePenaltyDecay:.5,invalidMessageDeliveriesWeight:-1,invalidMessageDeliveriesDecay:.3};function fc(s={}){return{...Zh,...s,topics:s.topics!=null?Object.entries(s.topics).reduce((e,[t,r])=>(e[t]=Xh(r),e),{}):{}}}function Xh(s={}){return{...Yh,...s}}function dc(s){for(let[e,t]of Object.entries(s.topics))try{Jh(t)}catch(r){throw new V(`invalid score parameters for topic ${e}: ${r.message}`)}if(s.topicScoreCap<0)throw new V("invalid topic score cap; must be positive (or 0 for no cap)");if(s.appSpecificScore===null||s.appSpecificScore===void 0)throw new V("missing application specific score function");if(s.IPColocationFactorWeight>0)throw new V("invalid IPColocationFactorWeight; must be negative (or 0 to disable)");if(s.IPColocationFactorWeight!==0&&s.IPColocationFactorThreshold<1)throw new V("invalid IPColocationFactorThreshold; must be at least 1");if(s.behaviourPenaltyWeight>0)throw new V("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)");if(s.behaviourPenaltyWeight!==0&&(s.behaviourPenaltyDecay<=0||s.behaviourPenaltyDecay>=1))throw new V("invalid BehaviourPenaltyDecay; must be between 0 and 1");if(s.decayInterval<1e3)throw new V("invalid DecayInterval; must be at least 1s");if(s.decayToZero<=0||s.decayToZero>=1)throw new V("invalid DecayToZero; must be between 0 and 1")}function Jh(s){if(s.topicWeight<0)throw new V("invalid topic weight; must be >= 0");if(s.timeInMeshQuantum===0)throw new V("invalid TimeInMeshQuantum; must be non zero");if(s.timeInMeshWeight<0)throw new V("invalid TimeInMeshWeight; must be positive (or 0 to disable)");if(s.timeInMeshWeight!==0&&s.timeInMeshQuantum<=0)throw new V("invalid TimeInMeshQuantum; must be positive");if(s.timeInMeshWeight!==0&&s.timeInMeshCap<=0)throw new V("invalid TimeInMeshCap; must be positive");if(s.firstMessageDeliveriesWeight<0)throw new V("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)");if(s.firstMessageDeliveriesWeight!==0&&(s.firstMessageDeliveriesDecay<=0||s.firstMessageDeliveriesDecay>=1))throw new V("invalid FirstMessageDeliveriesDecay; must be between 0 and 1");if(s.firstMessageDeliveriesWeight!==0&&s.firstMessageDeliveriesCap<=0)throw new V("invalid FirstMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight>0)throw new V("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.meshMessageDeliveriesWeight!==0&&(s.meshMessageDeliveriesDecay<=0||s.meshMessageDeliveriesDecay>=1))throw new V("invalid MeshMessageDeliveriesDecay; must be between 0 and 1");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesCap<=0)throw new V("invalid MeshMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesThreshold<=0)throw new V("invalid MeshMessageDeliveriesThreshold; must be positive");if(s.meshMessageDeliveriesWindow<0)throw new V("invalid MeshMessageDeliveriesWindow; must be non-negative");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesActivation<1e3)throw new V("invalid MeshMessageDeliveriesActivation; must be at least 1s");if(s.meshFailurePenaltyWeight>0)throw new V("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)");if(s.meshFailurePenaltyWeight!==0&&(s.meshFailurePenaltyDecay<=0||s.meshFailurePenaltyDecay>=1))throw new V("invalid MeshFailurePenaltyDecay; must be between 0 and 1");if(s.invalidMessageDeliveriesWeight>0)throw new V("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.invalidMessageDeliveriesDecay<=0||s.invalidMessageDeliveriesDecay>=1)throw new V("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1")}var Qh={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function pc(s={}){return{...Qh,...s}}function Fr(s,e,t=()=>!0){let r=new Set;if(e<=0)return r;for(let n of s){if(r.size>=e)break;t(n)&&(r.add(n),s.delete(n))}return r}function mc(s,e){return Fr(s,e,()=>!0)}var Cr=class extends Map{getDefault;constructor(e){super(),this.getDefault=e}getOrDefault(e){let t=super.get(e);return t===void 0&&(t=this.getDefault(),this.set(e,t)),t}};function gc(s,e,t,r){let n=0;Object.entries(e.topics).forEach(([o,a])=>{let l=t.topics[o];if(l===void 0)return;let u=0;if(a.inMesh){let y=a.meshTime/l.timeInMeshQuantum;y>l.timeInMeshCap&&(y=l.timeInMeshCap),u+=y*l.timeInMeshWeight}let p=a.firstMessageDeliveries;if(p>l.firstMessageDeliveriesCap&&(p=l.firstMessageDeliveriesCap),u+=p*l.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries<l.meshMessageDeliveriesThreshold){let y=l.meshMessageDeliveriesThreshold-a.meshMessageDeliveries,f=y*y;u+=f*l.meshMessageDeliveriesWeight}let m=a.meshFailurePenalty;u+=m*l.meshFailurePenaltyWeight;let x=a.invalidMessageDeliveries*a.invalidMessageDeliveries;u+=x*l.invalidMessageDeliveriesWeight,n+=u*l.topicWeight}),t.topicScoreCap>0&&n>t.topicScoreCap&&(n=t.topicScoreCap);let i=t.appSpecificScore(s);if(n+=i*t.appSpecificWeight,e.knownIPs.forEach(o=>{if(t.IPColocationFactorWhitelist.has(o))return;let a=r.get(o),l=a!=null?a.size:0;if(l>t.IPColocationFactorThreshold){let u=l-t.IPColocationFactorThreshold,p=u*u;n+=p*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let o=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=o*o;n+=a*t.behaviourPenaltyWeight}return n}var wc=Hc(yc(),1);var Se;(function(s){s[s.unknown=0]="unknown",s[s.valid=1]="valid",s[s.invalid=2]="invalid",s[s.ignored=3]="ignored"})(Se||(Se={}));var Nr=class{records;queue;constructor(){this.records=new Map,this.queue=new wc.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:Se.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let r={msgId:e,expire:Date.now()+12e4};return this.queue.push(r),t}gc(){let e=Date.now(),t=this.queue.peekFront();for(;t!=null&&t.expire<e;)this.records.delete(t.msgId),this.queue.shift(),t=this.queue.peekFront()}clear(){this.records.clear(),this.queue.clear()}};var Or=class{params;metrics;peerStats=new Map;peerIPs=new Cr(()=>new Set);scoreCache=new Map;deliveryRecords=new Nr;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,r,n){this.params=e,this.metrics=t,dc(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??gc,this.log=r.forComponent("libp2p:gossipsub:score")}get size(){return this.peerStats.size}start(){if(this._backgroundInterval!=null){this.log("Peer score already running");return}this._backgroundInterval=setInterval(()=>{this.background()},this.params.decayInterval),this.log("started")}stop(){if(this._backgroundInterval==null){this.log("Peer score already stopped");return}clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),this.log("stopped")}background(){this.refreshScores(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map(([e,t])=>[e,t]))}messageFirstSeenTimestampMs(e){let t=this.deliveryRecords.getRecord(e);return t!=null?t.firstSeenTsMs:null}refreshScores(){let e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach((r,n)=>{if(!r.connected){e>r.expire&&(this.removeIPsForPeer(n,r.knownIPs),this.peerStats.delete(n),this.scoreCache.delete(n));return}Object.entries(r.topics).forEach(([i,o])=>{let a=this.params.topics[i];a!==void 0&&(o.firstMessageDeliveries*=a.firstMessageDeliveriesDecay,o.firstMessageDeliveries<t&&(o.firstMessageDeliveries=0),o.meshMessageDeliveries*=a.meshMessageDeliveriesDecay,o.meshMessageDeliveries<t&&(o.meshMessageDeliveries=0),o.meshFailurePenalty*=a.meshFailurePenaltyDecay,o.meshFailurePenalty<t&&(o.meshFailurePenalty=0),o.invalidMessageDeliveries*=a.invalidMessageDeliveriesDecay,o.invalidMessageDeliveries<t&&(o.invalidMessageDeliveries=0),o.inMesh&&(o.meshTime=e-o.graftTime,o.meshTime>a.meshMessageDeliveriesActivation&&(o.meshMessageDeliveriesActive=!0)))}),r.behaviourPenalty*=this.params.behaviourPenaltyDecay,r.behaviourPenalty<t&&(r.behaviourPenalty=0)})}score(e){this.metrics?.scoreFnCalls.inc();let t=this.peerStats.get(e);if(t==null)return 0;let r=Date.now(),n=this.scoreCache.get(e);if(n!=null&&n.cacheUntil>r)return n.score;this.metrics?.scoreFnRuns.inc();let i=this.computeScore(e,t,this.params,this.peerIPs),o=r+this.scoreCacheValidityMs;return n!=null?(this.metrics?.scoreCachedDelta.observe(Math.abs(i-n.score)),n.score=i,n.cacheUntil=o):this.scoreCache.set(e,{score:i,cacheUntil:o}),i}addPenalty(e,t,r){let n=this.peerStats.get(e);n!=null&&(n.behaviourPenalty+=t,this.metrics?.onScorePenalty(r))}addPeer(e){let t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){let r=this.peerStats.get(e);r?.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){let r=this.peerStats.get(e);r?.knownIPs.delete(t);let n=this.peerIPs.get(t);n!=null&&(n.delete(e),n.size===0&&this.peerIPs.delete(t))}removePeer(e){let t=this.peerStats.get(e);if(t!=null){if(this.score(e)>0){this.removeIPsForPeer(e,t.knownIPs),this.peerStats.delete(e);return}Object.entries(t.topics).forEach(([r,n])=>{n.firstMessageDeliveries=0;let i=this.params.topics[r].meshMessageDeliveriesThreshold;if(n.inMesh&&n.meshMessageDeliveriesActive&&n.meshMessageDeliveries<i){let o=i-n.meshMessageDeliveries;n.meshFailurePenalty+=o*o}n.inMesh=!1,n.meshMessageDeliveriesActive=!1}),t.connected=!1,t.expire=Date.now()+this.params.retainScore}}graft(e,t){let r=this.peerStats.get(e);if(r!=null){let n=this.getPtopicStats(r,t);n!=null&&(n.inMesh=!0,n.graftTime=Date.now(),n.meshTime=0,n.meshMessageDeliveriesActive=!1)}}prune(e,t){let r=this.peerStats.get(e);if(r!=null){let n=this.getPtopicStats(r,t);if(n!=null){let i=this.params.topics[t].meshMessageDeliveriesThreshold;if(n.meshMessageDeliveriesActive&&n.meshMessageDeliveries<i){let o=i-n.meshMessageDeliveries;n.meshFailurePenalty+=o*o}n.meshMessageDeliveriesActive=!1,n.inMesh=!1}}}validateMessage(e){this.deliveryRecords.ensureRecord(e)}deliverMessage(e,t,r){this.markFirstMessageDelivery(e,r);let n=this.deliveryRecords.ensureRecord(t),i=Date.now();if(n.status!==Se.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,i-n.firstSeenTsMs,Se[n.status]);return}n.status=Se.valid,n.validated=i,n.peers.forEach(o=>{o!==e.toString()&&this.markDuplicateMessageDelivery(o,r)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,r,n){switch(n){case Ee.Error:this.markInvalidMessageDelivery(e,r);return;case Ee.Blacklisted:return}let i=this.deliveryRecords.ensureRecord(t);if(i.status!==Se.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-i.firstSeenTsMs,Se[i.status]);return}if(n===Ee.Ignore){i.status=Se.ignored,i.peers.clear();return}i.status=Se.invalid,this.markInvalidMessageDelivery(e,r),i.peers.forEach(o=>{this.markInvalidMessageDelivery(o,r)}),i.peers.clear()}duplicateMessage(e,t,r){let n=this.deliveryRecords.ensureRecord(t);if(!n.peers.has(e))switch(n.status){case Se.unknown:n.peers.add(e);break;case Se.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,r,n.validated);break;case Se.invalid:this.markInvalidMessageDelivery(e,r);break;case Se.ignored:break}}markInvalidMessageDelivery(e,t){let r=this.peerStats.get(e);if(r!=null){let n=this.getPtopicStats(r,t);n!=null&&(n.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){let r=this.peerStats.get(e);if(r!=null){let n=this.getPtopicStats(r,t);if(n!=null){let i=this.params.topics[t].firstMessageDeliveriesCap;n.firstMessageDeliveries=Math.min(i,n.firstMessageDeliveries+1),n.inMesh&&(i=this.params.topics[t].meshMessageDeliveriesCap,n.meshMessageDeliveries=Math.min(i,n.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,r){let n=this.peerStats.get(e);if(n!=null){let i=r!==void 0?Date.now():0,o=this.getPtopicStats(n,t);if(o!=null&&o.inMesh){let a=this.params.topics[t];if(r!==void 0){let u=i-r,p=u>a.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,u,p),p)return}let l=a.meshMessageDeliveriesCap;o.meshMessageDeliveries=Math.min(l,o.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(let r of t){let n=this.peerIPs.get(r);n!=null&&(n.delete(e),n.size===0&&this.peerIPs.delete(r))}}getPtopicStats(e,t){let r=e.topics[t];return r!==void 0?r:this.params.topics[t]!==void 0?(r={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=r,r):null}};function ef(s,e,t,r,n){let i=0,o=new Map;if(Object.entries(e.topics).forEach(([x,y])=>{let f=n.get(x)??"unknown",g=t.topics[x];if(g===void 0)return;let w=o.get(f);w==null&&(w={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},o.set(f,w));let E=0,S=0,c=0,h=0,d=0;if(y.inMesh){let D=Math.max(y.meshTime/g.timeInMeshQuantum,g.timeInMeshCap);E+=D*g.timeInMeshWeight}let b=y.firstMessageDeliveries;if(b>g.firstMessageDeliveriesCap&&(b=g.firstMessageDeliveriesCap),S+=b*g.firstMessageDeliveriesWeight,y.meshMessageDeliveriesActive&&y.meshMessageDeliveries<g.meshMessageDeliveriesThreshold){let D=g.meshMessageDeliveriesThreshold-y.meshMessageDeliveries,P=D*D;c+=P*g.meshMessageDeliveriesWeight}let v=y.meshFailurePenalty;h+=v*g.meshFailurePenaltyWeight;let _=y.invalidMessageDeliveries*y.invalidMessageDeliveries;d+=_*g.invalidMessageDeliveriesWeight,i+=(E+S+c+h+d)*g.topicWeight,w.p1w+=E,w.p2w+=S,w.p3w+=c,w.p3bw+=h,w.p4w+=d}),t.topicScoreCap>0&&i>t.topicScoreCap){i=t.topicScoreCap;let x=t.topicScoreCap/i;for(let y of o.values())y.p1w*=x,y.p2w*=x,y.p3w*=x,y.p3bw*=x,y.p4w*=x}let a=0,l=0,u=0,p=t.appSpecificScore(s);a+=p*t.appSpecificWeight,e.knownIPs.forEach(x=>{if(t.IPColocationFactorWhitelist.has(x))return;let y=r.get(x),f=y!=null?y.size:0;if(f>t.IPColocationFactorThreshold){let g=f-t.IPColocationFactorThreshold,w=g*g;l+=w*t.IPColocationFactorWeight}});let m=e.behaviourPenalty*e.behaviourPenalty;return u+=m*t.behaviourPenaltyWeight,i+=a+l+u,{byTopic:o,p5w:a,p6w:l,p7w:u,score:i}}function xc(s,e,t,r,n){let i={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let o of s){let a=e.get(o);if(a!=null){let l=ef(o,a,t,r,n);for(let[u,p]of l.byTopic){let m=i.byTopic.get(u);m==null&&(m={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},i.byTopic.set(u,m)),m.p1w.push(p.p1w),m.p2w.push(p.p2w),m.p3w.push(p.p3w),m.p3bw.push(p.p3bw),m.p4w.push(p.p4w)}i.p5w.push(l.p5w),i.p6w.push(l.p6w),i.p7w.push(l.p7w),i.score.push(l.score)}else i.p5w.push(0),i.p6w.push(0),i.p7w.push(0),i.score.push(0)}return i}function qi(s){let e=s.getComponents(),t={},r=0;return e[r]?.name==="ip6zone"&&(t.zone=`${e[r].value}`,r++),e[r]?.name==="ip4"||e[r]?.name==="ip6"||e[r]?.name==="dns"||e[r]?.name==="dns4"||e[r]?.name==="dns6"?(t.type=e[r].name,t.host=e[r].value,r++):e[r]?.name==="dnsaddr"&&(t.type=e[r].name,t.host=`_dnsaddr.${e[r].value}`,r++),(e[r]?.name==="tcp"||e[r]?.name==="udp")&&(t.protocol=e[r].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[r].value}`),r++),e[r]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[r].value}`):t.type==="ip6"&&(t.cidr=`${e[r].value}`),r++),t.type==null||t.host==null?null:(e[r]?.name==="tls"&&e[r+1]?.name==="sni"&&(t.sni=e[r+1].value,r+=2),t)}function vc(s){let e=qi(s);if(e==null)throw new re(`Multiaddr ${s} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function Ec(s){return qi(s)!==null}var Gi=class s extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,s)}},Sc=s=>s.reason??new DOMException("This operation was aborted.","AbortError");function Hi(s,e){let{milliseconds:t,fallback:r,message:n,customTimers:i={setTimeout,clearTimeout},signal:o}=e,a,l,p=new Promise((m,x)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(o?.aborted){x(Sc(o));return}if(o&&(l=()=>{x(Sc(o))},o.addEventListener("abort",l,{once:!0})),s.then(m,x),t===Number.POSITIVE_INFINITY)return;let y=new Gi;a=i.setTimeout.call(void 0,()=>{if(r){try{m(r())}catch(f){x(f)}return}typeof s.cancel=="function"&&s.cancel(),n===!1?m():n instanceof Error?x(n):(y.message=n??`Promise timed out after ${t} milliseconds`,x(y))},t)}).finally(()=>{p.clear(),l&&o&&o.removeEventListener("abort",l)});return p.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},p}var tf=s=>{let e=s.addEventListener||s.on||s.addListener,t=s.removeEventListener||s.off||s.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(s),removeListener:t.bind(s)}};function sf(s,e,t){let r,n=new Promise((i,o)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),l=[],{addListener:u,removeListener:p}=tf(s),m=async(...y)=>{let f=t.multiArgs?y:y[0];if(t.filter)try{if(!await t.filter(f))return}catch(g){r(),o(g);return}l.push(f),t.count===l.length&&(r(),i(l))},x=(...y)=>{r(),o(t.rejectionMultiArgs?y:y[0])};r=()=>{for(let y of a)p(y,m);for(let y of t.rejectionEvents)a.includes(y)||p(y,x)};for(let y of a)u(y,m);for(let y of t.rejectionEvents)a.includes(y)||u(y,x);t.signal&&t.signal.addEventListener("abort",()=>{x(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(l)});if(n.cancel=r,typeof t.timeout=="number"){let i=Hi(n,{milliseconds:t.timeout});return i.cancel=()=>{r(),i.clear()},i}return n}function _c(s,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let r=sf(s,e,t),n=r.then(i=>i[0]);return n.cancel=r.cancel,n}function rf(s){return s?.addEventListener!=null}function nf(s){let e=Ct(),t,r=o=>{e.push(o.data)},n=()=>{e.end(),s.removeEventListener("message",r),s.removeEventListener("close",i),s.removeEventListener("remoteCloseWrite",n)},i=o=>{e.end(o.error),o.error!=null&&t?.reject(o.error),s.removeEventListener("message",r),s.removeEventListener("close",i),s.removeEventListener("remoteCloseWrite",n)};return s.addEventListener("message",r),s.addEventListener("close",i,{once:!0}),s.addEventListener("remoteCloseWrite",n,{once:!0}),{source:e,async sink(o){async function*a(){yield*o}let l=a();for(;;){t=Promise.withResolvers();let{done:u,value:p}=await Promise.race([l.next(),t.promise]);if(s.writeStatus==="closing"||s.writeStatus==="closed"||(p!=null&&(s.send(p)||await Promise.race([_c(s,"drain",{rejectionEvents:["close"]})])),u===!0))break}await s.close()}}}function Ic(...s){let e=s.map(t=>rf(t)?nf(t):t);return Ns(...e)}var Ur=class{rawStream;constructor(e,t,r){this.rawStream=e,r.maxBufferSize!=null&&(e.maxWriteBufferLength=r.maxBufferSize),e.addEventListener("close",n=>{n.error!=null&&t(n.error)})}get protocol(){return this.rawStream.protocol}push(e){this.pushPrefixed(is.single(e))}pushPrefixed(e){this.rawStream.send(e)}async close(e){await this.rawStream.close(e).catch(t=>{this.rawStream.abort(t)})}},Kr=class{source;rawStream;closeController;constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(r=>{e.abort(r)})}),this.source=Ic(this.rawStream,r=>Fs(r,t))}async close(){this.closeController.abort()}};var zr=class{gossipsubIWantFollowupMs;msgIdToStrFn;metrics;promises=new Map;requestMsByMsg=new Map;requestMsByMsgExpire;constructor(e,t,r){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=r,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){let r=Math.floor(Math.random()*t.length),n=t[r],i=this.msgIdToStrFn(n),o=this.promises.get(i);o==null&&(o=new Map,this.promises.set(i,o));let a=Date.now();o.has(e)||(o.set(e,a+this.gossipsubIWantFollowupMs),this.metrics!=null&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(i)||this.requestMsByMsg.set(i,a)))}getBrokenPromises(){let e=Date.now(),t=new Map,r=0;return this.promises.forEach((n,i)=>{n.forEach((o,a)=>{o<e&&(t.set(a,(t.get(a)??0)+1),n.delete(a),r++)}),n.size===0&&this.promises.delete(i)}),this.metrics?.iwantPromiseBroken.inc(r),t}deliverMessage(e,t=!1){this.trackMessage(e);let r=this.promises.get(e);r!=null&&(this.promises.delete(e),this.metrics!=null&&(this.metrics.iwantPromiseResolved.inc(1),t&&this.metrics.iwantPromiseResolvedFromDuplicate.inc(1),this.metrics.iwantPromiseResolvedPeers.inc(r.size)))}rejectMessage(e,t){this.trackMessage(e),t!==Ee.Error&&this.promises.delete(e)}clear(){this.promises.clear()}prune(){let e=Date.now()-this.requestMsByMsgExpire,t=0;for(let[r,n]of this.requestMsByMsg.entries())if(n<e)this.requestMsByMsg.delete(r),t++;else break;this.metrics?.iwantMessagePruned.inc(t)}trackMessage(e){if(this.metrics!=null){let t=this.requestMsByMsg.get(e);t!==void 0&&(this.metrics.iwantPromiseDeliveryTime.observe((Date.now()-t)/1e3),this.requestMsByMsg.delete(e))}}};var Tc=j("libp2p-pubsub:"),of=BigInt(Date.now())*1000000n;function af(){let s=++of,e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,s,!1),e}async function Dc(s,e,t,r){switch(s.type){case yt.Signing:{let n={from:s.author.toMultihash().bytes,data:r,seqno:af(),topic:e,signature:void 0,key:void 0},i=Et([Tc,rt.Message.encode(n)]);n.signature=await s.privateKey.sign(i),n.key=s.key;let o={type:"signed",from:s.author,data:t,sequenceNumber:BigInt(`0x${$(n.seqno??new Uint8Array(0),"base16")}`),topic:e,signature:n.signature,key:Ci(n.key)};return{raw:n,msg:o}}case yt.Anonymous:return{raw:{from:void 0,data:r,seqno:void 0,topic:e,signature:void 0,key:void 0},msg:{type:"unsigned",data:t,topic:e}};default:throw new Error("Unreachable")}}async function Ac(s,e){switch(s){case Ft:return e.signature!=null?{valid:!1,error:le.SignaturePresent}:e.seqno!=null?{valid:!1,error:le.SeqnoPresent}:e.key!=null?{valid:!1,error:le.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case wt:{if(e.seqno==null)return{valid:!1,error:le.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:le.InvalidSeqno};if(e.signature==null)return{valid:!1,error:le.InvalidSignature};if(e.from==null)return{valid:!1,error:le.InvalidPeerId};let t;try{t=rs(Ye(e.from))}catch{return{valid:!1,error:le.InvalidPeerId}}let r;if(e.key!=null){try{r=Ci(e.key)}catch{return{valid:!1,error:le.InvalidPeerId}}if(!t.equals(r.toMultihash().bytes))return{valid:!1,error:le.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:le.InvalidPeerId};r=t.publicKey}let n={from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0},i=Et([Tc,rt.Message.encode(n)]),o;try{o=await r.verify(i,e.signature)}catch{o=!1}return o?{valid:!0,message:{type:"signed",from:t,data:e.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${$(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:r}}:{valid:!1,error:le.InvalidSignature}}default:throw new Error("Unreachable")}}function ze(s=[],e){return{subscriptions:[],messages:s,control:e!==void 0?{graft:e.graft??[],prune:e.prune??[],ihave:e.ihave??[],iwant:e.iwant??[],idontwant:e.idontwant??[]}:void 0}}function Wi(s){return s.control===void 0&&(s.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),s}function Ze(s){if(s.length<=1)return s;let e=()=>Math.floor(Math.random()*Math.floor(s.length));for(let t=0;t<s.length;t++){let r=e(),n=s[t];s[t]=s[r],s[r]=n}return s}function Mc(s){return $(s,"base64")}function Pc(s,e,t){switch(s){case wt:return{type:yt.Signing,author:e,key:We(t.publicKey),privateKey:t};case Ft:return{type:yt.Anonymous};default:throw new Error(`Unknown signature policy "${s}"`)}}var cf=(s,e)=>{let t=j(e.toString(16).padStart(16,"0"),"base16"),r=We(s),n=new Uint8Array(r.byteLength+t.length);return n.set(r,0),n.set(t,r.byteLength),n};function Bc(s){if(s.type!=="signed")throw new Error("expected signed message type");if(s.sequenceNumber==null)throw Error("missing seqno field");return cf(s.from.publicKey??s.key,s.sequenceNumber)}async function kc(s){return St.encode(s.data)}function Rc(s){if(Ec(s)){let e=vc(s);switch(e.type){case"ip4":case"ip6":return e.host;default:break}}return null}var us=class{entries=new Map;validityMs;constructor(e){this.validityMs=e.validityMs}get size(){return this.entries.size}put(e,t){return this.entries.has(e)?!0:(this.entries.set(e,{value:t,validUntilMs:Date.now()+this.validityMs}),!1)}prune(){let e=Date.now();for(let[t,r]of this.entries.entries())if(r.validUntilMs<e)this.entries.delete(t);else break}has(e){return this.entries.has(e)}get(e){let t=this.entries.get(e);return t!=null&&t.validUntilMs>=Date.now()?t.value:void 0}clear(){this.entries.clear()}};var Pe;(function(s){s[s.started=0]="started",s[s.stopped=1]="stopped"})(Pe||(Pe={}));var qr=class extends zs{globalSignaturePolicy;protocols=[Ot,ji,Wr];publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=Ct({objectMode:!0});direct=new Set;floodsubPeers=new Set;seenCache;acceptFromWhitelist=new Map;topics=new Map;subscriptions=new Set;mesh=new Map;fanout=new Map;fanoutLastpub=new Map;gossip=new Map;control=new Map;peerhave=new Map;iasked=new Map;iwantCounts=new Map;backoff=new Map;outbound=new Map;msgIdFn;fastMsgIdFn;msgIdToStrFn;fastMsgIdCache;publishedMessageIds;mcache;score;topicValidators=new Map;log;heartbeatTicks=0;gossipTracer;idontwantCounts=new Map;idontwants=new Map;components;directPeerInitial=null;static multicodec=Ot;opts;decodeRpcLimits;metrics;status={code:Pe.stopped};maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;allowedTopics;maxTopicBytesPerPeer;peerTopicBytes=new Map;heartbeatTimer=null;constructor(e,t={}){super();let r={fallbackToFloodsub:!0,floodPublish:!0,batchPublish:!1,tagMeshPeers:!0,doPX:!1,directPeers:[],D:6,Dlo:4,Dhi:12,Dscore:4,Dout:2,Dlazy:6,heartbeatInterval:1e3,fanoutTTL:6e4,mcacheLength:5,mcacheGossip:3,seenTTL:12e4,gossipsubIWantFollowupMs:3e3,prunePeers:16,pruneBackoff:6e4,unsubcribeBackoff:1e4,graftFloodThreshold:1e4,opportunisticGraftPeers:2,opportunisticGraftTicks:60,directConnectTicks:300,gossipFactor:.25,idontwantMinDataSize:512,idontwantMaxMessages:512,...t,scoreParams:fc(t.scoreParams),scoreThresholds:pc(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=r.decodeRpcLimits??cc,this.globalSignaturePolicy=r.globalSignaturePolicy??wt,r.fallbackToFloodsub&&this.protocols.push(Hr),this.log=e.logger.forComponent(r.debugName??"libp2p:gossipsub"),this.opts=r,this.direct=new Set(r.directPeers.map(n=>n.id.toString())),this.seenCache=new us({validityMs:r.seenTTL}),this.publishedMessageIds=new us({validityMs:r.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case wt:this.msgIdFn=Bc;break;case Ft:this.msgIdFn=kc;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new us({validityMs:r.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??Mc,this.mcache=t.messageCache??new Lr(r.mcacheGossip,r.mcacheLength,this.msgIdToStrFn),t.dataTransform!=null&&(this.dataTransform=t.dataTransform),t.metricsRegister!=null){if(t.metricsTopicStrToLabel==null)throw Error("Must set metricsTopicStrToLabel with metrics");let n=Math.max(...Object.values(r.scoreParams.topics).map(o=>o.meshMessageDeliveriesWindow),1e3),i=hc(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:r.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:n/1e3});i.mcacheSize.addCollect(()=>{this.onScrapeMetrics(i)});for(let o of this.protocols)i.protocolsEnabled.set({protocol:o},1);this.metrics=i}else this.metrics=null;this.gossipTracer=new zr(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new Or(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:r.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnLimitedConnection=t.runOnLimitedConnection,this.allowedTopics=r.allowedTopics!=null?new Set(r.allowedTopics):null,this.maxTopicBytesPerPeer=r.maxTopicBytesPerPeer??1048576}[Symbol.toStringTag]="@libp2p/gossipsub";[Qi]=["@libp2p/pubsub"];[eo]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===Pe.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=Pc(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=Ct({objectMode:!0}),Ns(this.outboundInflightQueue,async i=>{for await(let{peerId:o,connection:a}of i)await this.createOutboundStream(o,a)}).catch(i=>{this.log.error("outbound inflight queue error",i)}),await Promise.all(this.opts.directPeers.map(async i=>{await this.components.peerStore.merge(i.id,{multiaddrs:i.addrs})}));let e=this.components.registrar;await Promise.all(this.protocols.map(async i=>e.handle(i,this.onIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection})));let t={onConnect:this.onPeerConnected.bind(this),onDisconnect:this.onPeerDisconnected.bind(this),notifyOnLimitedConnection:this.runOnLimitedConnection},r=await Promise.all(this.protocols.map(async i=>e.register(i,t))),n=setTimeout(this.runHeartbeat,100);this.status={code:Pe.started,registrarTopologyIds:r,heartbeatTimeout:n,hearbeatStartMs:Date.now()+100},this.score.start(),this.directPeerInitial=setTimeout(()=>{Promise.resolve().then(async()=>{await Promise.all(Array.from(this.direct).map(async i=>this.connect(i)))}).catch(i=>{this.log(i)})},1e3),this.opts.tagMeshPeers&&(this.addEventListener("gossipsub:graft",this.tagMeshPeer),this.addEventListener("gossipsub:prune",this.untagMeshPeer)),this.log("started")}async stop(){if(this.log("stopping"),this.status.code!==Pe.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:Pe.stopped},this.opts.tagMeshPeers&&(this.removeEventListener("gossipsub:graft",this.tagMeshPeer),this.removeEventListener("gossipsub:prune",this.untagMeshPeer));let t=this.components.registrar;await Promise.all(this.protocols.map(async n=>t.unhandle(n))),e.forEach(n=>{t.unregister(n)}),this.outboundInflightQueue.end();let r=[];for(let n of this.streamsOutbound.values())r.push(n.close());this.streamsOutbound.clear();for(let n of this.streamsInbound.values())r.push(n.close());this.streamsInbound.clear(),await Promise.all(r),this.peers.clear(),this.subscriptions.clear(),this.topics.clear(),this.peerTopicBytes.clear(),this.heartbeatTimer!=null&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.iwantCounts.clear(),this.backoff.clear(),this.outbound.clear(),this.gossipTracer.clear(),this.seenCache.clear(),this.fastMsgIdCache!=null&&this.fastMsgIdCache.clear(),this.directPeerInitial!=null&&clearTimeout(this.directPeerInitial),this.idontwantCounts.clear(),this.idontwants.clear(),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream(e,t){if(!this.isStarted())return;let r=t.remotePeer;this.addPeer(r,t.direction,t.remoteAddr),this.createInboundStream(r,e),this.outboundInflightQueue.push({peerId:r,connection:t})}onPeerConnected(e,t){this.metrics?.newConnectionCount.inc({status:t.status}),!(!this.isStarted()||t.status!=="open")&&(this.addPeer(e,t.direction,t.remoteAddr),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}async createOutboundStream(e,t){if(!this.isStarted())return;let r=e.toString();if(this.peers.has(r)&&!this.streamsOutbound.has(r))try{let n=await t.newStream(this.protocols,{runOnLimitedConnection:this.runOnLimitedConnection}),i=new Ur(n,a=>{this.log.error("outbound pipe error",a)},{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(r,i);let o=i.protocol;o===Hr&&this.floodsubPeers.add(r),this.metrics?.peersPerProtocol.inc({protocol:o},1),n.addEventListener("close",()=>{this.streamsOutbound.get(r)===i&&(this.streamsOutbound.delete(r),this.floodsubPeers.delete(r),this.metrics?.peersPerProtocol.inc({protocol:o},-1))},{once:!0}),this.subscriptions.size>0&&(this.log("send subscriptions to",r),this.sendSubscriptions(r,Array.from(this.subscriptions),!0))}catch(n){this.log.error("createOutboundStream error",n)}}createInboundStream(e,t){if(!this.isStarted())return;let r=e.toString();if(!this.peers.has(r))return;let n=this.streamsInbound.get(r);n!==void 0&&(this.log("replacing existing inbound steam %s",r),n.close().catch(o=>{this.log.error(o)})),this.log("create inbound stream %s",r);let i=new Kr(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(r,i),this.pipePeerReadStream(e,i.source).catch(o=>{this.log(o)})}addPeer(e,t,r){let n=e.toString();if(!this.peers.has(n)){this.peers.set(n,e),this.score.addPeer(n);let i=Rc(r);i!==null?this.score.addIP(n,i):this.log("Added peer has no IP in current address %s %s",n,r.toString()),this.outbound.has(n)||this.outbound.set(n,t==="outbound")}}removePeer(e){let t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);let r=this.streamsOutbound.get(t),n=this.streamsInbound.get(t);r!=null&&this.metrics?.peersPerProtocol.inc({protocol:r.protocol},-1),r?.close().catch(i=>{this.log.error(i)}),n?.close().catch(i=>{this.log.error(i)}),this.streamsOutbound.delete(t),this.streamsInbound.delete(t);for(let[i,o]of this.topics)o.delete(t),o.size===0&&this.topics.delete(i);this.peerTopicBytes.delete(t);for(let[i,o]of this.mesh)o.delete(t)&&this.metrics?.onRemoveFromMesh(i,Ke.Dc,1);for(let i of this.fanout.values())i.delete(t);this.floodsubPeers.delete(t),this.gossip.delete(t),this.control.delete(t),this.outbound.delete(t),this.idontwantCounts.delete(t),this.idontwants.delete(t),this.score.removePeer(t),this.acceptFromWhitelist.delete(t)}get started(){return this.status.code===Pe.started}getMeshPeers(e){let t=this.mesh.get(e);return t!=null?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(t!=null?Array.from(t):[]).map(r=>this.peers.get(r)??Rt(r))}getTopics(){return Array.from(this.subscriptions)}decodeRpc(e){return rt.decode(e,{limits:{subscriptions:this.decodeRpcLimits.maxSubscriptions,messages:this.decodeRpcLimits.maxMessages,control:{ihave:this.decodeRpcLimits.maxControlMessages,ihave$:{messageIDs:this.decodeRpcLimits.maxIhaveMessageIDs},iwant:this.decodeRpcLimits.maxControlMessages,iwant$:{messageIDs:this.decodeRpcLimits.maxIwantMessageIDs},graft:this.decodeRpcLimits.maxControlMessages,prune:this.decodeRpcLimits.maxControlMessages,prune$:{peers:this.decodeRpcLimits.maxPeerInfos},idontwant:this.decodeRpcLimits.maxControlMessages,idontwant$:{messageIDs:this.decodeRpcLimits.maxIdontwantMessageIDs}}}})}async pipePeerReadStream(e,t){try{await Ns(t,async r=>{for await(let n of r)try{let i=n.subarray(),o=this.decodeRpc(i);if(this.metrics?.onRpcRecv(o,i.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,o)}catch(a){this.metrics?.onRpcRecvError(),this.log(a)}else this.handleReceivedRpc(e,o).catch(a=>{this.metrics?.onRpcRecvError(),this.log(a)})}catch(i){this.metrics?.onRpcDataError(),this.log(i)}})}catch(r){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(r,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){if(!this.acceptFrom(e.toString())){this.log("received message from unacceptable peer %p",e),this.metrics?.rpcRecvNotAccepted.inc();return}let r=t.subscriptions!=null?t.subscriptions.length:0,n=t.messages!=null?t.messages.length:0,i=0,o=0,a=0,l=0;if(t.control!=null&&(t.control.ihave!=null&&(i=t.control.ihave.length),t.control.iwant!=null&&(o=t.control.iwant.length),t.control.graft!=null&&(a=t.control.graft.length),t.control.prune!=null&&(l=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${r} messages ${n} ihave ${i} iwant ${o} graft ${a} prune ${l}`),t.subscriptions!=null&&t.subscriptions.length>0){let u=[],p=e.toString(),m=[];t.subscriptions.forEach(x=>{let y=x.topic,f=x.subscribe===!0;if(y!=null){if(this.allowedTopics!=null&&!this.allowedTopics.has(y)||!this.handleReceivedSubscription(e,y,f))return;f&&this.graftOnSubscribe(p,y)&&m.push(y),u.push({topic:y,subscribe:f})}}),m.length>0&&this.sendGraft(p,m),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:u}})}for(let u of t.messages){if(this.allowedTopics!=null&&!this.allowedTopics.has(u.topic))continue;let p=this.handleReceivedMessage(e,u).catch(m=>{this.metrics?.onMsgRecvError(u.topic),this.log(m)});this.opts.awaitRpcMessageHandler&&await p}t.control!=null&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,r){this.log("subscription update from %p topic %s",e,t);let n=e.toString(),i=this.topics.get(t),o=t.length+1024;if(r){if(i?.has(n)===!0)return!0;let a=this.peerTopicBytes.get(n)??0;if(a+o>this.maxTopicBytesPerPeer)return this.log("ignoring subscription from %p topic %s, over per-peer topic budget",e,t),!1;this.peerTopicBytes.set(n,a+o),i==null&&(i=new Set,this.topics.set(t,i)),i.add(n)}else i?.has(n)===!0&&(i.delete(n),this.peerTopicBytes.set(n,Math.max(0,(this.peerTopicBytes.get(n)??0)-o)),i.size===0&&this.topics.delete(t));return!0}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);let r=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,r.code);let n=r.code;switch(n){case pe.duplicate:this.score.duplicateMessage(e.toString(),r.msgIdStr,t.topic),this.gossipTracer.deliverMessage(r.msgIdStr,!0),this.mcache.observeDuplicate(r.msgIdStr,e.toString());return;case pe.invalid:if(r.msgIdStr!=null){let i=r.msgIdStr;this.score.rejectMessage(e.toString(),i,t.topic,r.reason),this.gossipTracer.rejectMessage(i,r.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);this.metrics?.onMsgRecvInvalid(t.topic,r);return;case pe.valid:this.score.validateMessage(r.messageId.msgIdStr),this.gossipTracer.deliverMessage(r.messageId.msgIdStr),this.mcache.put(r.messageId,t,!this.opts.asyncValidation),this.subscriptions.has(t.topic)&&(!this.components.peerId.equals(e)||this.opts.emitSelf)&&(super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:e,msgId:r.messageId.msgIdStr,msg:r.msg}})),super.dispatchEvent(new CustomEvent("message",{detail:r.msg}))),this.opts.asyncValidation||this.forwardMessage(r.messageId.msgIdStr,t,e.toString());break;default:throw new Error(`Invalid validation result: ${n}`)}}async validateReceivedMessage(e,t){let r=this.fastMsgIdFn?.(t),n=r!==void 0?this.fastMsgIdCache?.get(r):void 0;if(n!=null)return{code:pe.duplicate,msgIdStr:n};let i=await Ac(this.globalSignaturePolicy,t);if(!i.valid)return{code:pe.invalid,reason:Ee.Error,error:i.error};let o=i.message;try{this.dataTransform!=null&&(o.data=this.dataTransform.inboundTransform(t.topic,o.data))}catch(m){return this.log("Invalid message, transform failed",m),{code:pe.invalid,reason:Ee.Error,error:le.TransformFailed}}let a=await this.msgIdFn(o),l=this.msgIdToStrFn(a),u={msgId:a,msgIdStr:l};if(r!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(r,l)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(l))return{code:pe.duplicate,msgIdStr:l};this.seenCache.put(l),(t.data?.length??0)>=this.opts.idontwantMinDataSize&&this.sendIDontWants(a,t.topic,e.toString());let p=this.topicValidators.get(t.topic);if(p!=null){let m;try{m=await p(e,o)}catch(x){let y=x.code;y===Yi&&(m=me.Ignore),y===Zi?m=me.Reject:m=me.Ignore}if(m!==me.Accept)return{code:pe.invalid,reason:zi(m),msgIdStr:l}}return{code:pe.valid,messageId:u,msg:o}}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,r){this.sendRpc(e,{subscriptions:t.map(n=>({topic:n,subscribe:r})),messages:[]})}async handleControlMessage(e,t){if(t===void 0)return;let r=t.ihave?.length>0?this.handleIHave(e,t.ihave):[],n=t.iwant?.length>0?this.handleIWant(e,t.iwant):[],i=t.graft?.length>0?await this.handleGraft(e,t.graft):[];if(t.prune?.length>0&&await this.handlePrune(e,t.prune),t.idontwant?.length>0&&this.handleIdontwant(e,t.idontwant),r.length===0&&n.length===0&&i.length===0)return;let o=this.sendRpc(e,ze(n,{iwant:r,prune:i})),a=r[0]?.messageIDs;a!=null&&(o?this.gossipTracer.addPromise(e,a):this.metrics?.iwantPromiseUntracked.inc(1))}acceptFrom(e){if(this.direct.has(e))return!0;let t=Date.now(),r=this.acceptFromWhitelist.get(e);if(r!=null&&r.messagesAccepted<128&&r.acceptUntil>=t)return r.messagesAccepted+=1,!0;let n=this.score.score(e);return n>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),n>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){if(t.length===0)return[];let r=this.score.score(e);if(r<this.opts.scoreThresholds.gossipThreshold)return this.log("IHAVE: ignoring peer %s with score below threshold [ score = %d ]",e,r),this.metrics?.ihaveRcvIgnored.inc({reason:ls.LowScore}),[];let n=(this.peerhave.get(e)??0)+1;if(this.peerhave.set(e,n),n>10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:ls.MaxIhave}),[];let i=this.iasked.get(e)??0;if(i>=5e3)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,i),this.metrics?.ihaveRcvIgnored.inc({reason:ls.MaxIasked}),[];let o=new Map,a=0;e:for(let{topicID:p,messageIDs:m}of t){if(p==null||m==null||!this.mesh.has(p))continue;let x=0;for(let y of m){if(a>=5e3)break e;a++;let f=this.msgIdToStrFn(y);this.seenCache.has(f)||(o.set(f,y),x++)}this.metrics?.onIhaveRcv(p,m.length,x)}if(o.size===0)return[];let l=o.size;l+i>5e3&&(l=5e3-i),this.log("IHAVE: Asking for %d out of %d messages from %s",l,o.size,e);let u=Array.from(o.values());return Ze(u),u=u.slice(0,l),this.iasked.set(e,i+l),[{messageIDs:u}]}handleIWant(e,t){if(t.length===0)return[];let r=this.score.score(e);if(r<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,r),[];let n=(this.iwantCounts.get(e)??0)+1;if(this.iwantCounts.set(e,n),n>10)return this.log("IWANT: peer %s has requested too many times within this heartbeat interval; ignoring",e),[];let i=new Map,o=new Map,a=0,l=0;e:for(let{messageIDs:u}of t)if(u!=null)for(let p of u){if(l>=5e3)break e;l++;let m=this.msgIdToStrFn(p),x=this.mcache.getWithIWantCount(m,e);if(x==null){a++;continue}if(o.set(x.msg.topic,1+(o.get(x.msg.topic)??0)),x.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,p);continue}i.set(m,x.msg)}return this.metrics?.onIwantRcv(o,a),i.size===0?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",i.size,e),Array.from(i.values()))}async handleGraft(e,t){let r=[],n=this.score.score(e),i=Date.now(),o=this.opts.doPX;if(t.forEach(({topicID:l})=>{if(l==null)return;let u=this.mesh.get(l);if(u==null){o=!1;return}if(u.has(e))return;let p=this.backoff.get(l)?.get(e);if(this.direct.has(e))this.log("GRAFT: ignoring request from direct peer %s",e),r.push(l),o=!1;else if(typeof p=="number"&&i<p){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,cs.GraftBackoff),o=!1;let m=p+this.opts.graftFloodThreshold-this.opts.pruneBackoff;i<m&&this.score.addPenalty(e,1,cs.GraftBackoff),this.addBackoff(e,l),r.push(l)}else n<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,n,l),r.push(l),o=!1,this.addBackoff(e,l)):u.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(r.push(l),this.addBackoff(e,l)):(this.log("GRAFT: Add mesh link from %s in %s",e,l),this.addToMesh(e,l,ge.Subscribed));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:l,direction:"inbound"}})}),r.length===0)return[];let a=!1;return Promise.all(r.map(async l=>this.makePrune(e,l,o,a)))}async handlePrune(e,t){let r=this.score.score(e);for(let{topicID:n,backoff:i,peers:o}of t){if(n==null)continue;let a=this.mesh.get(n);if(a==null)return;this.log("PRUNE: Remove mesh link to %s in %s",e,n),this.score.prune(e,n),a.has(e)&&(a.delete(e),this.metrics?.onRemoveFromMesh(n,Ke.Prune,1)),typeof i=="number"&&i>0?this.doAddBackoff(e,n,i*1e3):this.addBackoff(e,n),o!=null&&o.length>0&&(r<this.opts.scoreThresholds.acceptPXThreshold?this.log("PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]",e,r,n):await this.pxConnect(o)),this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:n,direction:"inbound"}})}}handleIdontwant(e,t){let r=this.idontwantCounts.get(e)??0;if(r>=this.opts.idontwantMaxMessages)return;let n=r,i=this.idontwants.get(e);i==null&&(i=new Map,this.idontwants.set(e,i));let o=0;e:for(let{messageIDs:l}of t)for(let u of l){if(r>=this.opts.idontwantMaxMessages)break e;r++;let p=this.msgIdToStrFn(u);i.set(p,this.heartbeatTicks),this.mcache.msgs.has(p)||o++}this.idontwantCounts.set(e,r);let a=r-n;this.metrics?.onIdontwantRcv(a,o)}addBackoff(e,t){this.doAddBackoff(e,t,this.opts.pruneBackoff)}doAddBackoff(e,t,r){let n=this.backoff.get(t);n==null&&(n=new Map,this.backoff.set(t,n));let i=Date.now()+r;(n.get(e)??0)<i&&n.set(e,i)}applyIwantPenalties(){this.gossipTracer.getBrokenPromises().forEach((e,t)=>{this.log("peer %s didn't follow up in %d IWANT requests; adding penalty",t,e),this.score.addPenalty(t,e,cs.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!==0)return;let e=Date.now();this.backoff.forEach((t,r)=>{t.forEach((n,i)=>{n+1*this.opts.heartbeatInterval<e&&t.delete(i)}),t.size===0&&this.backoff.delete(r)})}async directConnect(){let e=[];this.direct.forEach(t=>{this.streamsOutbound.has(t)||e.push(t)}),await Promise.all(e.map(async t=>this.connect(t)))}async pxConnect(e){e.length>this.opts.prunePeers&&(Ze(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async r=>{if(r.peerID==null)return;let n=rs(Ye(r.peerID)),i=n.toString();if(!this.peers.has(i)){if(r.signedPeerRecord==null){t.push(i);return}try{if(!await this.components.peerStore.consumePeerRecord(r.signedPeerRecord,{expectedPeer:n})){this.log("bogus peer record obtained through px: could not add peer record to address book");return}t.push(i)}catch{this.log("bogus peer record obtained through px: invalid signature or not a peer record")}}})),t.length!==0&&await Promise.all(t.map(async r=>this.connect(r)))}async connect(e){this.log("Initiating connection with %s",e);let t=Rt(e),r=await this.components.connectionManager.openConnection(t);for(let n of this.protocols)for(let i of this.components.registrar.getTopologies(n))i.onConnect?.(t,r)}subscribe(e){if(this.status.code!==Pe.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(let t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==Pe.started)throw new Error("Pubsub is not started");let t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(let r of this.peers.keys())this.sendSubscriptions(r,[e],!1);this.leave(e)}join(e){if(this.status.code!==Pe.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);let t=new Set,r=this.backoff.get(e),n=this.fanout.get(e);if(n!=null&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),n.forEach(i=>{!this.direct.has(i)&&this.score.score(i)>=0&&r?.has(i)!==!0&&t.add(i)}),this.metrics?.onAddToMesh(e,ge.Fanout,t.size)),t.size<this.opts.D){let i=t.size;this.getRandomGossipPeers(e,this.opts.D,a=>!t.has(a)&&!this.direct.has(a)&&this.score.score(a)>=0&&r?.has(a)!==!0).forEach(a=>{t.add(a)}),this.metrics?.onAddToMesh(e,ge.Random,t.size-i)}this.mesh.set(e,t),t.forEach(i=>{this.log("JOIN: Add mesh link to %s in %s",i,e),this.sendGraft(i,[e])})}leave(e){if(this.status.code!==Pe.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);let t=this.mesh.get(e);t!=null&&(Promise.all(Array.from(t).map(async r=>{this.log("LEAVE: Remove mesh link to %s in %s",r,e),await this.sendPrune(r,e)})).catch(r=>{this.log("Error sending prunes to mesh peers",r)}),this.mesh.delete(e))}selectPeersToForward(e,t,r){let n=new Set,i=this.topics.get(e);i!=null&&(this.direct.forEach(a=>{i.has(a)&&t!==a&&!(r?.has(a)??!1)&&n.add(a)}),this.floodsubPeers.forEach(a=>{i.has(a)&&t!==a&&!(r?.has(a)??!1)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&n.add(a)}));let o=this.mesh.get(e);return o!=null&&o.size>0&&o.forEach(a=>{t!==a&&!(r?.has(a)??!1)&&n.add(a)}),n}selectPeersToPublish(e){let t=new Set,r={direct:0,floodsub:0,mesh:0,fanout:0},n=this.topics.get(e);if(n!=null)if(this.opts.floodPublish)n.forEach(i=>{this.direct.has(i)?(t.add(i),r.direct++):this.score.score(i)>=this.opts.scoreThresholds.publishThreshold&&(t.add(i),r.floodsub++)});else{this.direct.forEach(o=>{n.has(o)&&(t.add(o),r.direct++)}),this.floodsubPeers.forEach(o=>{n.has(o)&&this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),r.floodsub++)});let i=this.mesh.get(e);if(i!=null&&i.size>0)i.forEach(o=>{t.add(o),r.mesh++}),i.size<this.opts.D&&this.getRandomGossipPeers(e,this.opts.D-i.size,a=>!i.has(a)&&!this.direct.has(a)&&!this.floodsubPeers.has(a)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold).forEach(a=>{t.add(a),r.mesh++});else{let o=this.fanout.get(e);if(o!=null&&o.size>0)o.forEach(a=>{t.add(a),r.fanout++});else{let a=this.getRandomGossipPeers(e,this.opts.D,l=>this.score.score(l)>=this.opts.scoreThresholds.publishThreshold);a.size>0&&(this.fanout.set(e,a),a.forEach(l=>{t.add(l),r.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:r}}forwardMessage(e,t,r,n){r!=null&&this.score.deliverMessage(r,e,t.topic);let i=this.selectPeersToForward(t.topic,r,n);i.forEach(o=>{this.sendRpc(o,ze([t]))}),this.metrics?.onForwardMsg(t.topic,i.size)}async publish(e,t,r){let n=Date.now(),i=this.dataTransform!=null?this.dataTransform.outboundTransform(e,t):t;if(this.publishConfig==null)throw Error("PublishError.Uninitialized");let{raw:o,msg:a}=await Dc(this.publishConfig,e,t,i),l=await this.msgIdFn(a),u=this.msgIdToStrFn(l),p=r?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(u)){if(p)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:m,tosendCount:x}=this.selectPeersToPublish(e),y=this.opts.emitSelf&&this.subscriptions.has(e),f=r?.allowPublishToZeroTopicPeers??this.opts.allowPublishToZeroTopicPeers;if(m.size===0&&!f&&!y)throw Error("PublishError.NoPeersSubscribedToTopic");this.seenCache.put(u),this.mcache.put({msgId:l,msgIdStr:u},o,!0),this.gossipTracer.deliverMessage(u),this.publishedMessageIds.put(u);let g=r?.batchPublish??this.opts.batchPublish,w=ze([o]);if(g)this.sendRpcInBatch(m,w);else for(let S of m)this.sendRpc(S,w)||m.delete(S);let E=Date.now()-n;return this.metrics?.onPublishMsg(e,x,m.size,o.data!=null?o.data.length:0,E),y&&(m.add(this.components.peerId.toString()),super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:u,msg:a}})),super.dispatchEvent(new CustomEvent("message",{detail:a}))),{recipients:Array.from(m.values()).map(S=>this.peers.get(S)??Rt(S))}}sendRpcInBatch(e,t){let r=rt.encode(t),n=is.single(r);for(let i of e){let o=this.streamsOutbound.get(i);if(o==null){this.log(`Cannot send RPC to ${i} as there is no open stream to it available`),e.delete(i);continue}try{o.pushPrefixed(n)}catch(a){e.delete(i),this.log.error(`Cannot send rpc to ${i}`,a)}this.metrics?.onRpcSent(t,r.length)}}reportMessageValidationResult(e,t,r){let n;if(r===me.Accept){if(n=this.mcache.validate(e),n!=null){let{message:o,originatingPeers:a}=n;this.score.deliverMessage(t,e,o.topic),this.forwardMessage(e,n.message,t,a)}}else if(n=this.mcache.remove(e),n!=null){let o=zi(r),{message:a,originatingPeers:l}=n;this.score.rejectMessage(t,e,a.topic,o);for(let u of l)this.score.rejectMessage(u,e,a.topic,o)}let i=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(n,r,i)}sendGraft(e,t){let r=t.map(i=>({topicID:i})),n=ze([],{graft:r});this.sendRpc(e,n)}addToMesh(e,t,r){this.score.graft(e,t),this.mesh.get(t)?.add(e),this.metrics?.onAddToMesh(t,r,1)}graftOnSubscribe(e,t){let r=this.mesh.get(t);if(r==null||r.has(e)||r.size>=this.opts.Dlo)return!1;let n=this.streamsOutbound.get(e);return n==null||!this.protocols.includes(n.protocol)||this.direct.has(e)||this.score.score(e)<0||(this.backoff.get(t)?.has(e)??!1)?!1:(this.addToMesh(e,t,ge.Subscribed),!0)}async sendPrune(e,t){let n=[await this.makePrune(e,t,this.opts.doPX,!0)],i=ze([],{prune:n});this.sendRpc(e,i)}sendIDontWants(e,t,r){let n=this.mesh.get(t);if(n==null)return;let i=new Set(n);i.delete(r);for(let a of i)this.streamsOutbound.get(a)?.protocol!==Ot&&i.delete(a);let o=ze([],{idontwant:[{messageIDs:[e]}]});this.sendRpcInBatch(i,o)}sendRpc(e,t){let r=this.streamsOutbound.get(e);if(r==null)return this.log(`Cannot send RPC to ${e} as there is no open stream to it available`),!1;let n=this.control.get(e);n!=null&&(this.piggybackControl(e,t,n),this.control.delete(e));let i=this.gossip.get(e);i!=null&&(this.piggybackGossip(e,t,i),this.gossip.delete(e));let o=rt.encode(t);try{r.push(o)}catch(a){return this.log.error(`Cannot send rpc to ${e}`,a),n!=null&&this.control.set(e,n),i!=null&&this.gossip.set(e,i),!1}if(this.metrics?.onRpcSent(t,o.length),t.control?.graft!=null)for(let a of t.control?.graft)a.topicID!=null&&this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:a.topicID,direction:"outbound"}});if(t.control?.prune!=null)for(let a of t.control?.prune)a.topicID!=null&&this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:a.topicID,direction:"outbound"}});return!0}piggybackControl(e,t,r){let n=Wi(t);for(let i of r.graft)i.topicID!=null&&(this.mesh.get(i.topicID)?.has(e)??!1)&&n.control.graft.push(i);for(let i of r.prune)i.topicID!=null&&!(this.mesh.get(i.topicID)?.has(e)??!1)&&n.control.prune.push(i)}piggybackGossip(e,t,r){let n=Wi(t);n.control.ihave=r}async sendGraftPrune(e,t,r){let n=this.opts.doPX,i=!1;for(let[o,a]of e){let l=a.map(m=>({topicID:m})),u=[],p=t.get(o);p!=null&&(u=await Promise.all(p.map(async m=>this.makePrune(o,m,n&&!(r.get(o)??!1),i))),t.delete(o)),this.sendRpc(o,ze([],{graft:l,prune:u}))}for(let[o,a]of t){let l=await Promise.all(a.map(async u=>this.makePrune(o,u,n&&!(r.get(o)??!1),i)));this.sendRpc(o,ze([],{prune:l}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[r,n]of e)this.doEmitGossip(r,n,t.get(r)??[])}doEmitGossip(e,t,r){if(r.length===0||(Ze(r),r.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",r.length),t.size===0))return;let n=this.opts.Dlazy,o=this.opts.gossipFactor*t.size,a=t;o>n&&(n=o),n>a.size?n=a.size:a=Ze(Array.from(a)).slice(0,n),a.forEach(l=>{let u=r;r.length>5e3&&(u=Ze(u.slice()).slice(0,5e3)),this.pushGossip(l,{topicID:e,messageIDs:u})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,ze([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let r=ze([],{graft:t.graft,prune:t.prune});this.sendRpc(e,r)}}pushGossip(e,t){this.log("Add gossip to %s",e);let r=this.gossip.get(e)??[];this.gossip.set(e,r.concat(t))}async makePrune(e,t,r,n){if(this.score.prune(e,t),this.streamsOutbound.get(e)?.protocol===Wr)return{topicID:t,peers:[]};let i=n?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,o=i/1e3;if(this.doAddBackoff(e,t,i),!r)return{topicID:t,peers:[],backoff:o};let a=this.getRandomGossipPeers(t,this.opts.prunePeers,u=>u!==e&&this.score.score(u)>=0),l=await Promise.all(Array.from(a).map(async u=>{let p=this.peers.get(u)??Rt(u),m;try{m=await this.components.peerStore.get(p)}catch(x){if(x.name!=="NotFoundError")throw x}return{peerID:p.toMultihash().bytes,signedPeerRecord:m?.peerRecordEnvelope}}));return{topicID:t,peers:l,backoff:o}}runHeartbeat=()=>{let e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch(t=>{this.log("Error running heartbeat",t)}).finally(()=>{if(e?.(),this.status.code===Pe.started){clearTimeout(this.status.heartbeatTimeout);let t=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;t<this.opts.heartbeatInterval*.25&&(t+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,t)}})};async heartbeat(){let{D:e,Dlo:t,Dhi:r,Dscore:n,Dout:i,fanoutTTL:o}=this.opts;this.heartbeatTicks++;let a=new Map,l=f=>{let g=a.get(f);return g===void 0&&(g=this.score.score(f),a.set(f,g)),g},u=new Map,p=new Map,m=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.iwantCounts.clear(),this.applyIwantPenalties(),this.idontwantCounts.clear();for(let f of this.idontwants.values())for(let[g,w]of f)this.heartbeatTicks-w>=this.opts.mcacheLength&&f.delete(g);this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let x=new Map;this.mesh.forEach((f,g)=>{let w=this.topics.get(g),E=new Set,S=new Set;if(x.set(g,S),w!=null){let d=Ze(Array.from(w)),b=this.backoff.get(g);for(let v of d){let _=this.streamsOutbound.get(v);if(_!=null&&this.protocols.includes(_.protocol)&&!f.has(v)&&!this.direct.has(v)){let D=l(v);b?.has(v)!==!0&&D>=0&&E.add(v),D>=this.opts.scoreThresholds.gossipThreshold&&S.add(v)}}}let c=(d,b)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",d,g),this.addBackoff(d,g),f.delete(d),l(d)>=this.opts.scoreThresholds.gossipThreshold&&S.add(d),this.metrics?.onRemoveFromMesh(g,b,1);let v=p.get(d);v==null?p.set(d,[g]):v.push(g)},h=(d,b)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",d,g),this.addToMesh(d,g,b),S.delete(d);let v=u.get(d);v==null?u.set(d,[g]):v.push(g)};if(f.forEach(d=>{let b=l(d);b<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",d,b,g),c(d,Ke.BadScore),m.set(d,!0))}),f.size<t){let d=e-f.size;mc(E,d).forEach(v=>{h(v,ge.NotEnough)})}if(f.size>r){let d=Array.from(f);d.sort((v,_)=>l(_)-l(v)),d=d.slice(0,n).concat(Ze(d.slice(n)));let b=0;if(d.slice(0,e).forEach(v=>{(this.outbound.get(v)??!1)&&b++}),b<i){let v=D=>{let P=d[D];for(let K=D;K>0;K--)d[K]=d[K-1];d[0]=P};if(b>0){let D=b;for(let P=1;P<e&&D>0;P++)(this.outbound.get(d[P])??!1)&&(v(P),D--)}let _=e-b;for(let D=e;D<d.length&&_>0;D++)(this.outbound.get(d[D])??!1)&&(v(D),_--)}d.slice(e).forEach(v=>{c(v,Ke.Excess)})}if(f.size>=t){let d=0;if(f.forEach(b=>{(this.outbound.get(b)??!1)&&d++}),d<i){let b=i-d;Fr(E,b,_=>this.outbound.get(_)===!0).forEach(_=>{h(_,ge.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&f.size>1){let d=Array.from(f).sort((_,D)=>l(_)-l(D)),b=Math.floor(f.size/2),v=l(d[b]);if(v<this.opts.scoreThresholds.opportunisticGraftThreshold){let _=this.opts.opportunisticGraftPeers,D=Fr(E,_,P=>l(P)>v);for(let P of D)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",P,g),h(P,ge.Opportunistic)}}});let y=Date.now();this.fanoutLastpub.forEach((f,g)=>{f+o<y&&(this.fanout.delete(g),this.fanoutLastpub.delete(g))}),this.fanout.forEach((f,g)=>{let w=this.topics.get(g);f.forEach(h=>{(!(w?.has(h)??!1)||l(h)<this.opts.scoreThresholds.publishThreshold)&&f.delete(h)});let E=this.topics.get(g),S=[],c=new Set;if(x.set(g,c),E!=null){let h=Ze(Array.from(E));for(let d of h){let b=this.streamsOutbound.get(d);if(b!=null&&this.protocols.includes(b.protocol)&&!f.has(d)&&!this.direct.has(d)){let v=l(d);v>=this.opts.scoreThresholds.publishThreshold&&S.push(d),v>=this.opts.scoreThresholds.gossipThreshold&&c.add(d)}}}if(f.size<e){let h=e-f.size;S.slice(0,h).forEach(d=>{f.add(d),c?.delete(d)})}}),this.emitGossip(x),await this.sendGraftPrune(u,p,m),this.flush(),this.mcache.shift(),this.dispatchEvent(new CustomEvent("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,r=()=>!0){let n=this.topics.get(e);if(n==null)return new Set;let i=[];return n.forEach(o=>{let a=this.streamsOutbound.get(o);a!=null&&this.protocols.includes(a.protocol)&&r(o)&&i.push(o)}),i=Ze(i),t>0&&i.length>t&&(i=i.slice(0,t)),new Set(i)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0,r=Date.now();e.connectedPeersBackoffSec.reset();for(let l of this.backoff.values()){t+=l.size;for(let[u,p]of l.entries())this.peers.has(u)&&e.connectedPeersBackoffSec.observe(Math.max(0,p-r)/1e3)}e.cacheSize.set({cache:"backoff"},t);let n=0;for(let l of this.idontwants.values())n+=l.size;e.cacheSize.set({cache:"idontwants"},n);for(let[l,u]of this.topics)e.topicPeersCount.set({topicStr:l},u.size);for(let[l,u]of this.mesh)e.meshPeerCounts.set({topicStr:l},u.size);let i=[],o=new Map;e.behaviourPenalty.reset();for(let l of this.peers.keys()){let u=this.score.score(l);i.push(u),o.set(l,u),e.behaviourPenalty.observe(this.score.peerStats.get(l)?.behaviourPenalty??0)}e.registerScores(i,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,o);let a=xc(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(a)}tagMeshPeer=e=>{let{peerId:t,topic:r}=e.detail;this.components.peerStore.merge(this.peers.get(t)??Rt(t),{tags:{[r]:{value:100}}}).catch(n=>{this.log.error("Error tagging peer %s with topic %s",t,r,n)})};untagMeshPeer=e=>{let{peerId:t,topic:r}=e.detail;this.components.peerStore.merge(this.peers.get(t)??Rt(t),{tags:{[r]:void 0}}).catch(n=>{this.log.error("Error untagging peer %s with topic %s",t,r,n)})}};var wt="StrictSign",Ft="StrictNoSign",me;(function(s){s.Accept="accept",s.Ignore="ignore",s.Reject="reject"})(me||(me={}));var Uf=Ot;function Kf(s={}){return e=>new qr(e,s)}return Wc(zf);})();
3
3
  /*! Bundled license information:
4
4
 
5
5
  @noble/curves/utils.js:
@@ -7,6 +7,7 @@
7
7
  @noble/curves/abstract/curve.js:
8
8
  @noble/curves/abstract/edwards.js:
9
9
  @noble/curves/ed25519.js:
10
+ @noble/curves/abstract/der.js:
10
11
  @noble/curves/abstract/weierstrass.js:
11
12
  @noble/curves/secp256k1.js:
12
13
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)