@libp2p/gossipsub 15.0.11 → 15.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +1 -1
- package/dist/index.min.js.map +4 -4
- package/dist/src/utils/msgIdFn.d.ts +5 -0
- package/dist/src/utils/msgIdFn.d.ts.map +1 -1
- package/dist/src/utils/msgIdFn.js +13 -1
- package/dist/src/utils/msgIdFn.js.map +1 -1
- package/package.json +6 -6
- package/src/utils/msgIdFn.ts +17 -1
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 sc=Object.create;var Ls=Object.defineProperty;var rc=Object.getOwnPropertyDescriptor;var nc=Object.getOwnPropertyNames;var ic=Object.getPrototypeOf,oc=Object.prototype.hasOwnProperty;var ac=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Ee=(s,e)=>{for(var t in e)Ls(s,t,{get:e[t],enumerable:!0})},Si=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of nc(e))!oc.call(s,n)&&n!==t&&Ls(s,n,{get:()=>e[n],enumerable:!(r=rc(e,n))||r.enumerable});return s};var cc=(s,e,t)=>(t=s!=null?sc(ic(s)):{},Si(e||!s||!s.__esModule?Ls(t,"default",{value:s,enumerable:!0}):t,s)),lc=s=>Si(Ls({},"__esModule",{value:!0}),s);var Ua=ac((K0,Oa)=>{"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 c;for(n=new Array(t),c=0;c<t;c++)n[c]=this._list[this._head+r+c&this._capacityMask];if(r=this._head+r&this._capacityMask,e+t===o){for(this._tail=this._tail-t+a&this._capacityMask,c=t;c>0;c--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(e===0){for(this._head=this._head+t+a&this._capacityMask,c=t-1;c>0;c--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(r<o/2){for(this._head=this._head+e+t+a&this._capacityMask,c=e;c>0;c--)this.unshift(this._list[r=r-1+a&this._capacityMask]);for(r=this._head-1+a&this._capacityMask;i>0;)this._list[r=r-1+a&this._capacityMask]=void 0,i--;e<0&&(this._tail=r)}else{for(this._tail=r,r=r+t+a&this._capacityMask,c=o-(t+e);c>0;c--)this.push(this._list[r++]);for(r=this._tail;i>0;)this._list[r=r+1+a&this._capacityMask]=void 0,i--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),n}}};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,c=arguments.length,f=this._list.length,m=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+f&this._capacityMask)):(a=this.remove(r,t),this._head=this._head+r+f&this._capacityMask);c>m;)this.unshift(arguments[--c]);for(i=r;i>0;i--)this.unshift(o[i-1])}else{o=new Array(n-(r+t));var h=o.length;for(i=0;i<h;i++)o[i]=this._list[this._head+r+t+i&this._capacityMask];for(t===0?(a=[],r!=n&&(this._tail=this._head+r+f&this._capacityMask)):(a=this.remove(r,t),this._tail=this._tail-h+f&this._capacityMask);m<c;)this.push(arguments[m++]);for(i=0;i<h;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,c;if(e||this._head>this._tail){for(c=this._head;c<n;c++)o[a++]=r[c];for(c=0;c<this._tail;c++)o[a++]=r[c]}else for(c=this._head;c<this._tail;c++)o[a++]=r[c];return o};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)};Oa.exports=Z});var Bh={};Ee(Bh,{StrictNoSign:()=>Mt,StrictSign:()=>mt,TopicValidatorResult:()=>pe,gossipsub:()=>kh,multicodec:()=>Lh});var _r="/floodsub/1.0.0",Ir="/meshsub/1.0.0",_i="/meshsub/1.1.0",Pt="/meshsub/1.2.0";var Ii="ERR_TOPIC_VALIDATOR_REJECT",Ti="ERR_TOPIC_VALIDATOR_IGNORE";var W=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Lt=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var ks=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Bs=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 Tr=Symbol.for("@libp2p/peer-id");var Rs=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){super.addEventListener(e,t,r);let n=this.#e.get(e);n==null&&(n=[],this.#e.set(e,n)),n.push({callback:t,once:(r!==!0&&r!==!1&&r?.once)??!1})}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))}dispatchEvent(e){let t=super.dispatchEvent(e),r=this.#e.get(e.type);return r==null||(r=r.filter(({once:n})=>!n),this.#e.set(e.type,r)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Di=Symbol.for("@libp2p/service-capabilities"),Mi=Symbol.for("@libp2p/service-dependencies");var Lr={};Ee(Lr,{base58btc:()=>Q,base58flickr:()=>gc});var uf=new Uint8Array(0);function Pi(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 ze(s){if(s instanceof Uint8Array&&s.constructor.name==="Uint8Array")return s;if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return new Uint8Array(s.buffer,s.byteOffset,s.byteLength);throw new Error("Unknown type, must be binary type")}function Li(s){return new TextEncoder().encode(s)}function ki(s){return new TextDecoder().decode(s)}function uc(s,e){if(s.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<s.length;n++){var i=s.charAt(n),o=i.charCodeAt(0);if(t[o]!==255)throw new TypeError(i+" is ambiguous");t[o]=n}var a=s.length,c=s.charAt(0),f=Math.log(a)/Math.log(256),m=Math.log(256)/Math.log(a);function h(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";for(var p=0,d=0,b=0,y=u.length;b!==y&&u[b]===0;)b++,p++;for(var v=(y-b)*m+1>>>0,T=new Uint8Array(v);b!==y;){for(var E=u[b],M=0,D=v-1;(E!==0||M<d)&&D!==-1;D--,M++)E+=256*T[D]>>>0,T[D]=E%a>>>0,E=E/a>>>0;if(E!==0)throw new Error("Non-zero carry");d=M,b++}for(var I=v-d;I!==v&&T[I]===0;)I++;for(var w=c.repeat(p);I<v;++I)w+=s.charAt(T[I]);return w}function g(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;var p=0;if(u[p]!==" "){for(var d=0,b=0;u[p]===c;)d++,p++;for(var y=(u.length-p)*f+1>>>0,v=new Uint8Array(y);u[p];){var T=t[u.charCodeAt(p)];if(T===255)return;for(var E=0,M=y-1;(T!==0||E<b)&&M!==-1;M--,E++)T+=a*v[M]>>>0,v[M]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");b=E,p++}if(u[p]!==" "){for(var D=y-b;D!==y&&v[D]===0;)D++;for(var I=new Uint8Array(d+(y-D)),w=d;D!==y;)I[w++]=v[D++];return I}}}function l(u){var p=g(u);if(p)return p;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:g,decode:l}}var hc=uc,fc=hc,Ri=fc;var Ar=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")}},Dr=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 Ci(this,e)}},Mr=class{decoders;constructor(e){this.decoders=e}or(e){return Ci(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 Ci(s,e){return new Mr({...s.decoders??{[s.prefix]:s},...e.decoders??{[e.prefix]:e}})}var Pr=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 Ar(e,t,r),this.decoder=new Dr(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Bt({name:s,prefix:e,encode:t,decode:r}){return new Pr(s,e,t,r)}function rt({name:s,prefix:e,alphabet:t}){let{encode:r,decode:n}=Ri(t,s);return Bt({prefix:e,name:s,encode:r,decode:i=>ze(n(i))})}function dc(s,e,t,r){let n=s.length;for(;s[n-1]==="=";)--n;let i=new Uint8Array(n*t/8|0),o=0,a=0,c=0;for(let f=0;f<n;++f){let m=e[s[f]];if(m===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<t|m,o+=t,o>=8&&(o-=8,i[c++]=255&a>>o)}if(o>=t||(255&a<<8-o)!==0)throw new SyntaxError("Unexpected end of data");return i}function pc(s,e,t){let r=e[e.length-1]==="=",n=(1<<t)-1,i="",o=0,a=0;for(let c=0;c<s.length;++c)for(a=a<<8|s[c],o+=8;o>t;)o-=t,i+=e[n&a>>o];if(o!==0&&(i+=e[n&a<<t-o]),r)for(;(i.length*t&7)!==0;)i+="=";return i}function mc(s){let e={};for(let t=0;t<s.length;++t)e[s[t]]=t;return e}function J({name:s,prefix:e,bitsPerChar:t,alphabet:r}){let n=mc(r);return Bt({prefix:e,name:s,encode(i){return pc(i,r,t)},decode(i){return dc(i,n,t,s)}})}var Q=rt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),gc=rt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var kr={};Ee(kr,{base32:()=>Rt,base32hex:()=>xc,base32hexpad:()=>Ec,base32hexpadupper:()=>Sc,base32hexupper:()=>vc,base32pad:()=>yc,base32padupper:()=>wc,base32upper:()=>bc,base32z:()=>_c});var Rt=J({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),bc=J({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),yc=J({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),wc=J({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),xc=J({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),vc=J({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ec=J({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Sc=J({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),_c=J({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Br={};Ee(Br,{base36:()=>is,base36upper:()=>Ic});var is=rt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ic=rt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Tc=Ui,Ni=128,Ac=127,Dc=~Ac,Mc=Math.pow(2,31);function Ui(s,e,t){e=e||[],t=t||0;for(var r=t;s>=Mc;)e[t++]=s&255|Ni,s/=128;for(;s&Dc;)e[t++]=s&255|Ni,s>>>=7;return e[t]=s|0,Ui.bytes=t-r+1,e}var Pc=Rr,Lc=128,Oi=127;function Rr(s,r){var t=0,r=r||0,n=0,i=r,o,a=s.length;do{if(i>=a)throw Rr.bytes=0,new RangeError("Could not decode varint");o=s[i++],t+=n<28?(o&Oi)<<n:(o&Oi)*Math.pow(2,n),n+=7}while(o>=Lc);return Rr.bytes=i-r,t}var kc=Math.pow(2,7),Bc=Math.pow(2,14),Rc=Math.pow(2,21),Cc=Math.pow(2,28),Nc=Math.pow(2,35),Oc=Math.pow(2,42),Uc=Math.pow(2,49),Kc=Math.pow(2,56),Fc=Math.pow(2,63),Gc=function(s){return s<kc?1:s<Bc?2:s<Rc?3:s<Cc?4:s<Nc?5:s<Oc?6:s<Uc?7:s<Kc?8:s<Fc?9:10},Hc={encode:Tc,decode:Pc,encodingLength:Gc},qc=Hc,os=qc;function as(s,e=0){return[os.decode(s,e),os.decode.bytes]}function Ct(s,e,t=0){return os.encode(s,e,t),e}function Nt(s){return os.encodingLength(s)}function Oe(s,e){let t=e.byteLength,r=Nt(s),n=r+Nt(t),i=new Uint8Array(n+t);return Ct(s,i,0),Ct(t,i,r),i.set(e,n),new Ot(s,t,e,i)}function Ue(s){let e=ze(s),[t,r]=as(e),[n,i]=as(e.subarray(r)),o=e.subarray(r+i);if(o.byteLength!==n)throw new Error("Incorrect length");return new Ot(t,n,o,e)}function Ki(s,e){if(s===e)return!0;{let t=e;return s.code===t.code&&s.size===t.size&&t.bytes instanceof Uint8Array&&Pi(s.bytes,t.bytes)}}var Ot=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}};function Fi(s,e){let{bytes:t,version:r}=s;switch(r){case 0:return Vc(t,Cr(s),e??Q.encoder);default:return Wc(t,Cr(s),e??Rt.encoder)}}var Gi=new WeakMap;function Cr(s){let e=Gi.get(s);if(e==null){let t=new Map;return Gi.set(s,t),t}return e}var oe=class s{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=n,this["/"]=n}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!==cs)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==$c)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=Oe(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&&Ki(e.multihash,r.multihash)}toString(e){return Fi(this,e)}toJSON(){return{"/":Fi(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??Hi(r,n,i.bytes))}else if(t[Zc]===!0){let{version:r,multihash:n,code:i}=t,o=Ue(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!==cs)throw new Error(`Version 0 CID must use dag-pb (code: ${cs}) block encoding`);return new s(e,t,r,r.bytes)}case 1:{let n=Hi(e,t,r.bytes);return new s(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return s.create(0,cs,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=ze(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 Ot(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[h,g]=as(e.subarray(t));return t+=g,h},n=r(),i=cs;if(n===18?(n=0,t=0):i=r(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let o=t,a=r(),c=r(),f=t+c,m=f-o;return{version:n,codec:i,multihashCode:a,digestSize:c,multihashSize:m,size:f}}static parse(e,t){let[r,n]=zc(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 Cr(i).set(r,e),i}};function zc(s,e){switch(s[0]){case"Q":{let t=e??Q;return[Q.prefix,t.decode(`${Q.prefix}${s}`)]}case Q.prefix:{let t=e??Q;return[Q.prefix,t.decode(s)]}case Rt.prefix:{let t=e??Rt;return[Rt.prefix,t.decode(s)]}case is.prefix:{let t=e??is;return[is.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 Vc(s,e,t){let{prefix:r}=t;if(r!==Q.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 Wc(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 cs=112,$c=18;function Hi(s,e,t){let r=Nt(s),n=r+Nt(e),i=new Uint8Array(n+t.byteLength);return Ct(s,i,0),Ct(e,i,r),i.set(t,n),i}var Zc=Symbol.for("@ipld/js-cid/CID");var Nr={};Ee(Nr,{identity:()=>Le});var qi=0,jc="identity",zi=ze;function Xc(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 Oe(qi,zi(s))}var Le={code:qi,name:jc,encode:zi,digest:Xc};function Se(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 We(s=0){return new Uint8Array(s)}function le(s=0){return new Uint8Array(s)}function gt(s,e){e==null&&(e=s.reduce((n,i)=>n+i.length,0));let t=le(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var Wi=Symbol.for("@achingbrain/uint8arraylist");function Vi(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 Ns(s){return!!s?.[Wi]}var se=class s{bufs;length;[Wi]=!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(Ns(r))t+=r.byteLength,this.bufs.push(...r.bufs);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(Ns(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=Vi(this.bufs,e);return t.buf[t.index]}set(e,t){let r=Vi(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(Ns(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 gt(r,n)}subarray(e,t){let{bufs:r,length:n}=this._subList(e,t);return r.length===1?r[0]:gt(r,n)}sublist(e,t){let{bufs:r,length:n}=this._subList(e,t),i=new s;return i.length=n,i.bufs=[...r],i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let r=[],n=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],a=n,c=a+o.byteLength;if(n=c,e>=c)continue;let f=e>=a&&e<c,m=t>a&&t<=c;if(f&&m){if(e===a&&t===c){r.push(o);break}let h=e-a;r.push(o.subarray(h,h+(t-e)));break}if(f){if(e===0){r.push(o);continue}r.push(o.subarray(e-a));continue}if(m){if(t===c){r.push(o);break}r.push(o.subarray(0,t-a));break}r.push(o)}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!Ns(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 h=0;h<i;h++)o[h]=-1;for(let h=0;h<n;h++)o[r[h]]=h;let a=o,c=this.byteLength-r.byteLength,f=r.byteLength-1,m;for(let h=t;h<=c;h+=m){m=0;for(let g=f;g>=0;g--){let l=this.get(h+g);if(r[g]!==l){m=Math.max(1,g-a[l]);break}}if(m===0)return h}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=le(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=We(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=We(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=We(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=le(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=We(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=We(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=We(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=We(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=We(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(!Se(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 Or={};Ee(Or,{base10:()=>Yc});var Yc=rt({prefix:"9",name:"base10",alphabet:"0123456789"});var Ur={};Ee(Ur,{base16:()=>Jc,base16upper:()=>Qc});var Jc=J({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Qc=J({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Kr={};Ee(Kr,{base2:()=>el});var el=J({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Fr={};Ee(Fr,{base256emoji:()=>il});var $i=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}"),tl=$i.reduce((s,e,t)=>(s[t]=e,s),[]),sl=$i.reduce((s,e,t)=>{let r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return s[r]=t,s},[]);function rl(s){return s.reduce((e,t)=>(e+=tl[t],e),"")}function nl(s){let e=[];for(let t of s){let r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);let n=sl[r];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var il=Bt({prefix:"\u{1F680}",name:"base256emoji",encode:rl,decode:nl});var Gr={};Ee(Gr,{base64:()=>ol,base64pad:()=>al,base64url:()=>cl,base64urlpad:()=>ll});var ol=J({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),al=J({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cl=J({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ll=J({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Hr={};Ee(Hr,{base8:()=>ul});var ul=J({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var qr={};Ee(qr,{identity:()=>hl});var hl=Bt({prefix:"\0",name:"identity",encode:s=>ki(s),decode:s=>Li(s)});var $f=new TextEncoder,Zf=new TextDecoder;var Wr={};Ee(Wr,{sha256:()=>nt,sha512:()=>ml});var pl=20;function Vr({name:s,code:e,encode:t,minDigestLength:r,maxDigestLength:n}){return new zr(s,e,t,r,n)}var zr=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,r,n,i){this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??pl,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?Zi(r,this.code,t?.truncate):r.then(n=>Zi(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Zi(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 Oe(e,s)}function Xi(s){return async e=>new Uint8Array(await crypto.subtle.digest(s,e))}var nt=Vr({name:"sha2-256",code:18,encode:Xi("SHA-256")}),ml=Vr({name:"sha2-512",code:19,encode:Xi("SHA-512")});var $r={...qr,...Kr,...Hr,...Or,...Ur,...kr,...Br,...Lr,...Gr,...Fr},od={...Wr,...Nr};function Ji(s,e,t,r){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:r}}}var Yi=Ji("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),Zr=Ji("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=le(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),gl={utf8:Yi,"utf-8":Yi,hex:$r.base16,latin1:Zr,ascii:Zr,binary:Zr,...$r},Os=gl;function z(s,e="utf8"){let t=Os[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${s}`)}function G(s,e="utf8"){let t=Os[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(s).substring(1)}var bl=parseInt("11111",2),jr=parseInt("10000000",2),yl=parseInt("01111111",2),Qi={0:ls,1:ls,2:wl,3:El,4:Sl,5:vl,6:xl,16:ls,22:ls,48:ls};function $e(s,e={offset:0}){let t=s[e.offset]&bl;if(e.offset++,Qi[t]!=null)return Qi[t](s,e);throw new Error("No decoder for tag "+t)}function us(s,e){let t=0;if((s[e.offset]&jr)===jr){let r=s[e.offset]&yl,n="0x";e.offset++;for(let i=0;i<r;i++,e.offset++)n+=s[e.offset].toString(16).padStart(2,"0");t=parseInt(n,16)}else t=s[e.offset],e.offset++;return t}function ls(s,e){us(s,e);let t=[];for(;!(e.offset>=s.byteLength);){let r=$e(s,e);if(r===null)break;t.push(r)}return t}function wl(s,e){let t=us(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 xl(s,e){let t=us(s,e),r=e.offset+t,n=s[e.offset];e.offset++;let i=0,o=0;n<40?(i=0,o=n):n<80?(i=1,o=n-40):(i=2,o=n-80);let a=`${i}.${o}`,c=[];for(;e.offset<r;){let f=s[e.offset];if(e.offset++,c.push(f&127),f<128){c.reverse();let m=0;for(let h=0;h<c.length;h++)m+=c[h]<<h*7;a+=`.${m}`,c=[]}}return a}function vl(s,e){return e.offset++,null}function El(s,e){let t=us(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 Sl(s,e){let t=us(s,e),r=s.subarray(e.offset,e.offset+t);return e.offset+=t,r}function _l(s){let e=s.toString(16);e.length%2===1&&(e="0"+e);let t=new se;for(let r=0;r<e.length;r+=2)t.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return t}function Xr(s){if(s.byteLength<128)return Uint8Array.from([s.byteLength]);let e=_l(s.byteLength);return new se(Uint8Array.from([e.byteLength|jr]),e)}function _e(s){let e=new se,t=128;return(s.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(s),new se(Uint8Array.from([2]),Xr(e),e)}function Us(s){let e=Uint8Array.from([0]),t=new se(e,s);return new se(Uint8Array.from([3]),Xr(t),t)}function it(s,e=48){let t=new se;for(let r of s)t.append(r);return new se(Uint8Array.from([e]),Xr(t),t)}async function eo(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,e,t.subarray());return r?.signal?.throwIfAborted(),i}var Il=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Tl=Uint8Array.from([6,5,43,129,4,0,34]),Al=Uint8Array.from([6,5,43,129,4,0,35]),Dl={ext:!0,kty:"EC",crv:"P-256"},Ml={ext:!0,kty:"EC",crv:"P-384"},Pl={ext:!0,kty:"EC",crv:"P-521"},Yr=32,Jr=48,Qr=66;function en(s){let e=$e(s);return to(e)}function to(s){let e=s[1][1][0],t=1,r,n;if(e.byteLength===Yr*2+1)return r=G(e.subarray(t,t+Yr),"base64url"),n=G(e.subarray(t+Yr),"base64url"),new Ut({...Dl,key_ops:["verify"],x:r,y:n});if(e.byteLength===Jr*2+1)return r=G(e.subarray(t,t+Jr),"base64url"),n=G(e.subarray(t+Jr),"base64url"),new Ut({...Ml,key_ops:["verify"],x:r,y:n});if(e.byteLength===Qr*2+1)return r=G(e.subarray(t,t+Qr),"base64url"),n=G(e.subarray(t+Qr),"base64url"),new Ut({...Pl,key_ops:["verify"],x:r,y:n});throw new W(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function so(s){return it([_e(Uint8Array.from([1])),it([Ll(s.crv)],160),it([Us(new se(Uint8Array.from([4]),z(s.x??"","base64url"),z(s.y??"","base64url")))],161)]).subarray()}function Ll(s){if(s==="P-256")return Il;if(s==="P-384")return Tl;if(s==="P-521")return Al;throw new W(`Invalid curve ${s}`)}var Ut=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=so(this.jwk)),this._raw}toMultihash(){return Le.digest(Ke(this))}toCID(){return oe.createV1(114,this.toMultihash())}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Se(this.raw,e.raw)}async verify(e,t,r){return eo(this.jwk,t,e,r)}};function bt(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Fe(s,e=""){if(!Number.isSafeInteger(s)||s<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${s}`)}}function K(s,e,t=""){let r=bt(s),n=s?.length,i=e!==void 0;if(!r||i&&n!==e){let o=t&&`"${t}" `,a=i?` of length ${e}`:"",c=r?`length=${n}`:`type=${typeof s}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return s}function Ks(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Fe(s.outputLen),Fe(s.blockLen)}function Kt(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 no(s,e){K(s,void 0,"digestInto() output");let t=e.outputLen;if(s.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function je(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Fs(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function ke(s,e){return s<<32-e|s>>>e}var io=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",kl=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Xe(s){if(K(s),io)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=kl[s[t]];return e}var Ze={_0:48,_9:57,A:65,F:70,a:97,f:102};function ro(s){if(s>=Ze._0&&s<=Ze._9)return s-Ze._0;if(s>=Ze.A&&s<=Ze.F)return s-(Ze.A-10);if(s>=Ze.a&&s<=Ze.f)return s-(Ze.a-10)}function Ye(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(io)return Uint8Array.fromHex(s);let e=s.length,t=e/2;if(e%2)throw new Error("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=ro(s.charCodeAt(i)),a=ro(s.charCodeAt(i+1));if(o===void 0||a===void 0){let c=s[i]+s[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[n]=o*16+a}return r}function Ie(...s){let e=0;for(let r=0;r<s.length;r++){let n=s[r];K(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 tn(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.create=n=>s(n),Object.assign(t,e),Object.freeze(t)}function ot(s=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(s))}var sn=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function oo(s,e,t){return s&e^~s&t}function ao(s,e,t){return s&e^s&t^e&t}var hs=class{blockLen;outputLen;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=Fs(this.buffer)}update(e){Kt(this),K(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 c=Fs(e);for(;n<=i-o;o+=n)this.process(c,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){Kt(this),no(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,je(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(r,0),o=0);for(let h=o;h<n;h++)t[h]=0;r.setBigUint64(n-8,BigInt(this.length*8),i),this.process(r,0);let a=Fs(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,m=this.get();if(f>m.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<f;h++)a.setUint32(4*h,m[h],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()}},Je=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ae=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Gs=BigInt(4294967295),co=BigInt(32);function Bl(s,e=!1){return e?{h:Number(s&Gs),l:Number(s>>co&Gs)}:{h:Number(s>>co&Gs)|0,l:Number(s&Gs)|0}}function lo(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}=Bl(s[i],e);[r[i],n[i]]=[o,a]}return[r,n]}var rn=(s,e,t)=>s>>>t,nn=(s,e,t)=>s<<32-t|e>>>t,yt=(s,e,t)=>s>>>t|e<<32-t,wt=(s,e,t)=>s<<32-t|e>>>t,fs=(s,e,t)=>s<<64-t|e>>>t-32,ds=(s,e,t)=>s>>>t-32|e<<64-t;function Ge(s,e,t,r){let n=(e>>>0)+(r>>>0);return{h:s+t+(n/2**32|0)|0,l:n|0}}var uo=(s,e,t)=>(s>>>0)+(e>>>0)+(t>>>0),ho=(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),po=(s,e,t,r,n)=>e+t+r+n+(s/2**32|0)|0,mo=(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 Cl=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]),at=new Uint32Array(64),on=class extends hs{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:n,E:i,F:o,G:a,H:c}=this;return[e,t,r,n,i,o,a,c]}set(e,t,r,n,i,o,a,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)at[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let g=at[h-15],l=at[h-2],u=ke(g,7)^ke(g,18)^g>>>3,p=ke(l,17)^ke(l,19)^l>>>10;at[h]=p+at[h-7]+u+at[h-16]|0}let{A:r,B:n,C:i,D:o,E:a,F:c,G:f,H:m}=this;for(let h=0;h<64;h++){let g=ke(a,6)^ke(a,11)^ke(a,25),l=m+g+oo(a,c,f)+Cl[h]+at[h]|0,p=(ke(r,2)^ke(r,13)^ke(r,22))+ao(r,n,i)|0;m=f,f=c,c=a,a=o+l|0,o=i,i=n,n=r,r=l+p|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,m=m+this.H|0,this.set(r,n,i,o,a,c,f,m)}roundClean(){je(at)}destroy(){this.set(0,0,0,0,0,0,0,0),je(this.buffer)}},an=class extends on{A=Je[0]|0;B=Je[1]|0;C=Je[2]|0;D=Je[3]|0;E=Je[4]|0;F=Je[5]|0;G=Je[6]|0;H=Je[7]|0;constructor(){super(32)}};var bo=lo(["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))),Nl=bo[0],Ol=bo[1],ct=new Uint32Array(80),lt=new Uint32Array(80),cn=class extends hs{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:o,Dh:a,Dl:c,Eh:f,El:m,Fh:h,Fl:g,Gh:l,Gl:u,Hh:p,Hl:d}=this;return[e,t,r,n,i,o,a,c,f,m,h,g,l,u,p,d]}set(e,t,r,n,i,o,a,c,f,m,h,g,l,u,p,d){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=n|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=f|0,this.El=m|0,this.Fh=h|0,this.Fl=g|0,this.Gh=l|0,this.Gl=u|0,this.Hh=p|0,this.Hl=d|0}process(e,t){for(let v=0;v<16;v++,t+=4)ct[v]=e.getUint32(t),lt[v]=e.getUint32(t+=4);for(let v=16;v<80;v++){let T=ct[v-15]|0,E=lt[v-15]|0,M=yt(T,E,1)^yt(T,E,8)^rn(T,E,7),D=wt(T,E,1)^wt(T,E,8)^nn(T,E,7),I=ct[v-2]|0,w=lt[v-2]|0,L=yt(I,w,19)^fs(I,w,61)^rn(I,w,6),O=wt(I,w,19)^ds(I,w,61)^nn(I,w,6),R=fo(D,O,lt[v-7],lt[v-16]),S=po(R,M,L,ct[v-7],ct[v-16]);ct[v]=S|0,lt[v]=R|0}let{Ah:r,Al:n,Bh:i,Bl:o,Ch:a,Cl:c,Dh:f,Dl:m,Eh:h,El:g,Fh:l,Fl:u,Gh:p,Gl:d,Hh:b,Hl:y}=this;for(let v=0;v<80;v++){let T=yt(h,g,14)^yt(h,g,18)^fs(h,g,41),E=wt(h,g,14)^wt(h,g,18)^ds(h,g,41),M=h&l^~h&p,D=g&u^~g&d,I=mo(y,E,D,Ol[v],lt[v]),w=go(I,b,T,M,Nl[v],ct[v]),L=I|0,O=yt(r,n,28)^fs(r,n,34)^fs(r,n,39),R=wt(r,n,28)^ds(r,n,34)^ds(r,n,39),S=r&i^r&a^i&a,_=n&o^n&c^o&c;b=p|0,y=d|0,p=l|0,d=u|0,l=h|0,u=g|0,{h,l:g}=Ge(f|0,m|0,w|0,L|0),f=a|0,m=c|0,a=i|0,c=o|0,i=r|0,o=n|0;let x=uo(L,R,_);r=ho(x,w,O,S),n=x|0}({h:r,l:n}=Ge(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=Ge(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=Ge(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:m}=Ge(this.Dh|0,this.Dl|0,f|0,m|0),{h,l:g}=Ge(this.Eh|0,this.El|0,h|0,g|0),{h:l,l:u}=Ge(this.Fh|0,this.Fl|0,l|0,u|0),{h:p,l:d}=Ge(this.Gh|0,this.Gl|0,p|0,d|0),{h:b,l:y}=Ge(this.Hh|0,this.Hl|0,b|0,y|0),this.set(r,n,i,o,a,c,f,m,h,g,l,u,p,d,b,y)}roundClean(){je(ct,lt)}destroy(){je(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},ln=class extends cn{Ah=ae[0]|0;Al=ae[1]|0;Bh=ae[2]|0;Bl=ae[3]|0;Ch=ae[4]|0;Cl=ae[5]|0;Dh=ae[6]|0;Dl=ae[7]|0;Eh=ae[8]|0;El=ae[9]|0;Fh=ae[10]|0;Fl=ae[11]|0;Gh=ae[12]|0;Gl=ae[13]|0;Hh=ae[14]|0;Hl=ae[15]|0;constructor(){super(64)}};var Ft=tn(()=>new an,sn(1));var yo=tn(()=>new ln,sn(3));var hn=BigInt(0),un=BigInt(1);function Qe(s,e=""){if(typeof s!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof s)}return s}function wo(s){if(typeof s=="bigint"){if(!Hs(s))throw new Error("positive bigint expected, got "+s)}else Fe(s);return s}function ps(s){let e=wo(s).toString(16);return e.length&1?"0"+e:e}function xo(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?hn:BigInt("0x"+s)}function Gt(s){return xo(Xe(s))}function xt(s){return xo(Xe(zs(K(s)).reverse()))}function qs(s,e){Fe(e),s=wo(s);let t=Ye(s.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function fn(s,e){return qs(s,e).reverse()}function zs(s){return Uint8Array.from(s)}var Hs=s=>typeof s=="bigint"&&hn<=s;function Ul(s,e,t){return Hs(s)&&Hs(e)&&Hs(t)&&e<=s&&s<t}function ms(s,e,t,r){if(!Ul(e,t,r))throw new Error("expected valid "+s+": "+t+" <= n < "+r+", got "+e)}function dn(s){let e;for(e=0;s>hn;s>>=un,e+=1);return e}var gs=s=>(un<<BigInt(s))-un;function vo(s,e,t){if(Fe(s,"hashLen"),Fe(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let r=d=>new Uint8Array(d),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3,c=r(s),f=r(s),m=0,h=()=>{c.fill(1),f.fill(0),m=0},g=(...d)=>t(f,Ie(c,...d)),l=(d=n)=>{f=g(i,d),c=g(),d.length!==0&&(f=g(o,d),c=g())},u=()=>{if(m++>=a)throw new Error("drbg: tried max amount of iterations");let d=0,b=[];for(;d<e;){c=g();let y=c.slice();b.push(y),d+=c.length}return Ie(...b)};return(d,b)=>{h(),l(d);let y;for(;!(y=b(u()));)l();return h(),y}}function ut(s,e={},t={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function r(i,o,a){let c=s[i];if(a&&c===void 0)return;let f=typeof c;if(f!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${f}`)}let n=(i,o)=>Object.entries(i).forEach(([a,c])=>r(a,c,o));n(e,!1),n(t,!0)}function Ht(s){let e=new WeakMap;return(t,...r)=>{let n=e.get(t);if(n!==void 0)return n;let i=s(t,...r);return e.set(t,i),i}}var me=BigInt(0),re=BigInt(1),vt=BigInt(2),_o=BigInt(3),Io=BigInt(4),To=BigInt(5),Kl=BigInt(7),Ao=BigInt(8),Fl=BigInt(9),Do=BigInt(16);function ee(s,e){let t=s%e;return t>=me?t:e+t}function $(s,e,t){let r=s;for(;e-- >me;)r*=r,r%=t;return r}function Eo(s,e){if(s===me)throw new Error("invert: expected non-zero number");if(e<=me)throw new Error("invert: expected positive modulus, got "+e);let t=ee(s,e),r=e,n=me,i=re,o=re,a=me;for(;t!==me;){let f=r/t,m=r%t,h=n-o*f,g=i-a*f;r=t,t=m,n=o,i=a,o=h,a=g}if(r!==re)throw new Error("invert: does not exist");return ee(n,e)}function mn(s,e,t){if(!s.eql(s.sqr(e),t))throw new Error("Cannot find square root")}function Mo(s,e){let t=(s.ORDER+re)/Io,r=s.pow(e,t);return mn(s,r,e),r}function Gl(s,e){let t=(s.ORDER-To)/Ao,r=s.mul(e,vt),n=s.pow(r,t),i=s.mul(e,n),o=s.mul(s.mul(i,vt),n),a=s.mul(i,s.sub(o,s.ONE));return mn(s,a,e),a}function Hl(s){let e=qt(s),t=Po(s),r=t(e,e.neg(e.ONE)),n=t(e,r),i=t(e,e.neg(r)),o=(s+Kl)/Do;return(a,c)=>{let f=a.pow(c,o),m=a.mul(f,r),h=a.mul(f,n),g=a.mul(f,i),l=a.eql(a.sqr(m),c),u=a.eql(a.sqr(h),c);f=a.cmov(f,m,l),m=a.cmov(g,h,u);let p=a.eql(a.sqr(m),c),d=a.cmov(f,m,p);return mn(a,d,c),d}}function Po(s){if(s<_o)throw new Error("sqrt is not defined for small field");let e=s-re,t=0;for(;e%vt===me;)e/=vt,t++;let r=vt,n=qt(s);for(;So(n,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Mo;let i=n.pow(r,e),o=(e+re)/vt;return function(c,f){if(c.is0(f))return f;if(So(c,f)!==1)throw new Error("Cannot find square root");let m=t,h=c.mul(c.ONE,i),g=c.pow(f,e),l=c.pow(f,o);for(;!c.eql(g,c.ONE);){if(c.is0(g))return c.ZERO;let u=1,p=c.sqr(g);for(;!c.eql(p,c.ONE);)if(u++,p=c.sqr(p),u===m)throw new Error("Cannot find square root");let d=re<<BigInt(m-u-1),b=c.pow(h,d);m=u,h=c.sqr(b),g=c.mul(g,h),l=c.mul(l,b)}return l}}function ql(s){return s%Io===_o?Mo:s%Ao===To?Gl:s%Do===Fl?Hl(s):Po(s)}var Lo=(s,e)=>(ee(s,e)&re)===re,zl=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function gn(s){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=zl.reduce((r,n)=>(r[n]="function",r),e);return ut(s,t),s}function Vl(s,e,t){if(t<me)throw new Error("invalid exponent, negatives unsupported");if(t===me)return s.ONE;if(t===re)return e;let r=s.ONE,n=e;for(;t>me;)t&re&&(r=s.mul(r,n)),n=s.sqr(n),t>>=re;return r}function bs(s,e,t=!1){let r=new Array(e.length).fill(t?s.ZERO:void 0),n=e.reduce((o,a,c)=>s.is0(a)?o:(r[c]=o,s.mul(o,a)),s.ONE),i=s.inv(n);return e.reduceRight((o,a,c)=>s.is0(a)?o:(r[c]=s.mul(o,r[c]),s.mul(o,a)),i),r}function So(s,e){let t=(s.ORDER-re)/vt,r=s.pow(e,t),n=s.eql(r,s.ONE),i=s.eql(r,s.ZERO),o=s.eql(r,s.neg(s.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function Wl(s,e){e!==void 0&&Fe(e);let t=e!==void 0?e:s.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}var pn=class{ORDER;BITS;BYTES;isLE;ZERO=me;ONE=re;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=me)throw new Error("invalid field: expected ORDER > 0, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:n,nByteLength:i}=Wl(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ee(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return me<=e&&e<this.ORDER}is0(e){return e===me}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&re)===re}neg(e){return ee(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ee(e*e,this.ORDER)}add(e,t){return ee(e+t,this.ORDER)}sub(e,t){return ee(e-t,this.ORDER)}mul(e,t){return ee(e*t,this.ORDER)}pow(e,t){return Vl(this,e,t)}div(e,t){return ee(e*Eo(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 Eo(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=ql(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?fn(e,this.BYTES):qs(e,this.BYTES)}fromBytes(e,t=!1){K(e);let{_lengths:r,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(r){if(!r.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let f=new Uint8Array(n);f.set(e,i?0:f.length-e.length),e=f}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?xt(e):Gt(e);if(a&&(c=ee(c,o)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return bs(this,e)}cmov(e,t,r){return r?t:e}};function qt(s,e={}){return new pn(s,e)}function ko(s){if(typeof s!="bigint")throw new Error("field order must be bigint");let e=s.toString(2).length;return Math.ceil(e/8)}function bn(s){let e=ko(s);return e+Math.ceil(e/2)}function yn(s,e,t=!1){K(s);let r=s.length,n=ko(e),i=bn(e);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let o=t?xt(s):Gt(s),a=ee(o,e-re)+re;return t?fn(a,n):qs(a,n)}var zt=BigInt(0),Et=BigInt(1);function ys(s,e){let t=e.negate();return s?t:e}function St(s,e){let t=bs(s.Fp,e.map(r=>r.Z));return e.map((r,n)=>s.fromAffine(r.toAffine(t[n])))}function No(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function wn(s,e){No(s,e);let t=Math.ceil(e/s)+1,r=2**(s-1),n=2**s,i=gs(s),o=BigInt(s);return{windows:t,windowSize:r,mask:i,maxNumber:n,shiftBy:o}}function Bo(s,e,t){let{windowSize:r,mask:n,maxNumber:i,shiftBy:o}=t,a=Number(s&n),c=s>>o;a>r&&(a-=i,c+=Et);let f=e*r,m=f+Math.abs(a)-1,h=a===0,g=a<0,l=e%2!==0;return{nextN:c,offset:m,isZero:h,isNeg:g,isNegF:l,offsetF:f}}var xn=new WeakMap,Oo=new WeakMap;function vn(s){return Oo.get(s)||1}function Ro(s){if(s!==zt)throw new Error("invalid wNAF")}var Vt=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>zt;)t&Et&&(r=r.add(n)),n=n.double(),t>>=Et;return r}precomputeWindow(e,t){let{windows:r,windowSize:n}=wn(t,this.bits),i=[],o=e,a=o;for(let c=0;c<r;c++){a=o,i.push(a);for(let f=1;f<n;f++)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=wn(e,this.bits);for(let a=0;a<o.windows;a++){let{nextN:c,offset:f,isZero:m,isNeg:h,isNegF:g,offsetF:l}=Bo(r,a,o);r=c,m?i=i.add(ys(g,t[l])):n=n.add(ys(h,t[f]))}return Ro(r),{p:n,f:i}}wNAFUnsafe(e,t,r,n=this.ZERO){let i=wn(e,this.bits);for(let o=0;o<i.windows&&r!==zt;o++){let{nextN:a,offset:c,isZero:f,isNeg:m}=Bo(r,o,i);if(r=a,!f){let h=t[c];n=n.add(m?h.negate():h)}}return Ro(r),n}getPrecomputes(e,t,r){let n=xn.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(n=r(n)),xn.set(t,n))),n}cached(e,t,r){let n=vn(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){let i=vn(e);return i===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),t,n)}createCache(e,t){No(t,this.bits),Oo.set(e,t),xn.delete(e)}hasCache(e){return vn(e)!==1}};function Uo(s,e,t,r){let n=e,i=s.ZERO,o=s.ZERO;for(;t>zt||r>zt;)t&Et&&(i=i.add(n)),r&Et&&(o=o.add(n)),n=n.double(),t>>=Et,r>>=Et;return{p1:i,p2:o}}function Co(s,e,t){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return gn(e),e}else return qt(s,{isLE:t})}function Vs(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 c of["p","n","h"]){let f=e[c];if(!(typeof f=="bigint"&&f>zt))throw new Error(`CURVE.${c} must be positive bigint`)}let n=Co(e.p,t.Fp,r),i=Co(e.n,t.Fn,r),a=["Gx","Gy","a",s==="weierstrass"?"b":"d"];for(let c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function Ws(s,e){return function(r){let n=s(r);return{secretKey:n,publicKey:e(n)}}}var ht=BigInt(0),ne=BigInt(1),En=BigInt(2),$l=BigInt(8);function Zl(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 Ko(s,e={}){let t=Vs("edwards",s,e,e.FpFnLE),{Fp:r,Fn:n}=t,i=t.CURVE,{h:o}=i;ut(e,{},{uvRatio:"function"});let a=En<<BigInt(n.BYTES*8)-ne,c=d=>r.create(d),f=e.uvRatio||((d,b)=>{try{return{isValid:!0,value:r.sqrt(r.div(d,b))}}catch{return{isValid:!1,value:ht}}});if(!Zl(r,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function m(d,b,y=!1){let v=y?ne:ht;return ms("coordinate "+d,b,v,a),b}function h(d){if(!(d instanceof u))throw new Error("EdwardsPoint expected")}let g=Ht((d,b)=>{let{X:y,Y:v,Z:T}=d,E=d.is0();b==null&&(b=E?$l:r.inv(T));let M=c(y*b),D=c(v*b),I=r.mul(T,b);if(E)return{x:ht,y:ne};if(I!==ne)throw new Error("invZ was invalid");return{x:M,y:D}}),l=Ht(d=>{let{a:b,d:y}=i;if(d.is0())throw new Error("bad point: ZERO");let{X:v,Y:T,Z:E,T:M}=d,D=c(v*v),I=c(T*T),w=c(E*E),L=c(w*w),O=c(D*b),R=c(w*c(O+I)),S=c(L+c(y*c(D*I)));if(R!==S)throw new Error("bad point: equation left != right (1)");let _=c(v*T),x=c(E*M);if(_!==x)throw new Error("bad point: equation left != right (2)");return!0});class u{static BASE=new u(i.Gx,i.Gy,ne,c(i.Gx*i.Gy));static ZERO=new u(ht,ne,ne,ht);static Fp=r;static Fn=n;X;Y;Z;T;constructor(b,y,v,T){this.X=m("x",b),this.Y=m("y",y),this.Z=m("z",v,!0),this.T=m("t",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(b){if(b instanceof u)throw new Error("extended point not allowed");let{x:y,y:v}=b||{};return m("x",y),m("y",v),new u(y,v,ne,c(y*v))}static fromBytes(b,y=!1){let v=r.BYTES,{a:T,d:E}=i;b=zs(K(b,v,"point")),Qe(y,"zip215");let M=zs(b),D=b[v-1];M[v-1]=D&-129;let I=xt(M),w=y?a:r.ORDER;ms("point.y",I,ht,w);let L=c(I*I),O=c(L-ne),R=c(E*L-T),{isValid:S,value:_}=f(O,R);if(!S)throw new Error("bad point: invalid y coordinate");let x=(_&ne)===ne,A=(D&128)!==0;if(!y&&_===ht&&A)throw new Error("bad point: x=0 and x_0=1");return A!==x&&(_=c(-_)),u.fromAffine({x:_,y:I})}static fromHex(b,y=!1){return u.fromBytes(Ye(b),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,y=!0){return p.createCache(this,b),y||this.multiply(En),this}assertValidity(){l(this)}equals(b){h(b);let{X:y,Y:v,Z:T}=this,{X:E,Y:M,Z:D}=b,I=c(y*D),w=c(E*T),L=c(v*D),O=c(M*T);return I===w&&L===O}is0(){return this.equals(u.ZERO)}negate(){return new u(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:b}=i,{X:y,Y:v,Z:T}=this,E=c(y*y),M=c(v*v),D=c(En*c(T*T)),I=c(b*E),w=y+v,L=c(c(w*w)-E-M),O=I+M,R=O-D,S=I-M,_=c(L*R),x=c(O*S),A=c(L*S),P=c(R*O);return new u(_,x,P,A)}add(b){h(b);let{a:y,d:v}=i,{X:T,Y:E,Z:M,T:D}=this,{X:I,Y:w,Z:L,T:O}=b,R=c(T*I),S=c(E*w),_=c(D*v*O),x=c(M*L),A=c((T+E)*(I+w)-R-S),P=x-_,B=x+_,C=c(S-y*R),k=c(A*P),N=c(B*C),U=c(A*C),j=c(P*B);return new u(k,N,j,U)}subtract(b){return this.add(b.negate())}multiply(b){if(!n.isValidNot0(b))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:y,f:v}=p.cached(this,b,T=>St(u,T));return St(u,[y,v])[0]}multiplyUnsafe(b,y=u.ZERO){if(!n.isValid(b))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return b===ht?u.ZERO:this.is0()||b===ne?this:p.unsafe(this,b,v=>St(u,v),y)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return p.unsafe(this,i.n).is0()}toAffine(b){return g(this,b)}clearCofactor(){return o===ne?this:this.multiplyUnsafe(o)}toBytes(){let{x:b,y}=this.toAffine(),v=r.toBytes(y);return v[v.length-1]|=b&ne?128:0,v}toHex(){return Xe(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let p=new Vt(u,n.BITS);return u.BASE.precompute(8),u}function Fo(s,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');ut(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:r}=t,{BASE:n,Fp:i,Fn:o}=s,a=t.randomBytes||ot,c=t.adjustScalarBytes||(I=>I),f=t.domain||((I,w,L)=>{if(Qe(L,"phflag"),w.length||L)throw new Error("Contexts/pre-hash are not supported");return I});function m(I){return o.create(xt(I))}function h(I){let w=v.secretKey;K(I,v.secretKey,"secretKey");let L=K(e(I),2*w,"hashedSecretKey"),O=c(L.slice(0,w)),R=L.slice(w,2*w),S=m(O);return{head:O,prefix:R,scalar:S}}function g(I){let{head:w,prefix:L,scalar:O}=h(I),R=n.multiply(O),S=R.toBytes();return{head:w,prefix:L,scalar:O,point:R,pointBytes:S}}function l(I){return g(I).pointBytes}function u(I=Uint8Array.of(),...w){let L=Ie(...w);return m(e(f(L,K(I,void 0,"context"),!!r)))}function p(I,w,L={}){I=K(I,void 0,"message"),r&&(I=r(I));let{prefix:O,scalar:R,pointBytes:S}=g(w),_=u(L.context,O,I),x=n.multiply(_).toBytes(),A=u(L.context,x,S,I),P=o.create(_+A*R);if(!o.isValid(P))throw new Error("sign failed: invalid s");let B=Ie(x,o.toBytes(P));return K(B,v.signature,"result")}let d={zip215:!0};function b(I,w,L,O=d){let{context:R,zip215:S}=O,_=v.signature;I=K(I,_,"signature"),w=K(w,void 0,"message"),L=K(L,v.publicKey,"publicKey"),S!==void 0&&Qe(S,"zip215"),r&&(w=r(w));let x=_/2,A=I.subarray(0,x),P=xt(I.subarray(x,_)),B,C,k;try{B=s.fromBytes(L,S),C=s.fromBytes(A,S),k=n.multiplyUnsafe(P)}catch{return!1}if(!S&&B.isSmallOrder())return!1;let N=u(R,C.toBytes(),B.toBytes(),w);return C.add(B.multiplyUnsafe(N)).subtract(k).clearCofactor().is0()}let y=i.BYTES,v={secretKey:y,publicKey:y,signature:2*y,seed:y};function T(I=a(v.seed)){return K(I,v.seed,"seed")}function E(I){return bt(I)&&I.length===o.BYTES}function M(I,w){try{return!!s.fromBytes(I,w)}catch{return!1}}let D={getExtendedPublicKey:g,randomSecretKey:T,isValidSecretKey:E,isValidPublicKey:M,toMontgomery(I){let{y:w}=s.fromBytes(I),L=v.publicKey,O=L===32;if(!O&&L!==57)throw new Error("only defined for 25519 and 448");let R=O?i.div(ne+w,ne-w):i.div(w-ne,w+ne);return i.toBytes(R)},toMontgomerySecret(I){let w=v.secretKey;K(I,w);let L=e(I.subarray(0,w));return c(L).subarray(0,w)}};return Object.freeze({keygen:Ws(T,l),getPublicKey:l,sign:p,verify:b,utils:D,Point:s,lengths:v})}var jl=BigInt(1),Go=BigInt(2);var Xl=BigInt(5),Yl=BigInt(8),Sn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Jl={p:Sn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Yl,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ql(s){let e=BigInt(10),t=BigInt(20),r=BigInt(40),n=BigInt(80),i=Sn,a=s*s%i*s%i,c=$(a,Go,i)*a%i,f=$(c,jl,i)*s%i,m=$(f,Xl,i)*f%i,h=$(m,e,i)*m%i,g=$(h,t,i)*h%i,l=$(g,r,i)*g%i,u=$(l,n,i)*l%i,p=$(u,n,i)*l%i,d=$(p,e,i)*m%i;return{pow_p_5_8:$(d,Go,i)*s%i,b2:a}}function eu(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}var Ho=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function tu(s,e){let t=Sn,r=ee(e*e*e,t),n=ee(r*r*e,t),i=Ql(s*n).pow_p_5_8,o=ee(s*r*i,t),a=ee(e*o*o,t),c=o,f=ee(o*Ho,t),m=a===s,h=a===ee(-s,t),g=a===ee(-s*Ho,t);return m&&(o=c),(h||g)&&(o=f),Lo(o,t)&&(o=ee(-o,t)),{isValid:m||h,value:o}}var su=Ko(Jl,{uvRatio:tu});function ru(s){return Fo(su,yo,Object.assign({adjustScalarBytes:eu},s))}var qo=ru({});var ws=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},$s=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var zo={get(s=globalThis){let e=s.crypto;if(e?.subtle==null)throw new $s("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 Me=zo;var Zs=32;var _n,nu=(async()=>{try{return await Me.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function iu(s,e,t){if(s.buffer instanceof ArrayBuffer){let r=await Me.get().subtle.importKey("raw",s.buffer,{name:"Ed25519"},!1,["verify"]);return await Me.get().subtle.verify({name:"Ed25519"},r,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function ou(s,e,t){return qo.verify(e,t instanceof Uint8Array?t:t.subarray(),s)}async function Vo(s,e,t){return _n==null&&(_n=await nu),_n?iu(s,e,t):ou(s,e,t)}function js(s){return s==null?!1:typeof s.then=="function"&&typeof s.catch=="function"&&typeof s.finally=="function"}var Xs=class{type="Ed25519";raw;constructor(e){this.raw=In(e,Zs)}toMultihash(){return Le.digest(Ke(this))}toCID(){return oe.createV1(114,this.toMultihash())}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Se(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();let n=Vo(this.raw,t,e);return js(n)?n.then(i=>(r?.signal?.throwIfAborted(),i)):n}};function Tn(s){return s=In(s,Zs),new Xs(s)}function In(s,e){if(s=Uint8Array.from(s??[]),s.length!==e)throw new W(`Key must be a Uint8Array of length ${e}, got ${s.length}`);return s}var cu=Math.pow(2,7),lu=Math.pow(2,14),uu=Math.pow(2,21),An=Math.pow(2,28),Dn=Math.pow(2,35),Mn=Math.pow(2,42),Pn=Math.pow(2,49),H=128,ue=127;function Pe(s){if(s<cu)return 1;if(s<lu)return 2;if(s<uu)return 3;if(s<An)return 4;if(s<Dn)return 5;if(s<Mn)return 6;if(s<Pn)return 7;if(Number.MAX_SAFE_INTEGER!=null&&s>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ln(s,e,t=0){switch(Pe(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 hu(s,e,t=0){switch(Pe(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 kn(s,e){let t=s[e],r=0;if(r+=t&ue,t<H||(t=s[e+1],r+=(t&ue)<<7,t<H)||(t=s[e+2],r+=(t&ue)<<14,t<H)||(t=s[e+3],r+=(t&ue)<<21,t<H)||(t=s[e+4],r+=(t&ue)*An,t<H)||(t=s[e+5],r+=(t&ue)*Dn,t<H)||(t=s[e+6],r+=(t&ue)*Mn,t<H)||(t=s[e+7],r+=(t&ue)*Pn,t<H))return r;throw new RangeError("Could not decode varint")}function fu(s,e){let t=s.get(e),r=0;if(r+=t&ue,t<H||(t=s.get(e+1),r+=(t&ue)<<7,t<H)||(t=s.get(e+2),r+=(t&ue)<<14,t<H)||(t=s.get(e+3),r+=(t&ue)<<21,t<H)||(t=s.get(e+4),r+=(t&ue)*An,t<H)||(t=s.get(e+5),r+=(t&ue)*Dn,t<H)||(t=s.get(e+6),r+=(t&ue)*Mn,t<H)||(t=s.get(e+7),r+=(t&ue)*Pn,t<H))return r;throw new RangeError("Could not decode varint")}function Bn(s,e,t=0){return e==null&&(e=le(Pe(s))),e instanceof Uint8Array?Ln(s,e,t):hu(s,e,t)}function Rn(s,e=0){return s instanceof Uint8Array?kn(s,e):fu(s,e)}var Nn=new Float32Array([-0]),ft=new Uint8Array(Nn.buffer);function $o(s,e,t){Nn[0]=s,e[t]=ft[0],e[t+1]=ft[1],e[t+2]=ft[2],e[t+3]=ft[3]}function Zo(s,e){return ft[0]=s[e],ft[1]=s[e+1],ft[2]=s[e+2],ft[3]=s[e+3],Nn[0]}var On=new Float64Array([-0]),he=new Uint8Array(On.buffer);function jo(s,e,t){On[0]=s,e[t]=he[0],e[t+1]=he[1],e[t+2]=he[2],e[t+3]=he[3],e[t+4]=he[4],e[t+5]=he[5],e[t+6]=he[6],e[t+7]=he[7]}function Xo(s,e){return he[0]=s[e],he[1]=s[e+1],he[2]=s[e+2],he[3]=s[e+3],he[4]=s[e+4],he[5]=s[e+5],he[6]=s[e+6],he[7]=s[e+7],On[0]}var du=BigInt(Number.MAX_SAFE_INTEGER),pu=BigInt(Number.MIN_SAFE_INTEGER),Ae=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 _t;if(e<du&&e>pu)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>Yo&&(n=0n,++r>Yo&&(r=0n))),new s(Number(n),Number(r))}static fromNumber(e){if(e===0)return _t;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):_t}},_t=new Ae(0,0);_t.toBigInt=function(){return 0n};_t.zzEncode=_t.zzDecode=function(){return this};_t.length=function(){return 1};var Yo=4294967296n;function Jo(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 Qo(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 Un(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 Be(s,e){return RangeError(`index out of range: ${s.pos} + ${e??1} > ${s.len}`)}function Ys(s,e){return(s[e-4]|s[e-3]<<8|s[e-2]<<16|s[e-1]<<24)>>>0}var Kn=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Be(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 Be(this,4);return Ys(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Be(this,4);return Ys(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Be(this,4);let e=Zo(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Be(this,4);let e=Xo(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 Be(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){let e=this.bytes();return Qo(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Be(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Be(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 Ae(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 Be(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 Be(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 Be(this,8);let e=Ys(this.buf,this.pos+=4),t=Ys(this.buf,this.pos+=4);return new Ae(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=kn(this.buf,this.pos);return this.pos+=Pe(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 Fn(s){return new Kn(s instanceof Uint8Array?s:s.subarray())}function ge(s,e,t){let r=Fn(s);return e.decode(r,void 0,t)}function Gn(s){let e=s??8192,t=e>>>1,r,n=e;return function(o){if(o<1||o>t)return le(o);n+o>e&&(r=le(e),n=0);let a=r.subarray(n,n+=o);return(n&7)!==0&&(n=(n|7)+1),a}}var It=class{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}};function Hn(){}var zn=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},mu=Gn();function gu(s){return globalThis.Buffer!=null?le(s):mu(s)}var vs=class{len;head;tail;states;constructor(){this.len=0,this.head=new It(Hn,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new It(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Vn((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(Js,10,Ae.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ae.fromBigInt(e);return this._push(Js,t.length(),t)}uint64Number(e){return this._push(Ln,Pe(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=Ae.fromBigInt(e).zzEncode();return this._push(Js,t.length(),t)}sint64Number(e){let t=Ae.fromNumber(e).zzEncode();return this._push(Js,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(qn,1,e?1:0)}fixed32(e){return this._push(xs,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ae.fromBigInt(e);return this._push(xs,4,t.lo)._push(xs,4,t.hi)}fixed64Number(e){let t=Ae.fromNumber(e);return this._push(xs,4,t.lo)._push(xs,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($o,4,e)}double(e){return this._push(jo,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(qn,1,0):this.uint32(t)._push(yu,t,e)}string(e){let t=Jo(e);return t!==0?this.uint32(t)._push(Un,t,e):this._push(qn,1,0)}fork(){return this.states=new zn(this),this.head=this.tail=new It(Hn,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 It(Hn,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=gu(this.len),r=0;for(;e!=null;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}};function qn(s,e,t){e[t]=s&255}function bu(s,e,t){for(;s>127;)e[t++]=s&127|128,s>>>=7;e[t]=s}var Vn=class extends It{next;constructor(e,t){super(bu,e,t),this.next=void 0}};function Js(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 xs(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 yu(s,e,t){e.set(s,t)}globalThis.Buffer!=null&&(vs.prototype.bytes=function(s){let e=s.length>>>0;return this.uint32(e),e>0&&this._push(wu,e,s),this},vs.prototype.string=function(s){let e=globalThis.Buffer.byteLength(s);return this.uint32(e),e>0&&this._push(xu,e,s),this});function wu(s,e,t){e.set(s,t)}function xu(s,e,t){s.length<40?Un(s,e,t):e.utf8Write!=null?e.utf8Write(s,t):e.set(z(s),t)}function Wn(){return new vs}function be(s,e){let t=Wn();return e.encode(s,t,{lengthDelimited:!1}),t.finish()}var Wt;(function(s){s[s.VARINT=0]="VARINT",s[s.BIT64=1]="BIT64",s[s.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",s[s.START_GROUP=3]="START_GROUP",s[s.END_GROUP=4]="END_GROUP",s[s.BIT32=5]="BIT32"})(Wt||(Wt={}));function Qs(s,e,t,r){return{name:s,type:e,encode:t,decode:r}}function $n(s){function e(n){if(s[n.toString()]==null)throw new Error("Invalid enum value");return s[n]}let t=function(i,o){let a=e(i);o.int32(a)},r=function(i){let o=i.int32();return e(o)};return Qs("enum",Wt.VARINT,t,r)}function ye(s,e){return Qs("message",Wt.LENGTH_DELIMITED,s,e)}var Te=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var te;(function(s){s.RSA="RSA",s.Ed25519="Ed25519",s.secp256k1="secp256k1",s.ECDSA="ECDSA"})(te||(te={}));var Zn;(function(s){s[s.RSA=0]="RSA",s[s.Ed25519=1]="Ed25519",s[s.secp256k1=2]="secp256k1",s[s.ECDSA=3]="ECDSA"})(Zn||(Zn={}));(function(s){s.codec=()=>$n(Zn)})(te||(te={}));var He;(function(s){let e;s.codec=()=>(e==null&&(e=ye((t,r,n={})=>{n.lengthDelimited!==!1&&r.fork(),t.Type!=null&&(r.uint32(8),te.codec().encode(t.Type,r)),t.Data!=null&&(r.uint32(18),r.bytes(t.Data)),n.lengthDelimited!==!1&&r.ldelim()},(t,r,n={})=>{let i={},o=r==null?t.len:t.pos+r;for(;t.pos<o;){let a=t.uint32();switch(a>>>3){case 1:{i.Type=te.codec().decode(t);break}case 2:{i.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return i})),e),s.encode=t=>be(t,s.codec()),s.decode=(t,r)=>ge(t,s.codec(),r)})(He||(He={}));var jn;(function(s){let e;s.codec=()=>(e==null&&(e=ye((t,r,n={})=>{n.lengthDelimited!==!1&&r.fork(),t.Type!=null&&(r.uint32(8),te.codec().encode(t.Type,r)),t.Data!=null&&(r.uint32(18),r.bytes(t.Data)),n.lengthDelimited!==!1&&r.ldelim()},(t,r,n={})=>{let i={},o=r==null?t.len:t.pos+r;for(;t.pos<o;){let a=t.uint32();switch(a>>>3){case 1:{i.Type=te.codec().decode(t);break}case 2:{i.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return i})),e),s.encode=t=>be(t,s.codec()),s.decode=(t,r)=>ge(t,s.codec(),r)})(jn||(jn={}));function er(s){if(isNaN(s)||s<=0)throw new W("random bytes length must be a Number bigger than 0");return ot(s)}var Ss={};Ee(Ss,{MAX_RSA_KEY_SIZE:()=>Xn,generateRSAKeyPair:()=>ia,jwkToJWKKeyPair:()=>oa,jwkToPkcs1:()=>_u,jwkToPkix:()=>ei,jwkToRSAPrivateKey:()=>ni,pkcs1MessageToJwk:()=>Jn,pkcs1MessageToRSAPrivateKey:()=>ti,pkcs1ToJwk:()=>Su,pkcs1ToRSAPrivateKey:()=>na,pkixMessageToJwk:()=>Qn,pkixMessageToRSAPublicKey:()=>ri,pkixToJwk:()=>Iu,pkixToRSAPublicKey:()=>si});var $t=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Ss.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return oe.createV1(114,this._multihash)}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Se(this.raw,e.raw)}verify(e,t,r){return ra(this.jwk,t,e,r)}},Es=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Ss.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Se(this.raw,e.raw)}sign(e,t){return sa(this.jwk,e,t)}};var Xn=8192,Yn=18,vu=1062,Eu=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Su(s){let e=$e(s);return Jn(e)}function Jn(s){return{n:G(s[1],"base64url"),e:G(s[2],"base64url"),d:G(s[3],"base64url"),p:G(s[4],"base64url"),q:G(s[5],"base64url"),dp:G(s[6],"base64url"),dq:G(s[7],"base64url"),qi:G(s[8],"base64url"),kty:"RSA"}}function _u(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 W("JWK was missing components");return it([_e(Uint8Array.from([0])),_e(z(s.n,"base64url")),_e(z(s.e,"base64url")),_e(z(s.d,"base64url")),_e(z(s.p,"base64url")),_e(z(s.q,"base64url")),_e(z(s.dp,"base64url")),_e(z(s.dq,"base64url")),_e(z(s.qi,"base64url"))]).subarray()}function Iu(s){let e=$e(s,{offset:0});return Qn(e)}function Qn(s){let e=$e(s[1],{offset:0});return{kty:"RSA",n:G(e[0],"base64url"),e:G(e[1],"base64url")}}function ei(s){if(s.n==null||s.e==null)throw new W("JWK was missing components");return it([Eu,Us(it([_e(z(s.n,"base64url")),_e(z(s.e,"base64url"))]))]).subarray()}function na(s){let e=$e(s);return ti(e)}function ti(s){let e=Jn(s);return ni(e)}function si(s,e){if(s.byteLength>=vu)throw new Lt("Key size is too large");let t=$e(s,{offset:0});return ri(t,s,e)}function ri(s,e,t){let r=Qn(s);if(t==null){let n=Ft(He.encode({Type:te.RSA,Data:e}));t=Oe(Yn,n)}return new $t(r,t)}function ni(s){if(ca(s)>Xn)throw new W("Key size is too large");let e=oa(s),t=Ft(He.encode({Type:te.RSA,Data:ei(e.publicKey)})),r=Oe(Yn,t);return new Es(e.privateKey,new $t(e.publicKey,r))}async function ia(s){if(s>Xn)throw new W("Key size is too large");let e=await aa(s),t=Ft(He.encode({Type:te.RSA,Data:ei(e.publicKey)})),r=Oe(Yn,t);return new Es(e.privateKey,new $t(e.publicKey,r))}function oa(s){if(s==null)throw new W("Missing key parameter");return{privateKey:s,publicKey:{kty:s.kty,n:s.n,e:s.e}}}async function aa(s,e){let t=await Me.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 Tu(t,e);return{privateKey:r[0],publicKey:r[1]}}async function sa(s,e,t){let r=await Me.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let n=await Me.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(n,0,n.byteLength)}async function ra(s,e,t,r){let n=await Me.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();let i=await Me.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray());return r?.signal?.throwIfAborted(),i}async function Tu(s,e){if(s.privateKey==null||s.publicKey==null)throw new W("Private and public key are required");let t=await Promise.all([Me.get().subtle.exportKey("jwk",s.privateKey),Me.get().subtle.exportKey("jwk",s.publicKey)]);return e?.signal?.throwIfAborted(),t}function ca(s){if(s.kty!=="RSA")throw new W("invalid key type");if(s.n==null)throw new W("invalid key modulus");return z(s.n,"base64url").length*8}var tr=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Ks(e),K(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),je(n)}update(e){return Kt(this),this.iHash.update(e),this}digestInto(e){Kt(this),K(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash: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()}},ii=(s,e,t)=>new tr(s,e).update(t).digest();ii.create=(s,e)=>new tr(s,e);var la=(s,e)=>(s+(s>=0?e:-e)/ua)/e;function Au(s,e,t){let[[r,n],[i,o]]=e,a=la(o*s,t),c=la(-n*s,t),f=s-a*r-c*i,m=-a*n-c*o,h=f<et,g=m<et;h&&(f=-f),g&&(m=-m);let l=gs(Math.ceil(dn(t)/2))+Zt;if(f<et||f>=l||m<et||m>=l)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:h,k1:f,k2neg:g,k2:m}}function ai(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function oi(s,e){let t={};for(let r of Object.keys(e))t[r]=s[r]===void 0?e[r]:s[r];return Qe(t.lowS,"lowS"),Qe(t.prehash,"prehash"),t.format!==void 0&&ai(t.format),t}var ci=class extends Error{constructor(e=""){super(e)}},dt={Err:ci,_tlv:{encode:(s,e)=>{let{Err:t}=dt;if(s<0||s>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let r=e.length/2,n=ps(r);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let i=r>127?ps(n.length/2|128):"";return ps(s)+i+n+e},decode(s,e){let{Err:t}=dt,r=0;if(s<0||s>256)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 c=n&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let f=e.subarray(r,r+c);if(f.length!==c)throw new t("tlv.decode: length bytes not complete");if(f[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let m of f)o=o<<8|m;if(r+=c,o<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(s){let{Err:e}=dt;if(s<et)throw new e("integer: negative integers are not allowed");let t=ps(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}=dt;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Gt(s)}},toSig(s){let{Err:e,_int:t,_tlv:r}=dt,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:c}=r.decode(2,i),{v:f,l:m}=r.decode(2,c);if(m.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(f)}},hexFromSig(s){let{_tlv:e,_int:t}=dt,r=e.encode(2,t.encode(s.r)),n=e.encode(2,t.encode(s.s)),i=r+n;return e.encode(48,i)}},et=BigInt(0),Zt=BigInt(1),ua=BigInt(2),sr=BigInt(3),Du=BigInt(4);function ha(s,e={}){let t=Vs("weierstrass",s,e),{Fp:r,Fn:n}=t,i=t.CURVE,{h:o,n:a}=i;ut(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let f=da(r,n);function m(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(R,S,_){let{x,y:A}=S.toAffine(),P=r.toBytes(x);if(Qe(_,"isCompressed"),_){m();let B=!r.isOdd(A);return Ie(fa(B),P)}else return Ie(Uint8Array.of(4),P,r.toBytes(A))}function g(R){K(R,void 0,"Point");let{publicKey:S,publicKeyUncompressed:_}=f,x=R.length,A=R[0],P=R.subarray(1);if(x===S&&(A===2||A===3)){let B=r.fromBytes(P);if(!r.isValid(B))throw new Error("bad point: is not on curve, wrong x");let C=p(B),k;try{k=r.sqrt(C)}catch(j){let V=j instanceof Error?": "+j.message:"";throw new Error("bad point: is not on curve, sqrt error"+V)}m();let N=r.isOdd(k);return(A&1)===1!==N&&(k=r.neg(k)),{x:B,y:k}}else if(x===_&&A===4){let B=r.BYTES,C=r.fromBytes(P.subarray(0,B)),k=r.fromBytes(P.subarray(B,B*2));if(!d(C,k))throw new Error("bad point: is not on curve");return{x:C,y:k}}else throw new Error(`bad point: got length ${x}, expected compressed=${S} or uncompressed=${_}`)}let l=e.toBytes||h,u=e.fromBytes||g;function p(R){let S=r.sqr(R),_=r.mul(S,R);return r.add(r.add(_,r.mul(R,i.a)),i.b)}function d(R,S){let _=r.sqr(S),x=p(R);return r.eql(_,x)}if(!d(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let b=r.mul(r.pow(i.a,sr),Du),y=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(b,y)))throw new Error("bad curve params: a or b");function v(R,S,_=!1){if(!r.isValid(S)||_&&r.is0(S))throw new Error(`bad point coordinate ${R}`);return S}function T(R){if(!(R instanceof w))throw new Error("Weierstrass Point expected")}function E(R){if(!c||!c.basises)throw new Error("no endo");return Au(R,c.basises,n.ORDER)}let M=Ht((R,S)=>{let{X:_,Y:x,Z:A}=R;if(r.eql(A,r.ONE))return{x:_,y:x};let P=R.is0();S==null&&(S=P?r.ONE:r.inv(A));let B=r.mul(_,S),C=r.mul(x,S),k=r.mul(A,S);if(P)return{x:r.ZERO,y:r.ZERO};if(!r.eql(k,r.ONE))throw new Error("invZ was invalid");return{x:B,y:C}}),D=Ht(R=>{if(R.is0()){if(e.allowInfinityPoint&&!r.is0(R.Y))return;throw new Error("bad point: ZERO")}let{x:S,y:_}=R.toAffine();if(!r.isValid(S)||!r.isValid(_))throw new Error("bad point: x or y not field elements");if(!d(S,_))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function I(R,S,_,x,A){return _=new w(r.mul(_.X,R),_.Y,_.Z),S=ys(x,S),_=ys(A,_),S.add(_)}class w{static BASE=new w(i.Gx,i.Gy,r.ONE);static ZERO=new w(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=n;X;Y;Z;constructor(S,_,x){this.X=v("x",S),this.Y=v("y",_,!0),this.Z=v("z",x),Object.freeze(this)}static CURVE(){return i}static fromAffine(S){let{x:_,y:x}=S||{};if(!S||!r.isValid(_)||!r.isValid(x))throw new Error("invalid affine point");if(S instanceof w)throw new Error("projective point not allowed");return r.is0(_)&&r.is0(x)?w.ZERO:new w(_,x,r.ONE)}static fromBytes(S){let _=w.fromAffine(u(K(S,void 0,"point")));return _.assertValidity(),_}static fromHex(S){return w.fromBytes(Ye(S))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(S=8,_=!0){return O.createCache(this,S),_||this.multiply(sr),this}assertValidity(){D(this)}hasEvenY(){let{y:S}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(S)}equals(S){T(S);let{X:_,Y:x,Z:A}=this,{X:P,Y:B,Z:C}=S,k=r.eql(r.mul(_,C),r.mul(P,A)),N=r.eql(r.mul(x,C),r.mul(B,A));return k&&N}negate(){return new w(this.X,r.neg(this.Y),this.Z)}double(){let{a:S,b:_}=i,x=r.mul(_,sr),{X:A,Y:P,Z:B}=this,C=r.ZERO,k=r.ZERO,N=r.ZERO,U=r.mul(A,A),j=r.mul(P,P),V=r.mul(B,B),F=r.mul(A,P);return F=r.add(F,F),N=r.mul(A,B),N=r.add(N,N),C=r.mul(S,N),k=r.mul(x,V),k=r.add(C,k),C=r.sub(j,k),k=r.add(j,k),k=r.mul(C,k),C=r.mul(F,C),N=r.mul(x,N),V=r.mul(S,V),F=r.sub(U,V),F=r.mul(S,F),F=r.add(F,N),N=r.add(U,U),U=r.add(N,U),U=r.add(U,V),U=r.mul(U,F),k=r.add(k,U),V=r.mul(P,B),V=r.add(V,V),U=r.mul(V,F),C=r.sub(C,U),N=r.mul(V,j),N=r.add(N,N),N=r.add(N,N),new w(C,k,N)}add(S){T(S);let{X:_,Y:x,Z:A}=this,{X:P,Y:B,Z:C}=S,k=r.ZERO,N=r.ZERO,U=r.ZERO,j=i.a,V=r.mul(i.b,sr),F=r.mul(_,P),X=r.mul(x,B),ie=r.mul(A,C),Ne=r.add(_,x),Y=r.add(P,B);Ne=r.mul(Ne,Y),Y=r.add(F,X),Ne=r.sub(Ne,Y),Y=r.add(_,A);let ce=r.add(P,C);return Y=r.mul(Y,ce),ce=r.add(F,ie),Y=r.sub(Y,ce),ce=r.add(x,A),k=r.add(B,C),ce=r.mul(ce,k),k=r.add(X,ie),ce=r.sub(ce,k),U=r.mul(j,Y),k=r.mul(V,ie),U=r.add(k,U),k=r.sub(X,U),U=r.add(X,U),N=r.mul(k,U),X=r.add(F,F),X=r.add(X,F),ie=r.mul(j,ie),Y=r.mul(V,Y),X=r.add(X,ie),ie=r.sub(F,ie),ie=r.mul(j,ie),Y=r.add(Y,ie),F=r.mul(X,Y),N=r.add(N,F),F=r.mul(ce,Y),k=r.mul(Ne,k),k=r.sub(k,F),F=r.mul(Ne,X),U=r.mul(ce,U),U=r.add(U,F),new w(k,N,U)}subtract(S){return this.add(S.negate())}is0(){return this.equals(w.ZERO)}multiply(S){let{endo:_}=e;if(!n.isValidNot0(S))throw new Error("invalid scalar: out of range");let x,A,P=B=>O.cached(this,B,C=>St(w,C));if(_){let{k1neg:B,k1:C,k2neg:k,k2:N}=E(S),{p:U,f:j}=P(C),{p:V,f:F}=P(N);A=j.add(F),x=I(_.beta,U,V,B,k)}else{let{p:B,f:C}=P(S);x=B,A=C}return St(w,[x,A])[0]}multiplyUnsafe(S){let{endo:_}=e,x=this;if(!n.isValid(S))throw new Error("invalid scalar: out of range");if(S===et||x.is0())return w.ZERO;if(S===Zt)return x;if(O.hasCache(this))return this.multiply(S);if(_){let{k1neg:A,k1:P,k2neg:B,k2:C}=E(S),{p1:k,p2:N}=Uo(w,x,P,C);return I(_.beta,k,N,A,B)}else return O.unsafe(x,S)}toAffine(S){return M(this,S)}isTorsionFree(){let{isTorsionFree:S}=e;return o===Zt?!0:S?S(w,this):O.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:S}=e;return o===Zt?this:S?S(w,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(S=!0){return Qe(S,"isCompressed"),this.assertValidity(),l(w,this,S)}toHex(S=!0){return Xe(this.toBytes(S))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let L=n.BITS,O=new Vt(w,e.endo?Math.ceil(L/2):L);return w.BASE.precompute(8),w}function fa(s){return Uint8Array.of(s?2:3)}function da(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Mu(s,e={}){let{Fn:t}=s,r=e.randomBytes||ot,n=Object.assign(da(s.Fp,t),{seed:bn(t.ORDER)});function i(l){try{let u=t.fromBytes(l);return t.isValidNot0(u)}catch{return!1}}function o(l,u){let{publicKey:p,publicKeyUncompressed:d}=n;try{let b=l.length;return u===!0&&b!==p||u===!1&&b!==d?!1:!!s.fromBytes(l)}catch{return!1}}function a(l=r(n.seed)){return yn(K(l,n.seed,"seed"),t.ORDER)}function c(l,u=!0){return s.BASE.multiply(t.fromBytes(l)).toBytes(u)}function f(l){let{secretKey:u,publicKey:p,publicKeyUncompressed:d}=n;if(!bt(l)||"_lengths"in t&&t._lengths||u===p)return;let b=K(l,void 0,"key").length;return b===p||b===d}function m(l,u,p=!0){if(f(l)===!0)throw new Error("first arg must be private key");if(f(u)===!1)throw new Error("second arg must be public key");let d=t.fromBytes(l);return s.fromBytes(u).multiply(d).toBytes(p)}let h={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},g=Ws(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:m,keygen:g,Point:s,utils:h,lengths:n})}function pa(s,e,t={}){Ks(e),ut(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let r=t.randomBytes||ot,n=t.hmac||((_,x)=>ii(e,_,x)),{Fp:i,Fn:o}=s,{ORDER:a,BITS:c}=o,{keygen:f,getPublicKey:m,getSharedSecret:h,utils:g,lengths:l}=Mu(s,t),u={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},p=a*ua<i.ORDER;function d(_){let x=a>>Zt;return _>x}function b(_,x){if(!o.isValidNot0(x))throw new Error(`invalid signature ${_}: out of range 1..Point.Fn.ORDER`);return x}function y(){if(p)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function v(_,x){ai(x);let A=l.signature,P=x==="compact"?A:x==="recovered"?A+1:void 0;return K(_,P)}class T{r;s;recovery;constructor(x,A,P){if(this.r=b("r",x),this.s=b("s",A),P!=null){if(y(),![0,1,2,3].includes(P))throw new Error("invalid recovery id");this.recovery=P}Object.freeze(this)}static fromBytes(x,A=u.format){v(x,A);let P;if(A==="der"){let{r:N,s:U}=dt.toSig(K(x));return new T(N,U)}A==="recovered"&&(P=x[0],A="compact",x=x.subarray(1));let B=l.signature/2,C=x.subarray(0,B),k=x.subarray(B,B*2);return new T(o.fromBytes(C),o.fromBytes(k),P)}static fromHex(x,A){return this.fromBytes(Ye(x),A)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new T(this.r,this.s,x)}recoverPublicKey(x){let{r:A,s:P}=this,B=this.assertRecovery(),C=B===2||B===3?A+a:A;if(!i.isValid(C))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let k=i.toBytes(C),N=s.fromBytes(Ie(fa((B&1)===0),k)),U=o.inv(C),j=M(K(x,void 0,"msgHash")),V=o.create(-j*U),F=o.create(P*U),X=s.BASE.multiplyUnsafe(V).add(N.multiplyUnsafe(F));if(X.is0())throw new Error("invalid recovery: point at infinify");return X.assertValidity(),X}hasHighS(){return d(this.s)}toBytes(x=u.format){if(ai(x),x==="der")return Ye(dt.hexFromSig(this));let{r:A,s:P}=this,B=o.toBytes(A),C=o.toBytes(P);return x==="recovered"?(y(),Ie(Uint8Array.of(this.assertRecovery()),B,C)):Ie(B,C)}toHex(x){return Xe(this.toBytes(x))}}let E=t.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let A=Gt(x),P=x.length*8-c;return P>0?A>>BigInt(P):A},M=t.bits2int_modN||function(x){return o.create(E(x))},D=gs(c);function I(_){return ms("num < 2^"+c,_,et,D),o.toBytes(_)}function w(_,x){return K(_,void 0,"message"),x?K(e(_),void 0,"prehashed message"):_}function L(_,x,A){let{lowS:P,prehash:B,extraEntropy:C}=oi(A,u);_=w(_,B);let k=M(_),N=o.fromBytes(x);if(!o.isValidNot0(N))throw new Error("invalid private key");let U=[I(N),I(k)];if(C!=null&&C!==!1){let X=C===!0?r(l.secretKey):C;U.push(K(X,void 0,"extraEntropy"))}let j=Ie(...U),V=k;function F(X){let ie=E(X);if(!o.isValidNot0(ie))return;let Ne=o.inv(ie),Y=s.BASE.multiply(ie).toAffine(),ce=o.create(Y.x);if(ce===et)return;let Ps=o.create(Ne*o.create(V+ce*N));if(Ps===et)return;let vi=(Y.x===ce?0:2)|Number(Y.y&Zt),Ei=Ps;return P&&d(Ps)&&(Ei=o.neg(Ps),vi^=1),new T(ce,Ei,p?void 0:vi)}return{seed:j,k2sig:F}}function O(_,x,A={}){let{seed:P,k2sig:B}=L(_,x,A);return vo(e.outputLen,o.BYTES,n)(P,B).toBytes(A.format)}function R(_,x,A,P={}){let{lowS:B,prehash:C,format:k}=oi(P,u);if(A=K(A,void 0,"publicKey"),x=w(x,C),!bt(_)){let N=_ instanceof T?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+N)}v(_,k);try{let N=T.fromBytes(_,k),U=s.fromBytes(A);if(B&&N.hasHighS())return!1;let{r:j,s:V}=N,F=M(x),X=o.inv(V),ie=o.create(F*X),Ne=o.create(j*X),Y=s.BASE.multiplyUnsafe(ie).add(U.multiplyUnsafe(Ne));return Y.is0()?!1:o.create(Y.x)===j}catch{return!1}}function S(_,x,A={}){let{prehash:P}=oi(A,u);return x=w(x,P),T.fromBytes(_,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:f,getPublicKey:m,getSharedSecret:h,utils:g,lengths:l,Point:s,sign:O,verify:R,recoverPublicKey:S,Signature:T,hash:e})}var ui={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Pu={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var ma=BigInt(2);function Lu(s){let e=ui.p,t=BigInt(3),r=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),f=s*s*s%e,m=f*f*s%e,h=$(m,t,e)*m%e,g=$(h,t,e)*m%e,l=$(g,ma,e)*f%e,u=$(l,n,e)*l%e,p=$(u,i,e)*u%e,d=$(p,a,e)*p%e,b=$(d,c,e)*d%e,y=$(b,a,e)*p%e,v=$(y,t,e)*m%e,T=$(v,o,e)*u%e,E=$(T,r,e)*f%e,M=$(E,ma,e);if(!li.eql(li.sqr(M),s))throw new Error("Cannot find square root");return M}var li=qt(ui.p,{sqrt:Lu}),ku=ha(ui,{Fp:li,endo:Pu}),jt=pa(ku,Ft);function ga(s,e,t,r){let n=nt.digest(t instanceof Uint8Array?t:t.subarray());if(js(n))return n.then(({digest:i})=>(r?.signal?.throwIfAborted(),jt.verify(e,i,s,{prehash:!1,format:"der"}))).catch(i=>{throw i.name==="AbortError"?i:new ws(String(i))});try{return r?.signal?.throwIfAborted(),jt.verify(e,n.digest,s,{prehash:!1,format:"der"})}catch(i){throw new ws(String(i))}}var rr=class{type="secp256k1";raw;_key;constructor(e){this._key=ya(e),this.raw=ba(this._key)}toMultihash(){return Le.digest(Ke(this))}toCID(){return oe.createV1(114,this.toMultihash())}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Se(this.raw,e.raw)}verify(e,t,r){return ga(this._key,t,e,r)}};function hi(s){return new rr(s)}function ba(s){return jt.Point.fromBytes(s).toBytes()}function ya(s){try{return jt.Point.fromBytes(s),s}catch(e){throw new Lt(String(e))}}function _s(s,e){let{Type:t,Data:r}=He.decode(s),n=r??new Uint8Array;switch(t){case te.RSA:return si(n,e);case te.Ed25519:return Tn(n);case te.secp256k1:return hi(n);case te.ECDSA:return en(n);default:throw new kt}}function wa(s){let{Type:e,Data:t}=He.decode(s.digest),r=t??new Uint8Array;switch(e){case te.Ed25519:return Tn(r);case te.secp256k1:return hi(r);case te.ECDSA:return en(r);default:throw new kt}}function Ke(s){return He.encode({Type:te[s.type],Data:s.raw})}var xa=Symbol.for("nodejs.util.inspect.custom"),Bu=114,Is=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()})`}[Tr]=!0;toString(){return this.string==null&&(this.string=Q.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return oe.createV1(Bu,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Se(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Se(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[xa](){return`PeerId(${this.toString()})`}},nr=class extends Is{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},ir=class extends Is{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},or=class extends Is{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Ru=2336,Ts=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Le.digest(z(this.url))}[xa](){return`PeerId(${this.url})`}[Tr]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return oe.createV1(Ru,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=G(e)),e.toString()===this.toString())}};var Cu=114,va=2336;function Tt(s,e){let t;if(s.charAt(0)==="1"||s.charAt(0)==="Q")t=Ue(Q.decode(`z${s}`));else{if(s.startsWith("k51qzi5uqu5")||s.startsWith("kzwfwjn5ji4")||s.startsWith("k2k4r8")||s.startsWith("bafz"))return Nu(oe.parse(s));if(e==null)throw new W('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ue(e.decode(s))}return Xt(t)}function Xt(s){if(Uu(s))return new nr({multihash:s});if(Ou(s))try{let e=wa(s);if(e.type==="Ed25519")return new ir({multihash:s,publicKey:e});if(e.type==="secp256k1")return new or({multihash:s,publicKey:e})}catch{let t=G(s.digest);return new Ts(new URL(t))}throw new Bs("Supplied PeerID Multihash is invalid")}function Nu(s){if(s?.multihash==null||s.version==null||s.version===1&&s.code!==Cu&&s.code!==va)throw new ks("Supplied PeerID CID is invalid");if(s.code===va){let e=G(s.multihash.digest);return new Ts(new URL(e))}return Xt(s.multihash)}function Ou(s){return s.code===Le.code}function Uu(s){return s.code===nt.code}var ar=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Yt=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},cr=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},As=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function lr(s){return s[Symbol.asyncIterator]!=null}function Ea(s,e){if(s.byteLength>e)throw new Yt("Message length too long")}var hr=s=>{let e=Pe(s),t=le(e);return Bn(s,t),hr.bytes=e,t};hr.bytes=0;function Jt(s,e){e=e??{};let t=e.lengthEncoder??hr,r=e?.maxDataLength??4194304;function*n(i){Ea(i,r);let o=t(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return lr(s)?(async function*(){for await(let i of s)yield*n(i)})():(function*(){for(let i of s)yield*n(i)})()}Jt.single=(s,e)=>{e=e??{};let t=e.lengthEncoder??hr,r=e?.maxDataLength??4194304;return Ea(s,r),new se(t(s.byteLength),s)};var At;(function(s){s[s.LENGTH=0]="LENGTH",s[s.DATA=1]="DATA"})(At||(At={}));var fi=s=>{let e=Rn(s);return fi.bytes=Pe(e),e};fi.bytes=0;function Ds(s,e){let t=new se,r=At.LENGTH,n=-1,i=e?.lengthDecoder??fi,o=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(r===At.LENGTH)try{if(n=i(t),n<0)throw new ar("Invalid message length");if(n>a)throw new Yt("Message length too long");let f=i.bytes;t.consume(f),e?.onLength!=null&&e.onLength(n),r=At.DATA}catch(f){if(f instanceof RangeError){if(t.byteLength>o)throw new cr("Message length length too long");break}throw f}if(r===At.DATA){if(t.byteLength<n)break;let f=t.sublist(0,n);t.consume(n),e?.onData!=null&&e.onData(f),yield f,r=At.LENGTH}}}return lr(s)?(async function*(){for await(let f of s)t.append(f),yield*c();if(t.byteLength>0)throw new As("Unexpected end of input")})():(function*(){for(let f of s)t.append(f),yield*c();if(t.byteLength>0)throw new As("Unexpected end of input")})()}Ds.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 Ds(r,{...e??{},onLength:i=>{t=i}})};function tt(){let s={};return s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),s}var fr=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Qt=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new fr(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new fr(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var di=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Dt(s={}){return Fu(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 Fu(s,e){e=e??{};let t=e.onEnd,r=new Qt,n,i,o,a=tt(),c=async()=>{try{return r.isEmpty()?o?{done:!0}:await new Promise((d,b)=>{i=y=>{i=null,r.push(y);try{d(s(r))}catch(v){b(v)}return n}}):s(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=tt()})}},f=d=>i!=null?i(d):(r.push(d),n),m=d=>(r=new Qt,i!=null?i({error:d}):(r.push({error:d}),n)),h=d=>{if(o)return n;if(e?.objectMode!==!0&&d?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:d})},g=d=>o?n:(o=!0,d!=null?m(d):f({done:!0})),l=()=>(r=new Qt,g(),{done:!0}),u=d=>(g(d),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:c,return:l,throw:u,push:h,end:g,get readableLength(){return r.size},onEmpty:async d=>{let b=d?.signal;if(b?.throwIfAborted(),r.isEmpty())return;let y,v;b!=null&&(y=new Promise((T,E)=>{v=()=>{E(new di)},b.addEventListener("abort",v)}));try{await Promise.race([a.promise,y])}finally{v!=null&&b!=null&&b?.removeEventListener("abort",v)}}},t==null)return n;let p=n;return n={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(d){return p.throw(d),t!=null&&(t(d),t=void 0),{done:!0}},return(){return p.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(d){return p.end(d),t!=null&&(t(d),t=void 0),n},get readableLength(){return p.readableLength},onEmpty:d=>p.onEmpty(d)},n}var dr=class extends Error{type;code;constructor(e,t,r){super(e??"The operation was aborted"),this.type="aborted",this.name=r??"AbortError",this.code=t??"ABORT_ERR"}};async function Sa(s,e,t){if(e==null)return s;if(e.aborted)return s.catch(()=>{}),Promise.reject(new dr(t?.errorMessage,t?.errorCode,t?.errorName));let r,n=new dr(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([s,new Promise((i,o)=>{r=()=>{o(n)},e.addEventListener("abort",r)})])}finally{r!=null&&e.removeEventListener("abort",r)}}var pi=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=tt(),this.haveNext=tt()}[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=tt(),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=tt(),await Sa(this.readNext.promise,t?.signal,t)}};function _a(){return new pi}function Gu(s){return s[Symbol.asyncIterator]!=null}async function Hu(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*qu(s){let e=new AbortController,t=_a();Hu(s,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*zu(s){for(let e of s)yield*e}function Vu(...s){let e=[];for(let t of s)Gu(t)||e.push(t);return e.length===s.length?zu(e):qu(s)}var Ia=Vu;function Ms(s,...e){if(s==null)throw new Error("Empty pipeline");if(mi(s)){let r=s;s=()=>r.source}else if(Aa(s)||Ta(s)){let r=s;s=()=>r}let t=[s,...e];if(t.length>1&&mi(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++)mi(t[r])&&(t[r]=$u(t[r]));return Wu(...t)}var Wu=(...s)=>{let e;for(;s.length>0;)e=s.shift()(e);return e},Ta=s=>s?.[Symbol.asyncIterator]!=null,Aa=s=>s?.[Symbol.iterator]!=null,mi=s=>s==null?!1:s.sink!=null&&s.source!=null,$u=s=>e=>{let t=s.sink(e);if(t?.then!=null){let r=Dt({objectMode:!0});t.then(()=>{r.end()},o=>{r.end(o)});let n,i=s.source;if(Ta(i))n=async function*(){yield*i,r.end()};else if(Aa(i))n=function*(){yield*i,r.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Ia(r,n())}return s.source};var Da={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxIdontwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};var st;(function(s){let e;(function(h){let g;h.codec=()=>(g==null&&(g=ye((l,u,p={})=>{p.lengthDelimited!==!1&&u.fork(),l.subscribe!=null&&(u.uint32(8),u.bool(l.subscribe)),l.topic!=null&&(u.uint32(18),u.string(l.topic)),p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let d={},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let y=l.uint32();switch(y>>>3){case 1:{d.subscribe=l.bool();break}case 2:{d.topic=l.string();break}default:{l.skipType(y&7);break}}}return d})),g),h.encode=l=>be(l,h.codec()),h.decode=(l,u)=>ge(l,h.codec(),u)})(e=s.SubOpts||(s.SubOpts={}));let t;(function(h){let g;h.codec=()=>(g==null&&(g=ye((l,u,p={})=>{p.lengthDelimited!==!1&&u.fork(),l.from!=null&&(u.uint32(10),u.bytes(l.from)),l.data!=null&&(u.uint32(18),u.bytes(l.data)),l.seqno!=null&&(u.uint32(26),u.bytes(l.seqno)),l.topic!=null&&l.topic!==""&&(u.uint32(34),u.string(l.topic)),l.signature!=null&&(u.uint32(42),u.bytes(l.signature)),l.key!=null&&(u.uint32(50),u.bytes(l.key)),p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let d={topic:""},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let y=l.uint32();switch(y>>>3){case 1:{d.from=l.bytes();break}case 2:{d.data=l.bytes();break}case 3:{d.seqno=l.bytes();break}case 4:{d.topic=l.string();break}case 5:{d.signature=l.bytes();break}case 6:{d.key=l.bytes();break}default:{l.skipType(y&7);break}}}return d})),g),h.encode=l=>be(l,h.codec()),h.decode=(l,u)=>ge(l,h.codec(),u)})(t=s.Message||(s.Message={}));let r;(function(h){let g;h.codec=()=>(g==null&&(g=ye((l,u,p={})=>{if(p.lengthDelimited!==!1&&u.fork(),l.ihave!=null)for(let d of l.ihave)u.uint32(10),s.ControlIHave.codec().encode(d,u);if(l.iwant!=null)for(let d of l.iwant)u.uint32(18),s.ControlIWant.codec().encode(d,u);if(l.graft!=null)for(let d of l.graft)u.uint32(26),s.ControlGraft.codec().encode(d,u);if(l.prune!=null)for(let d of l.prune)u.uint32(34),s.ControlPrune.codec().encode(d,u);if(l.idontwant!=null)for(let d of l.idontwant)u.uint32(42),s.ControlIDontWant.codec().encode(d,u);p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let d={ihave:[],iwant:[],graft:[],prune:[],idontwant:[]},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let y=l.uint32();switch(y>>>3){case 1:{if(p.limits?.ihave!=null&&d.ihave.length===p.limits.ihave)throw new Te('Decode error - map field "ihave" had too many elements');d.ihave.push(s.ControlIHave.codec().decode(l,l.uint32(),{limits:p.limits?.ihave$}));break}case 2:{if(p.limits?.iwant!=null&&d.iwant.length===p.limits.iwant)throw new Te('Decode error - map field "iwant" had too many elements');d.iwant.push(s.ControlIWant.codec().decode(l,l.uint32(),{limits:p.limits?.iwant$}));break}case 3:{if(p.limits?.graft!=null&&d.graft.length===p.limits.graft)throw new Te('Decode error - map field "graft" had too many elements');d.graft.push(s.ControlGraft.codec().decode(l,l.uint32(),{limits:p.limits?.graft$}));break}case 4:{if(p.limits?.prune!=null&&d.prune.length===p.limits.prune)throw new Te('Decode error - map field "prune" had too many elements');d.prune.push(s.ControlPrune.codec().decode(l,l.uint32(),{limits:p.limits?.prune$}));break}case 5:{if(p.limits?.idontwant!=null&&d.idontwant.length===p.limits.idontwant)throw new Te('Decode error - map field "idontwant" had too many elements');d.idontwant.push(s.ControlIDontWant.codec().decode(l,l.uint32(),{limits:p.limits?.idontwant$}));break}default:{l.skipType(y&7);break}}}return d})),g),h.encode=l=>be(l,h.codec()),h.decode=(l,u)=>ge(l,h.codec(),u)})(r=s.ControlMessage||(s.ControlMessage={}));let n;(function(h){let g;h.codec=()=>(g==null&&(g=ye((l,u,p={})=>{if(p.lengthDelimited!==!1&&u.fork(),l.topicID!=null&&(u.uint32(10),u.string(l.topicID)),l.messageIDs!=null)for(let d of l.messageIDs)u.uint32(18),u.bytes(d);p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let d={messageIDs:[]},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let y=l.uint32();switch(y>>>3){case 1:{d.topicID=l.string();break}case 2:{if(p.limits?.messageIDs!=null&&d.messageIDs.length===p.limits.messageIDs)throw new Te('Decode error - map field "messageIDs" had too many elements');d.messageIDs.push(l.bytes());break}default:{l.skipType(y&7);break}}}return d})),g),h.encode=l=>be(l,h.codec()),h.decode=(l,u)=>ge(l,h.codec(),u)})(n=s.ControlIHave||(s.ControlIHave={}));let i;(function(h){let g;h.codec=()=>(g==null&&(g=ye((l,u,p={})=>{if(p.lengthDelimited!==!1&&u.fork(),l.messageIDs!=null)for(let d of l.messageIDs)u.uint32(10),u.bytes(d);p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let d={messageIDs:[]},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let y=l.uint32();switch(y>>>3){case 1:{if(p.limits?.messageIDs!=null&&d.messageIDs.length===p.limits.messageIDs)throw new Te('Decode error - map field "messageIDs" had too many elements');d.messageIDs.push(l.bytes());break}default:{l.skipType(y&7);break}}}return d})),g),h.encode=l=>be(l,h.codec()),h.decode=(l,u)=>ge(l,h.codec(),u)})(i=s.ControlIWant||(s.ControlIWant={}));let o;(function(h){let g;h.codec=()=>(g==null&&(g=ye((l,u,p={})=>{p.lengthDelimited!==!1&&u.fork(),l.topicID!=null&&(u.uint32(10),u.string(l.topicID)),p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let d={},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let y=l.uint32();switch(y>>>3){case 1:{d.topicID=l.string();break}default:{l.skipType(y&7);break}}}return d})),g),h.encode=l=>be(l,h.codec()),h.decode=(l,u)=>ge(l,h.codec(),u)})(o=s.ControlGraft||(s.ControlGraft={}));let a;(function(h){let g;h.codec=()=>(g==null&&(g=ye((l,u,p={})=>{if(p.lengthDelimited!==!1&&u.fork(),l.topicID!=null&&(u.uint32(10),u.string(l.topicID)),l.peers!=null)for(let d of l.peers)u.uint32(18),s.PeerInfo.codec().encode(d,u);l.backoff!=null&&(u.uint32(24),u.uint64Number(l.backoff)),p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let d={peers:[]},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let y=l.uint32();switch(y>>>3){case 1:{d.topicID=l.string();break}case 2:{if(p.limits?.peers!=null&&d.peers.length===p.limits.peers)throw new Te('Decode error - map field "peers" had too many elements');d.peers.push(s.PeerInfo.codec().decode(l,l.uint32(),{limits:p.limits?.peers$}));break}case 3:{d.backoff=l.uint64Number();break}default:{l.skipType(y&7);break}}}return d})),g),h.encode=l=>be(l,h.codec()),h.decode=(l,u)=>ge(l,h.codec(),u)})(a=s.ControlPrune||(s.ControlPrune={}));let c;(function(h){let g;h.codec=()=>(g==null&&(g=ye((l,u,p={})=>{p.lengthDelimited!==!1&&u.fork(),l.peerID!=null&&(u.uint32(10),u.bytes(l.peerID)),l.signedPeerRecord!=null&&(u.uint32(18),u.bytes(l.signedPeerRecord)),p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let d={},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let y=l.uint32();switch(y>>>3){case 1:{d.peerID=l.bytes();break}case 2:{d.signedPeerRecord=l.bytes();break}default:{l.skipType(y&7);break}}}return d})),g),h.encode=l=>be(l,h.codec()),h.decode=(l,u)=>ge(l,h.codec(),u)})(c=s.PeerInfo||(s.PeerInfo={}));let f;(function(h){let g;h.codec=()=>(g==null&&(g=ye((l,u,p={})=>{if(p.lengthDelimited!==!1&&u.fork(),l.messageIDs!=null)for(let d of l.messageIDs)u.uint32(10),u.bytes(d);p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let d={messageIDs:[]},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let y=l.uint32();switch(y>>>3){case 1:{if(p.limits?.messageIDs!=null&&d.messageIDs.length===p.limits.messageIDs)throw new Te('Decode error - map field "messageIDs" had too many elements');d.messageIDs.push(l.bytes());break}default:{l.skipType(y&7);break}}}return d})),g),h.encode=l=>be(l,h.codec()),h.decode=(l,u)=>ge(l,h.codec(),u)})(f=s.ControlIDontWant||(s.ControlIDontWant={}));let m;s.codec=()=>(m==null&&(m=ye((h,g,l={})=>{if(l.lengthDelimited!==!1&&g.fork(),h.subscriptions!=null)for(let u of h.subscriptions)g.uint32(10),s.SubOpts.codec().encode(u,g);if(h.messages!=null)for(let u of h.messages)g.uint32(18),s.Message.codec().encode(u,g);h.control!=null&&(g.uint32(26),s.ControlMessage.codec().encode(h.control,g)),l.lengthDelimited!==!1&&g.ldelim()},(h,g,l={})=>{let u={subscriptions:[],messages:[]},p=g==null?h.len:h.pos+g;for(;h.pos<p;){let d=h.uint32();switch(d>>>3){case 1:{if(l.limits?.subscriptions!=null&&u.subscriptions.length===l.limits.subscriptions)throw new Te('Decode error - map field "subscriptions" had too many elements');u.subscriptions.push(s.SubOpts.codec().decode(h,h.uint32(),{limits:l.limits?.subscriptions$}));break}case 2:{if(l.limits?.messages!=null&&u.messages.length===l.limits.messages)throw new Te('Decode error - map field "messages" had too many elements');u.messages.push(s.Message.codec().decode(h,h.uint32(),{limits:l.limits?.messages$}));break}case 3:{u.control=s.ControlMessage.codec().decode(h,h.uint32(),{limits:l.limits?.control});break}default:{h.skipType(d&7);break}}}return u})),m),s.encode=h=>be(h,s.codec()),s.decode=(h,g)=>ge(h,s.codec(),g)})(st||(st={}));var pr=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 Ma;(function(s){s.StrictSign="StrictSign",s.StrictNoSign="StrictNoSign"})(Ma||(Ma={}));var pt;(function(s){s[s.Signing=0]="Signing",s[s.Anonymous=1]="Anonymous"})(pt||(pt={}));var we;(function(s){s.Error="error",s.Ignore="ignore",s.Reject="reject",s.Blacklisted="blacklisted"})(we||(we={}));var fe;(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"})(fe||(fe={}));var de;(function(s){s.duplicate="duplicate",s.invalid="invalid",s.valid="valid"})(de||(de={}));function gi(s){switch(s){case pe.Ignore:return we.Ignore;case pe.Reject:return we.Reject;default:throw new Error("Unreachable")}}var Pa;(function(s){s.forward="forward",s.publish="publish"})(Pa||(Pa={}));var xe;(function(s){s.Fanout="fanout",s.Random="random",s.Subscribed="subscribed",s.Outbound="outbound",s.NotEnough="not_enough",s.Opportunistic="opportunistic"})(xe||(xe={}));var Re;(function(s){s.Dc="disconnected",s.BadScore="bad_score",s.Prune="prune",s.Excess="excess"})(Re||(Re={}));var ts;(function(s){s.GraftBackoff="graft_backoff",s.BrokenPromise="broken_promise",s.MessageDeficit="message_deficit",s.IPColocation="IP_colocation"})(ts||(ts={}));var ss;(function(s){s.LowScore="low_score",s.MaxIhave="max_ihave",s.MaxIasked="max_iasked"})(ss||(ss={}));var es;(function(s){s.graylist="graylist",s.publish="publish",s.gossip="gossip",s.mesh="mesh"})(es||(es={}));function La(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 xe.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:o},i);break;case xe.Random:this.meshPeerInclusionEventsRandom.inc({topic:o},i);break;case xe.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:o},i);break;case xe.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:o},i);break;case xe.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:o},i);break;case xe.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 Re.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:o},i);break;case Re.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:o},i);break;case Re.Prune:this.meshPeerChurnEventsPrune.inc({topic:o},i);break;case Re.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 pe.Accept:this.acceptedMessagesTotal.inc({topic:o});break;case pe.Ignore:this.ignoredMessagesTotal.inc({topic:o});break;case pe.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 c=this.toTopic(r);this.msgPublishCount.inc({topic:c},1),this.msgPublishBytes.inc({topic:c},i*o),this.msgPublishPeersByTopic.inc({topic:c},i),this.directPeersPublishedTotal.inc({topic:c},n.direct),this.floodsubPeersPublishedTotal.inc({topic:c},n.floodsub),this.meshPeersPublishedTotal.inc({topic:c},n.mesh),this.fanoutPeersPublishedTotal.inc({topic:c},n.fanout),this.msgPublishTime.observe({topic:c},a/1e3)},onMsgRecvPreValidation(r){let n=this.toTopic(r);this.msgReceivedPreValidation.inc({topic:n},1)},onMsgRecvError(r){let n=this.toTopic(r);this.msgReceivedError.inc({topic:n},1)},onPrevalidationResult(r,n){let i=this.toTopic(r);switch(n){case de.duplicate:this.prevalidationDuplicateTotal.inc({topic:i});break;case de.invalid:this.prevalidationInvalidTotal.inc({topic:i});break;case de.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===we.Error?n.error:n.reason;this.msgReceivedInvalid.inc({error:o},1),this.msgReceivedInvalidByTopic.inc({topic:i},1)},onDuplicateMsgDelivery(r,n,i){let o=this.toTopic(r);this.duplicateMsgDeliveryDelay.observe({topic:o},n/1e3),i&&this.duplicateMsgLateDelivery.inc({topic:o},1)},onPublishDuplicateMsg(r){let n=this.toTopic(r);this.duplicateMsgIgnored.inc({topic:n},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(r,n){this.rpcRecvBytes.inc(n),this.rpcRecvCount.inc(1),r.subscriptions!=null&&this.rpcRecvSubscription.inc(r.subscriptions.length),r.messages!=null&&this.rpcRecvMessage.inc(r.messages.length),r.control!=null&&(this.rpcRecvControl.inc(1),r.control.ihave!=null&&this.rpcRecvIHave.inc(r.control.ihave.length),r.control.iwant!=null&&this.rpcRecvIWant.inc(r.control.iwant.length),r.control.graft!=null&&this.rpcRecvGraft.inc(r.control.graft.length),r.control.prune!=null&&this.rpcRecvPrune.inc(r.control.prune.length))},onRpcSent(r,n){if(this.rpcSentBytes.inc(n),this.rpcSentCount.inc(1),r.subscriptions!=null&&this.rpcSentSubscription.inc(r.subscriptions.length),r.messages!=null&&this.rpcSentMessage.inc(r.messages.length),r.control!=null){let i=r.control.ihave?.length??0,o=r.control.iwant?.length??0,a=r.control.graft?.length??0,c=r.control.prune?.length??0,f=r.control.idontwant?.length??0;i>0&&this.rpcSentIHave.inc(i),o>0&&this.rpcSentIWant.inc(o),a>0&&this.rpcSentGraft.inc(a),c>0&&this.rpcSentPrune.inc(c),f>0&&this.rpcSentIDontWant.inc(f),(i>0||o>0||a>0||c>0||f>0)&&this.rpcSentControl.inc(1)}},registerScores(r,n){let i=0,o=0,a=0,c=0;for(let f of r)f>=n.graylistThreshold&&i++,f>=n.publishThreshold&&o++,f>=n.gossipThreshold&&a++,f>=0&&c++;this.peersByScoreThreshold.set({threshold:es.graylist},i),this.peersByScoreThreshold.set({threshold:es.publish},o),this.peersByScoreThreshold.set({threshold:es.gossip},a),this.peersByScoreThreshold.set({threshold:es.mesh},c),this.score.set(r)},registerScoreWeights(r){for(let[n,i]of r.byTopic)this.scoreWeights.set({topic:n,p:"p1"},i.p1w),this.scoreWeights.set({topic:n,p:"p2"},i.p2w),this.scoreWeights.set({topic:n,p:"p3"},i.p3w),this.scoreWeights.set({topic:n,p:"p3b"},i.p3bw),this.scoreWeights.set({topic:n,p:"p4"},i.p4w);this.scoreWeights.set({p:"p5"},r.p5w),this.scoreWeights.set({p:"p6"},r.p6w),this.scoreWeights.set({p:"p7"},r.p7w)},registerScorePerMesh(r,n){let i=new Map;r.forEach((o,a)=>{let c=this.topicStrToLabel.get(a)??"unknown",f=i.get(c);f==null&&(f=new Set,i.set(c,f)),o.forEach(m=>f?.add(m))});for(let[o,a]of i){let c=[];a.forEach(f=>{c.push(n.get(f)??0)}),this.scorePerMesh.set({topic:o},c)}}}}var q=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var Zu={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},ju={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 ka(s={}){return{...Zu,...s,topics:s.topics!=null?Object.entries(s.topics).reduce((e,[t,r])=>(e[t]=Xu(r),e),{}):{}}}function Xu(s={}){return{...ju,...s}}function Ba(s){for(let[e,t]of Object.entries(s.topics))try{Yu(t)}catch(r){throw new q(`invalid score parameters for topic ${e}: ${r.message}`)}if(s.topicScoreCap<0)throw new q("invalid topic score cap; must be positive (or 0 for no cap)");if(s.appSpecificScore===null||s.appSpecificScore===void 0)throw new q("missing application specific score function");if(s.IPColocationFactorWeight>0)throw new q("invalid IPColocationFactorWeight; must be negative (or 0 to disable)");if(s.IPColocationFactorWeight!==0&&s.IPColocationFactorThreshold<1)throw new q("invalid IPColocationFactorThreshold; must be at least 1");if(s.behaviourPenaltyWeight>0)throw new q("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)");if(s.behaviourPenaltyWeight!==0&&(s.behaviourPenaltyDecay<=0||s.behaviourPenaltyDecay>=1))throw new q("invalid BehaviourPenaltyDecay; must be between 0 and 1");if(s.decayInterval<1e3)throw new q("invalid DecayInterval; must be at least 1s");if(s.decayToZero<=0||s.decayToZero>=1)throw new q("invalid DecayToZero; must be between 0 and 1")}function Yu(s){if(s.topicWeight<0)throw new q("invalid topic weight; must be >= 0");if(s.timeInMeshQuantum===0)throw new q("invalid TimeInMeshQuantum; must be non zero");if(s.timeInMeshWeight<0)throw new q("invalid TimeInMeshWeight; must be positive (or 0 to disable)");if(s.timeInMeshWeight!==0&&s.timeInMeshQuantum<=0)throw new q("invalid TimeInMeshQuantum; must be positive");if(s.timeInMeshWeight!==0&&s.timeInMeshCap<=0)throw new q("invalid TimeInMeshCap; must be positive");if(s.firstMessageDeliveriesWeight<0)throw new q("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)");if(s.firstMessageDeliveriesWeight!==0&&(s.firstMessageDeliveriesDecay<=0||s.firstMessageDeliveriesDecay>=1))throw new q("invalid FirstMessageDeliveriesDecay; must be between 0 and 1");if(s.firstMessageDeliveriesWeight!==0&&s.firstMessageDeliveriesCap<=0)throw new q("invalid FirstMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight>0)throw new q("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.meshMessageDeliveriesWeight!==0&&(s.meshMessageDeliveriesDecay<=0||s.meshMessageDeliveriesDecay>=1))throw new q("invalid MeshMessageDeliveriesDecay; must be between 0 and 1");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesCap<=0)throw new q("invalid MeshMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesThreshold<=0)throw new q("invalid MeshMessageDeliveriesThreshold; must be positive");if(s.meshMessageDeliveriesWindow<0)throw new q("invalid MeshMessageDeliveriesWindow; must be non-negative");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesActivation<1e3)throw new q("invalid MeshMessageDeliveriesActivation; must be at least 1s");if(s.meshFailurePenaltyWeight>0)throw new q("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)");if(s.meshFailurePenaltyWeight!==0&&(s.meshFailurePenaltyDecay<=0||s.meshFailurePenaltyDecay>=1))throw new q("invalid MeshFailurePenaltyDecay; must be between 0 and 1");if(s.invalidMessageDeliveriesWeight>0)throw new q("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.invalidMessageDeliveriesDecay<=0||s.invalidMessageDeliveriesDecay>=1)throw new q("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1")}var Ju={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function Ra(s={}){return{...Ju,...s}}function gr(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 Ca(s,e){return gr(s,e,()=>!0)}var mr=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 Na(s,e,t,r){let n=0;Object.entries(e.topics).forEach(([o,a])=>{let c=t.topics[o];if(c===void 0)return;let f=0;if(a.inMesh){let l=a.meshTime/c.timeInMeshQuantum;l>c.timeInMeshCap&&(l=c.timeInMeshCap),f+=l*c.timeInMeshWeight}let m=a.firstMessageDeliveries;if(m>c.firstMessageDeliveriesCap&&(m=c.firstMessageDeliveriesCap),f+=m*c.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries<c.meshMessageDeliveriesThreshold){let l=c.meshMessageDeliveriesThreshold-a.meshMessageDeliveries,u=l*l;f+=u*c.meshMessageDeliveriesWeight}let h=a.meshFailurePenalty;f+=h*c.meshFailurePenaltyWeight;let g=a.invalidMessageDeliveries*a.invalidMessageDeliveries;f+=g*c.invalidMessageDeliveriesWeight,n+=f*c.topicWeight}),t.topicScoreCap>0&&n>t.topicScoreCap&&(n=t.topicScoreCap);let i=t.appSpecificScore(s);if(n+=i*t.appSpecificWeight,e.knownIPs.forEach(o=>{if(t.IPColocationFactorWhitelist.has(o))return;let a=r.get(o),c=a!=null?a.size:0;if(c>t.IPColocationFactorThreshold){let f=c-t.IPColocationFactorThreshold,m=f*f;n+=m*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let o=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=o*o;n+=a*t.behaviourPenaltyWeight}return n}var Ka=cc(Ua(),1);var ve;(function(s){s[s.unknown=0]="unknown",s[s.valid=1]="valid",s[s.invalid=2]="invalid",s[s.ignored=3]="ignored"})(ve||(ve={}));var br=class{records;queue;constructor(){this.records=new Map,this.queue=new Ka.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:ve.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 yr=class{params;metrics;peerStats=new Map;peerIPs=new mr(()=>new Set);scoreCache=new Map;deliveryRecords=new br;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,r,n){this.params=e,this.metrics=t,Ba(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??Na,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!==ve.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,i-n.firstSeenTsMs,ve[n.status]);return}n.status=ve.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 we.Error:this.markInvalidMessageDelivery(e,r);return;case we.Blacklisted:return}let i=this.deliveryRecords.ensureRecord(t);if(i.status!==ve.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-i.firstSeenTsMs,ve[i.status]);return}if(n===we.Ignore){i.status=ve.ignored,i.peers.clear();return}i.status=ve.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 ve.unknown:n.peers.add(e);break;case ve.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,r,n.validated);break;case ve.invalid:this.markInvalidMessageDelivery(e,r);break;case ve.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 f=i-r,m=f>a.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,f,m),m)return}let c=a.meshMessageDeliveriesCap;o.meshMessageDeliveries=Math.min(c,o.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(let r of t){let n=this.peerIPs.get(r);n!=null&&(n.delete(e),n.size===0&&this.peerIPs.delete(r))}}getPtopicStats(e,t){let r=e.topics[t];return r!==void 0?r:this.params.topics[t]!==void 0?(r={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=r,r):null}};function Qu(s,e,t,r,n){let i=0,o=new Map;if(Object.entries(e.topics).forEach(([g,l])=>{let u=n.get(g)??"unknown",p=t.topics[g];if(p===void 0)return;let d=o.get(u);d==null&&(d={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},o.set(u,d));let b=0,y=0,v=0,T=0,E=0;if(l.inMesh){let w=Math.max(l.meshTime/p.timeInMeshQuantum,p.timeInMeshCap);b+=w*p.timeInMeshWeight}let M=l.firstMessageDeliveries;if(M>p.firstMessageDeliveriesCap&&(M=p.firstMessageDeliveriesCap),y+=M*p.firstMessageDeliveriesWeight,l.meshMessageDeliveriesActive&&l.meshMessageDeliveries<p.meshMessageDeliveriesThreshold){let w=p.meshMessageDeliveriesThreshold-l.meshMessageDeliveries,L=w*w;v+=L*p.meshMessageDeliveriesWeight}let D=l.meshFailurePenalty;T+=D*p.meshFailurePenaltyWeight;let I=l.invalidMessageDeliveries*l.invalidMessageDeliveries;E+=I*p.invalidMessageDeliveriesWeight,i+=(b+y+v+T+E)*p.topicWeight,d.p1w+=b,d.p2w+=y,d.p3w+=v,d.p3bw+=T,d.p4w+=E}),t.topicScoreCap>0&&i>t.topicScoreCap){i=t.topicScoreCap;let g=t.topicScoreCap/i;for(let l of o.values())l.p1w*=g,l.p2w*=g,l.p3w*=g,l.p3bw*=g,l.p4w*=g}let a=0,c=0,f=0,m=t.appSpecificScore(s);a+=m*t.appSpecificWeight,e.knownIPs.forEach(g=>{if(t.IPColocationFactorWhitelist.has(g))return;let l=r.get(g),u=l!=null?l.size:0;if(u>t.IPColocationFactorThreshold){let p=u-t.IPColocationFactorThreshold,d=p*p;c+=d*t.IPColocationFactorWeight}});let h=e.behaviourPenalty*e.behaviourPenalty;return f+=h*t.behaviourPenaltyWeight,i+=a+c+f,{byTopic:o,p5w:a,p6w:c,p7w:f,score:i}}function Fa(s,e,t,r,n){let i={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let o of s){let a=e.get(o);if(a!=null){let c=Qu(o,a,t,r,n);for(let[f,m]of c.byTopic){let h=i.byTopic.get(f);h==null&&(h={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},i.byTopic.set(f,h)),h.p1w.push(m.p1w),h.p2w.push(m.p2w),h.p3w.push(m.p3w),h.p3bw.push(m.p3bw),h.p4w.push(m.p4w)}i.p5w.push(c.p5w),i.p6w.push(c.p6w),i.p7w.push(c.p7w),i.score.push(c.score)}else i.p5w.push(0),i.p6w.push(0),i.p7w.push(0),i.score.push(0)}return i}function wr(s){let e=s.getComponents(),t={},r=0;if(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)throw new W(`Multiaddr ${s} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[r]?.name==="tls"&&e[r+1]?.name==="sni"&&(t.sni=e[r+1].value,r+=2),t}function Ga(s){try{return wr(s),!0}catch{return!1}}var bi=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},yi=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Ha=s=>globalThis.DOMException===void 0?new yi(s):new DOMException(s),qa=s=>{let e=s.reason===void 0?Ha("This operation was aborted."):s.reason;return e instanceof Error?e:Ha(e)};function wi(s,e){let{milliseconds:t,fallback:r,message:n,customTimers:i={setTimeout,clearTimeout}}=e,o,a,f=new Promise((m,h)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:l}=e;l.aborted&&h(qa(l)),a=()=>{h(qa(l))},l.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){s.then(m,h);return}let g=new bi;o=i.setTimeout.call(void 0,()=>{if(r){try{m(r())}catch(l){h(l)}return}typeof s.cancel=="function"&&s.cancel(),n===!1?m():n instanceof Error?h(n):(g.message=n??`Promise timed out after ${t} milliseconds`,h(g))},t),(async()=>{try{m(await s)}catch(l){h(l)}})()}).finally(()=>{f.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return f.clear=()=>{i.clearTimeout.call(void 0,o),o=void 0},f}var eh=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 th(s,e,t){let r,n=new Promise((i,o)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:f,removeListener:m}=eh(s),h=async(...l)=>{let u=t.multiArgs?l:l[0];if(t.filter)try{if(!await t.filter(u))return}catch(p){r(),o(p);return}c.push(u),t.count===c.length&&(r(),i(c))},g=(...l)=>{r(),o(t.rejectionMultiArgs?l:l[0])};r=()=>{for(let l of a)m(l,h);for(let l of t.rejectionEvents)a.includes(l)||m(l,g)};for(let l of a)f(l,h);for(let l of t.rejectionEvents)a.includes(l)||f(l,g);t.signal&&t.signal.addEventListener("abort",()=>{g(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(n.cancel=r,typeof t.timeout=="number"){let i=wi(n,{milliseconds:t.timeout});return i.cancel=()=>{r(),i.clear()},i}return n}function za(s,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let r=th(s,e,t),n=r.then(i=>i[0]);return n.cancel=r.cancel,n}function sh(s){return s?.addEventListener!=null}function rh(s){let e=Dt(),t,r=o=>{e.push(o.data)},n=()=>{e.end(),s.removeEventListener("message",r),s.removeEventListener("close",i),s.removeEventListener("remoteCloseWrite",n)},i=o=>{e.end(o.error),o.error!=null&&t?.reject(o.error),s.removeEventListener("message",r),s.removeEventListener("close",i),s.removeEventListener("remoteCloseWrite",n)};return s.addEventListener("message",r),s.addEventListener("close",i,{once:!0}),s.addEventListener("remoteCloseWrite",n,{once:!0}),{source:e,async sink(o){async function*a(){yield*o}let c=a();for(;;){t=Promise.withResolvers();let{done:f,value:m}=await Promise.race([c.next(),t.promise]);if(s.writeStatus==="closing"||s.writeStatus==="closed"||(m!=null&&(s.send(m)||await Promise.race([za(s,"drain",{rejectionEvents:["close"]})])),f===!0))break}await s.close()}}}function Va(...s){let e=s.map(t=>sh(t)?rh(t):t);return Ms(...e)}var xr=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}async push(e){return this.pushPrefixed(Jt.single(e))}pushPrefixed(e){this.rawStream.send(e)}async close(e){await this.rawStream.close(e).catch(t=>{this.rawStream.abort(t)})}},vr=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=Va(this.rawStream,r=>Ds(r,t))}async close(){this.closeController.abort()}};var Er=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){switch(this.trackMessage(e),t){case we.Error:return;default:break}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 Wa=z("libp2p-pubsub:");async function $a(s,e,t,r){switch(s.type){case pt.Signing:{let n={from:s.author.toMultihash().bytes,data:r,seqno:er(8),topic:e,signature:void 0,key:void 0},i=gt([Wa,st.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${G(n.seqno??new Uint8Array(0),"base16")}`),topic:e,signature:n.signature,key:_s(n.key)};return{raw:n,msg:o}}case pt.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 Za(s,e){switch(s){case Mt:return e.signature!=null?{valid:!1,error:fe.SignaturePresent}:e.seqno!=null?{valid:!1,error:fe.SeqnoPresent}:e.key!=null?{valid:!1,error:fe.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case mt:{if(e.seqno==null)return{valid:!1,error:fe.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:fe.InvalidSeqno};if(e.signature==null)return{valid:!1,error:fe.InvalidSignature};if(e.from==null)return{valid:!1,error:fe.InvalidPeerId};let t;try{t=Xt(Ue(e.from))}catch{return{valid:!1,error:fe.InvalidPeerId}}let r;if(e.key!=null){if(r=_s(e.key),t.publicKey!==void 0&&!r.equals(t.publicKey))return{valid:!1,error:fe.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:fe.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=gt([Wa,st.Message.encode(n)]);return await r.verify(i,e.signature)?{valid:!0,message:{type:"signed",from:t,data:e.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${G(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:e.key!=null?_s(e.key):r}}:{valid:!1,error:fe.InvalidSignature}}default:throw new Error("Unreachable")}}function Ce(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 xi(s){return s.control===void 0&&(s.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),s}function qe(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 ja(s){return G(s,"base64")}function Xa(s,e,t){switch(s){case mt:return{type:pt.Signing,author:e,key:Ke(t.publicKey),privateKey:t};case Mt:return{type:pt.Anonymous};default:throw new Error(`Unknown signature policy "${s}"`)}}var Ya=(s,e)=>{let t=z(e.toString(16).padStart(16,"0"),"base16"),r=Ke(s),n=new Uint8Array(r.byteLength+t.length);return n.set(r,0),n.set(t,r.byteLength),n};function Ja(s){if(s.type!=="signed")throw new Error("expected signed message type");if(s.sequenceNumber==null)throw Error("missing seqno field");return Ya(s.from.publicKey??s.key,s.sequenceNumber)}async function Qa(s){return nt.encode(s.data)}function ec(s){if(Ga(s)){let e=wr(s);switch(e.type){case"ip4":case"ip6":return e.host;default:break}}return null}var rs=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 De;(function(s){s[s.started=0]="started",s[s.stopped=1]="stopped"})(De||(De={}));var Sr=class extends Rs{globalSignaturePolicy;protocols=[Pt,_i,Ir];publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=Dt({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;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=Pt;opts;decodeRpcLimits;metrics;status={code:De.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:ka(t.scoreParams),scoreThresholds:Ra(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=r.decodeRpcLimits??Da,this.globalSignaturePolicy=r.globalSignaturePolicy??mt,r.fallbackToFloodsub&&this.protocols.push(_r),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 rs({validityMs:r.seenTTL}),this.publishedMessageIds=new rs({validityMs:r.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case mt:this.msgIdFn=Ja;break;case Mt:this.msgIdFn=Qa;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new rs({validityMs:r.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??ja,this.mcache=t.messageCache??new pr(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=La(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 Er(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new yr(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]="@chainsafe/libp2p-gossipsub";[Di]=["@libp2p/pubsub"];[Mi]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===De.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=Xa(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=Dt({objectMode:!0}),Ms(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:De.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!==De.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:De.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.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.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=new xr(await t.newStream(this.protocols,{runOnLimitedConnection:this.runOnLimitedConnection}),o=>{this.log.error("outbound pipe error",o)},{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(r,n);let i=n.protocol;i===_r&&this.floodsubPeers.add(r),this.metrics?.peersPerProtocol.inc({protocol:i},1),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 vr(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=ec(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 of this.topics.values())i.delete(t);for(let[i,o]of this.mesh)o.delete(t)&&this.metrics?.onRemoveFromMesh(i,Re.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===De.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)??Tt(r))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await Ms(t,async r=>{for await(let n of r)try{let i=n.subarray(),o=st.decode(i,{limits:{subscriptions:this.decodeRpcLimits.maxSubscriptions,messages:this.decodeRpcLimits.maxMessages,control$:{ihave:this.decodeRpcLimits.maxIhaveMessageIDs,iwant: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}}}});if(this.metrics?.onRpcRecv(o,i.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,o)}catch(a){this.metrics?.onRpcRecvError(),this.log(a)}else this.handleReceivedRpc(e,o).catch(a=>{this.metrics?.onRpcRecvError(),this.log(a)})}catch(i){this.metrics?.onRpcDataError(),this.log(i)}})}catch(r){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(r,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){if(!this.acceptFrom(e.toString())){this.log("received message from unacceptable peer %p",e),this.metrics?.rpcRecvNotAccepted.inc();return}let r=t.subscriptions!=null?t.subscriptions.length:0,n=t.messages!=null?t.messages.length:0,i=0,o=0,a=0,c=0;if(t.control!=null&&(t.control.ihave!=null&&(i=t.control.ihave.length),t.control.iwant!=null&&(o=t.control.iwant.length),t.control.graft!=null&&(a=t.control.graft.length),t.control.prune!=null&&(c=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${r} messages ${n} ihave ${i} iwant ${o} graft ${a} prune ${c}`),t.subscriptions!=null&&t.subscriptions.length>0){let f=[];t.subscriptions.forEach(m=>{let h=m.topic,g=m.subscribe===!0;if(h!=null){if(this.allowedTopics!=null&&!this.allowedTopics.has(h))return;this.handleReceivedSubscription(e,h,g),f.push({topic:h,subscribe:g})}}),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:f}})}for(let f of t.messages){if(this.allowedTopics!=null&&!this.allowedTopics.has(f.topic))continue;let m=this.handleReceivedMessage(e,f).catch(h=>{this.metrics?.onMsgRecvError(f.topic),this.log(h)});this.opts.awaitRpcMessageHandler&&await m}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);n==null&&(n=new Set,this.topics.set(t,n)),r?n.add(e.toString()):n.delete(e.toString())}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 de.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 de.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 de.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:de.duplicate,msgIdStr:n};let i=await Za(this.globalSignaturePolicy,t);if(!i.valid)return{code:de.invalid,reason:we.Error,error:i.error};let o=i.message;try{this.dataTransform!=null&&(o.data=this.dataTransform.inboundTransform(t.topic,o.data))}catch(h){return this.log("Invalid message, transform failed",h),{code:de.invalid,reason:we.Error,error:fe.TransformFailed}}let a=await this.msgIdFn(o),c=this.msgIdToStrFn(a),f={msgId:a,msgIdStr:c};if(r!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(r,c)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(c))return{code:de.duplicate,msgIdStr:c};this.seenCache.put(c),(t.data?.length??0)>=this.opts.idontwantMinDataSize&&this.sendIDontWants(a,t.topic,e.toString());let m=this.topicValidators.get(t.topic);if(m!=null){let h;try{h=await m(e,o)}catch(g){let l=g.code;l===Ti&&(h=pe.Ignore),l===Ii?h=pe.Reject:h=pe.Ignore}if(h!==pe.Accept)return{code:de.invalid,reason:gi(h),msgIdStr:c}}return{code:de.valid,messageId:f,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,Ce(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:ss.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:ss.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:ss.MaxIasked}),[];let o=new Map;if(t.forEach(({topicID:f,messageIDs:m})=>{if(f==null||m==null||!this.mesh.has(f))return;let h=0;m.forEach(g=>{let l=this.msgIdToStrFn(g);this.seenCache.has(l)||(o.set(l,g),h++)}),this.metrics?.onIhaveRcv(f,m.length,h)}),o.size===0)return[];let a=o.size;a+i>5e3&&(a=5e3-i),this.log("IHAVE: Asking for %d out of %d messages from %s",a,o.size,e);let c=Array.from(o.values());return qe(c),c=c.slice(0,a),this.iasked.set(e,i+a),[{messageIDs:c}]}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=new Map,i=new Map,o=0;return t.forEach(({messageIDs:a})=>{a?.forEach(c=>{let f=this.msgIdToStrFn(c),m=this.mcache.getWithIWantCount(f,e);if(m==null){o++;return}if(i.set(m.msg.topic,1+(i.get(m.msg.topic)??0)),m.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,c);return}n.set(f,m.msg)})}),this.metrics?.onIwantRcv(i,o),n.size===0?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",n.size,e),Array.from(n.values()))}async handleGraft(e,t){let r=[],n=this.score.score(e),i=Date.now(),o=this.opts.doPX;if(t.forEach(({topicID:c})=>{if(c==null)return;let f=this.mesh.get(c);if(f==null){o=!1;return}if(f.has(e))return;let m=this.backoff.get(c)?.get(e);if(this.direct.has(e))this.log("GRAFT: ignoring request from direct peer %s",e),r.push(c),o=!1;else if(typeof m=="number"&&i<m){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,ts.GraftBackoff),o=!1;let h=m+this.opts.graftFloodThreshold-this.opts.pruneBackoff;i<h&&this.score.addPenalty(e,1,ts.GraftBackoff),this.addBackoff(e,c),r.push(c)}else n<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,n,c),r.push(c),o=!1,this.addBackoff(e,c)):f.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(r.push(c),this.addBackoff(e,c)):(this.log("GRAFT: Add mesh link from %s in %s",e,c),this.score.graft(e,c),f.add(e),this.metrics?.onAddToMesh(c,xe.Subscribed,1));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:c,direction:"inbound"}})}),r.length===0)return[];let a=!1;return Promise.all(r.map(async c=>this.makePrune(e,c,o,a)))}async handlePrune(e,t){let r=this.score.score(e);for(let{topicID:n,backoff:i,peers:o}of t){if(n==null)continue;let a=this.mesh.get(n);if(a==null)return;this.log("PRUNE: Remove mesh link to %s in %s",e,n),this.score.prune(e,n),a.has(e)&&(a.delete(e),this.metrics?.onRemoveFromMesh(n,Re.Prune,1)),typeof i=="number"&&i>0?this.doAddBackoff(e,n,i*1e3):this.addBackoff(e,n),o!=null&&o.length>0&&(r<this.opts.scoreThresholds.acceptPXThreshold?this.log("PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]",e,r,n):await this.pxConnect(o)),this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:n,direction:"inbound"}})}}handleIdontwant(e,t){let r=this.idontwantCounts.get(e)??0;if(r>=this.opts.idontwantMaxMessages)return;let n=r,i=this.idontwants.get(e);i==null&&(i=new Map,this.idontwants.set(e,i));let o=0;e:for(let{messageIDs:c}of t)for(let f of c){if(r>=this.opts.idontwantMaxMessages)break e;r++;let m=this.msgIdToStrFn(f);i.set(m,this.heartbeatTicks),this.mcache.msgs.has(m)||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,ts.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&&(qe(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async r=>{if(r.peerID==null)return;let n=Xt(Ue(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=Tt(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!==De.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!==De.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!==De.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,xe.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,xe.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!==De.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,c=>this.score.score(c)>=this.opts.scoreThresholds.publishThreshold);a.size>0&&(this.fanout.set(e,a),a.forEach(c=>{t.add(c),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,Ce([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 $a(this.publishConfig,e,t,i),c=await this.msgIdFn(a),f=this.msgIdToStrFn(c),m=r?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(f)){if(m)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:h,tosendCount:g}=this.selectPeersToPublish(e),l=this.opts.emitSelf&&this.subscriptions.has(e),u=r?.allowPublishToZeroTopicPeers??this.opts.allowPublishToZeroTopicPeers;if(h.size===0&&!u&&!l)throw Error("PublishError.NoPeersSubscribedToTopic");this.seenCache.put(f),this.mcache.put({msgId:c,msgIdStr:f},o,!0),this.gossipTracer.deliverMessage(f),this.publishedMessageIds.put(f);let p=r?.batchPublish??this.opts.batchPublish,d=Ce([o]);if(p)this.sendRpcInBatch(h,d);else for(let y of h)this.sendRpc(y,d)||h.delete(y);let b=Date.now()-n;return this.metrics?.onPublishMsg(e,g,h.size,o.data!=null?o.data.length:0,b),l&&(h.add(this.components.peerId.toString()),super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:f,msg:a}})),super.dispatchEvent(new CustomEvent("message",{detail:a}))),{recipients:Array.from(h.values()).map(y=>this.peers.get(y)??Tt(y))}}sendRpcInBatch(e,t){let r=st.encode(t),n=Jt.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===pe.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=gi(r),{message:a,originatingPeers:c}=n;this.score.rejectMessage(t,e,a.topic,o);for(let f of c)this.score.rejectMessage(f,e,a.topic,o)}let i=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(n,r,i)}sendGraft(e,t){let n=Ce([],{graft:[{topicID:t}]});this.sendRpc(e,n)}async sendPrune(e,t){let n=[await this.makePrune(e,t,this.opts.doPX,!0)],i=Ce([],{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!==Pt&&i.delete(a);let o=Ce([],{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=st.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=xi(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=xi(t);n.control.ihave=r}async sendGraftPrune(e,t,r){let n=this.opts.doPX,i=!1;for(let[o,a]of e){let c=a.map(h=>({topicID:h})),f=[],m=t.get(o);m!=null&&(f=await Promise.all(m.map(async h=>this.makePrune(o,h,n&&!(r.get(o)??!1),i))),t.delete(o)),this.sendRpc(o,Ce([],{graft:c,prune:f}))}for(let[o,a]of t){let c=await Promise.all(a.map(async f=>this.makePrune(o,f,n&&!(r.get(o)??!1),i)));this.sendRpc(o,Ce([],{prune:c}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[r,n]of e)this.doEmitGossip(r,n,t.get(r)??[])}doEmitGossip(e,t,r){if(r.length===0||(qe(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=qe(Array.from(a)).slice(0,n),a.forEach(c=>{let f=r;r.length>5e3&&(f=qe(f.slice()).slice(0,5e3)),this.pushGossip(c,{topicID:e,messageIDs:f})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,Ce([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let r=Ce([],{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===Ir)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,f=>f!==e&&this.score.score(f)>=0),c=await Promise.all(Array.from(a).map(async f=>{let m=this.peers.get(f)??Tt(f),h;try{h=await this.components.peerStore.get(m)}catch(g){if(g.name!=="NotFoundError")throw g}return{peerID:m.toMultihash().bytes,signedPeerRecord:h?.peerRecordEnvelope}}));return{topicID:t,peers:c,backoff:o}}runHeartbeat=()=>{let e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch(t=>{this.log("Error running heartbeat",t)}).finally(()=>{if(e?.(),this.status.code===De.started){clearTimeout(this.status.heartbeatTimeout);let t=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;t<this.opts.heartbeatInterval*.25&&(t+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,t)}})};async heartbeat(){let{D:e,Dlo:t,Dhi:r,Dscore:n,Dout:i,fanoutTTL:o}=this.opts;this.heartbeatTicks++;let a=new Map,c=u=>{let p=a.get(u);return p===void 0&&(p=this.score.score(u),a.set(u,p)),p},f=new Map,m=new Map,h=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.applyIwantPenalties(),this.idontwantCounts.clear();for(let u of this.idontwants.values())for(let[p,d]of u)this.heartbeatTicks-d>=this.opts.mcacheLength&&u.delete(p);this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let g=new Map;this.mesh.forEach((u,p)=>{let d=this.topics.get(p),b=new Set,y=new Set;if(g.set(p,y),d!=null){let E=qe(Array.from(d)),M=this.backoff.get(p);for(let D of E){let I=this.streamsOutbound.get(D);if(I!=null&&this.protocols.includes(I.protocol)&&!u.has(D)&&!this.direct.has(D)){let w=c(D);M?.has(D)!==!0&&w>=0&&b.add(D),w>=this.opts.scoreThresholds.gossipThreshold&&y.add(D)}}}let v=(E,M)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",E,p),this.addBackoff(E,p),u.delete(E),c(E)>=this.opts.scoreThresholds.gossipThreshold&&y.add(E),this.metrics?.onRemoveFromMesh(p,M,1);let D=m.get(E);D==null?m.set(E,[p]):D.push(p)},T=(E,M)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",E,p),this.score.graft(E,p),u.add(E),y.delete(E),this.metrics?.onAddToMesh(p,M,1);let D=f.get(E);D==null?f.set(E,[p]):D.push(p)};if(u.forEach(E=>{let M=c(E);M<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",E,M,p),v(E,Re.BadScore),h.set(E,!0))}),u.size<t){let E=e-u.size;Ca(b,E).forEach(D=>{T(D,xe.NotEnough)})}if(u.size>r){let E=Array.from(u);E.sort((D,I)=>c(I)-c(D)),E=E.slice(0,n).concat(qe(E.slice(n)));let M=0;if(E.slice(0,e).forEach(D=>{(this.outbound.get(D)??!1)&&M++}),M<i){let D=w=>{let L=E[w];for(let O=w;O>0;O--)E[O]=E[O-1];E[0]=L};if(M>0){let w=M;for(let L=1;L<e&&w>0;L++)(this.outbound.get(E[L])??!1)&&(D(L),w--)}let I=e-M;for(let w=e;w<E.length&&I>0;w++)(this.outbound.get(E[w])??!1)&&(D(w),I--)}E.slice(e).forEach(D=>{v(D,Re.Excess)})}if(u.size>=t){let E=0;if(u.forEach(M=>{(this.outbound.get(M)??!1)&&E++}),E<i){let M=i-E;gr(b,M,I=>this.outbound.get(I)===!0).forEach(I=>{T(I,xe.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&u.size>1){let E=Array.from(u).sort((I,w)=>c(I)-c(w)),M=Math.floor(u.size/2),D=c(E[M]);if(D<this.opts.scoreThresholds.opportunisticGraftThreshold){let I=this.opts.opportunisticGraftPeers,w=gr(b,I,L=>c(L)>D);for(let L of w)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",L,p),T(L,xe.Opportunistic)}}});let l=Date.now();this.fanoutLastpub.forEach((u,p)=>{u+o<l&&(this.fanout.delete(p),this.fanoutLastpub.delete(p))}),this.fanout.forEach((u,p)=>{let d=this.topics.get(p);u.forEach(T=>{(!(d?.has(T)??!1)||c(T)<this.opts.scoreThresholds.publishThreshold)&&u.delete(T)});let b=this.topics.get(p),y=[],v=new Set;if(g.set(p,v),b!=null){let T=qe(Array.from(b));for(let E of T){let M=this.streamsOutbound.get(E);if(M!=null&&this.protocols.includes(M.protocol)&&!u.has(E)&&!this.direct.has(E)){let D=c(E);D>=this.opts.scoreThresholds.publishThreshold&&y.push(E),D>=this.opts.scoreThresholds.gossipThreshold&&v.add(E)}}}if(u.size<e){let T=e-u.size;y.slice(0,T).forEach(E=>{u.add(E),v?.delete(E)})}}),this.emitGossip(g),await this.sendGraftPrune(f,m,h),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=qe(i),t>0&&i.length>t&&(i=i.slice(0,t)),new Set(i)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0,r=Date.now();e.connectedPeersBackoffSec.reset();for(let c of this.backoff.values()){t+=c.size;for(let[f,m]of c.entries())this.peers.has(f)&&e.connectedPeersBackoffSec.observe(Math.max(0,m-r)/1e3)}e.cacheSize.set({cache:"backoff"},t);let n=0;for(let c of this.idontwants.values())n+=c.size;e.cacheSize.set({cache:"idontwants"},n);for(let[c,f]of this.topics)e.topicPeersCount.set({topicStr:c},f.size);for(let[c,f]of this.mesh)e.meshPeerCounts.set({topicStr:c},f.size);let i=[],o=new Map;e.behaviourPenalty.reset();for(let c of this.peers.keys()){let f=this.score.score(c);i.push(f),o.set(c,f),e.behaviourPenalty.observe(this.score.peerStats.get(c)?.behaviourPenalty??0)}e.registerScores(i,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,o);let a=Fa(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)??Tt(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)??Tt(t),{tags:{[r]:void 0}}).catch(n=>{this.log.error("Error untagging peer %s with topic %s",t,r,n)})}};var mt="StrictSign",Mt="StrictNoSign",pe;(function(s){s.Accept="accept",s.Ignore="ignore",s.Reject="reject"})(pe||(pe={}));var Lh=Pt;function kh(s={}){return e=>new Sr(e,s)}return lc(Bh);})();
|
|
2
|
+
"use strict";var Libp2PGossipsub=(()=>{var ec=Object.create;var Ps=Object.defineProperty;var tc=Object.getOwnPropertyDescriptor;var sc=Object.getOwnPropertyNames;var rc=Object.getPrototypeOf,nc=Object.prototype.hasOwnProperty;var ic=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Ee=(s,e)=>{for(var t in e)Ps(s,t,{get:e[t],enumerable:!0})},Si=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of sc(e))!nc.call(s,n)&&n!==t&&Ps(s,n,{get:()=>e[n],enumerable:!(r=tc(e,n))||r.enumerable});return s};var oc=(s,e,t)=>(t=s!=null?ec(rc(s)):{},Si(e||!s||!s.__esModule?Ps(t,"default",{value:s,enumerable:!0}):t,s)),ac=s=>Si(Ps({},"__esModule",{value:!0}),s);var Oa=ic((K0,Na)=>{"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 c;for(n=new Array(t),c=0;c<t;c++)n[c]=this._list[this._head+r+c&this._capacityMask];if(r=this._head+r&this._capacityMask,e+t===o){for(this._tail=this._tail-t+a&this._capacityMask,c=t;c>0;c--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(e===0){for(this._head=this._head+t+a&this._capacityMask,c=t-1;c>0;c--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(r<o/2){for(this._head=this._head+e+t+a&this._capacityMask,c=e;c>0;c--)this.unshift(this._list[r=r-1+a&this._capacityMask]);for(r=this._head-1+a&this._capacityMask;i>0;)this._list[r=r-1+a&this._capacityMask]=void 0,i--;e<0&&(this._tail=r)}else{for(this._tail=r,r=r+t+a&this._capacityMask,c=o-(t+e);c>0;c--)this.push(this._list[r++]);for(r=this._tail;i>0;)this._list[r=r+1+a&this._capacityMask]=void 0,i--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),n}}};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,c=arguments.length,f=this._list.length,m=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+f&this._capacityMask)):(a=this.remove(r,t),this._head=this._head+r+f&this._capacityMask);c>m;)this.unshift(arguments[--c]);for(i=r;i>0;i--)this.unshift(o[i-1])}else{o=new Array(n-(r+t));var h=o.length;for(i=0;i<h;i++)o[i]=this._list[this._head+r+t+i&this._capacityMask];for(t===0?(a=[],r!=n&&(this._tail=this._head+r+f&this._capacityMask)):(a=this.remove(r,t),this._tail=this._tail-h+f&this._capacityMask);m<c;)this.push(arguments[m++]);for(i=0;i<h;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,c;if(e||this._head>this._tail){for(c=this._head;c<n;c++)o[a++]=r[c];for(c=0;c<this._tail;c++)o[a++]=r[c]}else for(c=this._head;c<this._tail;c++)o[a++]=r[c];return o};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)};Na.exports=Z});var Bh={};Ee(Bh,{StrictNoSign:()=>Mt,StrictSign:()=>pt,TopicValidatorResult:()=>pe,gossipsub:()=>kh,multicodec:()=>Lh});var Sr="/floodsub/1.0.0",_r="/meshsub/1.0.0",_i="/meshsub/1.1.0",Pt="/meshsub/1.2.0";var Ii="ERR_TOPIC_VALIDATOR_REJECT",Ti="ERR_TOPIC_VALIDATOR_IGNORE";var W=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Lt=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Ls=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 Ir=Symbol.for("@libp2p/peer-id");var Bs=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){super.addEventListener(e,t,r);let n=this.#e.get(e);n==null&&(n=[],this.#e.set(e,n)),n.push({callback:t,once:(r!==!0&&r!==!1&&r?.once)??!1})}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))}dispatchEvent(e){let t=super.dispatchEvent(e),r=this.#e.get(e.type);return r==null||(r=r.filter(({once:n})=>!n),this.#e.set(e.type,r)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Di=Symbol.for("@libp2p/service-capabilities"),Mi=Symbol.for("@libp2p/service-dependencies");var Pr={};Ee(Pr,{base58btc:()=>Q,base58flickr:()=>pc});var uf=new Uint8Array(0);function Pi(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 qe(s){if(s instanceof Uint8Array&&s.constructor.name==="Uint8Array")return s;if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return new Uint8Array(s.buffer,s.byteOffset,s.byteLength);throw new Error("Unknown type, must be binary type")}function Li(s){return new TextEncoder().encode(s)}function ki(s){return new TextDecoder().decode(s)}function cc(s,e){if(s.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<s.length;n++){var i=s.charAt(n),o=i.charCodeAt(0);if(t[o]!==255)throw new TypeError(i+" is ambiguous");t[o]=n}var a=s.length,c=s.charAt(0),f=Math.log(a)/Math.log(256),m=Math.log(256)/Math.log(a);function h(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";for(var p=0,d=0,b=0,y=u.length;b!==y&&u[b]===0;)b++,p++;for(var v=(y-b)*m+1>>>0,T=new Uint8Array(v);b!==y;){for(var E=u[b],M=0,D=v-1;(E!==0||M<d)&&D!==-1;D--,M++)E+=256*T[D]>>>0,T[D]=E%a>>>0,E=E/a>>>0;if(E!==0)throw new Error("Non-zero carry");d=M,b++}for(var I=v-d;I!==v&&T[I]===0;)I++;for(var w=c.repeat(p);I<v;++I)w+=s.charAt(T[I]);return w}function g(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;var p=0;if(u[p]!==" "){for(var d=0,b=0;u[p]===c;)d++,p++;for(var y=(u.length-p)*f+1>>>0,v=new Uint8Array(y);u[p];){var T=t[u.charCodeAt(p)];if(T===255)return;for(var E=0,M=y-1;(T!==0||E<b)&&M!==-1;M--,E++)T+=a*v[M]>>>0,v[M]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");b=E,p++}if(u[p]!==" "){for(var D=y-b;D!==y&&v[D]===0;)D++;for(var I=new Uint8Array(d+(y-D)),w=d;D!==y;)I[w++]=v[D++];return I}}}function l(u){var p=g(u);if(p)return p;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:g,decode:l}}var lc=cc,uc=lc,Ri=uc;var Tr=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")}},Ar=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 Ci(this,e)}},Dr=class{decoders;constructor(e){this.decoders=e}or(e){return Ci(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 Ci(s,e){return new Dr({...s.decoders??{[s.prefix]:s},...e.decoders??{[e.prefix]:e}})}var Mr=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 Tr(e,t,r),this.decoder=new Ar(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Bt({name:s,prefix:e,encode:t,decode:r}){return new Mr(s,e,t,r)}function st({name:s,prefix:e,alphabet:t}){let{encode:r,decode:n}=Ri(t,s);return Bt({prefix:e,name:s,encode:r,decode:i=>qe(n(i))})}function hc(s,e,t,r){let n=s.length;for(;s[n-1]==="=";)--n;let i=new Uint8Array(n*t/8|0),o=0,a=0,c=0;for(let f=0;f<n;++f){let m=e[s[f]];if(m===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<t|m,o+=t,o>=8&&(o-=8,i[c++]=255&a>>o)}if(o>=t||(255&a<<8-o)!==0)throw new SyntaxError("Unexpected end of data");return i}function fc(s,e,t){let r=e[e.length-1]==="=",n=(1<<t)-1,i="",o=0,a=0;for(let c=0;c<s.length;++c)for(a=a<<8|s[c],o+=8;o>t;)o-=t,i+=e[n&a>>o];if(o!==0&&(i+=e[n&a<<t-o]),r)for(;(i.length*t&7)!==0;)i+="=";return i}function dc(s){let e={};for(let t=0;t<s.length;++t)e[s[t]]=t;return e}function J({name:s,prefix:e,bitsPerChar:t,alphabet:r}){let n=dc(r);return Bt({prefix:e,name:s,encode(i){return fc(i,r,t)},decode(i){return hc(i,n,t,s)}})}var Q=st({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),pc=st({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Lr={};Ee(Lr,{base32:()=>Rt,base32hex:()=>yc,base32hexpad:()=>xc,base32hexpadupper:()=>vc,base32hexupper:()=>wc,base32pad:()=>gc,base32padupper:()=>bc,base32upper:()=>mc,base32z:()=>Ec});var Rt=J({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),mc=J({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),gc=J({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),bc=J({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),yc=J({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),wc=J({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),xc=J({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),vc=J({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ec=J({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var kr={};Ee(kr,{base36:()=>is,base36upper:()=>Sc});var is=st({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Sc=st({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var _c=Ui,Ni=128,Ic=127,Tc=~Ic,Ac=Math.pow(2,31);function Ui(s,e,t){e=e||[],t=t||0;for(var r=t;s>=Ac;)e[t++]=s&255|Ni,s/=128;for(;s&Tc;)e[t++]=s&255|Ni,s>>>=7;return e[t]=s|0,Ui.bytes=t-r+1,e}var Dc=Br,Mc=128,Oi=127;function Br(s,r){var t=0,r=r||0,n=0,i=r,o,a=s.length;do{if(i>=a)throw Br.bytes=0,new RangeError("Could not decode varint");o=s[i++],t+=n<28?(o&Oi)<<n:(o&Oi)*Math.pow(2,n),n+=7}while(o>=Mc);return Br.bytes=i-r,t}var Pc=Math.pow(2,7),Lc=Math.pow(2,14),kc=Math.pow(2,21),Bc=Math.pow(2,28),Rc=Math.pow(2,35),Cc=Math.pow(2,42),Nc=Math.pow(2,49),Oc=Math.pow(2,56),Uc=Math.pow(2,63),Kc=function(s){return s<Pc?1:s<Lc?2:s<kc?3:s<Bc?4:s<Rc?5:s<Cc?6:s<Nc?7:s<Oc?8:s<Uc?9:10},Fc={encode:_c,decode:Dc,encodingLength:Kc},Gc=Fc,os=Gc;function as(s,e=0){return[os.decode(s,e),os.decode.bytes]}function Ct(s,e,t=0){return os.encode(s,e,t),e}function Nt(s){return os.encodingLength(s)}function Oe(s,e){let t=e.byteLength,r=Nt(s),n=r+Nt(t),i=new Uint8Array(n+t);return Ct(s,i,0),Ct(t,i,r),i.set(e,n),new Ot(s,t,e,i)}function ze(s){let e=qe(s),[t,r]=as(e),[n,i]=as(e.subarray(r)),o=e.subarray(r+i);if(o.byteLength!==n)throw new Error("Incorrect length");return new Ot(t,n,o,e)}function Ki(s,e){if(s===e)return!0;{let t=e;return s.code===t.code&&s.size===t.size&&t.bytes instanceof Uint8Array&&Pi(s.bytes,t.bytes)}}var Ot=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}};function Fi(s,e){let{bytes:t,version:r}=s;switch(r){case 0:return qc(t,Rr(s),e??Q.encoder);default:return zc(t,Rr(s),e??Rt.encoder)}}var Gi=new WeakMap;function Rr(s){let e=Gi.get(s);if(e==null){let t=new Map;return Gi.set(s,t),t}return e}var oe=class s{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=n,this["/"]=n}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!==cs)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Vc)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=Oe(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&&Ki(e.multihash,r.multihash)}toString(e){return Fi(this,e)}toJSON(){return{"/":Fi(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??Hi(r,n,i.bytes))}else if(t[Wc]===!0){let{version:r,multihash:n,code:i}=t,o=ze(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!==cs)throw new Error(`Version 0 CID must use dag-pb (code: ${cs}) block encoding`);return new s(e,t,r,r.bytes)}case 1:{let n=Hi(e,t,r.bytes);return new s(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return s.create(0,cs,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=qe(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 Ot(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[h,g]=as(e.subarray(t));return t+=g,h},n=r(),i=cs;if(n===18?(n=0,t=0):i=r(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let o=t,a=r(),c=r(),f=t+c,m=f-o;return{version:n,codec:i,multihashCode:a,digestSize:c,multihashSize:m,size:f}}static parse(e,t){let[r,n]=Hc(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 Rr(i).set(r,e),i}};function Hc(s,e){switch(s[0]){case"Q":{let t=e??Q;return[Q.prefix,t.decode(`${Q.prefix}${s}`)]}case Q.prefix:{let t=e??Q;return[Q.prefix,t.decode(s)]}case Rt.prefix:{let t=e??Rt;return[Rt.prefix,t.decode(s)]}case is.prefix:{let t=e??is;return[is.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 qc(s,e,t){let{prefix:r}=t;if(r!==Q.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 zc(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 cs=112,Vc=18;function Hi(s,e,t){let r=Nt(s),n=r+Nt(e),i=new Uint8Array(n+t.byteLength);return Ct(s,i,0),Ct(e,i,r),i.set(t,n),i}var Wc=Symbol.for("@ipld/js-cid/CID");var Cr={};Ee(Cr,{identity:()=>Le});var qi=0,$c="identity",zi=qe;function Zc(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 Oe(qi,zi(s))}var Le={code:qi,name:$c,encode:zi,digest:Zc};function Se(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 Ve(s=0){return new Uint8Array(s)}function le(s=0){return new Uint8Array(s)}function mt(s,e){e==null&&(e=s.reduce((n,i)=>n+i.length,0));let t=le(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var Wi=Symbol.for("@achingbrain/uint8arraylist");function Vi(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 Cs(s){return!!s?.[Wi]}var se=class s{bufs;length;[Wi]=!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(Cs(r))t+=r.byteLength,this.bufs.push(...r.bufs);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(Cs(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=Vi(this.bufs,e);return t.buf[t.index]}set(e,t){let r=Vi(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(Cs(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 mt(r,n)}subarray(e,t){let{bufs:r,length:n}=this._subList(e,t);return r.length===1?r[0]:mt(r,n)}sublist(e,t){let{bufs:r,length:n}=this._subList(e,t),i=new s;return i.length=n,i.bufs=[...r],i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let r=[],n=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],a=n,c=a+o.byteLength;if(n=c,e>=c)continue;let f=e>=a&&e<c,m=t>a&&t<=c;if(f&&m){if(e===a&&t===c){r.push(o);break}let h=e-a;r.push(o.subarray(h,h+(t-e)));break}if(f){if(e===0){r.push(o);continue}r.push(o.subarray(e-a));continue}if(m){if(t===c){r.push(o);break}r.push(o.subarray(0,t-a));break}r.push(o)}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!Cs(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 h=0;h<i;h++)o[h]=-1;for(let h=0;h<n;h++)o[r[h]]=h;let a=o,c=this.byteLength-r.byteLength,f=r.byteLength-1,m;for(let h=t;h<=c;h+=m){m=0;for(let g=f;g>=0;g--){let l=this.get(h+g);if(r[g]!==l){m=Math.max(1,g-a[l]);break}}if(m===0)return h}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=le(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=Ve(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=Ve(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=Ve(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=le(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=Ve(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=Ve(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=Ve(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=Ve(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=Ve(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(!Se(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 Nr={};Ee(Nr,{base10:()=>jc});var jc=st({prefix:"9",name:"base10",alphabet:"0123456789"});var Or={};Ee(Or,{base16:()=>Xc,base16upper:()=>Yc});var Xc=J({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Yc=J({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ur={};Ee(Ur,{base2:()=>Jc});var Jc=J({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Kr={};Ee(Kr,{base256emoji:()=>rl});var $i=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}"),Qc=$i.reduce((s,e,t)=>(s[t]=e,s),[]),el=$i.reduce((s,e,t)=>{let r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return s[r]=t,s},[]);function tl(s){return s.reduce((e,t)=>(e+=Qc[t],e),"")}function sl(s){let e=[];for(let t of s){let r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);let n=el[r];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var rl=Bt({prefix:"\u{1F680}",name:"base256emoji",encode:tl,decode:sl});var Fr={};Ee(Fr,{base64:()=>nl,base64pad:()=>il,base64url:()=>ol,base64urlpad:()=>al});var nl=J({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),il=J({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ol=J({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),al=J({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Gr={};Ee(Gr,{base8:()=>cl});var cl=J({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Hr={};Ee(Hr,{identity:()=>ll});var ll=Bt({prefix:"\0",name:"identity",encode:s=>ki(s),decode:s=>Li(s)});var $f=new TextEncoder,Zf=new TextDecoder;var Vr={};Ee(Vr,{sha256:()=>gt,sha512:()=>dl});var fl=20;function zr({name:s,code:e,encode:t,minDigestLength:r,maxDigestLength:n}){return new qr(s,e,t,r,n)}var qr=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,r,n,i){this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??fl,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?Zi(r,this.code,t?.truncate):r.then(n=>Zi(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Zi(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 Oe(e,s)}function Xi(s){return async e=>new Uint8Array(await crypto.subtle.digest(s,e))}var gt=zr({name:"sha2-256",code:18,encode:Xi("SHA-256")}),dl=zr({name:"sha2-512",code:19,encode:Xi("SHA-512")});var Wr={...Hr,...Ur,...Gr,...Nr,...Or,...Lr,...kr,...Pr,...Fr,...Kr},od={...Vr,...Cr};function Ji(s,e,t,r){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:r}}}var Yi=Ji("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),$r=Ji("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=le(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),pl={utf8:Yi,"utf-8":Yi,hex:Wr.base16,latin1:$r,ascii:$r,binary:$r,...Wr},Ns=pl;function z(s,e="utf8"){let t=Ns[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${s}`)}function q(s,e="utf8"){let t=Ns[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(s).substring(1)}var ml=parseInt("11111",2),Zr=parseInt("10000000",2),gl=parseInt("01111111",2),Qi={0:ls,1:ls,2:bl,3:xl,4:vl,5:wl,6:yl,16:ls,22:ls,48:ls};function We(s,e={offset:0}){let t=s[e.offset]&ml;if(e.offset++,Qi[t]!=null)return Qi[t](s,e);throw new Error("No decoder for tag "+t)}function us(s,e){let t=0;if((s[e.offset]&Zr)===Zr){let r=s[e.offset]&gl,n="0x";e.offset++;for(let i=0;i<r;i++,e.offset++)n+=s[e.offset].toString(16).padStart(2,"0");t=parseInt(n,16)}else t=s[e.offset],e.offset++;return t}function ls(s,e){us(s,e);let t=[];for(;!(e.offset>=s.byteLength);){let r=We(s,e);if(r===null)break;t.push(r)}return t}function bl(s,e){let t=us(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 yl(s,e){let t=us(s,e),r=e.offset+t,n=s[e.offset];e.offset++;let i=0,o=0;n<40?(i=0,o=n):n<80?(i=1,o=n-40):(i=2,o=n-80);let a=`${i}.${o}`,c=[];for(;e.offset<r;){let f=s[e.offset];if(e.offset++,c.push(f&127),f<128){c.reverse();let m=0;for(let h=0;h<c.length;h++)m+=c[h]<<h*7;a+=`.${m}`,c=[]}}return a}function wl(s,e){return e.offset++,null}function xl(s,e){let t=us(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 vl(s,e){let t=us(s,e),r=s.subarray(e.offset,e.offset+t);return e.offset+=t,r}function El(s){let e=s.toString(16);e.length%2===1&&(e="0"+e);let t=new se;for(let r=0;r<e.length;r+=2)t.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return t}function jr(s){if(s.byteLength<128)return Uint8Array.from([s.byteLength]);let e=El(s.byteLength);return new se(Uint8Array.from([e.byteLength|Zr]),e)}function _e(s){let e=new se,t=128;return(s.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(s),new se(Uint8Array.from([2]),jr(e),e)}function Os(s){let e=Uint8Array.from([0]),t=new se(e,s);return new se(Uint8Array.from([3]),jr(t),t)}function nt(s,e=48){let t=new se;for(let r of s)t.append(r);return new se(Uint8Array.from([e]),jr(t),t)}async function eo(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,e,t.subarray());return r?.signal?.throwIfAborted(),i}var Sl=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),_l=Uint8Array.from([6,5,43,129,4,0,34]),Il=Uint8Array.from([6,5,43,129,4,0,35]),Tl={ext:!0,kty:"EC",crv:"P-256"},Al={ext:!0,kty:"EC",crv:"P-384"},Dl={ext:!0,kty:"EC",crv:"P-521"},Xr=32,Yr=48,Jr=66;function Qr(s){let e=We(s);return to(e)}function to(s){let e=s[1][1][0],t=1,r,n;if(e.byteLength===Xr*2+1)return r=q(e.subarray(t,t+Xr),"base64url"),n=q(e.subarray(t+Xr),"base64url"),new Ut({...Tl,key_ops:["verify"],x:r,y:n});if(e.byteLength===Yr*2+1)return r=q(e.subarray(t,t+Yr),"base64url"),n=q(e.subarray(t+Yr),"base64url"),new Ut({...Al,key_ops:["verify"],x:r,y:n});if(e.byteLength===Jr*2+1)return r=q(e.subarray(t,t+Jr),"base64url"),n=q(e.subarray(t+Jr),"base64url"),new Ut({...Dl,key_ops:["verify"],x:r,y:n});throw new W(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function so(s){return nt([_e(Uint8Array.from([1])),nt([Ml(s.crv)],160),nt([Os(new se(Uint8Array.from([4]),z(s.x??"","base64url"),z(s.y??"","base64url")))],161)]).subarray()}function Ml(s){if(s==="P-256")return Sl;if(s==="P-384")return _l;if(s==="P-521")return Il;throw new W(`Invalid curve ${s}`)}var Ut=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=so(this.jwk)),this._raw}toMultihash(){return Le.digest(Ue(this))}toCID(){return oe.createV1(114,this.toMultihash())}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Se(this.raw,e.raw)}async verify(e,t,r){return eo(this.jwk,t,e,r)}};function bt(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Ke(s,e=""){if(!Number.isSafeInteger(s)||s<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${s}`)}}function K(s,e,t=""){let r=bt(s),n=s?.length,i=e!==void 0;if(!r||i&&n!==e){let o=t&&`"${t}" `,a=i?` of length ${e}`:"",c=r?`length=${n}`:`type=${typeof s}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return s}function Us(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Ke(s.outputLen),Ke(s.blockLen)}function Kt(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 no(s,e){K(s,void 0,"digestInto() output");let t=e.outputLen;if(s.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function Ze(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Ks(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function ke(s,e){return s<<32-e|s>>>e}var io=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Pl=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function je(s){if(K(s),io)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=Pl[s[t]];return e}var $e={_0:48,_9:57,A:65,F:70,a:97,f:102};function ro(s){if(s>=$e._0&&s<=$e._9)return s-$e._0;if(s>=$e.A&&s<=$e.F)return s-($e.A-10);if(s>=$e.a&&s<=$e.f)return s-($e.a-10)}function Xe(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(io)return Uint8Array.fromHex(s);let e=s.length,t=e/2;if(e%2)throw new Error("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=ro(s.charCodeAt(i)),a=ro(s.charCodeAt(i+1));if(o===void 0||a===void 0){let c=s[i]+s[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[n]=o*16+a}return r}function Ie(...s){let e=0;for(let r=0;r<s.length;r++){let n=s[r];K(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 en(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.create=n=>s(n),Object.assign(t,e),Object.freeze(t)}function it(s=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(s))}var tn=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function oo(s,e,t){return s&e^~s&t}function ao(s,e,t){return s&e^s&t^e&t}var hs=class{blockLen;outputLen;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=Ks(this.buffer)}update(e){Kt(this),K(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 c=Ks(e);for(;n<=i-o;o+=n)this.process(c,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){Kt(this),no(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,Ze(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(r,0),o=0);for(let h=o;h<n;h++)t[h]=0;r.setBigUint64(n-8,BigInt(this.length*8),i),this.process(r,0);let a=Ks(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,m=this.get();if(f>m.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<f;h++)a.setUint32(4*h,m[h],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()}},Ye=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ae=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Fs=BigInt(4294967295),co=BigInt(32);function Ll(s,e=!1){return e?{h:Number(s&Fs),l:Number(s>>co&Fs)}:{h:Number(s>>co&Fs)|0,l:Number(s&Fs)|0}}function lo(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}=Ll(s[i],e);[r[i],n[i]]=[o,a]}return[r,n]}var sn=(s,e,t)=>s>>>t,rn=(s,e,t)=>s<<32-t|e>>>t,yt=(s,e,t)=>s>>>t|e<<32-t,wt=(s,e,t)=>s<<32-t|e>>>t,fs=(s,e,t)=>s<<64-t|e>>>t-32,ds=(s,e,t)=>s>>>t-32|e<<64-t;function Fe(s,e,t,r){let n=(e>>>0)+(r>>>0);return{h:s+t+(n/2**32|0)|0,l:n|0}}var uo=(s,e,t)=>(s>>>0)+(e>>>0)+(t>>>0),ho=(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),po=(s,e,t,r,n)=>e+t+r+n+(s/2**32|0)|0,mo=(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 Bl=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]),ot=new Uint32Array(64),nn=class extends hs{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:n,E:i,F:o,G:a,H:c}=this;return[e,t,r,n,i,o,a,c]}set(e,t,r,n,i,o,a,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)ot[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let g=ot[h-15],l=ot[h-2],u=ke(g,7)^ke(g,18)^g>>>3,p=ke(l,17)^ke(l,19)^l>>>10;ot[h]=p+ot[h-7]+u+ot[h-16]|0}let{A:r,B:n,C:i,D:o,E:a,F:c,G:f,H:m}=this;for(let h=0;h<64;h++){let g=ke(a,6)^ke(a,11)^ke(a,25),l=m+g+oo(a,c,f)+Bl[h]+ot[h]|0,p=(ke(r,2)^ke(r,13)^ke(r,22))+ao(r,n,i)|0;m=f,f=c,c=a,a=o+l|0,o=i,i=n,n=r,r=l+p|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,m=m+this.H|0,this.set(r,n,i,o,a,c,f,m)}roundClean(){Ze(ot)}destroy(){this.set(0,0,0,0,0,0,0,0),Ze(this.buffer)}},on=class extends nn{A=Ye[0]|0;B=Ye[1]|0;C=Ye[2]|0;D=Ye[3]|0;E=Ye[4]|0;F=Ye[5]|0;G=Ye[6]|0;H=Ye[7]|0;constructor(){super(32)}};var bo=lo(["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))),Rl=bo[0],Cl=bo[1],at=new Uint32Array(80),ct=new Uint32Array(80),an=class extends hs{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:o,Dh:a,Dl:c,Eh:f,El:m,Fh:h,Fl:g,Gh:l,Gl:u,Hh:p,Hl:d}=this;return[e,t,r,n,i,o,a,c,f,m,h,g,l,u,p,d]}set(e,t,r,n,i,o,a,c,f,m,h,g,l,u,p,d){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=n|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=f|0,this.El=m|0,this.Fh=h|0,this.Fl=g|0,this.Gh=l|0,this.Gl=u|0,this.Hh=p|0,this.Hl=d|0}process(e,t){for(let v=0;v<16;v++,t+=4)at[v]=e.getUint32(t),ct[v]=e.getUint32(t+=4);for(let v=16;v<80;v++){let T=at[v-15]|0,E=ct[v-15]|0,M=yt(T,E,1)^yt(T,E,8)^sn(T,E,7),D=wt(T,E,1)^wt(T,E,8)^rn(T,E,7),I=at[v-2]|0,w=ct[v-2]|0,L=yt(I,w,19)^fs(I,w,61)^sn(I,w,6),O=wt(I,w,19)^ds(I,w,61)^rn(I,w,6),R=fo(D,O,ct[v-7],ct[v-16]),S=po(R,M,L,at[v-7],at[v-16]);at[v]=S|0,ct[v]=R|0}let{Ah:r,Al:n,Bh:i,Bl:o,Ch:a,Cl:c,Dh:f,Dl:m,Eh:h,El:g,Fh:l,Fl:u,Gh:p,Gl:d,Hh:b,Hl:y}=this;for(let v=0;v<80;v++){let T=yt(h,g,14)^yt(h,g,18)^fs(h,g,41),E=wt(h,g,14)^wt(h,g,18)^ds(h,g,41),M=h&l^~h&p,D=g&u^~g&d,I=mo(y,E,D,Cl[v],ct[v]),w=go(I,b,T,M,Rl[v],at[v]),L=I|0,O=yt(r,n,28)^fs(r,n,34)^fs(r,n,39),R=wt(r,n,28)^ds(r,n,34)^ds(r,n,39),S=r&i^r&a^i&a,_=n&o^n&c^o&c;b=p|0,y=d|0,p=l|0,d=u|0,l=h|0,u=g|0,{h,l:g}=Fe(f|0,m|0,w|0,L|0),f=a|0,m=c|0,a=i|0,c=o|0,i=r|0,o=n|0;let x=uo(L,R,_);r=ho(x,w,O,S),n=x|0}({h:r,l:n}=Fe(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=Fe(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=Fe(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:m}=Fe(this.Dh|0,this.Dl|0,f|0,m|0),{h,l:g}=Fe(this.Eh|0,this.El|0,h|0,g|0),{h:l,l:u}=Fe(this.Fh|0,this.Fl|0,l|0,u|0),{h:p,l:d}=Fe(this.Gh|0,this.Gl|0,p|0,d|0),{h:b,l:y}=Fe(this.Hh|0,this.Hl|0,b|0,y|0),this.set(r,n,i,o,a,c,f,m,h,g,l,u,p,d,b,y)}roundClean(){Ze(at,ct)}destroy(){Ze(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},cn=class extends an{Ah=ae[0]|0;Al=ae[1]|0;Bh=ae[2]|0;Bl=ae[3]|0;Ch=ae[4]|0;Cl=ae[5]|0;Dh=ae[6]|0;Dl=ae[7]|0;Eh=ae[8]|0;El=ae[9]|0;Fh=ae[10]|0;Fl=ae[11]|0;Gh=ae[12]|0;Gl=ae[13]|0;Hh=ae[14]|0;Hl=ae[15]|0;constructor(){super(64)}};var Ft=en(()=>new on,tn(1));var yo=en(()=>new cn,tn(3));var un=BigInt(0),ln=BigInt(1);function Je(s,e=""){if(typeof s!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof s)}return s}function wo(s){if(typeof s=="bigint"){if(!Gs(s))throw new Error("positive bigint expected, got "+s)}else Ke(s);return s}function ps(s){let e=wo(s).toString(16);return e.length&1?"0"+e:e}function xo(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?un:BigInt("0x"+s)}function Gt(s){return xo(je(s))}function xt(s){return xo(je(qs(K(s)).reverse()))}function Hs(s,e){Ke(e),s=wo(s);let t=Xe(s.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function hn(s,e){return Hs(s,e).reverse()}function qs(s){return Uint8Array.from(s)}var Gs=s=>typeof s=="bigint"&&un<=s;function Nl(s,e,t){return Gs(s)&&Gs(e)&&Gs(t)&&e<=s&&s<t}function ms(s,e,t,r){if(!Nl(e,t,r))throw new Error("expected valid "+s+": "+t+" <= n < "+r+", got "+e)}function fn(s){let e;for(e=0;s>un;s>>=ln,e+=1);return e}var gs=s=>(ln<<BigInt(s))-ln;function vo(s,e,t){if(Ke(s,"hashLen"),Ke(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let r=d=>new Uint8Array(d),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3,c=r(s),f=r(s),m=0,h=()=>{c.fill(1),f.fill(0),m=0},g=(...d)=>t(f,Ie(c,...d)),l=(d=n)=>{f=g(i,d),c=g(),d.length!==0&&(f=g(o,d),c=g())},u=()=>{if(m++>=a)throw new Error("drbg: tried max amount of iterations");let d=0,b=[];for(;d<e;){c=g();let y=c.slice();b.push(y),d+=c.length}return Ie(...b)};return(d,b)=>{h(),l(d);let y;for(;!(y=b(u()));)l();return h(),y}}function lt(s,e={},t={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function r(i,o,a){let c=s[i];if(a&&c===void 0)return;let f=typeof c;if(f!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${f}`)}let n=(i,o)=>Object.entries(i).forEach(([a,c])=>r(a,c,o));n(e,!1),n(t,!0)}function Ht(s){let e=new WeakMap;return(t,...r)=>{let n=e.get(t);if(n!==void 0)return n;let i=s(t,...r);return e.set(t,i),i}}var me=BigInt(0),re=BigInt(1),vt=BigInt(2),_o=BigInt(3),Io=BigInt(4),To=BigInt(5),Ol=BigInt(7),Ao=BigInt(8),Ul=BigInt(9),Do=BigInt(16);function ee(s,e){let t=s%e;return t>=me?t:e+t}function $(s,e,t){let r=s;for(;e-- >me;)r*=r,r%=t;return r}function Eo(s,e){if(s===me)throw new Error("invert: expected non-zero number");if(e<=me)throw new Error("invert: expected positive modulus, got "+e);let t=ee(s,e),r=e,n=me,i=re,o=re,a=me;for(;t!==me;){let f=r/t,m=r%t,h=n-o*f,g=i-a*f;r=t,t=m,n=o,i=a,o=h,a=g}if(r!==re)throw new Error("invert: does not exist");return ee(n,e)}function pn(s,e,t){if(!s.eql(s.sqr(e),t))throw new Error("Cannot find square root")}function Mo(s,e){let t=(s.ORDER+re)/Io,r=s.pow(e,t);return pn(s,r,e),r}function Kl(s,e){let t=(s.ORDER-To)/Ao,r=s.mul(e,vt),n=s.pow(r,t),i=s.mul(e,n),o=s.mul(s.mul(i,vt),n),a=s.mul(i,s.sub(o,s.ONE));return pn(s,a,e),a}function Fl(s){let e=qt(s),t=Po(s),r=t(e,e.neg(e.ONE)),n=t(e,r),i=t(e,e.neg(r)),o=(s+Ol)/Do;return(a,c)=>{let f=a.pow(c,o),m=a.mul(f,r),h=a.mul(f,n),g=a.mul(f,i),l=a.eql(a.sqr(m),c),u=a.eql(a.sqr(h),c);f=a.cmov(f,m,l),m=a.cmov(g,h,u);let p=a.eql(a.sqr(m),c),d=a.cmov(f,m,p);return pn(a,d,c),d}}function Po(s){if(s<_o)throw new Error("sqrt is not defined for small field");let e=s-re,t=0;for(;e%vt===me;)e/=vt,t++;let r=vt,n=qt(s);for(;So(n,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Mo;let i=n.pow(r,e),o=(e+re)/vt;return function(c,f){if(c.is0(f))return f;if(So(c,f)!==1)throw new Error("Cannot find square root");let m=t,h=c.mul(c.ONE,i),g=c.pow(f,e),l=c.pow(f,o);for(;!c.eql(g,c.ONE);){if(c.is0(g))return c.ZERO;let u=1,p=c.sqr(g);for(;!c.eql(p,c.ONE);)if(u++,p=c.sqr(p),u===m)throw new Error("Cannot find square root");let d=re<<BigInt(m-u-1),b=c.pow(h,d);m=u,h=c.sqr(b),g=c.mul(g,h),l=c.mul(l,b)}return l}}function Gl(s){return s%Io===_o?Mo:s%Ao===To?Kl:s%Do===Ul?Fl(s):Po(s)}var Lo=(s,e)=>(ee(s,e)&re)===re,Hl=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function mn(s){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=Hl.reduce((r,n)=>(r[n]="function",r),e);return lt(s,t),s}function ql(s,e,t){if(t<me)throw new Error("invalid exponent, negatives unsupported");if(t===me)return s.ONE;if(t===re)return e;let r=s.ONE,n=e;for(;t>me;)t&re&&(r=s.mul(r,n)),n=s.sqr(n),t>>=re;return r}function bs(s,e,t=!1){let r=new Array(e.length).fill(t?s.ZERO:void 0),n=e.reduce((o,a,c)=>s.is0(a)?o:(r[c]=o,s.mul(o,a)),s.ONE),i=s.inv(n);return e.reduceRight((o,a,c)=>s.is0(a)?o:(r[c]=s.mul(o,r[c]),s.mul(o,a)),i),r}function So(s,e){let t=(s.ORDER-re)/vt,r=s.pow(e,t),n=s.eql(r,s.ONE),i=s.eql(r,s.ZERO),o=s.eql(r,s.neg(s.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function zl(s,e){e!==void 0&&Ke(e);let t=e!==void 0?e:s.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}var dn=class{ORDER;BITS;BYTES;isLE;ZERO=me;ONE=re;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=me)throw new Error("invalid field: expected ORDER > 0, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:n,nByteLength:i}=zl(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ee(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return me<=e&&e<this.ORDER}is0(e){return e===me}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&re)===re}neg(e){return ee(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ee(e*e,this.ORDER)}add(e,t){return ee(e+t,this.ORDER)}sub(e,t){return ee(e-t,this.ORDER)}mul(e,t){return ee(e*t,this.ORDER)}pow(e,t){return ql(this,e,t)}div(e,t){return ee(e*Eo(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 Eo(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Gl(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?hn(e,this.BYTES):Hs(e,this.BYTES)}fromBytes(e,t=!1){K(e);let{_lengths:r,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(r){if(!r.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let f=new Uint8Array(n);f.set(e,i?0:f.length-e.length),e=f}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?xt(e):Gt(e);if(a&&(c=ee(c,o)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return bs(this,e)}cmov(e,t,r){return r?t:e}};function qt(s,e={}){return new dn(s,e)}function ko(s){if(typeof s!="bigint")throw new Error("field order must be bigint");let e=s.toString(2).length;return Math.ceil(e/8)}function gn(s){let e=ko(s);return e+Math.ceil(e/2)}function bn(s,e,t=!1){K(s);let r=s.length,n=ko(e),i=gn(e);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let o=t?xt(s):Gt(s),a=ee(o,e-re)+re;return t?hn(a,n):Hs(a,n)}var zt=BigInt(0),Et=BigInt(1);function ys(s,e){let t=e.negate();return s?t:e}function St(s,e){let t=bs(s.Fp,e.map(r=>r.Z));return e.map((r,n)=>s.fromAffine(r.toAffine(t[n])))}function No(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function yn(s,e){No(s,e);let t=Math.ceil(e/s)+1,r=2**(s-1),n=2**s,i=gs(s),o=BigInt(s);return{windows:t,windowSize:r,mask:i,maxNumber:n,shiftBy:o}}function Bo(s,e,t){let{windowSize:r,mask:n,maxNumber:i,shiftBy:o}=t,a=Number(s&n),c=s>>o;a>r&&(a-=i,c+=Et);let f=e*r,m=f+Math.abs(a)-1,h=a===0,g=a<0,l=e%2!==0;return{nextN:c,offset:m,isZero:h,isNeg:g,isNegF:l,offsetF:f}}var wn=new WeakMap,Oo=new WeakMap;function xn(s){return Oo.get(s)||1}function Ro(s){if(s!==zt)throw new Error("invalid wNAF")}var Vt=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>zt;)t&Et&&(r=r.add(n)),n=n.double(),t>>=Et;return r}precomputeWindow(e,t){let{windows:r,windowSize:n}=yn(t,this.bits),i=[],o=e,a=o;for(let c=0;c<r;c++){a=o,i.push(a);for(let f=1;f<n;f++)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=yn(e,this.bits);for(let a=0;a<o.windows;a++){let{nextN:c,offset:f,isZero:m,isNeg:h,isNegF:g,offsetF:l}=Bo(r,a,o);r=c,m?i=i.add(ys(g,t[l])):n=n.add(ys(h,t[f]))}return Ro(r),{p:n,f:i}}wNAFUnsafe(e,t,r,n=this.ZERO){let i=yn(e,this.bits);for(let o=0;o<i.windows&&r!==zt;o++){let{nextN:a,offset:c,isZero:f,isNeg:m}=Bo(r,o,i);if(r=a,!f){let h=t[c];n=n.add(m?h.negate():h)}}return Ro(r),n}getPrecomputes(e,t,r){let n=wn.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(n=r(n)),wn.set(t,n))),n}cached(e,t,r){let n=xn(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){let i=xn(e);return i===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),t,n)}createCache(e,t){No(t,this.bits),Oo.set(e,t),wn.delete(e)}hasCache(e){return xn(e)!==1}};function Uo(s,e,t,r){let n=e,i=s.ZERO,o=s.ZERO;for(;t>zt||r>zt;)t&Et&&(i=i.add(n)),r&Et&&(o=o.add(n)),n=n.double(),t>>=Et,r>>=Et;return{p1:i,p2:o}}function Co(s,e,t){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return mn(e),e}else return qt(s,{isLE:t})}function zs(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 c of["p","n","h"]){let f=e[c];if(!(typeof f=="bigint"&&f>zt))throw new Error(`CURVE.${c} must be positive bigint`)}let n=Co(e.p,t.Fp,r),i=Co(e.n,t.Fn,r),a=["Gx","Gy","a",s==="weierstrass"?"b":"d"];for(let c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function Vs(s,e){return function(r){let n=s(r);return{secretKey:n,publicKey:e(n)}}}var ut=BigInt(0),ne=BigInt(1),vn=BigInt(2),Vl=BigInt(8);function Wl(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 Ko(s,e={}){let t=zs("edwards",s,e,e.FpFnLE),{Fp:r,Fn:n}=t,i=t.CURVE,{h:o}=i;lt(e,{},{uvRatio:"function"});let a=vn<<BigInt(n.BYTES*8)-ne,c=d=>r.create(d),f=e.uvRatio||((d,b)=>{try{return{isValid:!0,value:r.sqrt(r.div(d,b))}}catch{return{isValid:!1,value:ut}}});if(!Wl(r,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function m(d,b,y=!1){let v=y?ne:ut;return ms("coordinate "+d,b,v,a),b}function h(d){if(!(d instanceof u))throw new Error("EdwardsPoint expected")}let g=Ht((d,b)=>{let{X:y,Y:v,Z:T}=d,E=d.is0();b==null&&(b=E?Vl:r.inv(T));let M=c(y*b),D=c(v*b),I=r.mul(T,b);if(E)return{x:ut,y:ne};if(I!==ne)throw new Error("invZ was invalid");return{x:M,y:D}}),l=Ht(d=>{let{a:b,d:y}=i;if(d.is0())throw new Error("bad point: ZERO");let{X:v,Y:T,Z:E,T:M}=d,D=c(v*v),I=c(T*T),w=c(E*E),L=c(w*w),O=c(D*b),R=c(w*c(O+I)),S=c(L+c(y*c(D*I)));if(R!==S)throw new Error("bad point: equation left != right (1)");let _=c(v*T),x=c(E*M);if(_!==x)throw new Error("bad point: equation left != right (2)");return!0});class u{static BASE=new u(i.Gx,i.Gy,ne,c(i.Gx*i.Gy));static ZERO=new u(ut,ne,ne,ut);static Fp=r;static Fn=n;X;Y;Z;T;constructor(b,y,v,T){this.X=m("x",b),this.Y=m("y",y),this.Z=m("z",v,!0),this.T=m("t",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(b){if(b instanceof u)throw new Error("extended point not allowed");let{x:y,y:v}=b||{};return m("x",y),m("y",v),new u(y,v,ne,c(y*v))}static fromBytes(b,y=!1){let v=r.BYTES,{a:T,d:E}=i;b=qs(K(b,v,"point")),Je(y,"zip215");let M=qs(b),D=b[v-1];M[v-1]=D&-129;let I=xt(M),w=y?a:r.ORDER;ms("point.y",I,ut,w);let L=c(I*I),O=c(L-ne),R=c(E*L-T),{isValid:S,value:_}=f(O,R);if(!S)throw new Error("bad point: invalid y coordinate");let x=(_&ne)===ne,A=(D&128)!==0;if(!y&&_===ut&&A)throw new Error("bad point: x=0 and x_0=1");return A!==x&&(_=c(-_)),u.fromAffine({x:_,y:I})}static fromHex(b,y=!1){return u.fromBytes(Xe(b),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,y=!0){return p.createCache(this,b),y||this.multiply(vn),this}assertValidity(){l(this)}equals(b){h(b);let{X:y,Y:v,Z:T}=this,{X:E,Y:M,Z:D}=b,I=c(y*D),w=c(E*T),L=c(v*D),O=c(M*T);return I===w&&L===O}is0(){return this.equals(u.ZERO)}negate(){return new u(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:b}=i,{X:y,Y:v,Z:T}=this,E=c(y*y),M=c(v*v),D=c(vn*c(T*T)),I=c(b*E),w=y+v,L=c(c(w*w)-E-M),O=I+M,R=O-D,S=I-M,_=c(L*R),x=c(O*S),A=c(L*S),P=c(R*O);return new u(_,x,P,A)}add(b){h(b);let{a:y,d:v}=i,{X:T,Y:E,Z:M,T:D}=this,{X:I,Y:w,Z:L,T:O}=b,R=c(T*I),S=c(E*w),_=c(D*v*O),x=c(M*L),A=c((T+E)*(I+w)-R-S),P=x-_,B=x+_,C=c(S-y*R),k=c(A*P),N=c(B*C),U=c(A*C),j=c(P*B);return new u(k,N,j,U)}subtract(b){return this.add(b.negate())}multiply(b){if(!n.isValidNot0(b))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:y,f:v}=p.cached(this,b,T=>St(u,T));return St(u,[y,v])[0]}multiplyUnsafe(b,y=u.ZERO){if(!n.isValid(b))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return b===ut?u.ZERO:this.is0()||b===ne?this:p.unsafe(this,b,v=>St(u,v),y)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return p.unsafe(this,i.n).is0()}toAffine(b){return g(this,b)}clearCofactor(){return o===ne?this:this.multiplyUnsafe(o)}toBytes(){let{x:b,y}=this.toAffine(),v=r.toBytes(y);return v[v.length-1]|=b&ne?128:0,v}toHex(){return je(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let p=new Vt(u,n.BITS);return u.BASE.precompute(8),u}function Fo(s,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');lt(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:r}=t,{BASE:n,Fp:i,Fn:o}=s,a=t.randomBytes||it,c=t.adjustScalarBytes||(I=>I),f=t.domain||((I,w,L)=>{if(Je(L,"phflag"),w.length||L)throw new Error("Contexts/pre-hash are not supported");return I});function m(I){return o.create(xt(I))}function h(I){let w=v.secretKey;K(I,v.secretKey,"secretKey");let L=K(e(I),2*w,"hashedSecretKey"),O=c(L.slice(0,w)),R=L.slice(w,2*w),S=m(O);return{head:O,prefix:R,scalar:S}}function g(I){let{head:w,prefix:L,scalar:O}=h(I),R=n.multiply(O),S=R.toBytes();return{head:w,prefix:L,scalar:O,point:R,pointBytes:S}}function l(I){return g(I).pointBytes}function u(I=Uint8Array.of(),...w){let L=Ie(...w);return m(e(f(L,K(I,void 0,"context"),!!r)))}function p(I,w,L={}){I=K(I,void 0,"message"),r&&(I=r(I));let{prefix:O,scalar:R,pointBytes:S}=g(w),_=u(L.context,O,I),x=n.multiply(_).toBytes(),A=u(L.context,x,S,I),P=o.create(_+A*R);if(!o.isValid(P))throw new Error("sign failed: invalid s");let B=Ie(x,o.toBytes(P));return K(B,v.signature,"result")}let d={zip215:!0};function b(I,w,L,O=d){let{context:R,zip215:S}=O,_=v.signature;I=K(I,_,"signature"),w=K(w,void 0,"message"),L=K(L,v.publicKey,"publicKey"),S!==void 0&&Je(S,"zip215"),r&&(w=r(w));let x=_/2,A=I.subarray(0,x),P=xt(I.subarray(x,_)),B,C,k;try{B=s.fromBytes(L,S),C=s.fromBytes(A,S),k=n.multiplyUnsafe(P)}catch{return!1}if(!S&&B.isSmallOrder())return!1;let N=u(R,C.toBytes(),B.toBytes(),w);return C.add(B.multiplyUnsafe(N)).subtract(k).clearCofactor().is0()}let y=i.BYTES,v={secretKey:y,publicKey:y,signature:2*y,seed:y};function T(I=a(v.seed)){return K(I,v.seed,"seed")}function E(I){return bt(I)&&I.length===o.BYTES}function M(I,w){try{return!!s.fromBytes(I,w)}catch{return!1}}let D={getExtendedPublicKey:g,randomSecretKey:T,isValidSecretKey:E,isValidPublicKey:M,toMontgomery(I){let{y:w}=s.fromBytes(I),L=v.publicKey,O=L===32;if(!O&&L!==57)throw new Error("only defined for 25519 and 448");let R=O?i.div(ne+w,ne-w):i.div(w-ne,w+ne);return i.toBytes(R)},toMontgomerySecret(I){let w=v.secretKey;K(I,w);let L=e(I.subarray(0,w));return c(L).subarray(0,w)}};return Object.freeze({keygen:Vs(T,l),getPublicKey:l,sign:p,verify:b,utils:D,Point:s,lengths:v})}var $l=BigInt(1),Go=BigInt(2);var Zl=BigInt(5),jl=BigInt(8),En=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Xl={p:En,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:jl,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Yl(s){let e=BigInt(10),t=BigInt(20),r=BigInt(40),n=BigInt(80),i=En,a=s*s%i*s%i,c=$(a,Go,i)*a%i,f=$(c,$l,i)*s%i,m=$(f,Zl,i)*f%i,h=$(m,e,i)*m%i,g=$(h,t,i)*h%i,l=$(g,r,i)*g%i,u=$(l,n,i)*l%i,p=$(u,n,i)*l%i,d=$(p,e,i)*m%i;return{pow_p_5_8:$(d,Go,i)*s%i,b2:a}}function Jl(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}var Ho=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ql(s,e){let t=En,r=ee(e*e*e,t),n=ee(r*r*e,t),i=Yl(s*n).pow_p_5_8,o=ee(s*r*i,t),a=ee(e*o*o,t),c=o,f=ee(o*Ho,t),m=a===s,h=a===ee(-s,t),g=a===ee(-s*Ho,t);return m&&(o=c),(h||g)&&(o=f),Lo(o,t)&&(o=ee(-o,t)),{isValid:m||h,value:o}}var eu=Ko(Xl,{uvRatio:Ql});function tu(s){return Fo(eu,yo,Object.assign({adjustScalarBytes:Jl},s))}var qo=tu({});var ws=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Ws=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var zo={get(s=globalThis){let e=s.crypto;if(e?.subtle==null)throw new Ws("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 Me=zo;var $s=32;var Sn,su=(async()=>{try{return await Me.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function ru(s,e,t){if(s.buffer instanceof ArrayBuffer){let r=await Me.get().subtle.importKey("raw",s.buffer,{name:"Ed25519"},!1,["verify"]);return await Me.get().subtle.verify({name:"Ed25519"},r,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function nu(s,e,t){return qo.verify(e,t instanceof Uint8Array?t:t.subarray(),s)}async function Vo(s,e,t){return Sn==null&&(Sn=await su),Sn?ru(s,e,t):nu(s,e,t)}function Zs(s){return s==null?!1:typeof s.then=="function"&&typeof s.catch=="function"&&typeof s.finally=="function"}var js=class{type="Ed25519";raw;constructor(e){this.raw=_n(e,$s)}toMultihash(){return Le.digest(Ue(this))}toCID(){return oe.createV1(114,this.toMultihash())}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Se(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();let n=Vo(this.raw,t,e);return Zs(n)?n.then(i=>(r?.signal?.throwIfAborted(),i)):n}};function In(s){return s=_n(s,$s),new js(s)}function _n(s,e){if(s=Uint8Array.from(s??[]),s.length!==e)throw new W(`Key must be a Uint8Array of length ${e}, got ${s.length}`);return s}var ou=Math.pow(2,7),au=Math.pow(2,14),cu=Math.pow(2,21),Tn=Math.pow(2,28),An=Math.pow(2,35),Dn=Math.pow(2,42),Mn=Math.pow(2,49),G=128,ue=127;function Pe(s){if(s<ou)return 1;if(s<au)return 2;if(s<cu)return 3;if(s<Tn)return 4;if(s<An)return 5;if(s<Dn)return 6;if(s<Mn)return 7;if(Number.MAX_SAFE_INTEGER!=null&&s>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Pn(s,e,t=0){switch(Pe(s)){case 8:e[t++]=s&255|G,s/=128;case 7:e[t++]=s&255|G,s/=128;case 6:e[t++]=s&255|G,s/=128;case 5:e[t++]=s&255|G,s/=128;case 4:e[t++]=s&255|G,s>>>=7;case 3:e[t++]=s&255|G,s>>>=7;case 2:e[t++]=s&255|G,s>>>=7;case 1:{e[t++]=s&255,s>>>=7;break}default:throw new Error("unreachable")}return e}function lu(s,e,t=0){switch(Pe(s)){case 8:e.set(t++,s&255|G),s/=128;case 7:e.set(t++,s&255|G),s/=128;case 6:e.set(t++,s&255|G),s/=128;case 5:e.set(t++,s&255|G),s/=128;case 4:e.set(t++,s&255|G),s>>>=7;case 3:e.set(t++,s&255|G),s>>>=7;case 2:e.set(t++,s&255|G),s>>>=7;case 1:{e.set(t++,s&255),s>>>=7;break}default:throw new Error("unreachable")}return e}function Ln(s,e){let t=s[e],r=0;if(r+=t&ue,t<G||(t=s[e+1],r+=(t&ue)<<7,t<G)||(t=s[e+2],r+=(t&ue)<<14,t<G)||(t=s[e+3],r+=(t&ue)<<21,t<G)||(t=s[e+4],r+=(t&ue)*Tn,t<G)||(t=s[e+5],r+=(t&ue)*An,t<G)||(t=s[e+6],r+=(t&ue)*Dn,t<G)||(t=s[e+7],r+=(t&ue)*Mn,t<G))return r;throw new RangeError("Could not decode varint")}function uu(s,e){let t=s.get(e),r=0;if(r+=t&ue,t<G||(t=s.get(e+1),r+=(t&ue)<<7,t<G)||(t=s.get(e+2),r+=(t&ue)<<14,t<G)||(t=s.get(e+3),r+=(t&ue)<<21,t<G)||(t=s.get(e+4),r+=(t&ue)*Tn,t<G)||(t=s.get(e+5),r+=(t&ue)*An,t<G)||(t=s.get(e+6),r+=(t&ue)*Dn,t<G)||(t=s.get(e+7),r+=(t&ue)*Mn,t<G))return r;throw new RangeError("Could not decode varint")}function kn(s,e,t=0){return e==null&&(e=le(Pe(s))),e instanceof Uint8Array?Pn(s,e,t):lu(s,e,t)}function Bn(s,e=0){return s instanceof Uint8Array?Ln(s,e):uu(s,e)}var Cn=new Float32Array([-0]),ht=new Uint8Array(Cn.buffer);function $o(s,e,t){Cn[0]=s,e[t]=ht[0],e[t+1]=ht[1],e[t+2]=ht[2],e[t+3]=ht[3]}function Zo(s,e){return ht[0]=s[e],ht[1]=s[e+1],ht[2]=s[e+2],ht[3]=s[e+3],Cn[0]}var Nn=new Float64Array([-0]),he=new Uint8Array(Nn.buffer);function jo(s,e,t){Nn[0]=s,e[t]=he[0],e[t+1]=he[1],e[t+2]=he[2],e[t+3]=he[3],e[t+4]=he[4],e[t+5]=he[5],e[t+6]=he[6],e[t+7]=he[7]}function Xo(s,e){return he[0]=s[e],he[1]=s[e+1],he[2]=s[e+2],he[3]=s[e+3],he[4]=s[e+4],he[5]=s[e+5],he[6]=s[e+6],he[7]=s[e+7],Nn[0]}var hu=BigInt(Number.MAX_SAFE_INTEGER),fu=BigInt(Number.MIN_SAFE_INTEGER),Ae=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 _t;if(e<hu&&e>fu)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>Yo&&(n=0n,++r>Yo&&(r=0n))),new s(Number(n),Number(r))}static fromNumber(e){if(e===0)return _t;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):_t}},_t=new Ae(0,0);_t.toBigInt=function(){return 0n};_t.zzEncode=_t.zzDecode=function(){return this};_t.length=function(){return 1};var Yo=4294967296n;function Jo(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 Qo(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 On(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 Be(s,e){return RangeError(`index out of range: ${s.pos} + ${e??1} > ${s.len}`)}function Xs(s,e){return(s[e-4]|s[e-3]<<8|s[e-2]<<16|s[e-1]<<24)>>>0}var Un=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Be(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 Be(this,4);return Xs(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Be(this,4);return Xs(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Be(this,4);let e=Zo(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Be(this,4);let e=Xo(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 Be(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){let e=this.bytes();return Qo(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Be(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Be(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 Ae(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 Be(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 Be(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 Be(this,8);let e=Xs(this.buf,this.pos+=4),t=Xs(this.buf,this.pos+=4);return new Ae(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=Ln(this.buf,this.pos);return this.pos+=Pe(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 Kn(s){return new Un(s instanceof Uint8Array?s:s.subarray())}function ge(s,e,t){let r=Kn(s);return e.decode(r,void 0,t)}function Fn(s){let e=s??8192,t=e>>>1,r,n=e;return function(o){if(o<1||o>t)return le(o);n+o>e&&(r=le(e),n=0);let a=r.subarray(n,n+=o);return(n&7)!==0&&(n=(n|7)+1),a}}var It=class{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}};function Gn(){}var qn=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},du=Fn();function pu(s){return globalThis.Buffer!=null?le(s):du(s)}var vs=class{len;head;tail;states;constructor(){this.len=0,this.head=new It(Gn,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new It(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new zn((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(Ys,10,Ae.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ae.fromBigInt(e);return this._push(Ys,t.length(),t)}uint64Number(e){return this._push(Pn,Pe(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=Ae.fromBigInt(e).zzEncode();return this._push(Ys,t.length(),t)}sint64Number(e){let t=Ae.fromNumber(e).zzEncode();return this._push(Ys,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Hn,1,e?1:0)}fixed32(e){return this._push(xs,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ae.fromBigInt(e);return this._push(xs,4,t.lo)._push(xs,4,t.hi)}fixed64Number(e){let t=Ae.fromNumber(e);return this._push(xs,4,t.lo)._push(xs,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($o,4,e)}double(e){return this._push(jo,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Hn,1,0):this.uint32(t)._push(gu,t,e)}string(e){let t=Jo(e);return t!==0?this.uint32(t)._push(On,t,e):this._push(Hn,1,0)}fork(){return this.states=new qn(this),this.head=this.tail=new It(Gn,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 It(Gn,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=pu(this.len),r=0;for(;e!=null;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}};function Hn(s,e,t){e[t]=s&255}function mu(s,e,t){for(;s>127;)e[t++]=s&127|128,s>>>=7;e[t]=s}var zn=class extends It{next;constructor(e,t){super(mu,e,t),this.next=void 0}};function Ys(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 xs(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 gu(s,e,t){e.set(s,t)}globalThis.Buffer!=null&&(vs.prototype.bytes=function(s){let e=s.length>>>0;return this.uint32(e),e>0&&this._push(bu,e,s),this},vs.prototype.string=function(s){let e=globalThis.Buffer.byteLength(s);return this.uint32(e),e>0&&this._push(yu,e,s),this});function bu(s,e,t){e.set(s,t)}function yu(s,e,t){s.length<40?On(s,e,t):e.utf8Write!=null?e.utf8Write(s,t):e.set(z(s),t)}function Vn(){return new vs}function be(s,e){let t=Vn();return e.encode(s,t,{lengthDelimited:!1}),t.finish()}var Wt;(function(s){s[s.VARINT=0]="VARINT",s[s.BIT64=1]="BIT64",s[s.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",s[s.START_GROUP=3]="START_GROUP",s[s.END_GROUP=4]="END_GROUP",s[s.BIT32=5]="BIT32"})(Wt||(Wt={}));function Js(s,e,t,r){return{name:s,type:e,encode:t,decode:r}}function Wn(s){function e(n){if(s[n.toString()]==null)throw new Error("Invalid enum value");return s[n]}let t=function(i,o){let a=e(i);o.int32(a)},r=function(i){let o=i.int32();return e(o)};return Js("enum",Wt.VARINT,t,r)}function ye(s,e){return Js("message",Wt.LENGTH_DELIMITED,s,e)}var Te=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var te;(function(s){s.RSA="RSA",s.Ed25519="Ed25519",s.secp256k1="secp256k1",s.ECDSA="ECDSA"})(te||(te={}));var $n;(function(s){s[s.RSA=0]="RSA",s[s.Ed25519=1]="Ed25519",s[s.secp256k1=2]="secp256k1",s[s.ECDSA=3]="ECDSA"})($n||($n={}));(function(s){s.codec=()=>Wn($n)})(te||(te={}));var Ge;(function(s){let e;s.codec=()=>(e==null&&(e=ye((t,r,n={})=>{n.lengthDelimited!==!1&&r.fork(),t.Type!=null&&(r.uint32(8),te.codec().encode(t.Type,r)),t.Data!=null&&(r.uint32(18),r.bytes(t.Data)),n.lengthDelimited!==!1&&r.ldelim()},(t,r,n={})=>{let i={},o=r==null?t.len:t.pos+r;for(;t.pos<o;){let a=t.uint32();switch(a>>>3){case 1:{i.Type=te.codec().decode(t);break}case 2:{i.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return i})),e),s.encode=t=>be(t,s.codec()),s.decode=(t,r)=>ge(t,s.codec(),r)})(Ge||(Ge={}));var Zn;(function(s){let e;s.codec=()=>(e==null&&(e=ye((t,r,n={})=>{n.lengthDelimited!==!1&&r.fork(),t.Type!=null&&(r.uint32(8),te.codec().encode(t.Type,r)),t.Data!=null&&(r.uint32(18),r.bytes(t.Data)),n.lengthDelimited!==!1&&r.ldelim()},(t,r,n={})=>{let i={},o=r==null?t.len:t.pos+r;for(;t.pos<o;){let a=t.uint32();switch(a>>>3){case 1:{i.Type=te.codec().decode(t);break}case 2:{i.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return i})),e),s.encode=t=>be(t,s.codec()),s.decode=(t,r)=>ge(t,s.codec(),r)})(Zn||(Zn={}));function Qs(s){if(isNaN(s)||s<=0)throw new W("random bytes length must be a Number bigger than 0");return it(s)}var Ss={};Ee(Ss,{MAX_RSA_KEY_SIZE:()=>jn,generateRSAKeyPair:()=>ia,jwkToJWKKeyPair:()=>oa,jwkToPkcs1:()=>Eu,jwkToPkix:()=>Qn,jwkToRSAPrivateKey:()=>ri,pkcs1MessageToJwk:()=>Yn,pkcs1MessageToRSAPrivateKey:()=>ei,pkcs1ToJwk:()=>vu,pkcs1ToRSAPrivateKey:()=>na,pkixMessageToJwk:()=>Jn,pkixMessageToRSAPublicKey:()=>si,pkixToJwk:()=>Su,pkixToRSAPublicKey:()=>ti});var $t=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Ss.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return oe.createV1(114,this._multihash)}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Se(this.raw,e.raw)}verify(e,t,r){return ra(this.jwk,t,e,r)}},Es=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Ss.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Se(this.raw,e.raw)}sign(e,t){return sa(this.jwk,e,t)}};var jn=8192,Xn=18,wu=1062,xu=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function vu(s){let e=We(s);return Yn(e)}function Yn(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 Eu(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 W("JWK was missing components");return nt([_e(Uint8Array.from([0])),_e(z(s.n,"base64url")),_e(z(s.e,"base64url")),_e(z(s.d,"base64url")),_e(z(s.p,"base64url")),_e(z(s.q,"base64url")),_e(z(s.dp,"base64url")),_e(z(s.dq,"base64url")),_e(z(s.qi,"base64url"))]).subarray()}function Su(s){let e=We(s,{offset:0});return Jn(e)}function Jn(s){let e=We(s[1],{offset:0});return{kty:"RSA",n:q(e[0],"base64url"),e:q(e[1],"base64url")}}function Qn(s){if(s.n==null||s.e==null)throw new W("JWK was missing components");return nt([xu,Os(nt([_e(z(s.n,"base64url")),_e(z(s.e,"base64url"))]))]).subarray()}function na(s){let e=We(s);return ei(e)}function ei(s){let e=Yn(s);return ri(e)}function ti(s,e){if(s.byteLength>=wu)throw new Lt("Key size is too large");let t=We(s,{offset:0});return si(t,s,e)}function si(s,e,t){let r=Jn(s);if(t==null){let n=Ft(Ge.encode({Type:te.RSA,Data:e}));t=Oe(Xn,n)}return new $t(r,t)}function ri(s){if(ca(s)>jn)throw new W("Key size is too large");let e=oa(s),t=Ft(Ge.encode({Type:te.RSA,Data:Qn(e.publicKey)})),r=Oe(Xn,t);return new Es(e.privateKey,new $t(e.publicKey,r))}async function ia(s){if(s>jn)throw new W("Key size is too large");let e=await aa(s),t=Ft(Ge.encode({Type:te.RSA,Data:Qn(e.publicKey)})),r=Oe(Xn,t);return new Es(e.privateKey,new $t(e.publicKey,r))}function oa(s){if(s==null)throw new W("Missing key parameter");return{privateKey:s,publicKey:{kty:s.kty,n:s.n,e:s.e}}}async function aa(s,e){let t=await Me.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 _u(t,e);return{privateKey:r[0],publicKey:r[1]}}async function sa(s,e,t){let r=await Me.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let n=await Me.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(n,0,n.byteLength)}async function ra(s,e,t,r){let n=await Me.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();let i=await Me.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray());return r?.signal?.throwIfAborted(),i}async function _u(s,e){if(s.privateKey==null||s.publicKey==null)throw new W("Private and public key are required");let t=await Promise.all([Me.get().subtle.exportKey("jwk",s.privateKey),Me.get().subtle.exportKey("jwk",s.publicKey)]);return e?.signal?.throwIfAborted(),t}function ca(s){if(s.kty!=="RSA")throw new W("invalid key type");if(s.n==null)throw new W("invalid key modulus");return z(s.n,"base64url").length*8}var er=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Us(e),K(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),Ze(n)}update(e){return Kt(this),this.iHash.update(e),this}digestInto(e){Kt(this),K(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash: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()}},ni=(s,e,t)=>new er(s,e).update(t).digest();ni.create=(s,e)=>new er(s,e);var la=(s,e)=>(s+(s>=0?e:-e)/ua)/e;function Iu(s,e,t){let[[r,n],[i,o]]=e,a=la(o*s,t),c=la(-n*s,t),f=s-a*r-c*i,m=-a*n-c*o,h=f<Qe,g=m<Qe;h&&(f=-f),g&&(m=-m);let l=gs(Math.ceil(fn(t)/2))+Zt;if(f<Qe||f>=l||m<Qe||m>=l)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:h,k1:f,k2neg:g,k2:m}}function oi(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function ii(s,e){let t={};for(let r of Object.keys(e))t[r]=s[r]===void 0?e[r]:s[r];return Je(t.lowS,"lowS"),Je(t.prehash,"prehash"),t.format!==void 0&&oi(t.format),t}var ai=class extends Error{constructor(e=""){super(e)}},ft={Err:ai,_tlv:{encode:(s,e)=>{let{Err:t}=ft;if(s<0||s>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let r=e.length/2,n=ps(r);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let i=r>127?ps(n.length/2|128):"";return ps(s)+i+n+e},decode(s,e){let{Err:t}=ft,r=0;if(s<0||s>256)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 c=n&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let f=e.subarray(r,r+c);if(f.length!==c)throw new t("tlv.decode: length bytes not complete");if(f[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let m of f)o=o<<8|m;if(r+=c,o<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(s){let{Err:e}=ft;if(s<Qe)throw new e("integer: negative integers are not allowed");let t=ps(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}=ft;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Gt(s)}},toSig(s){let{Err:e,_int:t,_tlv:r}=ft,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:c}=r.decode(2,i),{v:f,l:m}=r.decode(2,c);if(m.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(f)}},hexFromSig(s){let{_tlv:e,_int:t}=ft,r=e.encode(2,t.encode(s.r)),n=e.encode(2,t.encode(s.s)),i=r+n;return e.encode(48,i)}},Qe=BigInt(0),Zt=BigInt(1),ua=BigInt(2),tr=BigInt(3),Tu=BigInt(4);function ha(s,e={}){let t=zs("weierstrass",s,e),{Fp:r,Fn:n}=t,i=t.CURVE,{h:o,n:a}=i;lt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let f=da(r,n);function m(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(R,S,_){let{x,y:A}=S.toAffine(),P=r.toBytes(x);if(Je(_,"isCompressed"),_){m();let B=!r.isOdd(A);return Ie(fa(B),P)}else return Ie(Uint8Array.of(4),P,r.toBytes(A))}function g(R){K(R,void 0,"Point");let{publicKey:S,publicKeyUncompressed:_}=f,x=R.length,A=R[0],P=R.subarray(1);if(x===S&&(A===2||A===3)){let B=r.fromBytes(P);if(!r.isValid(B))throw new Error("bad point: is not on curve, wrong x");let C=p(B),k;try{k=r.sqrt(C)}catch(j){let V=j instanceof Error?": "+j.message:"";throw new Error("bad point: is not on curve, sqrt error"+V)}m();let N=r.isOdd(k);return(A&1)===1!==N&&(k=r.neg(k)),{x:B,y:k}}else if(x===_&&A===4){let B=r.BYTES,C=r.fromBytes(P.subarray(0,B)),k=r.fromBytes(P.subarray(B,B*2));if(!d(C,k))throw new Error("bad point: is not on curve");return{x:C,y:k}}else throw new Error(`bad point: got length ${x}, expected compressed=${S} or uncompressed=${_}`)}let l=e.toBytes||h,u=e.fromBytes||g;function p(R){let S=r.sqr(R),_=r.mul(S,R);return r.add(r.add(_,r.mul(R,i.a)),i.b)}function d(R,S){let _=r.sqr(S),x=p(R);return r.eql(_,x)}if(!d(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let b=r.mul(r.pow(i.a,tr),Tu),y=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(b,y)))throw new Error("bad curve params: a or b");function v(R,S,_=!1){if(!r.isValid(S)||_&&r.is0(S))throw new Error(`bad point coordinate ${R}`);return S}function T(R){if(!(R instanceof w))throw new Error("Weierstrass Point expected")}function E(R){if(!c||!c.basises)throw new Error("no endo");return Iu(R,c.basises,n.ORDER)}let M=Ht((R,S)=>{let{X:_,Y:x,Z:A}=R;if(r.eql(A,r.ONE))return{x:_,y:x};let P=R.is0();S==null&&(S=P?r.ONE:r.inv(A));let B=r.mul(_,S),C=r.mul(x,S),k=r.mul(A,S);if(P)return{x:r.ZERO,y:r.ZERO};if(!r.eql(k,r.ONE))throw new Error("invZ was invalid");return{x:B,y:C}}),D=Ht(R=>{if(R.is0()){if(e.allowInfinityPoint&&!r.is0(R.Y))return;throw new Error("bad point: ZERO")}let{x:S,y:_}=R.toAffine();if(!r.isValid(S)||!r.isValid(_))throw new Error("bad point: x or y not field elements");if(!d(S,_))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function I(R,S,_,x,A){return _=new w(r.mul(_.X,R),_.Y,_.Z),S=ys(x,S),_=ys(A,_),S.add(_)}class w{static BASE=new w(i.Gx,i.Gy,r.ONE);static ZERO=new w(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=n;X;Y;Z;constructor(S,_,x){this.X=v("x",S),this.Y=v("y",_,!0),this.Z=v("z",x),Object.freeze(this)}static CURVE(){return i}static fromAffine(S){let{x:_,y:x}=S||{};if(!S||!r.isValid(_)||!r.isValid(x))throw new Error("invalid affine point");if(S instanceof w)throw new Error("projective point not allowed");return r.is0(_)&&r.is0(x)?w.ZERO:new w(_,x,r.ONE)}static fromBytes(S){let _=w.fromAffine(u(K(S,void 0,"point")));return _.assertValidity(),_}static fromHex(S){return w.fromBytes(Xe(S))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(S=8,_=!0){return O.createCache(this,S),_||this.multiply(tr),this}assertValidity(){D(this)}hasEvenY(){let{y:S}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(S)}equals(S){T(S);let{X:_,Y:x,Z:A}=this,{X:P,Y:B,Z:C}=S,k=r.eql(r.mul(_,C),r.mul(P,A)),N=r.eql(r.mul(x,C),r.mul(B,A));return k&&N}negate(){return new w(this.X,r.neg(this.Y),this.Z)}double(){let{a:S,b:_}=i,x=r.mul(_,tr),{X:A,Y:P,Z:B}=this,C=r.ZERO,k=r.ZERO,N=r.ZERO,U=r.mul(A,A),j=r.mul(P,P),V=r.mul(B,B),F=r.mul(A,P);return F=r.add(F,F),N=r.mul(A,B),N=r.add(N,N),C=r.mul(S,N),k=r.mul(x,V),k=r.add(C,k),C=r.sub(j,k),k=r.add(j,k),k=r.mul(C,k),C=r.mul(F,C),N=r.mul(x,N),V=r.mul(S,V),F=r.sub(U,V),F=r.mul(S,F),F=r.add(F,N),N=r.add(U,U),U=r.add(N,U),U=r.add(U,V),U=r.mul(U,F),k=r.add(k,U),V=r.mul(P,B),V=r.add(V,V),U=r.mul(V,F),C=r.sub(C,U),N=r.mul(V,j),N=r.add(N,N),N=r.add(N,N),new w(C,k,N)}add(S){T(S);let{X:_,Y:x,Z:A}=this,{X:P,Y:B,Z:C}=S,k=r.ZERO,N=r.ZERO,U=r.ZERO,j=i.a,V=r.mul(i.b,tr),F=r.mul(_,P),X=r.mul(x,B),ie=r.mul(A,C),Ne=r.add(_,x),Y=r.add(P,B);Ne=r.mul(Ne,Y),Y=r.add(F,X),Ne=r.sub(Ne,Y),Y=r.add(_,A);let ce=r.add(P,C);return Y=r.mul(Y,ce),ce=r.add(F,ie),Y=r.sub(Y,ce),ce=r.add(x,A),k=r.add(B,C),ce=r.mul(ce,k),k=r.add(X,ie),ce=r.sub(ce,k),U=r.mul(j,Y),k=r.mul(V,ie),U=r.add(k,U),k=r.sub(X,U),U=r.add(X,U),N=r.mul(k,U),X=r.add(F,F),X=r.add(X,F),ie=r.mul(j,ie),Y=r.mul(V,Y),X=r.add(X,ie),ie=r.sub(F,ie),ie=r.mul(j,ie),Y=r.add(Y,ie),F=r.mul(X,Y),N=r.add(N,F),F=r.mul(ce,Y),k=r.mul(Ne,k),k=r.sub(k,F),F=r.mul(Ne,X),U=r.mul(ce,U),U=r.add(U,F),new w(k,N,U)}subtract(S){return this.add(S.negate())}is0(){return this.equals(w.ZERO)}multiply(S){let{endo:_}=e;if(!n.isValidNot0(S))throw new Error("invalid scalar: out of range");let x,A,P=B=>O.cached(this,B,C=>St(w,C));if(_){let{k1neg:B,k1:C,k2neg:k,k2:N}=E(S),{p:U,f:j}=P(C),{p:V,f:F}=P(N);A=j.add(F),x=I(_.beta,U,V,B,k)}else{let{p:B,f:C}=P(S);x=B,A=C}return St(w,[x,A])[0]}multiplyUnsafe(S){let{endo:_}=e,x=this;if(!n.isValid(S))throw new Error("invalid scalar: out of range");if(S===Qe||x.is0())return w.ZERO;if(S===Zt)return x;if(O.hasCache(this))return this.multiply(S);if(_){let{k1neg:A,k1:P,k2neg:B,k2:C}=E(S),{p1:k,p2:N}=Uo(w,x,P,C);return I(_.beta,k,N,A,B)}else return O.unsafe(x,S)}toAffine(S){return M(this,S)}isTorsionFree(){let{isTorsionFree:S}=e;return o===Zt?!0:S?S(w,this):O.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:S}=e;return o===Zt?this:S?S(w,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(S=!0){return Je(S,"isCompressed"),this.assertValidity(),l(w,this,S)}toHex(S=!0){return je(this.toBytes(S))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let L=n.BITS,O=new Vt(w,e.endo?Math.ceil(L/2):L);return w.BASE.precompute(8),w}function fa(s){return Uint8Array.of(s?2:3)}function da(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Au(s,e={}){let{Fn:t}=s,r=e.randomBytes||it,n=Object.assign(da(s.Fp,t),{seed:gn(t.ORDER)});function i(l){try{let u=t.fromBytes(l);return t.isValidNot0(u)}catch{return!1}}function o(l,u){let{publicKey:p,publicKeyUncompressed:d}=n;try{let b=l.length;return u===!0&&b!==p||u===!1&&b!==d?!1:!!s.fromBytes(l)}catch{return!1}}function a(l=r(n.seed)){return bn(K(l,n.seed,"seed"),t.ORDER)}function c(l,u=!0){return s.BASE.multiply(t.fromBytes(l)).toBytes(u)}function f(l){let{secretKey:u,publicKey:p,publicKeyUncompressed:d}=n;if(!bt(l)||"_lengths"in t&&t._lengths||u===p)return;let b=K(l,void 0,"key").length;return b===p||b===d}function m(l,u,p=!0){if(f(l)===!0)throw new Error("first arg must be private key");if(f(u)===!1)throw new Error("second arg must be public key");let d=t.fromBytes(l);return s.fromBytes(u).multiply(d).toBytes(p)}let h={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},g=Vs(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:m,keygen:g,Point:s,utils:h,lengths:n})}function pa(s,e,t={}){Us(e),lt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let r=t.randomBytes||it,n=t.hmac||((_,x)=>ni(e,_,x)),{Fp:i,Fn:o}=s,{ORDER:a,BITS:c}=o,{keygen:f,getPublicKey:m,getSharedSecret:h,utils:g,lengths:l}=Au(s,t),u={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},p=a*ua<i.ORDER;function d(_){let x=a>>Zt;return _>x}function b(_,x){if(!o.isValidNot0(x))throw new Error(`invalid signature ${_}: out of range 1..Point.Fn.ORDER`);return x}function y(){if(p)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function v(_,x){oi(x);let A=l.signature,P=x==="compact"?A:x==="recovered"?A+1:void 0;return K(_,P)}class T{r;s;recovery;constructor(x,A,P){if(this.r=b("r",x),this.s=b("s",A),P!=null){if(y(),![0,1,2,3].includes(P))throw new Error("invalid recovery id");this.recovery=P}Object.freeze(this)}static fromBytes(x,A=u.format){v(x,A);let P;if(A==="der"){let{r:N,s:U}=ft.toSig(K(x));return new T(N,U)}A==="recovered"&&(P=x[0],A="compact",x=x.subarray(1));let B=l.signature/2,C=x.subarray(0,B),k=x.subarray(B,B*2);return new T(o.fromBytes(C),o.fromBytes(k),P)}static fromHex(x,A){return this.fromBytes(Xe(x),A)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new T(this.r,this.s,x)}recoverPublicKey(x){let{r:A,s:P}=this,B=this.assertRecovery(),C=B===2||B===3?A+a:A;if(!i.isValid(C))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let k=i.toBytes(C),N=s.fromBytes(Ie(fa((B&1)===0),k)),U=o.inv(C),j=M(K(x,void 0,"msgHash")),V=o.create(-j*U),F=o.create(P*U),X=s.BASE.multiplyUnsafe(V).add(N.multiplyUnsafe(F));if(X.is0())throw new Error("invalid recovery: point at infinify");return X.assertValidity(),X}hasHighS(){return d(this.s)}toBytes(x=u.format){if(oi(x),x==="der")return Xe(ft.hexFromSig(this));let{r:A,s:P}=this,B=o.toBytes(A),C=o.toBytes(P);return x==="recovered"?(y(),Ie(Uint8Array.of(this.assertRecovery()),B,C)):Ie(B,C)}toHex(x){return je(this.toBytes(x))}}let E=t.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let A=Gt(x),P=x.length*8-c;return P>0?A>>BigInt(P):A},M=t.bits2int_modN||function(x){return o.create(E(x))},D=gs(c);function I(_){return ms("num < 2^"+c,_,Qe,D),o.toBytes(_)}function w(_,x){return K(_,void 0,"message"),x?K(e(_),void 0,"prehashed message"):_}function L(_,x,A){let{lowS:P,prehash:B,extraEntropy:C}=ii(A,u);_=w(_,B);let k=M(_),N=o.fromBytes(x);if(!o.isValidNot0(N))throw new Error("invalid private key");let U=[I(N),I(k)];if(C!=null&&C!==!1){let X=C===!0?r(l.secretKey):C;U.push(K(X,void 0,"extraEntropy"))}let j=Ie(...U),V=k;function F(X){let ie=E(X);if(!o.isValidNot0(ie))return;let Ne=o.inv(ie),Y=s.BASE.multiply(ie).toAffine(),ce=o.create(Y.x);if(ce===Qe)return;let Ms=o.create(Ne*o.create(V+ce*N));if(Ms===Qe)return;let vi=(Y.x===ce?0:2)|Number(Y.y&Zt),Ei=Ms;return P&&d(Ms)&&(Ei=o.neg(Ms),vi^=1),new T(ce,Ei,p?void 0:vi)}return{seed:j,k2sig:F}}function O(_,x,A={}){let{seed:P,k2sig:B}=L(_,x,A);return vo(e.outputLen,o.BYTES,n)(P,B).toBytes(A.format)}function R(_,x,A,P={}){let{lowS:B,prehash:C,format:k}=ii(P,u);if(A=K(A,void 0,"publicKey"),x=w(x,C),!bt(_)){let N=_ instanceof T?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+N)}v(_,k);try{let N=T.fromBytes(_,k),U=s.fromBytes(A);if(B&&N.hasHighS())return!1;let{r:j,s:V}=N,F=M(x),X=o.inv(V),ie=o.create(F*X),Ne=o.create(j*X),Y=s.BASE.multiplyUnsafe(ie).add(U.multiplyUnsafe(Ne));return Y.is0()?!1:o.create(Y.x)===j}catch{return!1}}function S(_,x,A={}){let{prehash:P}=ii(A,u);return x=w(x,P),T.fromBytes(_,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:f,getPublicKey:m,getSharedSecret:h,utils:g,lengths:l,Point:s,sign:O,verify:R,recoverPublicKey:S,Signature:T,hash:e})}var li={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Du={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var ma=BigInt(2);function Mu(s){let e=li.p,t=BigInt(3),r=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),f=s*s*s%e,m=f*f*s%e,h=$(m,t,e)*m%e,g=$(h,t,e)*m%e,l=$(g,ma,e)*f%e,u=$(l,n,e)*l%e,p=$(u,i,e)*u%e,d=$(p,a,e)*p%e,b=$(d,c,e)*d%e,y=$(b,a,e)*p%e,v=$(y,t,e)*m%e,T=$(v,o,e)*u%e,E=$(T,r,e)*f%e,M=$(E,ma,e);if(!ci.eql(ci.sqr(M),s))throw new Error("Cannot find square root");return M}var ci=qt(li.p,{sqrt:Mu}),Pu=ha(li,{Fp:ci,endo:Du}),jt=pa(Pu,Ft);function ga(s,e,t,r){let n=gt.digest(t instanceof Uint8Array?t:t.subarray());if(Zs(n))return n.then(({digest:i})=>(r?.signal?.throwIfAborted(),jt.verify(e,i,s,{prehash:!1,format:"der"}))).catch(i=>{throw i.name==="AbortError"?i:new ws(String(i))});try{return r?.signal?.throwIfAborted(),jt.verify(e,n.digest,s,{prehash:!1,format:"der"})}catch(i){throw new ws(String(i))}}var sr=class{type="secp256k1";raw;_key;constructor(e){this._key=ya(e),this.raw=ba(this._key)}toMultihash(){return Le.digest(Ue(this))}toCID(){return oe.createV1(114,this.toMultihash())}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Se(this.raw,e.raw)}verify(e,t,r){return ga(this._key,t,e,r)}};function ui(s){return new sr(s)}function ba(s){return jt.Point.fromBytes(s).toBytes()}function ya(s){try{return jt.Point.fromBytes(s),s}catch(e){throw new Lt(String(e))}}function rr(s,e){let{Type:t,Data:r}=Ge.decode(s),n=r??new Uint8Array;switch(t){case te.RSA:return ti(n,e);case te.Ed25519:return In(n);case te.secp256k1:return ui(n);case te.ECDSA:return Qr(n);default:throw new kt}}function wa(s){let{Type:e,Data:t}=Ge.decode(s.digest),r=t??new Uint8Array;switch(e){case te.Ed25519:return In(r);case te.secp256k1:return ui(r);case te.ECDSA:return Qr(r);default:throw new kt}}function Ue(s){return Ge.encode({Type:te[s.type],Data:s.raw})}var xa=Symbol.for("nodejs.util.inspect.custom"),Lu=114,_s=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()})`}[Ir]=!0;toString(){return this.string==null&&(this.string=Q.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return oe.createV1(Lu,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Se(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Se(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[xa](){return`PeerId(${this.toString()})`}},nr=class extends _s{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},ir=class extends _s{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},or=class extends _s{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},ku=2336,Is=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Le.digest(z(this.url))}[xa](){return`PeerId(${this.url})`}[Ir]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return oe.createV1(ku,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=q(e)),e.toString()===this.toString())}};var Bu=114,va=2336;function Tt(s,e){let t;if(s.charAt(0)==="1"||s.charAt(0)==="Q")t=ze(Q.decode(`z${s}`));else{if(s.startsWith("k51qzi5uqu5")||s.startsWith("kzwfwjn5ji4")||s.startsWith("k2k4r8")||s.startsWith("bafz"))return Ru(oe.parse(s));if(e==null)throw new W('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=ze(e.decode(s))}return Xt(t)}function Xt(s){if(Nu(s))return new nr({multihash:s});if(Cu(s))try{let e=wa(s);if(e.type==="Ed25519")return new ir({multihash:s,publicKey:e});if(e.type==="secp256k1")return new or({multihash:s,publicKey:e})}catch{let t=q(s.digest);return new Is(new URL(t))}throw new ks("Supplied PeerID Multihash is invalid")}function Ru(s){if(s?.multihash==null||s.version==null||s.version===1&&s.code!==Bu&&s.code!==va)throw new Ls("Supplied PeerID CID is invalid");if(s.code===va){let e=q(s.multihash.digest);return new Is(new URL(e))}return Xt(s.multihash)}function Cu(s){return s.code===Le.code}function Nu(s){return s.code===gt.code}var ar=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Yt=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},cr=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Ts=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function lr(s){return s[Symbol.asyncIterator]!=null}function Ea(s,e){if(s.byteLength>e)throw new Yt("Message length too long")}var hr=s=>{let e=Pe(s),t=le(e);return kn(s,t),hr.bytes=e,t};hr.bytes=0;function Jt(s,e){e=e??{};let t=e.lengthEncoder??hr,r=e?.maxDataLength??4194304;function*n(i){Ea(i,r);let o=t(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return lr(s)?(async function*(){for await(let i of s)yield*n(i)})():(function*(){for(let i of s)yield*n(i)})()}Jt.single=(s,e)=>{e=e??{};let t=e.lengthEncoder??hr,r=e?.maxDataLength??4194304;return Ea(s,r),new se(t(s.byteLength),s)};var At;(function(s){s[s.LENGTH=0]="LENGTH",s[s.DATA=1]="DATA"})(At||(At={}));var hi=s=>{let e=Bn(s);return hi.bytes=Pe(e),e};hi.bytes=0;function As(s,e){let t=new se,r=At.LENGTH,n=-1,i=e?.lengthDecoder??hi,o=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(r===At.LENGTH)try{if(n=i(t),n<0)throw new ar("Invalid message length");if(n>a)throw new Yt("Message length too long");let f=i.bytes;t.consume(f),e?.onLength!=null&&e.onLength(n),r=At.DATA}catch(f){if(f instanceof RangeError){if(t.byteLength>o)throw new cr("Message length length too long");break}throw f}if(r===At.DATA){if(t.byteLength<n)break;let f=t.sublist(0,n);t.consume(n),e?.onData!=null&&e.onData(f),yield f,r=At.LENGTH}}}return lr(s)?(async function*(){for await(let f of s)t.append(f),yield*c();if(t.byteLength>0)throw new Ts("Unexpected end of input")})():(function*(){for(let f of s)t.append(f),yield*c();if(t.byteLength>0)throw new Ts("Unexpected end of input")})()}As.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 As(r,{...e??{},onLength:i=>{t=i}})};function et(){let s={};return s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),s}var fr=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Qt=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new fr(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new fr(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var fi=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Dt(s={}){return Uu(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 Uu(s,e){e=e??{};let t=e.onEnd,r=new Qt,n,i,o,a=et(),c=async()=>{try{return r.isEmpty()?o?{done:!0}:await new Promise((d,b)=>{i=y=>{i=null,r.push(y);try{d(s(r))}catch(v){b(v)}return n}}):s(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=et()})}},f=d=>i!=null?i(d):(r.push(d),n),m=d=>(r=new Qt,i!=null?i({error:d}):(r.push({error:d}),n)),h=d=>{if(o)return n;if(e?.objectMode!==!0&&d?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:d})},g=d=>o?n:(o=!0,d!=null?m(d):f({done:!0})),l=()=>(r=new Qt,g(),{done:!0}),u=d=>(g(d),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:c,return:l,throw:u,push:h,end:g,get readableLength(){return r.size},onEmpty:async d=>{let b=d?.signal;if(b?.throwIfAborted(),r.isEmpty())return;let y,v;b!=null&&(y=new Promise((T,E)=>{v=()=>{E(new fi)},b.addEventListener("abort",v)}));try{await Promise.race([a.promise,y])}finally{v!=null&&b!=null&&b?.removeEventListener("abort",v)}}},t==null)return n;let p=n;return n={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(d){return p.throw(d),t!=null&&(t(d),t=void 0),{done:!0}},return(){return p.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(d){return p.end(d),t!=null&&(t(d),t=void 0),n},get readableLength(){return p.readableLength},onEmpty:d=>p.onEmpty(d)},n}function Ku(s){return s.reason}async function di(s,e,t){if(e==null)return s;let r=t?.translateError??Ku;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 pi=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=et(),this.haveNext=et()}[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=et(),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=et(),await di(this.readNext.promise,t?.signal,t)}};function Sa(){return new pi}function Fu(s){return s[Symbol.asyncIterator]!=null}async function Gu(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*Hu(s){let e=new AbortController,t=Sa();Gu(s,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*qu(s){for(let e of s)yield*e}function zu(...s){let e=[];for(let t of s)Fu(t)||e.push(t);return e.length===s.length?qu(e):Hu(s)}var _a=zu;function Ds(s,...e){if(s==null)throw new Error("Empty pipeline");if(mi(s)){let r=s;s=()=>r.source}else if(Ta(s)||Ia(s)){let r=s;s=()=>r}let t=[s,...e];if(t.length>1&&mi(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++)mi(t[r])&&(t[r]=Wu(t[r]));return Vu(...t)}var Vu=(...s)=>{let e;for(;s.length>0;)e=s.shift()(e);return e},Ia=s=>s?.[Symbol.asyncIterator]!=null,Ta=s=>s?.[Symbol.iterator]!=null,mi=s=>s==null?!1:s.sink!=null&&s.source!=null,Wu=s=>e=>{let t=s.sink(e);if(t?.then!=null){let r=Dt({objectMode:!0});t.then(()=>{r.end()},o=>{r.end(o)});let n,i=s.source;if(Ia(i))n=async function*(){yield*i,r.end()};else if(Ta(i))n=function*(){yield*i,r.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return _a(r,n())}return s.source};var Aa={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxIdontwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};var tt;(function(s){let e;(function(h){let g;h.codec=()=>(g==null&&(g=ye((l,u,p={})=>{p.lengthDelimited!==!1&&u.fork(),l.subscribe!=null&&(u.uint32(8),u.bool(l.subscribe)),l.topic!=null&&(u.uint32(18),u.string(l.topic)),p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let d={},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let y=l.uint32();switch(y>>>3){case 1:{d.subscribe=l.bool();break}case 2:{d.topic=l.string();break}default:{l.skipType(y&7);break}}}return d})),g),h.encode=l=>be(l,h.codec()),h.decode=(l,u)=>ge(l,h.codec(),u)})(e=s.SubOpts||(s.SubOpts={}));let t;(function(h){let g;h.codec=()=>(g==null&&(g=ye((l,u,p={})=>{p.lengthDelimited!==!1&&u.fork(),l.from!=null&&(u.uint32(10),u.bytes(l.from)),l.data!=null&&(u.uint32(18),u.bytes(l.data)),l.seqno!=null&&(u.uint32(26),u.bytes(l.seqno)),l.topic!=null&&l.topic!==""&&(u.uint32(34),u.string(l.topic)),l.signature!=null&&(u.uint32(42),u.bytes(l.signature)),l.key!=null&&(u.uint32(50),u.bytes(l.key)),p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let d={topic:""},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let y=l.uint32();switch(y>>>3){case 1:{d.from=l.bytes();break}case 2:{d.data=l.bytes();break}case 3:{d.seqno=l.bytes();break}case 4:{d.topic=l.string();break}case 5:{d.signature=l.bytes();break}case 6:{d.key=l.bytes();break}default:{l.skipType(y&7);break}}}return d})),g),h.encode=l=>be(l,h.codec()),h.decode=(l,u)=>ge(l,h.codec(),u)})(t=s.Message||(s.Message={}));let r;(function(h){let g;h.codec=()=>(g==null&&(g=ye((l,u,p={})=>{if(p.lengthDelimited!==!1&&u.fork(),l.ihave!=null)for(let d of l.ihave)u.uint32(10),s.ControlIHave.codec().encode(d,u);if(l.iwant!=null)for(let d of l.iwant)u.uint32(18),s.ControlIWant.codec().encode(d,u);if(l.graft!=null)for(let d of l.graft)u.uint32(26),s.ControlGraft.codec().encode(d,u);if(l.prune!=null)for(let d of l.prune)u.uint32(34),s.ControlPrune.codec().encode(d,u);if(l.idontwant!=null)for(let d of l.idontwant)u.uint32(42),s.ControlIDontWant.codec().encode(d,u);p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let d={ihave:[],iwant:[],graft:[],prune:[],idontwant:[]},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let y=l.uint32();switch(y>>>3){case 1:{if(p.limits?.ihave!=null&&d.ihave.length===p.limits.ihave)throw new Te('Decode error - map field "ihave" had too many elements');d.ihave.push(s.ControlIHave.codec().decode(l,l.uint32(),{limits:p.limits?.ihave$}));break}case 2:{if(p.limits?.iwant!=null&&d.iwant.length===p.limits.iwant)throw new Te('Decode error - map field "iwant" had too many elements');d.iwant.push(s.ControlIWant.codec().decode(l,l.uint32(),{limits:p.limits?.iwant$}));break}case 3:{if(p.limits?.graft!=null&&d.graft.length===p.limits.graft)throw new Te('Decode error - map field "graft" had too many elements');d.graft.push(s.ControlGraft.codec().decode(l,l.uint32(),{limits:p.limits?.graft$}));break}case 4:{if(p.limits?.prune!=null&&d.prune.length===p.limits.prune)throw new Te('Decode error - map field "prune" had too many elements');d.prune.push(s.ControlPrune.codec().decode(l,l.uint32(),{limits:p.limits?.prune$}));break}case 5:{if(p.limits?.idontwant!=null&&d.idontwant.length===p.limits.idontwant)throw new Te('Decode error - map field "idontwant" had too many elements');d.idontwant.push(s.ControlIDontWant.codec().decode(l,l.uint32(),{limits:p.limits?.idontwant$}));break}default:{l.skipType(y&7);break}}}return d})),g),h.encode=l=>be(l,h.codec()),h.decode=(l,u)=>ge(l,h.codec(),u)})(r=s.ControlMessage||(s.ControlMessage={}));let n;(function(h){let g;h.codec=()=>(g==null&&(g=ye((l,u,p={})=>{if(p.lengthDelimited!==!1&&u.fork(),l.topicID!=null&&(u.uint32(10),u.string(l.topicID)),l.messageIDs!=null)for(let d of l.messageIDs)u.uint32(18),u.bytes(d);p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let d={messageIDs:[]},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let y=l.uint32();switch(y>>>3){case 1:{d.topicID=l.string();break}case 2:{if(p.limits?.messageIDs!=null&&d.messageIDs.length===p.limits.messageIDs)throw new Te('Decode error - map field "messageIDs" had too many elements');d.messageIDs.push(l.bytes());break}default:{l.skipType(y&7);break}}}return d})),g),h.encode=l=>be(l,h.codec()),h.decode=(l,u)=>ge(l,h.codec(),u)})(n=s.ControlIHave||(s.ControlIHave={}));let i;(function(h){let g;h.codec=()=>(g==null&&(g=ye((l,u,p={})=>{if(p.lengthDelimited!==!1&&u.fork(),l.messageIDs!=null)for(let d of l.messageIDs)u.uint32(10),u.bytes(d);p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let d={messageIDs:[]},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let y=l.uint32();switch(y>>>3){case 1:{if(p.limits?.messageIDs!=null&&d.messageIDs.length===p.limits.messageIDs)throw new Te('Decode error - map field "messageIDs" had too many elements');d.messageIDs.push(l.bytes());break}default:{l.skipType(y&7);break}}}return d})),g),h.encode=l=>be(l,h.codec()),h.decode=(l,u)=>ge(l,h.codec(),u)})(i=s.ControlIWant||(s.ControlIWant={}));let o;(function(h){let g;h.codec=()=>(g==null&&(g=ye((l,u,p={})=>{p.lengthDelimited!==!1&&u.fork(),l.topicID!=null&&(u.uint32(10),u.string(l.topicID)),p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let d={},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let y=l.uint32();switch(y>>>3){case 1:{d.topicID=l.string();break}default:{l.skipType(y&7);break}}}return d})),g),h.encode=l=>be(l,h.codec()),h.decode=(l,u)=>ge(l,h.codec(),u)})(o=s.ControlGraft||(s.ControlGraft={}));let a;(function(h){let g;h.codec=()=>(g==null&&(g=ye((l,u,p={})=>{if(p.lengthDelimited!==!1&&u.fork(),l.topicID!=null&&(u.uint32(10),u.string(l.topicID)),l.peers!=null)for(let d of l.peers)u.uint32(18),s.PeerInfo.codec().encode(d,u);l.backoff!=null&&(u.uint32(24),u.uint64Number(l.backoff)),p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let d={peers:[]},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let y=l.uint32();switch(y>>>3){case 1:{d.topicID=l.string();break}case 2:{if(p.limits?.peers!=null&&d.peers.length===p.limits.peers)throw new Te('Decode error - map field "peers" had too many elements');d.peers.push(s.PeerInfo.codec().decode(l,l.uint32(),{limits:p.limits?.peers$}));break}case 3:{d.backoff=l.uint64Number();break}default:{l.skipType(y&7);break}}}return d})),g),h.encode=l=>be(l,h.codec()),h.decode=(l,u)=>ge(l,h.codec(),u)})(a=s.ControlPrune||(s.ControlPrune={}));let c;(function(h){let g;h.codec=()=>(g==null&&(g=ye((l,u,p={})=>{p.lengthDelimited!==!1&&u.fork(),l.peerID!=null&&(u.uint32(10),u.bytes(l.peerID)),l.signedPeerRecord!=null&&(u.uint32(18),u.bytes(l.signedPeerRecord)),p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let d={},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let y=l.uint32();switch(y>>>3){case 1:{d.peerID=l.bytes();break}case 2:{d.signedPeerRecord=l.bytes();break}default:{l.skipType(y&7);break}}}return d})),g),h.encode=l=>be(l,h.codec()),h.decode=(l,u)=>ge(l,h.codec(),u)})(c=s.PeerInfo||(s.PeerInfo={}));let f;(function(h){let g;h.codec=()=>(g==null&&(g=ye((l,u,p={})=>{if(p.lengthDelimited!==!1&&u.fork(),l.messageIDs!=null)for(let d of l.messageIDs)u.uint32(10),u.bytes(d);p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let d={messageIDs:[]},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let y=l.uint32();switch(y>>>3){case 1:{if(p.limits?.messageIDs!=null&&d.messageIDs.length===p.limits.messageIDs)throw new Te('Decode error - map field "messageIDs" had too many elements');d.messageIDs.push(l.bytes());break}default:{l.skipType(y&7);break}}}return d})),g),h.encode=l=>be(l,h.codec()),h.decode=(l,u)=>ge(l,h.codec(),u)})(f=s.ControlIDontWant||(s.ControlIDontWant={}));let m;s.codec=()=>(m==null&&(m=ye((h,g,l={})=>{if(l.lengthDelimited!==!1&&g.fork(),h.subscriptions!=null)for(let u of h.subscriptions)g.uint32(10),s.SubOpts.codec().encode(u,g);if(h.messages!=null)for(let u of h.messages)g.uint32(18),s.Message.codec().encode(u,g);h.control!=null&&(g.uint32(26),s.ControlMessage.codec().encode(h.control,g)),l.lengthDelimited!==!1&&g.ldelim()},(h,g,l={})=>{let u={subscriptions:[],messages:[]},p=g==null?h.len:h.pos+g;for(;h.pos<p;){let d=h.uint32();switch(d>>>3){case 1:{if(l.limits?.subscriptions!=null&&u.subscriptions.length===l.limits.subscriptions)throw new Te('Decode error - map field "subscriptions" had too many elements');u.subscriptions.push(s.SubOpts.codec().decode(h,h.uint32(),{limits:l.limits?.subscriptions$}));break}case 2:{if(l.limits?.messages!=null&&u.messages.length===l.limits.messages)throw new Te('Decode error - map field "messages" had too many elements');u.messages.push(s.Message.codec().decode(h,h.uint32(),{limits:l.limits?.messages$}));break}case 3:{u.control=s.ControlMessage.codec().decode(h,h.uint32(),{limits:l.limits?.control});break}default:{h.skipType(d&7);break}}}return u})),m),s.encode=h=>be(h,s.codec()),s.decode=(h,g)=>ge(h,s.codec(),g)})(tt||(tt={}));var dr=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 Da;(function(s){s.StrictSign="StrictSign",s.StrictNoSign="StrictNoSign"})(Da||(Da={}));var dt;(function(s){s[s.Signing=0]="Signing",s[s.Anonymous=1]="Anonymous"})(dt||(dt={}));var we;(function(s){s.Error="error",s.Ignore="ignore",s.Reject="reject",s.Blacklisted="blacklisted"})(we||(we={}));var fe;(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"})(fe||(fe={}));var de;(function(s){s.duplicate="duplicate",s.invalid="invalid",s.valid="valid"})(de||(de={}));function gi(s){switch(s){case pe.Ignore:return we.Ignore;case pe.Reject:return we.Reject;default:throw new Error("Unreachable")}}var Ma;(function(s){s.forward="forward",s.publish="publish"})(Ma||(Ma={}));var xe;(function(s){s.Fanout="fanout",s.Random="random",s.Subscribed="subscribed",s.Outbound="outbound",s.NotEnough="not_enough",s.Opportunistic="opportunistic"})(xe||(xe={}));var Re;(function(s){s.Dc="disconnected",s.BadScore="bad_score",s.Prune="prune",s.Excess="excess"})(Re||(Re={}));var ts;(function(s){s.GraftBackoff="graft_backoff",s.BrokenPromise="broken_promise",s.MessageDeficit="message_deficit",s.IPColocation="IP_colocation"})(ts||(ts={}));var ss;(function(s){s.LowScore="low_score",s.MaxIhave="max_ihave",s.MaxIasked="max_iasked"})(ss||(ss={}));var es;(function(s){s.graylist="graylist",s.publish="publish",s.gossip="gossip",s.mesh="mesh"})(es||(es={}));function Pa(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 xe.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:o},i);break;case xe.Random:this.meshPeerInclusionEventsRandom.inc({topic:o},i);break;case xe.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:o},i);break;case xe.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:o},i);break;case xe.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:o},i);break;case xe.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 Re.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:o},i);break;case Re.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:o},i);break;case Re.Prune:this.meshPeerChurnEventsPrune.inc({topic:o},i);break;case Re.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 pe.Accept:this.acceptedMessagesTotal.inc({topic:o});break;case pe.Ignore:this.ignoredMessagesTotal.inc({topic:o});break;case pe.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 c=this.toTopic(r);this.msgPublishCount.inc({topic:c},1),this.msgPublishBytes.inc({topic:c},i*o),this.msgPublishPeersByTopic.inc({topic:c},i),this.directPeersPublishedTotal.inc({topic:c},n.direct),this.floodsubPeersPublishedTotal.inc({topic:c},n.floodsub),this.meshPeersPublishedTotal.inc({topic:c},n.mesh),this.fanoutPeersPublishedTotal.inc({topic:c},n.fanout),this.msgPublishTime.observe({topic:c},a/1e3)},onMsgRecvPreValidation(r){let n=this.toTopic(r);this.msgReceivedPreValidation.inc({topic:n},1)},onMsgRecvError(r){let n=this.toTopic(r);this.msgReceivedError.inc({topic:n},1)},onPrevalidationResult(r,n){let i=this.toTopic(r);switch(n){case de.duplicate:this.prevalidationDuplicateTotal.inc({topic:i});break;case de.invalid:this.prevalidationInvalidTotal.inc({topic:i});break;case de.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===we.Error?n.error:n.reason;this.msgReceivedInvalid.inc({error:o},1),this.msgReceivedInvalidByTopic.inc({topic:i},1)},onDuplicateMsgDelivery(r,n,i){let o=this.toTopic(r);this.duplicateMsgDeliveryDelay.observe({topic:o},n/1e3),i&&this.duplicateMsgLateDelivery.inc({topic:o},1)},onPublishDuplicateMsg(r){let n=this.toTopic(r);this.duplicateMsgIgnored.inc({topic:n},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(r,n){this.rpcRecvBytes.inc(n),this.rpcRecvCount.inc(1),r.subscriptions!=null&&this.rpcRecvSubscription.inc(r.subscriptions.length),r.messages!=null&&this.rpcRecvMessage.inc(r.messages.length),r.control!=null&&(this.rpcRecvControl.inc(1),r.control.ihave!=null&&this.rpcRecvIHave.inc(r.control.ihave.length),r.control.iwant!=null&&this.rpcRecvIWant.inc(r.control.iwant.length),r.control.graft!=null&&this.rpcRecvGraft.inc(r.control.graft.length),r.control.prune!=null&&this.rpcRecvPrune.inc(r.control.prune.length))},onRpcSent(r,n){if(this.rpcSentBytes.inc(n),this.rpcSentCount.inc(1),r.subscriptions!=null&&this.rpcSentSubscription.inc(r.subscriptions.length),r.messages!=null&&this.rpcSentMessage.inc(r.messages.length),r.control!=null){let i=r.control.ihave?.length??0,o=r.control.iwant?.length??0,a=r.control.graft?.length??0,c=r.control.prune?.length??0,f=r.control.idontwant?.length??0;i>0&&this.rpcSentIHave.inc(i),o>0&&this.rpcSentIWant.inc(o),a>0&&this.rpcSentGraft.inc(a),c>0&&this.rpcSentPrune.inc(c),f>0&&this.rpcSentIDontWant.inc(f),(i>0||o>0||a>0||c>0||f>0)&&this.rpcSentControl.inc(1)}},registerScores(r,n){let i=0,o=0,a=0,c=0;for(let f of r)f>=n.graylistThreshold&&i++,f>=n.publishThreshold&&o++,f>=n.gossipThreshold&&a++,f>=0&&c++;this.peersByScoreThreshold.set({threshold:es.graylist},i),this.peersByScoreThreshold.set({threshold:es.publish},o),this.peersByScoreThreshold.set({threshold:es.gossip},a),this.peersByScoreThreshold.set({threshold:es.mesh},c),this.score.set(r)},registerScoreWeights(r){for(let[n,i]of r.byTopic)this.scoreWeights.set({topic:n,p:"p1"},i.p1w),this.scoreWeights.set({topic:n,p:"p2"},i.p2w),this.scoreWeights.set({topic:n,p:"p3"},i.p3w),this.scoreWeights.set({topic:n,p:"p3b"},i.p3bw),this.scoreWeights.set({topic:n,p:"p4"},i.p4w);this.scoreWeights.set({p:"p5"},r.p5w),this.scoreWeights.set({p:"p6"},r.p6w),this.scoreWeights.set({p:"p7"},r.p7w)},registerScorePerMesh(r,n){let i=new Map;r.forEach((o,a)=>{let c=this.topicStrToLabel.get(a)??"unknown",f=i.get(c);f==null&&(f=new Set,i.set(c,f)),o.forEach(m=>f?.add(m))});for(let[o,a]of i){let c=[];a.forEach(f=>{c.push(n.get(f)??0)}),this.scorePerMesh.set({topic:o},c)}}}}var H=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var $u={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},Zu={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 La(s={}){return{...$u,...s,topics:s.topics!=null?Object.entries(s.topics).reduce((e,[t,r])=>(e[t]=ju(r),e),{}):{}}}function ju(s={}){return{...Zu,...s}}function ka(s){for(let[e,t]of Object.entries(s.topics))try{Xu(t)}catch(r){throw new H(`invalid score parameters for topic ${e}: ${r.message}`)}if(s.topicScoreCap<0)throw new H("invalid topic score cap; must be positive (or 0 for no cap)");if(s.appSpecificScore===null||s.appSpecificScore===void 0)throw new H("missing application specific score function");if(s.IPColocationFactorWeight>0)throw new H("invalid IPColocationFactorWeight; must be negative (or 0 to disable)");if(s.IPColocationFactorWeight!==0&&s.IPColocationFactorThreshold<1)throw new H("invalid IPColocationFactorThreshold; must be at least 1");if(s.behaviourPenaltyWeight>0)throw new H("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)");if(s.behaviourPenaltyWeight!==0&&(s.behaviourPenaltyDecay<=0||s.behaviourPenaltyDecay>=1))throw new H("invalid BehaviourPenaltyDecay; must be between 0 and 1");if(s.decayInterval<1e3)throw new H("invalid DecayInterval; must be at least 1s");if(s.decayToZero<=0||s.decayToZero>=1)throw new H("invalid DecayToZero; must be between 0 and 1")}function Xu(s){if(s.topicWeight<0)throw new H("invalid topic weight; must be >= 0");if(s.timeInMeshQuantum===0)throw new H("invalid TimeInMeshQuantum; must be non zero");if(s.timeInMeshWeight<0)throw new H("invalid TimeInMeshWeight; must be positive (or 0 to disable)");if(s.timeInMeshWeight!==0&&s.timeInMeshQuantum<=0)throw new H("invalid TimeInMeshQuantum; must be positive");if(s.timeInMeshWeight!==0&&s.timeInMeshCap<=0)throw new H("invalid TimeInMeshCap; must be positive");if(s.firstMessageDeliveriesWeight<0)throw new H("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)");if(s.firstMessageDeliveriesWeight!==0&&(s.firstMessageDeliveriesDecay<=0||s.firstMessageDeliveriesDecay>=1))throw new H("invalid FirstMessageDeliveriesDecay; must be between 0 and 1");if(s.firstMessageDeliveriesWeight!==0&&s.firstMessageDeliveriesCap<=0)throw new H("invalid FirstMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight>0)throw new H("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.meshMessageDeliveriesWeight!==0&&(s.meshMessageDeliveriesDecay<=0||s.meshMessageDeliveriesDecay>=1))throw new H("invalid MeshMessageDeliveriesDecay; must be between 0 and 1");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesCap<=0)throw new H("invalid MeshMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesThreshold<=0)throw new H("invalid MeshMessageDeliveriesThreshold; must be positive");if(s.meshMessageDeliveriesWindow<0)throw new H("invalid MeshMessageDeliveriesWindow; must be non-negative");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesActivation<1e3)throw new H("invalid MeshMessageDeliveriesActivation; must be at least 1s");if(s.meshFailurePenaltyWeight>0)throw new H("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)");if(s.meshFailurePenaltyWeight!==0&&(s.meshFailurePenaltyDecay<=0||s.meshFailurePenaltyDecay>=1))throw new H("invalid MeshFailurePenaltyDecay; must be between 0 and 1");if(s.invalidMessageDeliveriesWeight>0)throw new H("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.invalidMessageDeliveriesDecay<=0||s.invalidMessageDeliveriesDecay>=1)throw new H("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1")}var Yu={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function Ba(s={}){return{...Yu,...s}}function mr(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 Ra(s,e){return mr(s,e,()=>!0)}var pr=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 Ca(s,e,t,r){let n=0;Object.entries(e.topics).forEach(([o,a])=>{let c=t.topics[o];if(c===void 0)return;let f=0;if(a.inMesh){let l=a.meshTime/c.timeInMeshQuantum;l>c.timeInMeshCap&&(l=c.timeInMeshCap),f+=l*c.timeInMeshWeight}let m=a.firstMessageDeliveries;if(m>c.firstMessageDeliveriesCap&&(m=c.firstMessageDeliveriesCap),f+=m*c.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries<c.meshMessageDeliveriesThreshold){let l=c.meshMessageDeliveriesThreshold-a.meshMessageDeliveries,u=l*l;f+=u*c.meshMessageDeliveriesWeight}let h=a.meshFailurePenalty;f+=h*c.meshFailurePenaltyWeight;let g=a.invalidMessageDeliveries*a.invalidMessageDeliveries;f+=g*c.invalidMessageDeliveriesWeight,n+=f*c.topicWeight}),t.topicScoreCap>0&&n>t.topicScoreCap&&(n=t.topicScoreCap);let i=t.appSpecificScore(s);if(n+=i*t.appSpecificWeight,e.knownIPs.forEach(o=>{if(t.IPColocationFactorWhitelist.has(o))return;let a=r.get(o),c=a!=null?a.size:0;if(c>t.IPColocationFactorThreshold){let f=c-t.IPColocationFactorThreshold,m=f*f;n+=m*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let o=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=o*o;n+=a*t.behaviourPenaltyWeight}return n}var Ua=oc(Oa(),1);var ve;(function(s){s[s.unknown=0]="unknown",s[s.valid=1]="valid",s[s.invalid=2]="invalid",s[s.ignored=3]="ignored"})(ve||(ve={}));var gr=class{records;queue;constructor(){this.records=new Map,this.queue=new Ua.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:ve.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 br=class{params;metrics;peerStats=new Map;peerIPs=new pr(()=>new Set);scoreCache=new Map;deliveryRecords=new gr;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,r,n){this.params=e,this.metrics=t,ka(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??Ca,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!==ve.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,i-n.firstSeenTsMs,ve[n.status]);return}n.status=ve.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 we.Error:this.markInvalidMessageDelivery(e,r);return;case we.Blacklisted:return}let i=this.deliveryRecords.ensureRecord(t);if(i.status!==ve.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-i.firstSeenTsMs,ve[i.status]);return}if(n===we.Ignore){i.status=ve.ignored,i.peers.clear();return}i.status=ve.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 ve.unknown:n.peers.add(e);break;case ve.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,r,n.validated);break;case ve.invalid:this.markInvalidMessageDelivery(e,r);break;case ve.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 f=i-r,m=f>a.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,f,m),m)return}let c=a.meshMessageDeliveriesCap;o.meshMessageDeliveries=Math.min(c,o.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(let r of t){let n=this.peerIPs.get(r);n!=null&&(n.delete(e),n.size===0&&this.peerIPs.delete(r))}}getPtopicStats(e,t){let r=e.topics[t];return r!==void 0?r:this.params.topics[t]!==void 0?(r={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=r,r):null}};function Ju(s,e,t,r,n){let i=0,o=new Map;if(Object.entries(e.topics).forEach(([g,l])=>{let u=n.get(g)??"unknown",p=t.topics[g];if(p===void 0)return;let d=o.get(u);d==null&&(d={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},o.set(u,d));let b=0,y=0,v=0,T=0,E=0;if(l.inMesh){let w=Math.max(l.meshTime/p.timeInMeshQuantum,p.timeInMeshCap);b+=w*p.timeInMeshWeight}let M=l.firstMessageDeliveries;if(M>p.firstMessageDeliveriesCap&&(M=p.firstMessageDeliveriesCap),y+=M*p.firstMessageDeliveriesWeight,l.meshMessageDeliveriesActive&&l.meshMessageDeliveries<p.meshMessageDeliveriesThreshold){let w=p.meshMessageDeliveriesThreshold-l.meshMessageDeliveries,L=w*w;v+=L*p.meshMessageDeliveriesWeight}let D=l.meshFailurePenalty;T+=D*p.meshFailurePenaltyWeight;let I=l.invalidMessageDeliveries*l.invalidMessageDeliveries;E+=I*p.invalidMessageDeliveriesWeight,i+=(b+y+v+T+E)*p.topicWeight,d.p1w+=b,d.p2w+=y,d.p3w+=v,d.p3bw+=T,d.p4w+=E}),t.topicScoreCap>0&&i>t.topicScoreCap){i=t.topicScoreCap;let g=t.topicScoreCap/i;for(let l of o.values())l.p1w*=g,l.p2w*=g,l.p3w*=g,l.p3bw*=g,l.p4w*=g}let a=0,c=0,f=0,m=t.appSpecificScore(s);a+=m*t.appSpecificWeight,e.knownIPs.forEach(g=>{if(t.IPColocationFactorWhitelist.has(g))return;let l=r.get(g),u=l!=null?l.size:0;if(u>t.IPColocationFactorThreshold){let p=u-t.IPColocationFactorThreshold,d=p*p;c+=d*t.IPColocationFactorWeight}});let h=e.behaviourPenalty*e.behaviourPenalty;return f+=h*t.behaviourPenaltyWeight,i+=a+c+f,{byTopic:o,p5w:a,p6w:c,p7w:f,score:i}}function Ka(s,e,t,r,n){let i={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let o of s){let a=e.get(o);if(a!=null){let c=Ju(o,a,t,r,n);for(let[f,m]of c.byTopic){let h=i.byTopic.get(f);h==null&&(h={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},i.byTopic.set(f,h)),h.p1w.push(m.p1w),h.p2w.push(m.p2w),h.p3w.push(m.p3w),h.p3bw.push(m.p3bw),h.p4w.push(m.p4w)}i.p5w.push(c.p5w),i.p6w.push(c.p6w),i.p7w.push(c.p7w),i.score.push(c.score)}else i.p5w.push(0),i.p6w.push(0),i.p7w.push(0),i.score.push(0)}return i}function yr(s){let e=s.getComponents(),t={},r=0;if(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)throw new W(`Multiaddr ${s} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[r]?.name==="tls"&&e[r+1]?.name==="sni"&&(t.sni=e[r+1].value,r+=2),t}function Fa(s){try{return yr(s),!0}catch{return!1}}var bi=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},yi=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Ga=s=>globalThis.DOMException===void 0?new yi(s):new DOMException(s),Ha=s=>{let e=s.reason===void 0?Ga("This operation was aborted."):s.reason;return e instanceof Error?e:Ga(e)};function wi(s,e){let{milliseconds:t,fallback:r,message:n,customTimers:i={setTimeout,clearTimeout}}=e,o,a,f=new Promise((m,h)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:l}=e;l.aborted&&h(Ha(l)),a=()=>{h(Ha(l))},l.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){s.then(m,h);return}let g=new bi;o=i.setTimeout.call(void 0,()=>{if(r){try{m(r())}catch(l){h(l)}return}typeof s.cancel=="function"&&s.cancel(),n===!1?m():n instanceof Error?h(n):(g.message=n??`Promise timed out after ${t} milliseconds`,h(g))},t),(async()=>{try{m(await s)}catch(l){h(l)}})()}).finally(()=>{f.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return f.clear=()=>{i.clearTimeout.call(void 0,o),o=void 0},f}var Qu=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 eh(s,e,t){let r,n=new Promise((i,o)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:f,removeListener:m}=Qu(s),h=async(...l)=>{let u=t.multiArgs?l:l[0];if(t.filter)try{if(!await t.filter(u))return}catch(p){r(),o(p);return}c.push(u),t.count===c.length&&(r(),i(c))},g=(...l)=>{r(),o(t.rejectionMultiArgs?l:l[0])};r=()=>{for(let l of a)m(l,h);for(let l of t.rejectionEvents)a.includes(l)||m(l,g)};for(let l of a)f(l,h);for(let l of t.rejectionEvents)a.includes(l)||f(l,g);t.signal&&t.signal.addEventListener("abort",()=>{g(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(n.cancel=r,typeof t.timeout=="number"){let i=wi(n,{milliseconds:t.timeout});return i.cancel=()=>{r(),i.clear()},i}return n}function qa(s,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let r=eh(s,e,t),n=r.then(i=>i[0]);return n.cancel=r.cancel,n}function th(s){return s?.addEventListener!=null}function sh(s){let e=Dt(),t,r=o=>{e.push(o.data)},n=()=>{e.end(),s.removeEventListener("message",r),s.removeEventListener("close",i),s.removeEventListener("remoteCloseWrite",n)},i=o=>{e.end(o.error),o.error!=null&&t?.reject(o.error),s.removeEventListener("message",r),s.removeEventListener("close",i),s.removeEventListener("remoteCloseWrite",n)};return s.addEventListener("message",r),s.addEventListener("close",i,{once:!0}),s.addEventListener("remoteCloseWrite",n,{once:!0}),{source:e,async sink(o){async function*a(){yield*o}let c=a();for(;;){t=Promise.withResolvers();let{done:f,value:m}=await Promise.race([c.next(),t.promise]);if(s.writeStatus==="closing"||s.writeStatus==="closed"||(m!=null&&(s.send(m)||await Promise.race([qa(s,"drain",{rejectionEvents:["close"]})])),f===!0))break}await s.close()}}}function za(...s){let e=s.map(t=>th(t)?sh(t):t);return Ds(...e)}var wr=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}async push(e){return this.pushPrefixed(Jt.single(e))}pushPrefixed(e){this.rawStream.send(e)}async close(e){await this.rawStream.close(e).catch(t=>{this.rawStream.abort(t)})}},xr=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=za(this.rawStream,r=>As(r,t))}async close(){this.closeController.abort()}};var vr=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){switch(this.trackMessage(e),t){case we.Error:return;default:break}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 Va=z("libp2p-pubsub:");async function Wa(s,e,t,r){switch(s.type){case dt.Signing:{let n={from:s.author.toMultihash().bytes,data:r,seqno:Qs(8),topic:e,signature:void 0,key:void 0},i=mt([Va,tt.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:rr(n.key)};return{raw:n,msg:o}}case dt.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 $a(s,e){switch(s){case Mt:return e.signature!=null?{valid:!1,error:fe.SignaturePresent}:e.seqno!=null?{valid:!1,error:fe.SeqnoPresent}:e.key!=null?{valid:!1,error:fe.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case pt:{if(e.seqno==null)return{valid:!1,error:fe.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:fe.InvalidSeqno};if(e.signature==null)return{valid:!1,error:fe.InvalidSignature};if(e.from==null)return{valid:!1,error:fe.InvalidPeerId};let t;try{t=Xt(ze(e.from))}catch{return{valid:!1,error:fe.InvalidPeerId}}let r;if(e.key!=null){if(r=rr(e.key),t.publicKey!==void 0&&!r.equals(t.publicKey))return{valid:!1,error:fe.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:fe.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=mt([Va,tt.Message.encode(n)]);return await r.verify(i,e.signature)?{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:e.key!=null?rr(e.key):r}}:{valid:!1,error:fe.InvalidSignature}}default:throw new Error("Unreachable")}}function Ce(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 xi(s){return s.control===void 0&&(s.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),s}function He(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 Za(s){return q(s,"base64")}function ja(s,e,t){switch(s){case pt:return{type:dt.Signing,author:e,key:Ue(t.publicKey),privateKey:t};case Mt:return{type:dt.Anonymous};default:throw new Error(`Unknown signature policy "${s}"`)}}var rh=(s,e)=>{let t=z(e.toString(16).padStart(16,"0"),"base16"),r=Ue(s),n=new Uint8Array(r.byteLength+t.length);return n.set(r,0),n.set(t,r.byteLength),n};function Xa(s){if(s.type!=="signed")throw new Error("expected signed message type");if(s.sequenceNumber==null)throw Error("missing seqno field");return rh(s.from.publicKey??s.key,s.sequenceNumber)}async function Ya(s){return gt.encode(s.data)}function Ja(s){if(Fa(s)){let e=yr(s);switch(e.type){case"ip4":case"ip6":return e.host;default:break}}return null}var rs=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 De;(function(s){s[s.started=0]="started",s[s.stopped=1]="stopped"})(De||(De={}));var Er=class extends Bs{globalSignaturePolicy;protocols=[Pt,_i,_r];publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=Dt({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;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=Pt;opts;decodeRpcLimits;metrics;status={code:De.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:La(t.scoreParams),scoreThresholds:Ba(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=r.decodeRpcLimits??Aa,this.globalSignaturePolicy=r.globalSignaturePolicy??pt,r.fallbackToFloodsub&&this.protocols.push(Sr),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 rs({validityMs:r.seenTTL}),this.publishedMessageIds=new rs({validityMs:r.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case pt:this.msgIdFn=Xa;break;case Mt:this.msgIdFn=Ya;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new rs({validityMs:r.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??Za,this.mcache=t.messageCache??new dr(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=Pa(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 vr(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new br(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]="@chainsafe/libp2p-gossipsub";[Di]=["@libp2p/pubsub"];[Mi]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===De.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=ja(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=Dt({objectMode:!0}),Ds(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:De.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!==De.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:De.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.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.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=new wr(await t.newStream(this.protocols,{runOnLimitedConnection:this.runOnLimitedConnection}),o=>{this.log.error("outbound pipe error",o)},{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(r,n);let i=n.protocol;i===Sr&&this.floodsubPeers.add(r),this.metrics?.peersPerProtocol.inc({protocol:i},1),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 xr(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=Ja(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 of this.topics.values())i.delete(t);for(let[i,o]of this.mesh)o.delete(t)&&this.metrics?.onRemoveFromMesh(i,Re.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===De.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)??Tt(r))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await Ds(t,async r=>{for await(let n of r)try{let i=n.subarray(),o=tt.decode(i,{limits:{subscriptions:this.decodeRpcLimits.maxSubscriptions,messages:this.decodeRpcLimits.maxMessages,control$:{ihave:this.decodeRpcLimits.maxIhaveMessageIDs,iwant: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}}}});if(this.metrics?.onRpcRecv(o,i.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,o)}catch(a){this.metrics?.onRpcRecvError(),this.log(a)}else this.handleReceivedRpc(e,o).catch(a=>{this.metrics?.onRpcRecvError(),this.log(a)})}catch(i){this.metrics?.onRpcDataError(),this.log(i)}})}catch(r){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(r,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){if(!this.acceptFrom(e.toString())){this.log("received message from unacceptable peer %p",e),this.metrics?.rpcRecvNotAccepted.inc();return}let r=t.subscriptions!=null?t.subscriptions.length:0,n=t.messages!=null?t.messages.length:0,i=0,o=0,a=0,c=0;if(t.control!=null&&(t.control.ihave!=null&&(i=t.control.ihave.length),t.control.iwant!=null&&(o=t.control.iwant.length),t.control.graft!=null&&(a=t.control.graft.length),t.control.prune!=null&&(c=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${r} messages ${n} ihave ${i} iwant ${o} graft ${a} prune ${c}`),t.subscriptions!=null&&t.subscriptions.length>0){let f=[];t.subscriptions.forEach(m=>{let h=m.topic,g=m.subscribe===!0;if(h!=null){if(this.allowedTopics!=null&&!this.allowedTopics.has(h))return;this.handleReceivedSubscription(e,h,g),f.push({topic:h,subscribe:g})}}),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:f}})}for(let f of t.messages){if(this.allowedTopics!=null&&!this.allowedTopics.has(f.topic))continue;let m=this.handleReceivedMessage(e,f).catch(h=>{this.metrics?.onMsgRecvError(f.topic),this.log(h)});this.opts.awaitRpcMessageHandler&&await m}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);n==null&&(n=new Set,this.topics.set(t,n)),r?n.add(e.toString()):n.delete(e.toString())}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 de.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 de.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 de.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:de.duplicate,msgIdStr:n};let i=await $a(this.globalSignaturePolicy,t);if(!i.valid)return{code:de.invalid,reason:we.Error,error:i.error};let o=i.message;try{this.dataTransform!=null&&(o.data=this.dataTransform.inboundTransform(t.topic,o.data))}catch(h){return this.log("Invalid message, transform failed",h),{code:de.invalid,reason:we.Error,error:fe.TransformFailed}}let a=await this.msgIdFn(o),c=this.msgIdToStrFn(a),f={msgId:a,msgIdStr:c};if(r!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(r,c)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(c))return{code:de.duplicate,msgIdStr:c};this.seenCache.put(c),(t.data?.length??0)>=this.opts.idontwantMinDataSize&&this.sendIDontWants(a,t.topic,e.toString());let m=this.topicValidators.get(t.topic);if(m!=null){let h;try{h=await m(e,o)}catch(g){let l=g.code;l===Ti&&(h=pe.Ignore),l===Ii?h=pe.Reject:h=pe.Ignore}if(h!==pe.Accept)return{code:de.invalid,reason:gi(h),msgIdStr:c}}return{code:de.valid,messageId:f,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,Ce(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:ss.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:ss.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:ss.MaxIasked}),[];let o=new Map;if(t.forEach(({topicID:f,messageIDs:m})=>{if(f==null||m==null||!this.mesh.has(f))return;let h=0;m.forEach(g=>{let l=this.msgIdToStrFn(g);this.seenCache.has(l)||(o.set(l,g),h++)}),this.metrics?.onIhaveRcv(f,m.length,h)}),o.size===0)return[];let a=o.size;a+i>5e3&&(a=5e3-i),this.log("IHAVE: Asking for %d out of %d messages from %s",a,o.size,e);let c=Array.from(o.values());return He(c),c=c.slice(0,a),this.iasked.set(e,i+a),[{messageIDs:c}]}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=new Map,i=new Map,o=0;return t.forEach(({messageIDs:a})=>{a?.forEach(c=>{let f=this.msgIdToStrFn(c),m=this.mcache.getWithIWantCount(f,e);if(m==null){o++;return}if(i.set(m.msg.topic,1+(i.get(m.msg.topic)??0)),m.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,c);return}n.set(f,m.msg)})}),this.metrics?.onIwantRcv(i,o),n.size===0?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",n.size,e),Array.from(n.values()))}async handleGraft(e,t){let r=[],n=this.score.score(e),i=Date.now(),o=this.opts.doPX;if(t.forEach(({topicID:c})=>{if(c==null)return;let f=this.mesh.get(c);if(f==null){o=!1;return}if(f.has(e))return;let m=this.backoff.get(c)?.get(e);if(this.direct.has(e))this.log("GRAFT: ignoring request from direct peer %s",e),r.push(c),o=!1;else if(typeof m=="number"&&i<m){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,ts.GraftBackoff),o=!1;let h=m+this.opts.graftFloodThreshold-this.opts.pruneBackoff;i<h&&this.score.addPenalty(e,1,ts.GraftBackoff),this.addBackoff(e,c),r.push(c)}else n<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,n,c),r.push(c),o=!1,this.addBackoff(e,c)):f.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(r.push(c),this.addBackoff(e,c)):(this.log("GRAFT: Add mesh link from %s in %s",e,c),this.score.graft(e,c),f.add(e),this.metrics?.onAddToMesh(c,xe.Subscribed,1));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:c,direction:"inbound"}})}),r.length===0)return[];let a=!1;return Promise.all(r.map(async c=>this.makePrune(e,c,o,a)))}async handlePrune(e,t){let r=this.score.score(e);for(let{topicID:n,backoff:i,peers:o}of t){if(n==null)continue;let a=this.mesh.get(n);if(a==null)return;this.log("PRUNE: Remove mesh link to %s in %s",e,n),this.score.prune(e,n),a.has(e)&&(a.delete(e),this.metrics?.onRemoveFromMesh(n,Re.Prune,1)),typeof i=="number"&&i>0?this.doAddBackoff(e,n,i*1e3):this.addBackoff(e,n),o!=null&&o.length>0&&(r<this.opts.scoreThresholds.acceptPXThreshold?this.log("PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]",e,r,n):await this.pxConnect(o)),this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:n,direction:"inbound"}})}}handleIdontwant(e,t){let r=this.idontwantCounts.get(e)??0;if(r>=this.opts.idontwantMaxMessages)return;let n=r,i=this.idontwants.get(e);i==null&&(i=new Map,this.idontwants.set(e,i));let o=0;e:for(let{messageIDs:c}of t)for(let f of c){if(r>=this.opts.idontwantMaxMessages)break e;r++;let m=this.msgIdToStrFn(f);i.set(m,this.heartbeatTicks),this.mcache.msgs.has(m)||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,ts.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&&(He(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async r=>{if(r.peerID==null)return;let n=Xt(ze(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=Tt(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!==De.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!==De.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!==De.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,xe.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,xe.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!==De.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,c=>this.score.score(c)>=this.opts.scoreThresholds.publishThreshold);a.size>0&&(this.fanout.set(e,a),a.forEach(c=>{t.add(c),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,Ce([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 Wa(this.publishConfig,e,t,i),c=await this.msgIdFn(a),f=this.msgIdToStrFn(c),m=r?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(f)){if(m)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:h,tosendCount:g}=this.selectPeersToPublish(e),l=this.opts.emitSelf&&this.subscriptions.has(e),u=r?.allowPublishToZeroTopicPeers??this.opts.allowPublishToZeroTopicPeers;if(h.size===0&&!u&&!l)throw Error("PublishError.NoPeersSubscribedToTopic");this.seenCache.put(f),this.mcache.put({msgId:c,msgIdStr:f},o,!0),this.gossipTracer.deliverMessage(f),this.publishedMessageIds.put(f);let p=r?.batchPublish??this.opts.batchPublish,d=Ce([o]);if(p)this.sendRpcInBatch(h,d);else for(let y of h)this.sendRpc(y,d)||h.delete(y);let b=Date.now()-n;return this.metrics?.onPublishMsg(e,g,h.size,o.data!=null?o.data.length:0,b),l&&(h.add(this.components.peerId.toString()),super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:f,msg:a}})),super.dispatchEvent(new CustomEvent("message",{detail:a}))),{recipients:Array.from(h.values()).map(y=>this.peers.get(y)??Tt(y))}}sendRpcInBatch(e,t){let r=tt.encode(t),n=Jt.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===pe.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=gi(r),{message:a,originatingPeers:c}=n;this.score.rejectMessage(t,e,a.topic,o);for(let f of c)this.score.rejectMessage(f,e,a.topic,o)}let i=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(n,r,i)}sendGraft(e,t){let n=Ce([],{graft:[{topicID:t}]});this.sendRpc(e,n)}async sendPrune(e,t){let n=[await this.makePrune(e,t,this.opts.doPX,!0)],i=Ce([],{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!==Pt&&i.delete(a);let o=Ce([],{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=tt.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=xi(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=xi(t);n.control.ihave=r}async sendGraftPrune(e,t,r){let n=this.opts.doPX,i=!1;for(let[o,a]of e){let c=a.map(h=>({topicID:h})),f=[],m=t.get(o);m!=null&&(f=await Promise.all(m.map(async h=>this.makePrune(o,h,n&&!(r.get(o)??!1),i))),t.delete(o)),this.sendRpc(o,Ce([],{graft:c,prune:f}))}for(let[o,a]of t){let c=await Promise.all(a.map(async f=>this.makePrune(o,f,n&&!(r.get(o)??!1),i)));this.sendRpc(o,Ce([],{prune:c}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[r,n]of e)this.doEmitGossip(r,n,t.get(r)??[])}doEmitGossip(e,t,r){if(r.length===0||(He(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=He(Array.from(a)).slice(0,n),a.forEach(c=>{let f=r;r.length>5e3&&(f=He(f.slice()).slice(0,5e3)),this.pushGossip(c,{topicID:e,messageIDs:f})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,Ce([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let r=Ce([],{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===_r)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,f=>f!==e&&this.score.score(f)>=0),c=await Promise.all(Array.from(a).map(async f=>{let m=this.peers.get(f)??Tt(f),h;try{h=await this.components.peerStore.get(m)}catch(g){if(g.name!=="NotFoundError")throw g}return{peerID:m.toMultihash().bytes,signedPeerRecord:h?.peerRecordEnvelope}}));return{topicID:t,peers:c,backoff:o}}runHeartbeat=()=>{let e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch(t=>{this.log("Error running heartbeat",t)}).finally(()=>{if(e?.(),this.status.code===De.started){clearTimeout(this.status.heartbeatTimeout);let t=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;t<this.opts.heartbeatInterval*.25&&(t+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,t)}})};async heartbeat(){let{D:e,Dlo:t,Dhi:r,Dscore:n,Dout:i,fanoutTTL:o}=this.opts;this.heartbeatTicks++;let a=new Map,c=u=>{let p=a.get(u);return p===void 0&&(p=this.score.score(u),a.set(u,p)),p},f=new Map,m=new Map,h=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.applyIwantPenalties(),this.idontwantCounts.clear();for(let u of this.idontwants.values())for(let[p,d]of u)this.heartbeatTicks-d>=this.opts.mcacheLength&&u.delete(p);this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let g=new Map;this.mesh.forEach((u,p)=>{let d=this.topics.get(p),b=new Set,y=new Set;if(g.set(p,y),d!=null){let E=He(Array.from(d)),M=this.backoff.get(p);for(let D of E){let I=this.streamsOutbound.get(D);if(I!=null&&this.protocols.includes(I.protocol)&&!u.has(D)&&!this.direct.has(D)){let w=c(D);M?.has(D)!==!0&&w>=0&&b.add(D),w>=this.opts.scoreThresholds.gossipThreshold&&y.add(D)}}}let v=(E,M)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",E,p),this.addBackoff(E,p),u.delete(E),c(E)>=this.opts.scoreThresholds.gossipThreshold&&y.add(E),this.metrics?.onRemoveFromMesh(p,M,1);let D=m.get(E);D==null?m.set(E,[p]):D.push(p)},T=(E,M)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",E,p),this.score.graft(E,p),u.add(E),y.delete(E),this.metrics?.onAddToMesh(p,M,1);let D=f.get(E);D==null?f.set(E,[p]):D.push(p)};if(u.forEach(E=>{let M=c(E);M<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",E,M,p),v(E,Re.BadScore),h.set(E,!0))}),u.size<t){let E=e-u.size;Ra(b,E).forEach(D=>{T(D,xe.NotEnough)})}if(u.size>r){let E=Array.from(u);E.sort((D,I)=>c(I)-c(D)),E=E.slice(0,n).concat(He(E.slice(n)));let M=0;if(E.slice(0,e).forEach(D=>{(this.outbound.get(D)??!1)&&M++}),M<i){let D=w=>{let L=E[w];for(let O=w;O>0;O--)E[O]=E[O-1];E[0]=L};if(M>0){let w=M;for(let L=1;L<e&&w>0;L++)(this.outbound.get(E[L])??!1)&&(D(L),w--)}let I=e-M;for(let w=e;w<E.length&&I>0;w++)(this.outbound.get(E[w])??!1)&&(D(w),I--)}E.slice(e).forEach(D=>{v(D,Re.Excess)})}if(u.size>=t){let E=0;if(u.forEach(M=>{(this.outbound.get(M)??!1)&&E++}),E<i){let M=i-E;mr(b,M,I=>this.outbound.get(I)===!0).forEach(I=>{T(I,xe.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&u.size>1){let E=Array.from(u).sort((I,w)=>c(I)-c(w)),M=Math.floor(u.size/2),D=c(E[M]);if(D<this.opts.scoreThresholds.opportunisticGraftThreshold){let I=this.opts.opportunisticGraftPeers,w=mr(b,I,L=>c(L)>D);for(let L of w)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",L,p),T(L,xe.Opportunistic)}}});let l=Date.now();this.fanoutLastpub.forEach((u,p)=>{u+o<l&&(this.fanout.delete(p),this.fanoutLastpub.delete(p))}),this.fanout.forEach((u,p)=>{let d=this.topics.get(p);u.forEach(T=>{(!(d?.has(T)??!1)||c(T)<this.opts.scoreThresholds.publishThreshold)&&u.delete(T)});let b=this.topics.get(p),y=[],v=new Set;if(g.set(p,v),b!=null){let T=He(Array.from(b));for(let E of T){let M=this.streamsOutbound.get(E);if(M!=null&&this.protocols.includes(M.protocol)&&!u.has(E)&&!this.direct.has(E)){let D=c(E);D>=this.opts.scoreThresholds.publishThreshold&&y.push(E),D>=this.opts.scoreThresholds.gossipThreshold&&v.add(E)}}}if(u.size<e){let T=e-u.size;y.slice(0,T).forEach(E=>{u.add(E),v?.delete(E)})}}),this.emitGossip(g),await this.sendGraftPrune(f,m,h),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=He(i),t>0&&i.length>t&&(i=i.slice(0,t)),new Set(i)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0,r=Date.now();e.connectedPeersBackoffSec.reset();for(let c of this.backoff.values()){t+=c.size;for(let[f,m]of c.entries())this.peers.has(f)&&e.connectedPeersBackoffSec.observe(Math.max(0,m-r)/1e3)}e.cacheSize.set({cache:"backoff"},t);let n=0;for(let c of this.idontwants.values())n+=c.size;e.cacheSize.set({cache:"idontwants"},n);for(let[c,f]of this.topics)e.topicPeersCount.set({topicStr:c},f.size);for(let[c,f]of this.mesh)e.meshPeerCounts.set({topicStr:c},f.size);let i=[],o=new Map;e.behaviourPenalty.reset();for(let c of this.peers.keys()){let f=this.score.score(c);i.push(f),o.set(c,f),e.behaviourPenalty.observe(this.score.peerStats.get(c)?.behaviourPenalty??0)}e.registerScores(i,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,o);let a=Ka(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)??Tt(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)??Tt(t),{tags:{[r]:void 0}}).catch(n=>{this.log.error("Error untagging peer %s with topic %s",t,r,n)})}};var pt="StrictSign",Mt="StrictNoSign",pe;(function(s){s.Accept="accept",s.Ignore="ignore",s.Reject="reject"})(pe||(pe={}));var Lh=Pt;function kh(s={}){return e=>new Er(e,s)}return ac(Bh);})();
|
|
3
3
|
/*! Bundled license information:
|
|
4
4
|
|
|
5
5
|
@noble/hashes/utils.js:
|