@libp2p/gossipsub 16.0.0-b7c6dc0f2 → 16.0.1-7ae12f9b0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,5 +1,5 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PGossipsub = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var Libp2PGossipsub=(()=>{var Gl=Object.create;var ir=Object.defineProperty;var ql=Object.getOwnPropertyDescriptor;var Vl=Object.getOwnPropertyNames;var Wl=Object.getPrototypeOf,$l=Object.prototype.hasOwnProperty;var jl=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),V=(s,e)=>{for(var t in e)ir(s,t,{get:e[t],enumerable:!0})},Ni=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Vl(e))!$l.call(s,n)&&n!==t&&ir(s,n,{get:()=>e[n],enumerable:!(r=ql(e,n))||r.enumerable});return s};var Zl=(s,e,t)=>(t=s!=null?Gl(Wl(s)):{},Ni(e||!s||!s.__esModule?ir(t,"default",{value:s,enumerable:!0}):t,s)),Yl=s=>Ni(ir({},"__esModule",{value:!0}),s);var Tl=jl((rv,Il)=>{"use strict";function Y(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))}Y.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]}};Y.prototype.get=function(e){return this.peekAt(e)};Y.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};Y.prototype.peekFront=function(){return this.peek()};Y.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(Y.prototype,"length",{get:function(){return this.size()}});Y.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};Y.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)};Y.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}};Y.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)};Y.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}};Y.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 o=this._list[t],i;if(e<r/2){for(i=e;i>0;i--)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(i=r-1-e;i>0;i--)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 o}}};Y.prototype.remove=function(e,t){var r=e,n,o=t;if(r===(r|0)&&this._head!==this._tail){var i=this.size(),a=this._list.length;if(!(r>=i||r<-i||t<1)){if(r<0&&(r+=i),t===1||!t)return n=new Array(1),n[0]=this.removeOne(r),n;if(r===0&&r+t>=i)return n=this.toArray(),this.clear(),n;r+t>i&&(t=i-r);var l;for(n=new Array(t),l=0;l<t;l++)n[l]=this._list[this._head+r+l&this._capacityMask];if(r=this._head+r&this._capacityMask,e+t===i){for(this._tail=this._tail-t+a&this._capacityMask,l=t;l>0;l--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(e===0){for(this._head=this._head+t+a&this._capacityMask,l=t-1;l>0;l--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(r<i/2){for(this._head=this._head+e+t+a&this._capacityMask,l=e;l>0;l--)this.unshift(this._list[r=r-1+a&this._capacityMask]);for(r=this._head-1+a&this._capacityMask;o>0;)this._list[r=r-1+a&this._capacityMask]=void 0,o--;e<0&&(this._tail=r)}else{for(this._tail=r,r=r+t+a&this._capacityMask,l=i-(t+e);l>0;l--)this.push(this._list[r++]);for(r=this._tail;o>0;)this._list[r=r+1+a&this._capacityMask]=void 0,o--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),n}}};Y.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 o,i,a,l=arguments.length,u=this._list.length,p=2;if(!n||r<n/2){for(i=new Array(r),o=0;o<r;o++)i[o]=this._list[this._head+o&this._capacityMask];for(t===0?(a=[],r>0&&(this._head=this._head+r+u&this._capacityMask)):(a=this.remove(r,t),this._head=this._head+r+u&this._capacityMask);l>p;)this.unshift(arguments[--l]);for(o=r;o>0;o--)this.unshift(i[o-1])}else{i=new Array(n-(r+t));var m=i.length;for(o=0;o<m;o++)i[o]=this._list[this._head+r+t+o&this._capacityMask];for(t===0?(a=[],r!=n&&(this._tail=this._head+r+u&this._capacityMask)):(a=this.remove(r,t),this._tail=this._tail-m+u&this._capacityMask);p<l;)this.push(arguments[p++]);for(o=0;o<m;o++)this.push(i[o])}return a}else return this.remove(r,t)}};Y.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0};Y.prototype.isEmpty=function(){return this._head===this._tail};Y.prototype.toArray=function(){return this._copyArray(!1)};Y.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]};Y.prototype._copyArray=function(e,t){var r=this._list,n=r.length,o=this.length;if(t=t|o,t==o&&this._head<this._tail)return this._list.slice(this._head,this._tail);var i=new Array(t),a=0,l;if(e||this._head>this._tail){for(l=this._head;l<n;l++)i[a++]=r[l];for(l=0;l<this._tail;l++)i[a++]=r[l]}else for(l=this._head;l<this._tail;l++)i[a++]=r[l];return i};Y.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};Y.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1};Y.prototype._nextPowerOf2=function(e){var t=Math.log(e)/Math.log(2),r=1<<t+1;return Math.max(r,4)};Il.exports=Y});var Vp={};V(Vp,{StrictNoSign:()=>zt,StrictSign:()=>_t,TopicValidatorResult:()=>be,gossipsub:()=>qp,multicodec:()=>Gp});var un="/floodsub/1.0.0",hn="/meshsub/1.0.0",Oi="/meshsub/1.1.0",Gt="/meshsub/1.2.0";var Ui="ERR_TOPIC_VALIDATOR_REJECT",Ki="ERR_TOPIC_VALIDATOR_IGNORE";var X=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},qt=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var ar=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},cr=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Vt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var fn=Symbol.for("@libp2p/peer-id");function Xl(s){return typeof s?.handleEvent=="function"}function Jl(s){return(s!==!0&&s!==!1&&s?.once)??!1}var lr=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,r){let n=Jl(r);super.addEventListener(e,i=>{if(n){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:l})=>l!==t),this.#e.set(i.type,a))}Xl(t)?t.handleEvent(i):t(i)},r);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:n})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),t??null,r);let n=this.#e.get(e);n!=null&&(n=n.filter(({callback:o})=>o!==t),this.#e.set(e,n))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Hi=Symbol.for("@libp2p/service-capabilities"),Gi=Symbol.for("@libp2p/service-dependencies");var bn={};V(bn,{base58btc:()=>Q,base58flickr:()=>ou});var vm=new Uint8Array(0);function qi(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 Xe(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 Vi(s){return new TextEncoder().encode(s)}function Wi(s){return new TextDecoder().decode(s)}function Ql(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 o=s.charAt(n),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=n}var a=s.length,l=s.charAt(0),u=Math.log(a)/Math.log(256),p=Math.log(256)/Math.log(a);function m(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var g=0,b=0,x=0,_=h.length;x!==_&&h[x]===0;)x++,g++;for(var c=(_-x)*p+1>>>0,f=new Uint8Array(c);x!==_;){for(var d=h[x],y=0,v=c-1;(d!==0||y<b)&&v!==-1;v--,y++)d+=256*f[v]>>>0,f[v]=d%a>>>0,d=d/a>>>0;if(d!==0)throw new Error("Non-zero carry");b=y,x++}for(var S=c-b;S!==c&&f[S]===0;)S++;for(var M=l.repeat(g);S<c;++S)M+=s.charAt(f[S]);return M}function E(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var g=0;if(h[g]!==" "){for(var b=0,x=0;h[g]===l;)b++,g++;for(var _=(h.length-g)*u+1>>>0,c=new Uint8Array(_);h[g];){var f=t[h.charCodeAt(g)];if(f===255)return;for(var d=0,y=_-1;(f!==0||d<x)&&y!==-1;y--,d++)f+=a*c[y]>>>0,c[y]=f%256>>>0,f=f/256>>>0;if(f!==0)throw new Error("Non-zero carry");x=d,g++}if(h[g]!==" "){for(var v=_-x;v!==_&&c[v]===0;)v++;for(var S=new Uint8Array(b+(_-v)),M=b;v!==_;)S[M++]=c[v++];return S}}}function w(h){var g=E(h);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:m,decodeUnsafe:E,decode:w}}var eu=Ql,tu=eu,ji=tu;var dn=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")}},pn=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 Zi(this,e)}},mn=class{decoders;constructor(e){this.decoders=e}or(e){return Zi(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 Zi(s,e){return new mn({...s.decoders??{[s.prefix]:s},...e.decoders??{[e.prefix]:e}})}var gn=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 dn(e,t,r),this.decoder=new pn(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Wt({name:s,prefix:e,encode:t,decode:r}){return new gn(s,e,t,r)}function lt({name:s,prefix:e,alphabet:t}){let{encode:r,decode:n}=ji(t,s);return Wt({prefix:e,name:s,encode:r,decode:o=>Xe(n(o))})}function su(s,e,t,r){let n=s.length;for(;s[n-1]==="=";)--n;let o=new Uint8Array(n*t/8|0),i=0,a=0,l=0;for(let u=0;u<n;++u){let p=e[s[u]];if(p===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<t|p,i+=t,i>=8&&(i-=8,o[l++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function ru(s,e,t){let r=e[e.length-1]==="=",n=(1<<t)-1,o="",i=0,a=0;for(let l=0;l<s.length;++l)for(a=a<<8|s[l],i+=8;i>t;)i-=t,o+=e[n&a>>i];if(i!==0&&(o+=e[n&a<<t-i]),r)for(;(o.length*t&7)!==0;)o+="=";return o}function nu(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=nu(r);return Wt({prefix:e,name:s,encode(o){return ru(o,r,t)},decode(o){return su(o,n,t,s)}})}var Q=lt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ou=lt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var yn={};V(yn,{base32:()=>$t,base32hex:()=>lu,base32hexpad:()=>hu,base32hexpadupper:()=>fu,base32hexupper:()=>uu,base32pad:()=>au,base32padupper:()=>cu,base32upper:()=>iu,base32z:()=>du});var $t=J({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),iu=J({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),au=J({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),cu=J({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),lu=J({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),uu=J({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),hu=J({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),fu=J({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),du=J({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var wn={};V(wn,{base36:()=>Is,base36upper:()=>pu});var Is=lt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),pu=lt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var mu=Ji,Yi=128,gu=127,bu=~gu,yu=Math.pow(2,31);function Ji(s,e,t){e=e||[],t=t||0;for(var r=t;s>=yu;)e[t++]=s&255|Yi,s/=128;for(;s&bu;)e[t++]=s&255|Yi,s>>>=7;return e[t]=s|0,Ji.bytes=t-r+1,e}var wu=xn,xu=128,Xi=127;function xn(s,r){var t=0,r=r||0,n=0,o=r,i,a=s.length;do{if(o>=a)throw xn.bytes=0,new RangeError("Could not decode varint");i=s[o++],t+=n<28?(i&Xi)<<n:(i&Xi)*Math.pow(2,n),n+=7}while(i>=xu);return xn.bytes=o-r,t}var vu=Math.pow(2,7),Eu=Math.pow(2,14),Su=Math.pow(2,21),_u=Math.pow(2,28),Iu=Math.pow(2,35),Tu=Math.pow(2,42),Du=Math.pow(2,49),Au=Math.pow(2,56),Mu=Math.pow(2,63),Pu=function(s){return s<vu?1:s<Eu?2:s<Su?3:s<_u?4:s<Iu?5:s<Tu?6:s<Du?7:s<Au?8:s<Mu?9:10},ku={encode:mu,decode:wu,encodingLength:Pu},Bu=ku,Ts=Bu;function Ds(s,e=0){return[Ts.decode(s,e),Ts.decode.bytes]}function jt(s,e,t=0){return Ts.encode(s,e,t),e}function Zt(s){return Ts.encodingLength(s)}function He(s,e){let t=e.byteLength,r=Zt(s),n=r+Zt(t),o=new Uint8Array(n+t);return jt(s,o,0),jt(t,o,r),o.set(e,n),new Yt(s,t,e,o)}function Je(s){let e=Xe(s),[t,r]=Ds(e),[n,o]=Ds(e.subarray(r)),i=e.subarray(r+o);if(i.byteLength!==n)throw new Error("Incorrect length");return new Yt(t,n,i,e)}function Qi(s,e){if(s===e)return!0;{let t=e;return s.code===t.code&&s.size===t.size&&t.bytes instanceof Uint8Array&&qi(s.bytes,t.bytes)}}var Yt=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}};function ea(s,e){let{bytes:t,version:r}=s;return r===0?Ru(t,vn(s),e??Q.encoder):Cu(t,vn(s),e??$t.encoder)}var ta=new WeakMap;function vn(s){let e=ta.get(s);if(e==null){let t=new Map;return ta.set(s,t),t}return e}var ue=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!==As)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Fu)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return s.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,r=He(e,t);return s.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return s.equals(this,e)}static equals(e,t){let r=t;return r!=null&&e.code===r.code&&e.version===r.version&&Qi(e.multihash,r.multihash)}toString(e){return ea(this,e)}toJSON(){return{"/":ea(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:o,bytes:i}=t;return new s(r,n,o,i??sa(r,n,o.bytes))}else if(t[Nu]===!0){let{version:r,multihash:n,code:o}=t,i=Je(n);return s.create(r,o,i)}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!==As)throw new Error(`Version 0 CID must use dag-pb (code: ${As}) block encoding`);return new s(e,t,r,r.bytes)}case 1:{let n=sa(e,t,r.bytes);return new s(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return s.create(0,As,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=Xe(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=n.subarray(t.multihashSize-t.digestSize),i=new Yt(t.multihashCode,t.digestSize,o,n);return[t.version===0?s.createV0(i):s.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,r=()=>{let[m,E]=Ds(e.subarray(t));return t+=E,m},n=r(),o=As;if(n===18?(n=0,t=0):o=r(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let i=t,a=r(),l=r(),u=t+l,p=u-i;return{version:n,codec:o,multihashCode:a,digestSize:l,multihashSize:p,size:u}}static parse(e,t){let[r,n]=Lu(e,t),o=s.decode(n);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return vn(o).set(r,e),o}};function Lu(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 $t.prefix:{let t=e??$t;return[$t.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 Ru(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 o=t.encode(s).slice(1);return e.set(r,o),o}else return n}function Cu(s,e,t){let{prefix:r}=t,n=e.get(r);if(n==null){let o=t.encode(s);return e.set(r,o),o}else return n}var As=112,Fu=18;function sa(s,e,t){let r=Zt(s),n=r+Zt(e),o=new Uint8Array(n+t.byteLength);return jt(s,o,0),jt(e,o,r),o.set(t,n),o}var Nu=Symbol.for("@ipld/js-cid/CID");var En={};V(En,{identity:()=>Le});var ra=0,Ou="identity",na=Xe;function Uu(s,e){if(e?.truncate!=null&&e.truncate!==s.byteLength){if(e.truncate<0||e.truncate>s.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${s.byteLength}`);s=s.subarray(0,e.truncate)}return He(ra,na(s))}var Le={code:ra,name:Ou,encode:na,digest:Uu};function Pe(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 Ku(s){return s.buffer instanceof ArrayBuffer}function Ge(s){return Ku(s)?s:s.slice()}async function oa(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 o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,Ge(e),Ge(t.subarray()));return r?.signal?.throwIfAborted(),o}function Qe(s=0){return new Uint8Array(s)}function Ms(s=0){return new Uint8Array(s)}function Sn(s,e){e==null&&(e=s.reduce((n,o)=>n+o.length,0));let t=Ms(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}function ia(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}var ca=Symbol.for("@achingbrain/uint8arraylist");function aa(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 hr(s){return!!s?.[ca]}var ce=class s{bufs;length;[ca]=!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(hr(r)){t+=r.byteLength;for(let n of r.bufs)this.bufs.push(n)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else if(hr(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=aa(this.bufs,e);return t.buf[t.index]}set(e,t){let r=aa(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(hr(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 Sn(r,n)}subarray(e,t){let{bufs:r,length:n}=this._subList(e,t);return r.length===1?r[0]:Sn(r,n)}sublist(e,t){let{bufs:r,length:n}=this._subList(e,t),o=new s;return o.length=n,o.bufs=r,o}_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 o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=n,l=a+i.byteLength;if(n=l,e>=l)continue;let u=e>=a&&e<l,p=t>a&&t<=l;if(u&&p){if(e===a&&t===l){r.push(i);break}let m=e-a;r.push(i.subarray(m,m+(t-e)));break}if(u){if(e===0){r.push(i);continue}r.push(i.subarray(e-a));continue}if(p){if(t===l){r.push(i);break}r.push(i.subarray(0,t-a));break}r.push(i)}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!hr(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 o=256,i=new Int32Array(o);for(let m=0;m<o;m++)i[m]=-1;for(let m=0;m<n;m++)i[r[m]]=m;let a=i,l=this.byteLength-r.byteLength,u=r.byteLength-1,p;for(let m=t;m<=l;m+=p){p=0;for(let E=u;E>=0;E--){let w=this.get(m+E);if(r[E]!==w){p=Math.max(1,E-a[w]);break}}if(p===0)return m}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let r=Ms(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=Qe(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=Qe(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=Qe(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=Ms(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=Qe(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=Qe(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=Qe(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=Qe(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=Qe(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(!ia(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,o)=>n+o.byteLength,0)),r.length=t,r}};var An={};V(An,{base10:()=>ju});var eg=new Uint8Array(0);function la(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 et(s){if(s instanceof Uint8Array&&s.constructor.name==="Uint8Array")return Tt(s);if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return Tt(new Uint8Array(s.buffer,s.byteOffset,s.byteLength));throw new Error("Unknown type, must be binary type")}function ua(s){return new TextEncoder().encode(s)}function ha(s){return new TextDecoder().decode(s)}function zu(s){return s?.buffer instanceof ArrayBuffer}function Tt(s){return zu(s)?s:s.slice()}function Hu(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 o=s.charAt(n),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=n}var a=s.length,l=s.charAt(0),u=Math.log(a)/Math.log(256),p=Math.log(256)/Math.log(a);function m(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var g=0,b=0,x=0,_=h.length;x!==_&&h[x]===0;)x++,g++;for(var c=(_-x)*p+1>>>0,f=new Uint8Array(c);x!==_;){for(var d=h[x],y=0,v=c-1;(d!==0||y<b)&&v!==-1;v--,y++)d+=256*f[v]>>>0,f[v]=d%a>>>0,d=d/a>>>0;if(d!==0)throw new Error("Non-zero carry");b=y,x++}for(var S=c-b;S!==c&&f[S]===0;)S++;for(var M=l.repeat(g);S<c;++S)M+=s.charAt(f[S]);return M}function E(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var g=0;if(h[g]!==" "){for(var b=0,x=0;h[g]===l;)b++,g++;for(var _=(h.length-g)*u+1>>>0,c=new Uint8Array(_);h[g];){var f=t[h.charCodeAt(g)];if(f===255)return;for(var d=0,y=_-1;(f!==0||d<x)&&y!==-1;y--,d++)f+=a*c[y]>>>0,c[y]=f%256>>>0,f=f/256>>>0;if(f!==0)throw new Error("Non-zero carry");x=d,g++}if(h[g]!==" "){for(var v=_-x;v!==_&&c[v]===0;)v++;for(var S=new Uint8Array(b+(_-v)),M=b;v!==_;)S[M++]=c[v++];return S}}}function w(h){var g=E(h);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:m,decodeUnsafe:E,decode:w}}var Gu=Hu,qu=Gu,da=qu;var _n=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")}},In=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 pa(this,e)}},Tn=class{decoders;constructor(e){this.decoders=e}or(e){return pa(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 pa(s,e){return new Tn({...s.decoders??{[s.prefix]:s},...e.decoders??{[e.prefix]:e}})}var Dn=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 _n(e,t,r),this.decoder=new In(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Xt({name:s,prefix:e,encode:t,decode:r}){return new Dn(s,e,t,r)}function ht({name:s,prefix:e,alphabet:t}){let{encode:r,decode:n}=da(t,s);return Xt({prefix:e,name:s,encode:r,decode:o=>et(n(o))})}function Vu(s,e,t,r){let n=s.length;for(;s[n-1]==="=";)--n;let o=new Uint8Array(n*t/8|0),i=0,a=0,l=0;for(let u=0;u<n;++u){let p=e[s[u]];if(p===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<t|p,i+=t,i>=8&&(i-=8,o[l++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Wu(s,e,t){let r=e[e.length-1]==="=",n=(1<<t)-1,o="",i=0,a=0;for(let l=0;l<s.length;++l)for(a=a<<8|s[l],i+=8;i>t;)i-=t,o+=e[n&a>>i];if(i!==0&&(o+=e[n&a<<t-i]),r)for(;(o.length*t&7)!==0;)o+="=";return o}function $u(s){let e={};for(let t=0;t<s.length;++t)e[s[t]]=t;return e}function ee({name:s,prefix:e,bitsPerChar:t,alphabet:r}){let n=$u(r);return Xt({prefix:e,name:s,encode(o){return Wu(o,r,t)},decode(o){return Vu(o,n,t,s)}})}var ju=ht({prefix:"9",name:"base10",alphabet:"0123456789"});var Mn={};V(Mn,{base16:()=>Zu,base16upper:()=>Yu});var Zu=ee({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Yu=ee({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Pn={};V(Pn,{base2:()=>Xu});var Xu=ee({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var kn={};V(kn,{base256emoji:()=>sh});var ma=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}"),Ju=ma.reduce((s,e,t)=>(s[t]=e,s),[]),Qu=ma.reduce((s,e,t)=>{let r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return s[r]=t,s},[]);function eh(s){return s.reduce((e,t)=>(e+=Ju[t],e),"")}function th(s){let e=[];for(let t of s){let r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);let n=Qu[r];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var sh=Xt({prefix:"\u{1F680}",name:"base256emoji",encode:eh,decode:th});var Bn={};V(Bn,{base32:()=>Jt,base32hex:()=>ih,base32hexpad:()=>ch,base32hexpadupper:()=>lh,base32hexupper:()=>ah,base32pad:()=>nh,base32padupper:()=>oh,base32upper:()=>rh,base32z:()=>uh});var Jt=ee({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),rh=ee({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),nh=ee({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),oh=ee({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ih=ee({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ah=ee({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ch=ee({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),lh=ee({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),uh=ee({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ln={};V(Ln,{base36:()=>Ps,base36upper:()=>hh});var Ps=ht({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),hh=ht({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Rn={};V(Rn,{base58btc:()=>qe,base58flickr:()=>fh});var qe=ht({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),fh=ht({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Cn={};V(Cn,{base64:()=>dh,base64pad:()=>ph,base64url:()=>mh,base64urlpad:()=>gh});var dh=ee({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ph=ee({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),mh=ee({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),gh=ee({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Fn={};V(Fn,{base8:()=>bh});var bh=ee({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Nn={};V(Nn,{identity:()=>yh});var yh=Xt({prefix:"\0",name:"identity",encode:s=>ha(s),decode:s=>ua(s)});var gg=new TextEncoder,bg=new TextDecoder;var Un={};V(Un,{identity:()=>zh});var vh=ya,ga=128,Eh=127,Sh=~Eh,_h=Math.pow(2,31);function ya(s,e,t){e=e||[],t=t||0;for(var r=t;s>=_h;)e[t++]=s&255|ga,s/=128;for(;s&Sh;)e[t++]=s&255|ga,s>>>=7;return e[t]=s|0,ya.bytes=t-r+1,e}var Ih=On,Th=128,ba=127;function On(s,r){var t=0,r=r||0,n=0,o=r,i,a=s.length;do{if(o>=a)throw On.bytes=0,new RangeError("Could not decode varint");i=s[o++],t+=n<28?(i&ba)<<n:(i&ba)*Math.pow(2,n),n+=7}while(i>=Th);return On.bytes=o-r,t}var Dh=Math.pow(2,7),Ah=Math.pow(2,14),Mh=Math.pow(2,21),Ph=Math.pow(2,28),kh=Math.pow(2,35),Bh=Math.pow(2,42),Lh=Math.pow(2,49),Rh=Math.pow(2,56),Ch=Math.pow(2,63),Fh=function(s){return s<Dh?1:s<Ah?2:s<Mh?3:s<Ph?4:s<kh?5:s<Bh?6:s<Lh?7:s<Rh?8:s<Ch?9:10},Nh={encode:vh,decode:Ih,encodingLength:Fh},Oh=Nh,ks=Oh;function Bs(s,e=0){return[ks.decode(s,e),ks.decode.bytes]}function Qt(s,e,t=0){return ks.encode(s,e,t),e}function es(s){return ks.encodingLength(s)}function ss(s,e){let t=e.byteLength,r=es(s),n=r+es(t),o=new Uint8Array(n+t);return Qt(s,o,0),Qt(t,o,r),o.set(e,n),new ts(s,t,e,o)}function wa(s){let e=et(s),[t,r]=Bs(e),[n,o]=Bs(e.subarray(r)),i=e.subarray(r+o);if(i.byteLength!==n)throw new Error("Incorrect length");return new ts(t,n,i,e)}function xa(s,e){if(s===e)return!0;{let t=e;return s.code===t.code&&s.size===t.size&&t.bytes instanceof Uint8Array&&la(s.bytes,t.bytes)}}var ts=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=Tt(r),this.bytes=Tt(n)}};var va=0,Uh="identity",Ea=et;function Kh(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 ss(va,Ea(s))}var zh={code:va,name:Uh,encode:Ea,digest:Kh};var Hn={};V(Hn,{sha256:()=>Gh,sha512:()=>qh});var Hh=20;function zn({name:s,code:e,encode:t,minDigestLength:r,maxDigestLength:n}){return new Kn(s,e,t,r,n)}var Kn=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,r,n,o){this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??Hh,this.maxDigestLength=o}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?Sa(r,this.code,t?.truncate):r.then(n=>Sa(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Sa(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 ss(e,s)}function Ia(s){return async e=>new Uint8Array(await crypto.subtle.digest(s,e))}var Gh=zn({name:"sha2-256",code:18,encode:Ia("SHA-256")}),qh=zn({name:"sha2-512",code:19,encode:Ia("SHA-512")});function Ta(s,e){let{bytes:t,version:r}=s;return r===0?Wh(t,Gn(s),e??qe.encoder):$h(t,Gn(s),e??Jt.encoder)}var Da=new WeakMap;function Gn(s){let e=Da.get(s);if(e==null){let t=new Map;return Da.set(s,t),t}return e}var dr=class s{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=Tt(n),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Rs)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==jh)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=ss(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&&xa(e.multihash,r.multihash)}toString(e){return Ta(this,e)}toJSON(){return{"/":Ta(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:o,bytes:i}=t;return new s(r,n,o,i??Aa(r,n,o.bytes))}else if(t[Zh]===!0){let{version:r,multihash:n,code:o}=t,i=wa(n);return s.create(r,o,i)}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!==Rs)throw new Error(`Version 0 CID must use dag-pb (code: ${Rs}) block encoding`);return new s(e,t,r,r.bytes)}case 1:{let n=Aa(e,t,r.bytes);return new s(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return s.create(0,Rs,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=et(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=n.subarray(t.multihashSize-t.digestSize),i=new ts(t.multihashCode,t.digestSize,o,n);return[t.version===0?s.createV0(i):s.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,r=()=>{let[m,E]=Bs(e.subarray(t));return t+=E,m},n=r(),o=Rs;if(n===18?(n=0,t=0):o=r(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let i=t,a=r(),l=r(),u=t+l,p=u-i;return{version:n,codec:o,multihashCode:a,digestSize:l,multihashSize:p,size:u}}static parse(e,t){let[r,n]=Vh(e,t),o=s.decode(n);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Gn(o).set(r,e),o}};function Vh(s,e){switch(s[0]){case"Q":{let t=e??qe;return[qe.prefix,t.decode(`${qe.prefix}${s}`)]}case qe.prefix:{let t=e??qe;return[qe.prefix,t.decode(s)]}case Jt.prefix:{let t=e??Jt;return[Jt.prefix,t.decode(s)]}case Ps.prefix:{let t=e??Ps;return[Ps.prefix,t.decode(s)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[s[0],e.decode(s)]}}}function Wh(s,e,t){let{prefix:r}=t;if(r!==qe.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let n=e.get(r);if(n==null){let o=t.encode(s).slice(1);return e.set(r,o),o}else return n}function $h(s,e,t){let{prefix:r}=t,n=e.get(r);if(n==null){let o=t.encode(s);return e.set(r,o),o}else return n}var Rs=112,jh=18;function Aa(s,e,t){let r=es(s),n=r+es(e),o=new Uint8Array(n+t.byteLength);return Qt(s,o,0),Qt(e,o,r),o.set(t,n),o}var Zh=Symbol.for("@ipld/js-cid/CID");var qn={...Nn,...Pn,...Fn,...An,...Mn,...Bn,...Ln,...Rn,...Cn,...kn},Ug={...Hn,...Un};function pr(s=0){return new Uint8Array(s)}function Pa(s,e,t,r){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:r}}}var Ma=Pa("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),Vn=Pa("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=pr(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),Yh={utf8:Ma,"utf-8":Ma,hex:qn.base16,latin1:Vn,ascii:Vn,binary:Vn,...qn},mr=Yh;function j(s,e="utf8"){let t=mr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${s}`)}function q(s,e="utf8"){let t=mr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(s).substring(1)}var Xh=parseInt("11111",2),Wn=parseInt("10000000",2),Jh=parseInt("01111111",2),ka={0:Cs,1:Cs,2:Qh,3:sf,4:rf,5:tf,6:ef,16:Cs,22:Cs,48:Cs};function tt(s,e={offset:0}){let t=s[e.offset]&Xh;if(e.offset++,ka[t]!=null)return ka[t](s,e);throw new Error("No decoder for tag "+t)}function Fs(s,e){let t=0;if((s[e.offset]&Wn)===Wn){let r=s[e.offset]&Jh,n="0x";e.offset++;for(let o=0;o<r;o++,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 Cs(s,e){Fs(s,e);let t=[];for(;!(e.offset>=s.byteLength);){let r=tt(s,e);if(r===null)break;t.push(r)}return t}function Qh(s,e){let t=Fs(s,e),r=e.offset,n=e.offset+t,o=[];for(let i=r;i<n;i++)i===r&&s[i]===0||o.push(s[i]);return e.offset+=t,Uint8Array.from(o)}function ef(s,e){let t=Fs(s,e),r=e.offset+t,n=s[e.offset];e.offset++;let o=0,i=0;n<40?(o=0,i=n):n<80?(o=1,i=n-40):(o=2,i=n-80);let a=`${o}.${i}`,l=[];for(;e.offset<r;){let u=s[e.offset];if(e.offset++,l.push(u&127),u<128){l.reverse();let p=0;for(let m=0;m<l.length;m++)p+=l[m]<<m*7;a+=`.${p}`,l=[]}}return a}function tf(s,e){return e.offset++,null}function sf(s,e){let t=Fs(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 rf(s,e){let t=Fs(s,e),r=s.subarray(e.offset,e.offset+t);return e.offset+=t,r}function nf(s){let e=s.toString(16);e.length%2===1&&(e="0"+e);let t=new ce;for(let r=0;r<e.length;r+=2)t.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return t}function $n(s){if(s.byteLength<128)return Uint8Array.from([s.byteLength]);let e=nf(s.byteLength);return new ce(Uint8Array.from([e.byteLength|Wn]),e)}function Te(s){let e=new ce,t=128;return(s.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(s),new ce(Uint8Array.from([2]),$n(e),e)}function gr(s){let e=Uint8Array.from([0]),t=new ce(e,s);return new ce(Uint8Array.from([3]),$n(t),t)}function ft(s,e=48){let t=new ce;for(let r of s)t.append(r);return new ce(Uint8Array.from([e]),$n(t),t)}var of=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),af=Uint8Array.from([6,5,43,129,4,0,34]),cf=Uint8Array.from([6,5,43,129,4,0,35]),lf={ext:!0,kty:"EC",crv:"P-256"},uf={ext:!0,kty:"EC",crv:"P-384"},hf={ext:!0,kty:"EC",crv:"P-521"},jn=32,Zn=48,Yn=66;function Xn(s){let e=tt(s);return Ba(e)}function Ba(s){let e=s[1][1][0],t=1,r,n;if(e.byteLength===jn*2+1)return r=q(e.subarray(t,t+jn),"base64url"),n=q(e.subarray(t+jn),"base64url"),new rs({...lf,key_ops:["verify"],x:r,y:n});if(e.byteLength===Zn*2+1)return r=q(e.subarray(t,t+Zn),"base64url"),n=q(e.subarray(t+Zn),"base64url"),new rs({...uf,key_ops:["verify"],x:r,y:n});if(e.byteLength===Yn*2+1)return r=q(e.subarray(t,t+Yn),"base64url"),n=q(e.subarray(t+Yn),"base64url"),new rs({...hf,key_ops:["verify"],x:r,y:n});throw new X(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function La(s){return ft([Te(Uint8Array.from([1])),ft([ff(s.crv)],160),ft([gr(new ce(Uint8Array.from([4]),j(s.x??"","base64url"),j(s.y??"","base64url")))],161)]).subarray()}function ff(s){if(s==="P-256")return of;if(s==="P-384")return af;if(s==="P-521")return cf;throw new X(`Invalid curve ${s}`)}var rs=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=La(this.jwk)),this._raw}toMultihash(){return Le.digest(Ve(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}async verify(e,t,r){return oa(this.jwk,t,e,r)}};function Jn(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in s&&s.BYTES_PER_ELEMENT===1}function dt(s,e=""){if(typeof s!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof s}`)}if(!Number.isSafeInteger(s)||s<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${s}`)}}function De(s,e,t=""){let r=Jn(s),n=s?.length,o=e!==void 0;if(!r||o&&n!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",l=r?`length=${n}`:`type=${typeof s}`,u=i+"expected Uint8Array"+a+", got "+l;throw r?new RangeError(u):new TypeError(u)}return s}function br(s){if(typeof s!="function"||typeof s.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(dt(s.outputLen),dt(s.blockLen),s.outputLen<1)throw new Error('"outputLen" must be >= 1');if(s.blockLen<1)throw new Error('"blockLen" must be >= 1')}function ns(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 yr(s,e){De(s,void 0,"digestInto() output");let t=e.outputLen;if(s.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function rt(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function wr(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Re(s,e){return s<<32-e|s>>>e}var Ca=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",df=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function xr(s){if(De(s),Ca)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=df[s[t]];return e}var st={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ra(s){if(s>=st._0&&s<=st._9)return s-st._0;if(s>=st.A&&s<=st.F)return s-(st.A-10);if(s>=st.a&&s<=st.f)return s-(st.a-10)}function Ns(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);if(Ca)try{return Uint8Array.fromHex(s)}catch(n){throw n instanceof SyntaxError?new RangeError(n.message):n}let e=s.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let n=0,o=0;n<t;n++,o+=2){let i=Ra(s.charCodeAt(o)),a=Ra(s.charCodeAt(o+1));if(i===void 0||a===void 0){let l=s[o]+s[o+1];throw new RangeError('hex string expected, got non-hex character "'+l+'" at index '+o)}r[n]=i*16+a}return r}function Qn(...s){let e=0;for(let r=0;r<s.length;r++){let n=s[r];De(n),e+=n.length}let t=new Uint8Array(e);for(let r=0,n=0;r<s.length;r++){let o=s[r];t.set(o,n),n+=o.length}return t}function eo(s,e={}){let t=(n,o)=>s(o).update(n).digest(),r=s(void 0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.canXOF=r.canXOF,t.create=n=>s(n),Object.assign(t,e),Object.freeze(t)}function Fa(s=32){dt(s,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(s>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${s}`);return e.getRandomValues(new Uint8Array(s))}var to=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function Na(s,e,t){return s&e^~s&t}function Oa(s,e,t){return s&e^s&t^e&t}var Os=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=wr(this.buffer)}update(e){ns(this),De(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(n-this.pos,o-i);if(a===n){let l=wr(e);for(;n<=o-i;i+=n)this.process(l,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ns(this),yr(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;t[i++]=128,rt(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(r,0),i=0);for(let m=i;m<n;m++)t[m]=0;r.setBigUint64(n-8,BigInt(this.length*8),o),this.process(r,0);let a=wr(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=l/4,p=this.get();if(u>p.length)throw new Error("_sha2: outputLen bigger than state");for(let m=0;m<u;m++)a.setUint32(4*m,p[m],o)}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:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=a,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}},nt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var he=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var vr=BigInt(4294967295),Ua=BigInt(32);function pf(s,e=!1){return e?{h:Number(s&vr),l:Number(s>>Ua&vr)}:{h:Number(s>>Ua&vr)|0,l:Number(s&vr)|0}}function Ka(s,e=!1){let t=s.length,r=new Uint32Array(t),n=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=pf(s[o],e);[r[o],n[o]]=[i,a]}return[r,n]}var so=(s,e,t)=>s>>>t,ro=(s,e,t)=>s<<32-t|e>>>t,Dt=(s,e,t)=>s>>>t|e<<32-t,At=(s,e,t)=>s<<32-t|e>>>t,Us=(s,e,t)=>s<<64-t|e>>>t-32,Ks=(s,e,t)=>s>>>t-32|e<<64-t;function We(s,e,t,r){let n=(e>>>0)+(r>>>0);return{h:s+t+(n/2**32|0)|0,l:n|0}}var za=(s,e,t)=>(s>>>0)+(e>>>0)+(t>>>0),Ha=(s,e,t,r)=>e+t+r+(s/2**32|0)|0,Ga=(s,e,t,r)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0),qa=(s,e,t,r,n)=>e+t+r+n+(s/2**32|0)|0,Va=(s,e,t,r,n)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Wa=(s,e,t,r,n,o)=>e+t+r+n+o+(s/2**32|0)|0;var gf=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]),pt=new Uint32Array(64),no=class extends Os{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:a,H:l}=this;return[e,t,r,n,o,i,a,l]}set(e,t,r,n,o,i,a,l){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=l|0}process(e,t){for(let m=0;m<16;m++,t+=4)pt[m]=e.getUint32(t,!1);for(let m=16;m<64;m++){let E=pt[m-15],w=pt[m-2],h=Re(E,7)^Re(E,18)^E>>>3,g=Re(w,17)^Re(w,19)^w>>>10;pt[m]=g+pt[m-7]+h+pt[m-16]|0}let{A:r,B:n,C:o,D:i,E:a,F:l,G:u,H:p}=this;for(let m=0;m<64;m++){let E=Re(a,6)^Re(a,11)^Re(a,25),w=p+E+Na(a,l,u)+gf[m]+pt[m]|0,g=(Re(r,2)^Re(r,13)^Re(r,22))+Oa(r,n,o)|0;p=u,u=l,l=a,a=i+w|0,i=o,o=n,n=r,r=w+g|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,l=l+this.F|0,u=u+this.G|0,p=p+this.H|0,this.set(r,n,o,i,a,l,u,p)}roundClean(){rt(pt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),rt(this.buffer)}},oo=class extends no{A=nt[0]|0;B=nt[1]|0;C=nt[2]|0;D=nt[3]|0;E=nt[4]|0;F=nt[5]|0;G=nt[6]|0;H=nt[7]|0;constructor(){super(32)}};var $a=Ka(["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))),bf=$a[0],yf=$a[1],mt=new Uint32Array(80),gt=new Uint32Array(80),io=class extends Os{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:o,Cl:i,Dh:a,Dl:l,Eh:u,El:p,Fh:m,Fl:E,Gh:w,Gl:h,Hh:g,Hl:b}=this;return[e,t,r,n,o,i,a,l,u,p,m,E,w,h,g,b]}set(e,t,r,n,o,i,a,l,u,p,m,E,w,h,g,b){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=n|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=l|0,this.Eh=u|0,this.El=p|0,this.Fh=m|0,this.Fl=E|0,this.Gh=w|0,this.Gl=h|0,this.Hh=g|0,this.Hl=b|0}process(e,t){for(let c=0;c<16;c++,t+=4)mt[c]=e.getUint32(t),gt[c]=e.getUint32(t+=4);for(let c=16;c<80;c++){let f=mt[c-15]|0,d=gt[c-15]|0,y=Dt(f,d,1)^Dt(f,d,8)^so(f,d,7),v=At(f,d,1)^At(f,d,8)^ro(f,d,7),S=mt[c-2]|0,M=gt[c-2]|0,C=Dt(S,M,19)^Us(S,M,61)^so(S,M,6),N=At(S,M,19)^Ks(S,M,61)^ro(S,M,6),I=Ga(v,N,gt[c-7],gt[c-16]),T=qa(I,y,C,mt[c-7],mt[c-16]);mt[c]=T|0,gt[c]=I|0}let{Ah:r,Al:n,Bh:o,Bl:i,Ch:a,Cl:l,Dh:u,Dl:p,Eh:m,El:E,Fh:w,Fl:h,Gh:g,Gl:b,Hh:x,Hl:_}=this;for(let c=0;c<80;c++){let f=Dt(m,E,14)^Dt(m,E,18)^Us(m,E,41),d=At(m,E,14)^At(m,E,18)^Ks(m,E,41),y=m&w^~m&g,v=E&h^~E&b,S=Va(_,d,v,yf[c],gt[c]),M=Wa(S,x,f,y,bf[c],mt[c]),C=S|0,N=Dt(r,n,28)^Us(r,n,34)^Us(r,n,39),I=At(r,n,28)^Ks(r,n,34)^Ks(r,n,39),T=r&o^r&a^o&a,P=n&i^n&l^i&l;x=g|0,_=b|0,g=w|0,b=h|0,w=m|0,h=E|0,{h:m,l:E}=We(u|0,p|0,M|0,C|0),u=a|0,p=l|0,a=o|0,l=i|0,o=r|0,i=n|0;let A=za(C,I,P);r=Ha(A,M,N,T),n=A|0}({h:r,l:n}=We(this.Ah|0,this.Al|0,r|0,n|0)),{h:o,l:i}=We(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l}=We(this.Ch|0,this.Cl|0,a|0,l|0),{h:u,l:p}=We(this.Dh|0,this.Dl|0,u|0,p|0),{h:m,l:E}=We(this.Eh|0,this.El|0,m|0,E|0),{h:w,l:h}=We(this.Fh|0,this.Fl|0,w|0,h|0),{h:g,l:b}=We(this.Gh|0,this.Gl|0,g|0,b|0),{h:x,l:_}=We(this.Hh|0,this.Hl|0,x|0,_|0),this.set(r,n,o,i,a,l,u,p,m,E,w,h,g,b,x,_)}roundClean(){rt(mt,gt)}destroy(){this.destroyed=!0,rt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},ao=class extends io{Ah=he[0]|0;Al=he[1]|0;Bh=he[2]|0;Bl=he[3]|0;Ch=he[4]|0;Cl=he[5]|0;Dh=he[6]|0;Dl=he[7]|0;Eh=he[8]|0;El=he[9]|0;Fh=he[10]|0;Fl=he[11]|0;Gh=he[12]|0;Gl=he[13]|0;Hh=he[14]|0;Hl=he[15]|0;constructor(){super(64)}};var os=eo(()=>new oo,to(1));var Er=eo(()=>new ao,to(3));var K=(s,e,t)=>De(s,e,t),lo=dt,is=xr,oe=(...s)=>Qn(...s),as=s=>Ns(s),Mt=Jn,zs=s=>Fa(s),_r=BigInt(0),co=BigInt(1);function Ce(s,e=""){if(typeof s!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof s)}return s}function Ir(s){if(typeof s=="bigint"){if(!Sr(s))throw new RangeError("positive bigint expected, got "+s)}else lo(s);return s}function Fe(s,e=""){if(typeof s!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof s)}if(!Number.isSafeInteger(s)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+s)}}function Hs(s){let e=Ir(s).toString(16);return e.length&1?"0"+e:e}function ja(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);return s===""?_r:BigInt("0x"+s)}function Pt(s){return ja(xr(s))}function $e(s){return ja(xr(Gs(De(s)).reverse()))}function Tr(s,e){if(dt(e),e===0)throw new RangeError("zero length");s=Ir(s);let t=s.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Ns(t.padStart(e*2,"0"))}function uo(s,e){return Tr(s,e).reverse()}function Za(s,e){if(s=K(s),e=K(e),s.length!==e.length)return!1;let t=0;for(let r=0;r<s.length;r++)t|=s[r]^e[r];return t===0}function Gs(s){return Uint8Array.from(K(s))}function Dr(s){if(typeof s!="string")throw new TypeError("ascii string expected, got "+typeof s);return Uint8Array.from(s,(e,t)=>{let r=e.charCodeAt(0);if(e.length!==1||r>127)throw new RangeError(`string contains non-ASCII character "${s[t]}" with code ${r} at position ${t}`);return r})}var Sr=s=>typeof s=="bigint"&&_r<=s;function wf(s,e,t){return Sr(s)&&Sr(e)&&Sr(t)&&e<=s&&s<t}function cs(s,e,t,r){if(!wf(e,t,r))throw new RangeError("expected valid "+s+": "+t+" <= n < "+r+", got "+e)}function ls(s){if(s<_r)throw new Error("expected non-negative bigint, got "+s);let e;for(e=0;s>_r;s>>=co,e+=1);return e}var qs=s=>(co<<BigInt(s))-co;function Ya(s,e,t){if(dt(s,"hashLen"),dt(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let r=b=>new Uint8Array(b),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,l=r(s),u=r(s),p=0,m=()=>{l.fill(1),u.fill(0),p=0},E=(...b)=>t(u,oe(l,...b)),w=(b=n)=>{u=E(o,b),l=E(),b.length!==0&&(u=E(i,b),l=E())},h=()=>{if(p++>=a)throw new Error("drbg: tried max amount of iterations");let b=0,x=[];for(;b<e;){l=E();let _=l.slice();x.push(_),b+=l.length}return oe(...x)};return(b,x)=>{m(),w(b);let _;for(;(_=x(h()))===void 0;)w();return m(),_}}function Ne(s,e={},t={}){if(Object.prototype.toString.call(s)!=="[object Object]")throw new TypeError("expected valid options object");function r(o,i,a){if(!a&&i!=="function"&&!Object.hasOwn(s,o))throw new TypeError(`param "${o}" is invalid: expected own property`);let l=s[o];if(a&&l===void 0)return;let u=typeof l;if(u!==i||l===null)throw new TypeError(`param "${o}" is invalid: expected ${i}, got ${u}`)}let n=(o,i)=>Object.entries(o).forEach(([a,l])=>r(a,l,i));n(e,!1),n(t,!0)}var ho=()=>{throw new Error("not implemented")};var fe=BigInt(0),te=BigInt(1),kt=BigInt(2),ec=BigInt(3),tc=BigInt(4),sc=BigInt(5),xf=BigInt(7),rc=BigInt(8),vf=BigInt(9),nc=BigInt(16);function re(s,e){if(e<=fe)throw new Error("mod: expected positive modulus, got "+e);let t=s%e;return t>=fe?t:e+t}function $(s,e,t){if(e<fe)throw new Error("pow2: expected non-negative exponent, got "+e);let r=s;for(;e-- >fe;)r*=r,r%=t;return r}function Xa(s,e){if(s===fe)throw new Error("invert: expected non-zero number");if(e<=fe)throw new Error("invert: expected positive modulus, got "+e);let t=re(s,e),r=e,n=fe,o=te,i=te,a=fe;for(;t!==fe;){let u=r/t,p=r-t*u,m=n-i*u,E=o-a*u;r=t,t=p,n=i,o=a,i=m,a=E}if(r!==te)throw new Error("invert: does not exist");return re(n,e)}function fo(s,e,t){let r=s;if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function oc(s,e){let t=s,r=(t.ORDER+te)/tc,n=t.pow(e,r);return fo(t,n,e),n}function Ef(s,e){let t=s,r=(t.ORDER-sc)/rc,n=t.mul(e,kt),o=t.pow(n,r),i=t.mul(e,o),a=t.mul(t.mul(i,kt),o),l=t.mul(i,t.sub(a,t.ONE));return fo(t,l,e),l}function Sf(s){let e=us(s),t=ic(s),r=t(e,e.neg(e.ONE)),n=t(e,r),o=t(e,e.neg(r)),i=(s+xf)/nc;return((a,l)=>{let u=a,p=u.pow(l,i),m=u.mul(p,r),E=u.mul(p,n),w=u.mul(p,o),h=u.eql(u.sqr(m),l),g=u.eql(u.sqr(E),l);p=u.cmov(p,m,h),m=u.cmov(w,E,g);let b=u.eql(u.sqr(m),l),x=u.cmov(p,m,b);return fo(u,x,l),x})}function ic(s){if(s<ec)throw new Error("sqrt is not defined for small field");let e=s-te,t=0;for(;e%kt===fe;)e/=kt,t++;let r=kt,n=us(s);for(;Ja(n,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return oc;let o=n.pow(r,e),i=(e+te)/kt;return function(l,u){let p=l;if(p.is0(u))return u;if(Ja(p,u)!==1)throw new Error("Cannot find square root");let m=t,E=p.mul(p.ONE,o),w=p.pow(u,e),h=p.pow(u,i);for(;!p.eql(w,p.ONE);){if(p.is0(w))return p.ZERO;let g=1,b=p.sqr(w);for(;!p.eql(b,p.ONE);)if(g++,b=p.sqr(b),g===m)throw new Error("Cannot find square root");let x=te<<BigInt(m-g-1),_=p.pow(E,x);m=g,E=p.sqr(_),w=p.mul(w,E),h=p.mul(h,_)}return h}}function _f(s){return s%tc===ec?oc:s%rc===sc?Ef:s%nc===vf?Sf(s):ic(s)}var ot=(s,e)=>(re(s,e)&te)===te,If=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function po(s){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=If.reduce((r,n)=>(r[n]="function",r),e);if(Ne(s,t),Fe(s.BYTES,"BYTES"),Fe(s.BITS,"BITS"),s.BYTES<1||s.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(s.ORDER<=te)throw new Error("invalid field: expected ORDER > 1, got "+s.ORDER);return s}function Tf(s,e,t){let r=s;if(t<fe)throw new Error("invalid exponent, negatives unsupported");if(t===fe)return r.ONE;if(t===te)return e;let n=r.ONE,o=e;for(;t>fe;)t&te&&(n=r.mul(n,o)),o=r.sqr(o),t>>=te;return n}function Vs(s,e,t=!1){let r=s,n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((a,l,u)=>r.is0(l)?a:(n[u]=a,r.mul(a,l)),r.ONE),i=r.inv(o);return e.reduceRight((a,l,u)=>r.is0(l)?a:(n[u]=r.mul(a,n[u]),r.mul(a,l)),i),n}function Ja(s,e){let t=s,r=(t.ORDER-te)/kt,n=t.pow(e,r),o=t.eql(n,t.ONE),i=t.eql(n,t.ZERO),a=t.eql(n,t.neg(t.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function Df(s,e){if(e!==void 0&&lo(e),s<=fe)throw new Error("invalid n length: expected positive n, got "+s);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=ls(s);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let r=e!==void 0?e:t,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var Qa=new WeakMap,Ar=class{ORDER;BITS;BYTES;isLE;ZERO=fe;ONE=te;_lengths;_mod;constructor(e,t={}){if(e<=te)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:n,nByteLength:o}=Df(e,r);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,Object.freeze(this)}create(e){return re(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return fe<=e&&e<this.ORDER}is0(e){return e===fe}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&te)===te}neg(e){return re(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return re(e*e,this.ORDER)}add(e,t){return re(e+t,this.ORDER)}sub(e,t){return re(e-t,this.ORDER)}mul(e,t){return re(e*t,this.ORDER)}pow(e,t){return Tf(this,e,t)}div(e,t){return re(e*Xa(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 Xa(e,this.ORDER)}sqrt(e){let t=Qa.get(this);return t||Qa.set(this,t=_f(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?uo(e,this.BYTES):Tr(e,this.BYTES)}fromBytes(e,t=!1){K(e);let{_lengths:r,BYTES:n,isLE:o,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let u=new Uint8Array(n);u.set(e,o?0:u.length-e.length),e=u}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=o?$e(e):Pt(e);if(a&&(l=re(l,i)),!t&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return Vs(this,e)}cmov(e,t,r){return Ce(r,"condition"),r?t:e}};Object.freeze(Ar.prototype);function us(s,e={}){return new Ar(s,e)}function ac(s){if(typeof s!="bigint")throw new Error("field order must be bigint");if(s<=te)throw new Error("field order must be greater than 1");let e=ls(s-te);return Math.ceil(e/8)}function mo(s){let e=ac(s);return e+Math.ceil(e/2)}function go(s,e,t=!1){K(s);let r=s.length,n=ac(e),o=Math.max(mo(e),16);if(r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);let i=t?$e(s):Pt(s),a=re(i,e-te)+te;return t?uo(a,n):Tr(a,n)}var hs=BigInt(0),Bt=BigInt(1);function Ws(s,e){let t=e.negate();return s?t:e}function Lt(s,e){let t=Vs(s.Fp,e.map(r=>r.Z));return e.map((r,n)=>s.fromAffine(r.toAffine(t[n])))}function hc(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function bo(s,e){hc(s,e);let t=Math.ceil(e/s)+1,r=2**(s-1),n=2**s,o=qs(s),i=BigInt(s);return{windows:t,windowSize:r,mask:o,maxNumber:n,shiftBy:i}}function cc(s,e,t){let{windowSize:r,mask:n,maxNumber:o,shiftBy:i}=t,a=Number(s&n),l=s>>i;a>r&&(a-=o,l+=Bt);let u=e*r,p=u+Math.abs(a)-1,m=a===0,E=a<0,w=e%2!==0;return{nextN:l,offset:p,isZero:m,isNeg:E,isNegF:w,offsetF:u}}var yo=new WeakMap,fc=new WeakMap;function wo(s){return fc.get(s)||1}function lc(s){if(s!==hs)throw new Error("invalid wNAF")}var fs=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>hs;)t&Bt&&(r=r.add(n)),n=n.double(),t>>=Bt;return r}precomputeWindow(e,t){let{windows:r,windowSize:n}=bo(t,this.bits),o=[],i=e,a=i;for(let l=0;l<r;l++){a=i,o.push(a);for(let u=1;u<n;u++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE,i=bo(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:l,offset:u,isZero:p,isNeg:m,isNegF:E,offsetF:w}=cc(r,a,i);r=l,p?o=o.add(Ws(E,t[w])):n=n.add(Ws(m,t[u]))}return lc(r),{p:n,f:o}}wNAFUnsafe(e,t,r,n=this.ZERO){let o=bo(e,this.bits);for(let i=0;i<o.windows&&r!==hs;i++){let{nextN:a,offset:l,isZero:u,isNeg:p}=cc(r,i,o);if(r=a,!u){let m=t[l];n=n.add(p?m.negate():m)}}return lc(r),n}getPrecomputes(e,t,r){let n=yo.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(n=r(n)),yo.set(t,n))),n}cached(e,t,r){let n=wo(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){let o=wo(e);return o===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,n)}createCache(e,t){hc(t,this.bits),fc.set(e,t),yo.delete(e)}hasCache(e){return wo(e)!==1}};function dc(s,e,t,r){let n=e,o=s.ZERO,i=s.ZERO;for(;t>hs||r>hs;)t&Bt&&(o=o.add(n)),r&Bt&&(i=i.add(n)),n=n.double(),t>>=Bt,r>>=Bt;return{p1:o,p2:i}}function uc(s,e,t){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return po(e),e}else return us(s,{isLE:t})}function Mr(s,e,t={},r){if(r===void 0&&(r=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(let l of["p","n","h"]){let u=e[l];if(!(typeof u=="bigint"&&u>hs))throw new Error(`CURVE.${l} must be positive bigint`)}let n=uc(e.p,t.Fp,r),o=uc(e.n,t.Fn,r),a=["Gx","Gy","a",s==="weierstrass"?"b":"d"];for(let l of a)if(!n.isValid(e[l]))throw new Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:o}}function Pr(s,e){return function(r){let n=s(r);return{secretKey:n,publicKey:e(n)}}}var bt=BigInt(0),le=BigInt(1),xo=BigInt(2),Af=BigInt(8);function Mf(s,e,t,r){let n=s.sqr(t),o=s.sqr(r),i=s.add(s.mul(e.a,n),o),a=s.add(s.ONE,s.mul(e.d,s.mul(n,o)));return s.eql(i,a)}function pc(s,e={}){let t=e,r=Mr("edwards",s,t,t.FpFnLE),{Fp:n,Fn:o}=r,i=r.CURVE,{h:a}=i;Ne(t,{},{uvRatio:"function"});let l=xo<<BigInt(o.BYTES*8)-le,u=g=>n.create(g),p=t.uvRatio===void 0?(g,b)=>{try{return{isValid:!0,value:n.sqrt(n.div(g,b))}}catch{return{isValid:!1,value:bt}}}:t.uvRatio;if(!Mf(n,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function m(g,b,x=!1){let _=x?le:bt;return cs("coordinate "+g,b,_,l),b}function E(g){if(!(g instanceof w))throw new Error("EdwardsPoint expected")}class w{static BASE=new w(i.Gx,i.Gy,le,u(i.Gx*i.Gy));static ZERO=new w(bt,le,le,bt);static Fp=n;static Fn=o;X;Y;Z;T;constructor(b,x,_,c){this.X=m("x",b),this.Y=m("y",x),this.Z=m("z",_,!0),this.T=m("t",c),Object.freeze(this)}static CURVE(){return i}static fromAffine(b){if(b instanceof w)throw new Error("extended point not allowed");let{x,y:_}=b||{};return m("x",x),m("y",_),new w(x,_,le,u(x*_))}static fromBytes(b,x=!1){let _=n.BYTES,{a:c,d:f}=i;b=Gs(K(b,_,"point")),Ce(x,"zip215");let d=Gs(b),y=b[_-1];d[_-1]=y&-129;let v=$e(d),S=x?l:n.ORDER;cs("point.y",v,bt,S);let M=u(v*v),C=u(M-le),N=u(f*M-c),{isValid:I,value:T}=p(C,N);if(!I)throw new Error("bad point: invalid y coordinate");let P=(T&le)===le,A=(y&128)!==0;if(!x&&T===bt&&A)throw new Error("bad point: x=0 and x_0=1");return A!==P&&(T=u(-T)),w.fromAffine({x:T,y:v})}static fromHex(b,x=!1){return w.fromBytes(as(b),x)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,x=!0){return h.createCache(this,b),x||this.multiply(xo),this}assertValidity(){let b=this,{a:x,d:_}=i;if(b.is0())throw new Error("bad point: ZERO");let{X:c,Y:f,Z:d,T:y}=b,v=u(c*c),S=u(f*f),M=u(d*d),C=u(M*M),N=u(v*x),I=u(M*u(N+S)),T=u(C+u(_*u(v*S)));if(I!==T)throw new Error("bad point: equation left != right (1)");let P=u(c*f),A=u(d*y);if(P!==A)throw new Error("bad point: equation left != right (2)")}equals(b){E(b);let{X:x,Y:_,Z:c}=this,{X:f,Y:d,Z:y}=b,v=u(x*y),S=u(f*c),M=u(_*y),C=u(d*c);return v===S&&M===C}is0(){return this.equals(w.ZERO)}negate(){return new w(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:b}=i,{X:x,Y:_,Z:c}=this,f=u(x*x),d=u(_*_),y=u(xo*u(c*c)),v=u(b*f),S=x+_,M=u(u(S*S)-f-d),C=v+d,N=C-y,I=v-d,T=u(M*N),P=u(C*I),A=u(M*I),D=u(N*C);return new w(T,P,D,A)}add(b){E(b);let{a:x,d:_}=i,{X:c,Y:f,Z:d,T:y}=this,{X:v,Y:S,Z:M,T:C}=b,N=u(c*v),I=u(f*S),T=u(y*_*C),P=u(d*M),A=u((c+f)*(v+S)-N-I),D=P-T,k=P+T,L=u(I-x*N),B=u(A*D),R=u(k*L),F=u(A*L),U=u(D*k);return new w(B,R,U,F)}subtract(b){return E(b),this.add(b.negate())}multiply(b){if(!o.isValidNot0(b))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:x,f:_}=h.cached(this,b,c=>Lt(w,c));return Lt(w,[x,_])[0]}multiplyUnsafe(b){if(!o.isValid(b))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return b===bt?w.ZERO:this.is0()||b===le?this:h.unsafe(this,b,x=>Lt(w,x))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return h.unsafe(this,i.n).is0()}toAffine(b){let x=this,_=b,{X:c,Y:f,Z:d}=x,y=x.is0();_==null&&(_=y?Af:n.inv(d));let v=u(c*_),S=u(f*_),M=n.mul(d,_);if(y)return{x:bt,y:le};if(M!==le)throw new Error("invZ was invalid");return{x:v,y:S}}clearCofactor(){return a===le?this:this.multiplyUnsafe(a)}toBytes(){let{x:b,y:x}=this.toAffine(),_=n.toBytes(x);return _[_.length-1]|=b&le?128:0,_}toHex(){return is(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let h=new fs(w,o.BITS);return o.BITS>=8&&w.BASE.precompute(8),Object.freeze(w.prototype),Object.freeze(w),w}var kr=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){ho()}static fromHex(e){ho()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return is(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function mc(s,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let r=e,n=t;Ne(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:o}=n,{BASE:i,Fp:a,Fn:l}=s,u=r.outputLen,p=2*a.BYTES;if(u!==void 0&&(Fe(u,"hash.outputLen"),u!==p))throw new Error(`hash.outputLen must be ${p}, got ${u}`);let m=n.randomBytes===void 0?zs:n.randomBytes,E=n.adjustScalarBytes===void 0?I=>I:n.adjustScalarBytes,w=n.domain===void 0?(I,T,P)=>{if(Ce(P,"phflag"),T.length||P)throw new Error("Contexts/pre-hash are not supported");return I}:n.domain;function h(I){return l.create($e(I))}function g(I){let T=v.secretKey;K(I,v.secretKey,"secretKey");let P=K(r(I),2*T,"hashedSecretKey"),A=E(P.slice(0,T)),D=P.slice(T,2*T),k=h(A);return{head:A,prefix:D,scalar:k}}function b(I){let{head:T,prefix:P,scalar:A}=g(I),D=i.multiply(A),k=D.toBytes();return{head:T,prefix:P,scalar:A,point:D,pointBytes:k}}function x(I){return b(I).pointBytes}function _(I=Uint8Array.of(),...T){let P=oe(...T);return h(r(w(P,K(I,void 0,"context"),!!o)))}function c(I,T,P={}){I=K(I,void 0,"message"),o&&(I=o(I));let{prefix:A,scalar:D,pointBytes:k}=b(T),L=_(P.context,A,I),B=i.multiply(L).toBytes(),R=_(P.context,B,k,I),F=l.create(L+R*D);if(!l.isValid(F))throw new Error("sign failed: invalid s");let U=oe(B,l.toBytes(F));return K(U,v.signature,"result")}let f={zip215:n.zip215};function d(I,T,P,A=f){let{context:D}=A,k=A.zip215===void 0?!!f.zip215:A.zip215,L=v.signature;I=K(I,L,"signature"),T=K(T,void 0,"message"),P=K(P,v.publicKey,"publicKey"),k!==void 0&&Ce(k,"zip215"),o&&(T=o(T));let B=L/2,R=I.subarray(0,B),F=$e(I.subarray(B,L)),U,z,O;try{U=s.fromBytes(P,k),z=s.fromBytes(R,k),O=i.multiplyUnsafe(F)}catch{return!1}if(!k&&U.isSmallOrder())return!1;let ne=_(D,R,P,T);return z.add(U.multiplyUnsafe(ne)).subtract(O).clearCofactor().is0()}let y=a.BYTES,v={secretKey:y,publicKey:y,signature:2*y,seed:y};function S(I){return I=I===void 0?m(v.seed):I,K(I,v.seed,"seed")}function M(I){return Mt(I)&&I.length===v.secretKey}function C(I,T){try{return!!s.fromBytes(I,T===void 0?f.zip215:T)}catch{return!1}}let N={getExtendedPublicKey:b,randomSecretKey:S,isValidSecretKey:M,isValidPublicKey:C,toMontgomery(I){let{y:T}=s.fromBytes(I),P=v.publicKey,A=P===32;if(!A&&P!==57)throw new Error("only defined for 25519 and 448");let D=A?a.div(le+T,le-T):a.div(T-le,T+le);return a.toBytes(D)},toMontgomerySecret(I){let T=v.secretKey;K(I,T);let P=r(I.subarray(0,T));return E(P).subarray(0,T)}};return Object.freeze(v),Object.freeze(N),Object.freeze({keygen:Pr(S,x),getPublicKey:x,sign:c,verify:d,utils:N,Point:s,lengths:v})}function $s(s,e){if(Fe(s),Fe(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(s<0||s>2**(8*e)-1)throw new Error("invalid I2OSP input: "+s);let t=Array.from({length:e}).fill(0);for(let r=e-1;r>=0;r--)t[r]=s&255,s>>>=8;return new Uint8Array(t)}function Pf(s,e){let t=new Uint8Array(s.length);for(let r=0;r<s.length;r++)t[r]=s[r]^e[r];return t}function kf(s){if(!Mt(s)&&typeof s!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof s=="string"?Dr(s):s;if(e.length===0)throw new Error("DST must be non-empty");return e}function vo(s,e,t,r){K(s),Fe(t),e=kf(e),e.length>255&&(e=r(oe(Dr("H2C-OVERSIZE-DST-"),e)));let{outputLen:n,blockLen:o}=r,i=Math.ceil(t/n);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=oe(e,$s(e.length,1)),l=new Uint8Array(o),u=$s(t,2),p=new Array(i),m=r(oe(l,s,u,$s(0,1),a));p[0]=r(oe(m,$s(1,1),a));for(let w=1;w<i;w++){let h=[Pf(m,p[w-1]),$s(w+1,1),a];p[w]=r(oe(...h))}return oe(...p).slice(0,t)}var gc="HashToScalar-";var Bf=BigInt(0),it=BigInt(1),bc=BigInt(2);var Lf=BigInt(5),Rf=BigInt(8),ds=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Io={p:ds,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Rf,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Cf(s){let e=BigInt(10),t=BigInt(20),r=BigInt(40),n=BigInt(80),o=ds,a=s*s%o*s%o,l=$(a,bc,o)*a%o,u=$(l,it,o)*s%o,p=$(u,Lf,o)*u%o,m=$(p,e,o)*p%o,E=$(m,t,o)*m%o,w=$(E,r,o)*E%o,h=$(w,n,o)*w%o,g=$(h,n,o)*w%o,b=$(g,e,o)*p%o;return{pow_p_5_8:$(b,bc,o)*s%o,b2:a}}function Ff(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}var Eo=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function To(s,e){let t=ds,r=re(e*e*e,t),n=re(r*r*e,t),o=Cf(s*n).pow_p_5_8,i=re(s*r*o,t),a=re(e*i*i,t),l=i,u=re(i*Eo,t),p=a===s,m=a===re(-s,t),E=a===re(-s*Eo,t);return p&&(i=l),(m||E)&&(i=u),ot(i,t)&&(i=re(-i,t)),{isValid:p||m,value:i}}var wt=pc(Io,{uvRatio:To}),yt=wt.Fp,xc=wt.Fn;function Nf(s){return mc(wt,Er,Object.assign({adjustScalarBytes:Ff,zip215:!0},s))}var vc=Nf({});var So=Eo,Of=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Uf=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Kf=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),zf=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),yc=s=>To(it,s),Hf=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),_o=s=>yt.create($e(s)&Hf);function wc(s){let{d:e}=Io,t=ds,r=x=>yt.create(x),n=r(So*s*s),o=r((n+it)*Kf),i=BigInt(-1),a=r((i-e*n)*r(n+e)),{isValid:l,value:u}=To(o,a),p=r(u*s);ot(p,t)||(p=r(-p)),l||(u=p),l||(i=n);let m=r(i*(n-it)*zf-a),E=u*u,w=r((u+u)*a),h=r(m*Of),g=r(it-E),b=r(it+E);return new wt(r(w*b),r(g*h),r(h*b),r(w*g))}var xt=class s extends kr{static BASE=new s(wt.BASE);static ZERO=new s(wt.ZERO);static Fp=yt;static Fn=xc;constructor(e){super(e)}static fromAffine(e){return new s(wt.fromAffine(e))}assertSame(e){if(!(e instanceof s))throw new Error("RistrettoPoint expected")}init(e){return new s(e)}static fromBytes(e){De(e,32);let{a:t,d:r}=Io,n=ds,o=f=>yt.create(f),i=_o(e);if(!Za(yt.toBytes(i),e)||ot(i,n))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),l=o(it+t*a),u=o(it-t*a),p=o(l*l),m=o(u*u),E=o(t*r*p-m),{isValid:w,value:h}=yc(o(E*m)),g=o(h*u),b=o(h*g*E),x=o((i+i)*g);ot(x,n)&&(x=o(-x));let _=o(l*b),c=o(x*_);if(!w||ot(c,n)||_===Bf)throw new Error("invalid ristretto255 encoding 2");return new s(new wt(x,_,it,c))}static fromHex(e){return s.fromBytes(Ns(e))}toBytes(){let{X:e,Y:t,Z:r,T:n}=this.ep,o=ds,i=b=>yt.create(b),a=i(i(r+t)*i(r-t)),l=i(e*t),u=i(l*l),{value:p}=yc(i(a*u)),m=i(p*a),E=i(p*l),w=i(m*E*n),h;if(ot(n*w,o)){let b=i(t*So),x=i(e*So);e=b,t=x,h=i(m*Uf)}else h=E;ot(e*w,o)&&(t=i(-t));let g=i((r-t)*h);return ot(g,o)&&(g=i(-g)),yt.toBytes(g)}equals(e){this.assertSame(e);let{X:t,Y:r}=this.ep,{X:n,Y:o}=e.ep,i=u=>yt.create(u),a=i(t*o)===i(r*n),l=i(r*o)===i(t*n);return a||l}is0(){return this.equals(s.ZERO)}};Object.freeze(xt.BASE);Object.freeze(xt.ZERO);Object.freeze(xt.prototype);Object.freeze(xt);var Gf=Object.freeze({Point:xt,hashToCurve(s,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,r=vo(s,t,64,Er);return Gf.deriveToCurve(r)},hashToScalar(s,e={DST:gc}){let t=vo(s,e.DST,64,Er);return xc.create($e(t))},deriveToCurve(s){De(s,64);let e=_o(s.subarray(0,32)),t=wc(e),r=_o(s.subarray(32,64)),n=wc(r);return new xt(t.add(n))}});var js=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Br=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var ke={get(s=globalThis){let e=s.crypto;if(e?.subtle==null)throw new Br("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 Lr=32;var Do,qf=(async()=>{try{return await ke.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Vf(s,e,t){if(s.buffer instanceof ArrayBuffer){let r=await ke.get().subtle.importKey("raw",s.buffer,{name:"Ed25519"},!1,["verify"]);return await ke.get().subtle.verify({name:"Ed25519"},r,Ge(e),Ge(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Wf(s,e,t){return vc.verify(e,t instanceof Uint8Array?t:t.subarray(),s)}async function Ec(s,e,t){return Do==null&&(Do=await qf),Do?Vf(s,e,t):Wf(s,e,t)}function $f(s){return s?.buffer instanceof ArrayBuffer}function _c(s){if($f(s))return s;let e=s.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Rr(s,e){e==null&&(e=s.reduce((n,o)=>n+o.length,0));let t=pr(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return _c(t)}function Cr(s){return s==null?!1:typeof s.then=="function"&&typeof s.catch=="function"&&typeof s.finally=="function"}var Fr=class{type="Ed25519";raw;constructor(e){this.raw=Ao(e,Lr)}toMultihash(){return Le.digest(Ve(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();let n=Ec(this.raw,t,e);return Cr(n)?n.then(o=>(r?.signal?.throwIfAborted(),o)):n}};function Mo(s){return s=Ao(s,Lr),new Fr(s)}function Ao(s,e){if(s=Uint8Array.from(s??[]),s.length!==e)throw new X(`Key must be a Uint8Array of length ${e}, got ${s.length}`);return s}function Ic(s=0){return new Uint8Array(s)}var Zf=Math.pow(2,7),Yf=Math.pow(2,14),Xf=Math.pow(2,21),Po=Math.pow(2,28),ko=Math.pow(2,35),Bo=Math.pow(2,42),Lo=Math.pow(2,49),H=128,de=127;function Be(s){if(s<Zf)return 1;if(s<Yf)return 2;if(s<Xf)return 3;if(s<Po)return 4;if(s<ko)return 5;if(s<Bo)return 6;if(s<Lo)return 7;if(Number.MAX_SAFE_INTEGER!=null&&s>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ro(s,e,t=0){switch(Be(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 Jf(s,e,t=0){switch(Be(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 Co(s,e){let t=s[e],r=0;if(r+=t&de,t<H||(t=s[e+1],r+=(t&de)<<7,t<H)||(t=s[e+2],r+=(t&de)<<14,t<H)||(t=s[e+3],r+=(t&de)<<21,t<H)||(t=s[e+4],r+=(t&de)*Po,t<H)||(t=s[e+5],r+=(t&de)*ko,t<H)||(t=s[e+6],r+=(t&de)*Bo,t<H)||(t=s[e+7],r+=(t&de)*Lo,t<H))return r;throw new RangeError("Could not decode varint")}function Qf(s,e){let t=s.get(e),r=0;if(r+=t&de,t<H||(t=s.get(e+1),r+=(t&de)<<7,t<H)||(t=s.get(e+2),r+=(t&de)<<14,t<H)||(t=s.get(e+3),r+=(t&de)<<21,t<H)||(t=s.get(e+4),r+=(t&de)*Po,t<H)||(t=s.get(e+5),r+=(t&de)*ko,t<H)||(t=s.get(e+6),r+=(t&de)*Bo,t<H)||(t=s.get(e+7),r+=(t&de)*Lo,t<H))return r;throw new RangeError("Could not decode varint")}function Fo(s,e,t=0){return e==null&&(e=Ic(Be(s))),e instanceof Uint8Array?Ro(s,e,t):Jf(s,e,t)}function No(s,e=0){return s instanceof Uint8Array?Co(s,e):Qf(s,e)}var Uo=new Float32Array([-0]),vt=new Uint8Array(Uo.buffer);function Tc(s,e,t){Uo[0]=s,e[t]=vt[0],e[t+1]=vt[1],e[t+2]=vt[2],e[t+3]=vt[3]}function Dc(s,e){return vt[0]=s[e],vt[1]=s[e+1],vt[2]=s[e+2],vt[3]=s[e+3],Uo[0]}var Ko=new Float64Array([-0]),pe=new Uint8Array(Ko.buffer);function Ac(s,e,t){Ko[0]=s,e[t]=pe[0],e[t+1]=pe[1],e[t+2]=pe[2],e[t+3]=pe[3],e[t+4]=pe[4],e[t+5]=pe[5],e[t+6]=pe[6],e[t+7]=pe[7]}function Mc(s,e){return pe[0]=s[e],pe[1]=s[e+1],pe[2]=s[e+2],pe[3]=s[e+3],pe[4]=s[e+4],pe[5]=s[e+5],pe[6]=s[e+6],pe[7]=s[e+7],Ko[0]}var ed=BigInt(Number.MAX_SAFE_INTEGER),td=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 Rt;if(e<ed&&e>td)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>Pc&&(n=0n,++r>Pc&&(r=0n))),new s(Number(n),Number(r))}static fromNumber(e){if(e===0)return Rt;let t=e<0;t&&(e=-e);let r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new s(r,n)}static from(e){return typeof e=="number"?s.fromNumber(e):typeof e=="bigint"?s.fromBigInt(e):typeof e=="string"?s.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new s(e.low>>>0,e.high>>>0):Rt}},Rt=new Ae(0,0);Rt.toBigInt=function(){return 0n};Rt.zzEncode=Rt.zzDecode=function(){return this};Rt.length=function(){return 1};var Pc=4294967296n;function kc(s){let e=0,t=0;for(let r=0;r<s.length;++r)t=s.charCodeAt(r),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(s.charCodeAt(r+1)&64512)===56320?(++r,e+=4):e+=3;return e}function Bc(s,e,t){if(t-e<1)return"";let n,o=[],i=0,a;for(;e<t;)a=s[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(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,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(s[e++]&63)<<6|s[e++]&63,i>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,o)),i=0);return n!=null?(i>0&&n.push(String.fromCharCode.apply(String,o.slice(0,i))),n.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function zo(s,e,t){let r=t,n,o;for(let i=0;i<s.length;++i)n=s.charCodeAt(i),n<128?e[t++]=n:n<2048?(e[t++]=n>>6|192,e[t++]=n&63|128):(n&64512)===55296&&((o=s.charCodeAt(i+1))&64512)===56320?(n=65536+((n&1023)<<10)+(o&1023),++i,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 Oe(s,e){return RangeError(`index out of range: ${s.pos} + ${e??1} > ${s.len}`)}function Nr(s,e){return(s[e-4]|s[e-3]<<8|s[e-2]<<16|s[e-1]<<24)>>>0}var Ho=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,Oe(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 Oe(this,4);return Nr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Oe(this,4);return Nr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Oe(this,4);let e=Dc(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Oe(this,4);let e=Mc(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 Oe(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){let e=this.bytes();return Bc(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Oe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Oe(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 Oe(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 Oe(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 Oe(this,8);let e=Nr(this.buf,this.pos+=4),t=Nr(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=Co(this.buf,this.pos);return this.pos+=Be(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 Zs(s){return new Ho(s instanceof Uint8Array?s:s.subarray())}function ye(s,e,t){let r=Zs(s);return e.decode(r,void 0,t)}function Ct(s=0){return new Uint8Array(s)}var Go={};V(Go,{base10:()=>sd});var sd=lt({prefix:"9",name:"base10",alphabet:"0123456789"});var qo={};V(qo,{base16:()=>rd,base16upper:()=>nd});var rd=J({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),nd=J({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Vo={};V(Vo,{base2:()=>od});var od=J({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Wo={};V(Wo,{base256emoji:()=>ud});var Rc=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}"),id=Rc.reduce((s,e,t)=>(s[t]=e,s),[]),ad=Rc.reduce((s,e,t)=>{let r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return s[r]=t,s},[]);function cd(s){return s.reduce((e,t)=>(e+=id[t],e),"")}function ld(s){let e=[];for(let t of s){let r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);let n=ad[r];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var ud=Wt({prefix:"\u{1F680}",name:"base256emoji",encode:cd,decode:ld});var $o={};V($o,{base64:()=>hd,base64pad:()=>fd,base64url:()=>dd,base64urlpad:()=>pd});var hd=J({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),fd=J({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),dd=J({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),pd=J({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var jo={};V(jo,{base8:()=>md});var md=J({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Zo={};V(Zo,{identity:()=>gd});var gd=Wt({prefix:"\0",name:"identity",encode:s=>Wi(s),decode:s=>Vi(s)});var U0=new TextEncoder,K0=new TextDecoder;var Jo={};V(Jo,{sha256:()=>Ft,sha512:()=>xd});var wd=20;function Xo({name:s,code:e,encode:t,minDigestLength:r,maxDigestLength:n}){return new Yo(s,e,t,r,n)}var Yo=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,r,n,o){this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??wd,this.maxDigestLength=o}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?Cc(r,this.code,t?.truncate):r.then(n=>Cc(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Cc(s,e,t){if(t!=null&&t!==s.byteLength){if(t>s.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${s.byteLength}`);s=s.subarray(0,t)}return He(e,s)}function Nc(s){return async e=>new Uint8Array(await crypto.subtle.digest(s,e))}var Ft=Xo({name:"sha2-256",code:18,encode:Nc("SHA-256")}),xd=Xo({name:"sha2-512",code:19,encode:Nc("SHA-512")});var Qo={...Zo,...Vo,...jo,...Go,...qo,...yn,...wn,...bn,...$o,...Wo},J0={...Jo,...En};function Uc(s,e,t,r){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:r}}}var Oc=Uc("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),ei=Uc("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=Ct(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),vd={utf8:Oc,"utf-8":Oc,hex:Qo.base16,latin1:ei,ascii:ei,binary:ei,...Qo},Kc=vd;function zc(s,e="utf8"){let t=Kc[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${s}`)}function ti(s){let e=s??8192,t=e>>>1,r,n=e;return function(i){if(i<1||i>t)return Ct(i);n+i>e&&(r=Ct(e),n=0);let a=r.subarray(n,n+=i);return(n&7)!==0&&(n=(n|7)+1),a}}var Nt=class{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}};function si(){}var ni=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Ed=ti();function Sd(s){return globalThis.Buffer!=null?Ct(s):Ed(s)}var Xs=class{len;head;tail;states;constructor(){this.len=0,this.head=new Nt(si,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new Nt(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new oi((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(Or,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(Or,t.length(),t)}uint64Number(e){return this._push(Ro,Be(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(Or,t.length(),t)}sint64Number(e){let t=Ae.fromNumber(e).zzEncode();return this._push(Or,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(ri,1,e?1:0)}fixed32(e){return this._push(Ys,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ae.fromBigInt(e);return this._push(Ys,4,t.lo)._push(Ys,4,t.hi)}fixed64Number(e){let t=Ae.fromNumber(e);return this._push(Ys,4,t.lo)._push(Ys,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(Tc,4,e)}double(e){return this._push(Ac,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(ri,1,0):this.uint32(t)._push(Id,t,e)}string(e){let t=kc(e);return t!==0?this.uint32(t)._push(zo,t,e):this._push(ri,1,0)}fork(){return this.states=new ni(this),this.head=this.tail=new Nt(si,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 Nt(si,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=Sd(this.len),r=0;for(;e!=null;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}};function ri(s,e,t){e[t]=s&255}function _d(s,e,t){for(;s>127;)e[t++]=s&127|128,s>>>=7;e[t]=s}var oi=class extends Nt{next;constructor(e,t){super(_d,e,t),this.next=void 0}};function Or(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 Ys(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 Id(s,e,t){e.set(s,t)}globalThis.Buffer!=null&&(Xs.prototype.bytes=function(s){let e=s.length>>>0;return this.uint32(e),e>0&&this._push(Td,e,s),this},Xs.prototype.string=function(s){let e=globalThis.Buffer.byteLength(s);return this.uint32(e),e>0&&this._push(Dd,e,s),this});function Td(s,e,t){e.set(s,t)}function Dd(s,e,t){s.length<40?zo(s,e,t):e.utf8Write!=null?e.utf8Write(s,t):e.set(zc(s),t)}function ii(){return new Xs}function we(s,e){let t=ii();return e.encode(s,t,{lengthDelimited:!1}),t.finish()}function*xe(s,e,t){let r=Zs(s);yield*e.stream(r,void 0,"$",t)}var Ur={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Kr(s,e,t,r,n){return{name:s,type:e,encode:t,decode:r,stream:n}}function ai(s){function e(o){if(s[o.toString()]==null)throw new Error("Invalid enum value");return s[o]}let t=function(i,a){let l=e(i);a.int32(l)},r=function(i){let a=i.int32();return e(a)},n=function*(i){let a=i.int32();yield e(a)};return Kr("enum",Ur.VARINT,t,r,n)}function ve(s,e,t){return Kr("message",Ur.LENGTH_DELIMITED,s,e,t)}var W=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var Z;(function(s){s.RSA="RSA",s.Ed25519="Ed25519",s.secp256k1="secp256k1",s.ECDSA="ECDSA"})(Z||(Z={}));var ci;(function(s){s[s.RSA=0]="RSA",s[s.Ed25519=1]="Ed25519",s[s.secp256k1=2]="secp256k1",s[s.ECDSA=3]="ECDSA"})(ci||(ci={}));(function(s){s.codec=()=>ai(ci)})(Z||(Z={}));var je;(function(s){let e;s.codec=()=>(e==null&&(e=ve((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),Z.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let l={},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let p=o.uint32();switch(p>>>3){case 1:{l.Type=Z.codec().decode(o);break}case 2:{l.Data=o.bytes();break}default:{o.skipType(p&7);break}}}return l},function*(o,i,a,l={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let p=o.uint32();switch(p>>>3){case 1:{yield{field:`${a}.Type`,value:Z.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(p&7);break}}}})),e);function t(o){return we(o,s.codec())}s.encode=t;function r(o,i){return ye(o,s.codec(),i)}s.decode=r;function n(o,i){return xe(o,s.codec(),i)}s.stream=n})(je||(je={}));var li;(function(s){let e;s.codec=()=>(e==null&&(e=ve((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),Z.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let l={},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let p=o.uint32();switch(p>>>3){case 1:{l.Type=Z.codec().decode(o);break}case 2:{l.Data=o.bytes();break}default:{o.skipType(p&7);break}}}return l},function*(o,i,a,l={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let p=o.uint32();switch(p>>>3){case 1:{yield{field:`${a}.Type`,value:Z.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(p&7);break}}}})),e);function t(o){return we(o,s.codec())}s.encode=t;function r(o,i){return ye(o,s.codec(),i)}s.decode=r;function n(o,i){return xe(o,s.codec(),i)}s.stream=n})(li||(li={}));var Qs={};V(Qs,{MAX_RSA_KEY_SIZE:()=>ui,generateRSAKeyPair:()=>Wc,jwkToJWKKeyPair:()=>$c,jwkToPkcs1:()=>kd,jwkToPkix:()=>pi,jwkToRSAPrivateKey:()=>yi,pkcs1MessageToJwk:()=>fi,pkcs1MessageToRSAPrivateKey:()=>mi,pkcs1ToJwk:()=>Pd,pkcs1ToRSAPrivateKey:()=>Vc,pkixMessageToJwk:()=>di,pkixMessageToRSAPublicKey:()=>bi,pkixToJwk:()=>Bd,pkixToRSAPublicKey:()=>gi});var ps=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Qs.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ue.createV1(114,this._multihash)}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}verify(e,t,r){return qc(this.jwk,t,e,r)}},Js=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Qs.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}sign(e,t){return Gc(this.jwk,e,t)}};var ui=8192,hi=18,Ad=1062,Md=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Pd(s){let e=tt(s);return fi(e)}function fi(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 kd(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 X("JWK was missing components");return ft([Te(Uint8Array.from([0])),Te(j(s.n,"base64url")),Te(j(s.e,"base64url")),Te(j(s.d,"base64url")),Te(j(s.p,"base64url")),Te(j(s.q,"base64url")),Te(j(s.dp,"base64url")),Te(j(s.dq,"base64url")),Te(j(s.qi,"base64url"))]).subarray()}function Bd(s){let e=tt(s,{offset:0});return di(e)}function di(s){let e=tt(s[1],{offset:0});return{kty:"RSA",n:q(e[0],"base64url"),e:q(e[1],"base64url")}}function pi(s){if(s.n==null||s.e==null)throw new X("JWK was missing components");return ft([Md,gr(ft([Te(j(s.n,"base64url")),Te(j(s.e,"base64url"))]))]).subarray()}function Vc(s){let e=tt(s);return mi(e)}function mi(s){let e=fi(s);return yi(e)}function gi(s,e){if(s.byteLength>=Ad)throw new qt("Key size is too large");let t=tt(s,{offset:0});return bi(t,s,e)}function bi(s,e,t){let r=di(s);if(t==null){let n=os(je.encode({Type:Z.RSA,Data:e}));t=He(hi,n)}return new ps(r,t)}function yi(s){if(Zc(s)>ui)throw new X("Key size is too large");let e=$c(s),t=os(je.encode({Type:Z.RSA,Data:pi(e.publicKey)})),r=He(hi,t);return new Js(e.privateKey,new ps(e.publicKey,r))}async function Wc(s){if(s>ui)throw new X("Key size is too large");let e=await jc(s),t=os(je.encode({Type:Z.RSA,Data:pi(e.publicKey)})),r=He(hi,t);return new Js(e.privateKey,new ps(e.publicKey,r))}function $c(s){if(s==null)throw new X("Missing key parameter");return{privateKey:s,publicKey:{kty:s.kty,n:s.n,e:s.e}}}async function jc(s,e){let t=await ke.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:s,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let r=await Ld(t,e);return{privateKey:r[0],publicKey:r[1]}}async function Gc(s,e,t){let r=await ke.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let n=await ke.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,Ge(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(n,0,n.byteLength)}async function qc(s,e,t,r){let n=await ke.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();let o=await ke.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,Ge(e),Ge(t instanceof Uint8Array?t:t.subarray()));return r?.signal?.throwIfAborted(),o}async function Ld(s,e){if(s.privateKey==null||s.publicKey==null)throw new X("Private and public key are required");let t=await Promise.all([ke.get().subtle.exportKey("jwk",s.privateKey),ke.get().subtle.exportKey("jwk",s.publicKey)]);return e?.signal?.throwIfAborted(),t}function Zc(s){if(s.kty!=="RSA")throw new X("invalid key type");if(s.n==null)throw new X("invalid key modulus");return j(s.n,"base64url").length*8}var zr=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(br(e),De(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 o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),rt(n)}update(e){return ns(this),this.iHash.update(e),this}digestInto(e){ns(this),yr(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:n,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,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()}},Yc=(()=>{let s=((e,t,r)=>new zr(e,t).update(r).digest());return s.create=(e,t)=>new zr(e,t),s})();var Xc=(s,e)=>(s+(s>=0?e:-e)/Jc)/e;function Rd(s,e,t){cs("scalar",s,Ze,t);let[[r,n],[o,i]]=e,a=Xc(i*s,t),l=Xc(-n*s,t),u=s-a*r-l*o,p=-a*n-l*i,m=u<Ze,E=p<Ze;m&&(u=-u),E&&(p=-p);let w=qs(Math.ceil(ls(t)/2))+Et;if(u<Ze||u>=w||p<Ze||p>=w)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:m,k1:u,k2neg:E,k2:p}}function xi(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function wi(s,e){Ne(s);let t={};for(let r of Object.keys(e))t[r]=s[r]===void 0?e[r]:s[r];return Ce(t.lowS,"lowS"),Ce(t.prehash,"prehash"),t.format!==void 0&&xi(t.format),t}var vi=class extends Error{constructor(e=""){super(e)}},Ue={Err:vi,_tlv:{encode:(s,e)=>{let{Err:t}=Ue;if(Fe(s,"tag"),s<0||s>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let r=e.length/2,n=Hs(r);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let o=r>127?Hs(n.length/2|128):"";return Hs(s)+o+n+e},decode(s,e){let{Err:t}=Ue;e=K(e,void 0,"DER data");let r=0;if(s<0||s>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[r++]!==s)throw new t("tlv.decode: wrong tlv");let n=e[r++],o=!!(n&128),i=0;if(!o)i=n;else{let l=n&127;if(!l)throw new t("tlv.decode(long): indefinite length not supported");if(l>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(r,r+l);if(u.length!==l)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let p of u)i=i<<8|p;if(r+=l,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+i)}}},_int:{encode(s){let{Err:e}=Ue;if(Ir(s),s<Ze)throw new e("integer: negative integers are not allowed");let t=Hs(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}=Ue;if(s.length<1)throw new e("invalid signature integer: empty");if(s[0]&128)throw new e("invalid signature integer: negative");if(s.length>1&&s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Pt(s)}},toSig(s){let{Err:e,_int:t,_tlv:r}=Ue,n=K(s,void 0,"signature"),{v:o,l:i}=r.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l}=r.decode(2,o),{v:u,l:p}=r.decode(2,l);if(p.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(s){let{_tlv:e,_int:t}=Ue,r=e.encode(2,t.encode(s.r)),n=e.encode(2,t.encode(s.s)),o=r+n;return e.encode(48,o)}};Object.freeze(Ue._tlv);Object.freeze(Ue._int);Object.freeze(Ue);var Ze=BigInt(0),Et=BigInt(1),Jc=BigInt(2),Hr=BigInt(3),Cd=BigInt(4);function Qc(s,e={}){let t=Mr("weierstrass",s,e),r=t.Fp,n=t.Fn,o=t.CURVE,{h:i,n:a}=o;Ne(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:l,allowInfinityPoint:u}=e;if(l&&(!r.is0(o.a)||typeof l.beta!="bigint"||!Array.isArray(l.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let p=tl(r,n);function m(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function E(N,I,T){if(u&&I.is0())return Uint8Array.of(0);let{x:P,y:A}=I.toAffine(),D=r.toBytes(P);if(Ce(T,"isCompressed"),T){m();let k=!r.isOdd(A);return oe(el(k),D)}else return oe(Uint8Array.of(4),D,r.toBytes(A))}function w(N){K(N,void 0,"Point");let{publicKey:I,publicKeyUncompressed:T}=p,P=N.length,A=N[0],D=N.subarray(1);if(u&&P===1&&A===0)return{x:r.ZERO,y:r.ZERO};if(P===I&&(A===2||A===3)){let k=r.fromBytes(D);if(!r.isValid(k))throw new Error("bad point: is not on curve, wrong x");let L=b(k),B;try{B=r.sqrt(L)}catch(U){let z=U instanceof Error?": "+U.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}m();let R=r.isOdd(B);return(A&1)===1!==R&&(B=r.neg(B)),{x:k,y:B}}else if(P===T&&A===4){let k=r.BYTES,L=r.fromBytes(D.subarray(0,k)),B=r.fromBytes(D.subarray(k,k*2));if(!x(L,B))throw new Error("bad point: is not on curve");return{x:L,y:B}}else throw new Error(`bad point: got length ${P}, expected compressed=${I} or uncompressed=${T}`)}let h=e.toBytes===void 0?E:e.toBytes,g=e.fromBytes===void 0?w:e.fromBytes;function b(N){let I=r.sqr(N),T=r.mul(I,N);return r.add(r.add(T,r.mul(N,o.a)),o.b)}function x(N,I){let T=r.sqr(I),P=b(N);return r.eql(T,P)}if(!x(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let _=r.mul(r.pow(o.a,Hr),Cd),c=r.mul(r.sqr(o.b),BigInt(27));if(r.is0(r.add(_,c)))throw new Error("bad curve params: a or b");function f(N,I,T=!1){if(!r.isValid(I)||T&&r.is0(I))throw new Error(`bad point coordinate ${N}`);return I}function d(N){if(!(N instanceof S))throw new Error("Weierstrass Point expected")}function y(N){if(!l||!l.basises)throw new Error("no endo");return Rd(N,l.basises,n.ORDER)}function v(N,I,T,P,A){return T=new S(r.mul(T.X,N),T.Y,T.Z),I=Ws(P,I),T=Ws(A,T),I.add(T)}class S{static BASE=new S(o.Gx,o.Gy,r.ONE);static ZERO=new S(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=n;X;Y;Z;constructor(I,T,P){this.X=f("x",I),this.Y=f("y",T,!0),this.Z=f("z",P),Object.freeze(this)}static CURVE(){return o}static fromAffine(I){let{x:T,y:P}=I||{};if(!I||!r.isValid(T)||!r.isValid(P))throw new Error("invalid affine point");if(I instanceof S)throw new Error("projective point not allowed");return r.is0(T)&&r.is0(P)?S.ZERO:new S(T,P,r.ONE)}static fromBytes(I){let T=S.fromAffine(g(K(I,void 0,"point")));return T.assertValidity(),T}static fromHex(I){return S.fromBytes(as(I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,T=!0){return C.createCache(this,I),T||this.multiply(Hr),this}assertValidity(){let I=this;if(I.is0()){if(e.allowInfinityPoint&&r.is0(I.X)&&r.eql(I.Y,r.ONE)&&r.is0(I.Z))return;throw new Error("bad point: ZERO")}let{x:T,y:P}=I.toAffine();if(!r.isValid(T)||!r.isValid(P))throw new Error("bad point: x or y not field elements");if(!x(T,P))throw new Error("bad point: equation left != right");if(!I.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:I}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(I)}equals(I){d(I);let{X:T,Y:P,Z:A}=this,{X:D,Y:k,Z:L}=I,B=r.eql(r.mul(T,L),r.mul(D,A)),R=r.eql(r.mul(P,L),r.mul(k,A));return B&&R}negate(){return new S(this.X,r.neg(this.Y),this.Z)}double(){let{a:I,b:T}=o,P=r.mul(T,Hr),{X:A,Y:D,Z:k}=this,L=r.ZERO,B=r.ZERO,R=r.ZERO,F=r.mul(A,A),U=r.mul(D,D),z=r.mul(k,k),O=r.mul(A,D);return O=r.add(O,O),R=r.mul(A,k),R=r.add(R,R),L=r.mul(I,R),B=r.mul(P,z),B=r.add(L,B),L=r.sub(U,B),B=r.add(U,B),B=r.mul(L,B),L=r.mul(O,L),R=r.mul(P,R),z=r.mul(I,z),O=r.sub(F,z),O=r.mul(I,O),O=r.add(O,R),R=r.add(F,F),F=r.add(R,F),F=r.add(F,z),F=r.mul(F,O),B=r.add(B,F),z=r.mul(D,k),z=r.add(z,z),F=r.mul(z,O),L=r.sub(L,F),R=r.mul(z,U),R=r.add(R,R),R=r.add(R,R),new S(L,B,R)}add(I){d(I);let{X:T,Y:P,Z:A}=this,{X:D,Y:k,Z:L}=I,B=r.ZERO,R=r.ZERO,F=r.ZERO,U=o.a,z=r.mul(o.b,Hr),O=r.mul(T,D),ne=r.mul(P,k),ie=r.mul(A,L),ae=r.add(T,P),se=r.add(D,k);ae=r.mul(ae,se),se=r.add(O,ne),ae=r.sub(ae,se),se=r.add(T,A);let Ie=r.add(D,L);return se=r.mul(se,Ie),Ie=r.add(O,ie),se=r.sub(se,Ie),Ie=r.add(P,A),B=r.add(k,L),Ie=r.mul(Ie,B),B=r.add(ne,ie),Ie=r.sub(Ie,B),F=r.mul(U,se),B=r.mul(z,ie),F=r.add(B,F),B=r.sub(ne,F),F=r.add(ne,F),R=r.mul(B,F),ne=r.add(O,O),ne=r.add(ne,O),ie=r.mul(U,ie),se=r.mul(z,se),ne=r.add(ne,ie),ie=r.sub(O,ie),ie=r.mul(U,ie),se=r.add(se,ie),O=r.mul(ne,se),R=r.add(R,O),O=r.mul(Ie,se),B=r.mul(ae,B),B=r.sub(B,O),O=r.mul(ae,ne),F=r.mul(Ie,F),F=r.add(F,O),new S(B,R,F)}subtract(I){return d(I),this.add(I.negate())}is0(){return this.equals(S.ZERO)}multiply(I){let{endo:T}=e;if(!n.isValidNot0(I))throw new RangeError("invalid scalar: out of range");let P,A,D=k=>C.cached(this,k,L=>Lt(S,L));if(T){let{k1neg:k,k1:L,k2neg:B,k2:R}=y(I),{p:F,f:U}=D(L),{p:z,f:O}=D(R);A=U.add(O),P=v(T.beta,F,z,k,B)}else{let{p:k,f:L}=D(I);P=k,A=L}return Lt(S,[P,A])[0]}multiplyUnsafe(I){let{endo:T}=e,P=this,A=I;if(!n.isValid(A))throw new RangeError("invalid scalar: out of range");if(A===Ze||P.is0())return S.ZERO;if(A===Et)return P;if(C.hasCache(this))return this.multiply(A);if(T){let{k1neg:D,k1:k,k2neg:L,k2:B}=y(A),{p1:R,p2:F}=dc(S,P,k,B);return v(T.beta,R,F,D,L)}else return C.unsafe(P,A)}toAffine(I){let T=this,P=I,{X:A,Y:D,Z:k}=T;if(r.eql(k,r.ONE))return{x:A,y:D};let L=T.is0();P==null&&(P=L?r.ONE:r.inv(k));let B=r.mul(A,P),R=r.mul(D,P),F=r.mul(k,P);if(L)return{x:r.ZERO,y:r.ZERO};if(!r.eql(F,r.ONE))throw new Error("invZ was invalid");return{x:B,y:R}}isTorsionFree(){let{isTorsionFree:I}=e;return i===Et?!0:I?I(S,this):C.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:I}=e;return i===Et?this:I?I(S,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Et?this.is0():this.clearCofactor().is0()}toBytes(I=!0){return Ce(I,"isCompressed"),this.assertValidity(),h(S,this,I)}toHex(I=!0){return is(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let M=n.BITS,C=new fs(S,e.endo?Math.ceil(M/2):M);return M>=8&&S.BASE.precompute(8),Object.freeze(S.prototype),Object.freeze(S),S}function el(s){return Uint8Array.of(s?2:3)}function tl(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Fd(s,e={}){let{Fn:t}=s,r=e.randomBytes===void 0?zs:e.randomBytes,n=Object.assign(tl(s.Fp,t),{seed:Math.max(mo(t.ORDER),16)});function o(w){try{let h=t.fromBytes(w);return t.isValidNot0(h)}catch{return!1}}function i(w,h){let{publicKey:g,publicKeyUncompressed:b}=n;try{let x=w.length;return h===!0&&x!==g||h===!1&&x!==b?!1:!!s.fromBytes(w)}catch{return!1}}function a(w){return w=w===void 0?r(n.seed):w,go(K(w,n.seed,"seed"),t.ORDER)}function l(w,h=!0){return s.BASE.multiply(t.fromBytes(w)).toBytes(h)}function u(w){let{secretKey:h,publicKey:g,publicKeyUncompressed:b}=n,x=t._lengths;if(!Mt(w))return;let _=K(w,void 0,"key").length,c=_===g||_===b,f=_===h||!!x?.includes(_);if(!(c&&f))return c}function p(w,h,g=!0){if(u(w)===!0)throw new Error("first arg must be private key");if(u(h)===!1)throw new Error("second arg must be public key");let b=t.fromBytes(w);return s.fromBytes(h).multiply(b).toBytes(g)}let m={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},E=Pr(a,l);return Object.freeze(m),Object.freeze(n),Object.freeze({getPublicKey:l,getSharedSecret:p,keygen:E,Point:s,utils:m,lengths:n})}function sl(s,e,t={}){let r=e;br(r),Ne(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes===void 0?zs:t.randomBytes,o=t.hmac===void 0?(A,D)=>Yc(r,A,D):t.hmac,{Fp:i,Fn:a}=s,{ORDER:l,BITS:u}=a,{keygen:p,getPublicKey:m,getSharedSecret:E,utils:w,lengths:h}=Fd(s,t),g={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},b=l*Jc+Et<i.ORDER;function x(A){let D=l>>Et;return A>D}function _(A,D){if(!a.isValidNot0(D))throw new Error(`invalid signature ${A}: out of range 1..Point.Fn.ORDER`);return D}function c(){if(b)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function f(A,D){xi(D);let k=h.signature,L=D==="compact"?k:D==="recovered"?k+1:void 0;return K(A,L)}class d{r;s;recovery;constructor(D,k,L){if(this.r=_("r",D),this.s=_("s",k),L!=null){if(c(),![0,1,2,3].includes(L))throw new Error("invalid recovery id");this.recovery=L}Object.freeze(this)}static fromBytes(D,k=g.format){f(D,k);let L;if(k==="der"){let{r:U,s:z}=Ue.toSig(K(D));return new d(U,z)}k==="recovered"&&(L=D[0],k="compact",D=D.subarray(1));let B=h.signature/2,R=D.subarray(0,B),F=D.subarray(B,B*2);return new d(a.fromBytes(R),a.fromBytes(F),L)}static fromHex(D,k){return this.fromBytes(as(D),k)}assertRecovery(){let{recovery:D}=this;if(D==null)throw new Error("invalid recovery id: must be present");return D}addRecoveryBit(D){return new d(this.r,this.s,D)}recoverPublicKey(D){let{r:k,s:L}=this,B=this.assertRecovery(),R=B===2||B===3?k+l:k;if(!i.isValid(R))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let F=i.toBytes(R),U=s.fromBytes(oe(el((B&1)===0),F)),z=a.inv(R),O=v(K(D,void 0,"msgHash")),ne=a.create(-O*z),ie=a.create(L*z),ae=s.BASE.multiplyUnsafe(ne).add(U.multiplyUnsafe(ie));if(ae.is0())throw new Error("invalid recovery: point at infinify");return ae.assertValidity(),ae}hasHighS(){return x(this.s)}toBytes(D=g.format){if(xi(D),D==="der")return as(Ue.hexFromSig(this));let{r:k,s:L}=this,B=a.toBytes(k),R=a.toBytes(L);return D==="recovered"?(c(),oe(Uint8Array.of(this.assertRecovery()),B,R)):oe(B,R)}toHex(D){return is(this.toBytes(D))}}Object.freeze(d.prototype),Object.freeze(d);let y=t.bits2int===void 0?function(D){if(D.length>8192)throw new Error("input is too large");let k=Pt(D),L=D.length*8-u;return L>0?k>>BigInt(L):k}:t.bits2int,v=t.bits2int_modN===void 0?function(D){return a.create(y(D))}:t.bits2int_modN,S=qs(u);function M(A){return cs("num < 2^"+u,A,Ze,S),a.toBytes(A)}function C(A,D){return K(A,void 0,"message"),D?K(r(A),void 0,"prehashed message"):A}function N(A,D,k){let{lowS:L,prehash:B,extraEntropy:R}=wi(k,g);A=C(A,B);let F=v(A),U=a.fromBytes(D);if(!a.isValidNot0(U))throw new Error("invalid private key");let z=[M(U),M(F)];if(R!=null&&R!==!1){let ae=R===!0?n(h.secretKey):R;z.push(K(ae,void 0,"extraEntropy"))}let O=oe(...z),ne=F;function ie(ae){let se=y(ae);if(!a.isValidNot0(se))return;let Ie=a.inv(se),Ht=s.BASE.multiply(se).toAffine(),_s=a.create(Ht.x);if(_s===Ze)return;let or=a.create(Ie*a.create(ne+_s*U));if(or===Ze)return;let Ci=(Ht.x===_s?0:2)|Number(Ht.y&Et),Fi=or;return L&&x(or)&&(Fi=a.neg(or),Ci^=1),new d(_s,Fi,b?void 0:Ci)}return{seed:O,k2sig:ie}}function I(A,D,k={}){let{seed:L,k2sig:B}=N(A,D,k);return Ya(r.outputLen,a.BYTES,o)(L,B).toBytes(k.format)}function T(A,D,k,L={}){let{lowS:B,prehash:R,format:F}=wi(L,g);if(k=K(k,void 0,"publicKey"),D=C(D,R),!Mt(A)){let U=A instanceof d?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+U)}f(A,F);try{let U=d.fromBytes(A,F),z=s.fromBytes(k);if(B&&U.hasHighS())return!1;let{r:O,s:ne}=U,ie=v(D),ae=a.inv(ne),se=a.create(ie*ae),Ie=a.create(O*ae),Ht=s.BASE.multiplyUnsafe(se).add(z.multiplyUnsafe(Ie));return Ht.is0()?!1:a.create(Ht.x)===O}catch{return!1}}function P(A,D,k={}){let{prehash:L}=wi(k,g);return D=C(D,L),d.fromBytes(A,"recovered").recoverPublicKey(D).toBytes()}return Object.freeze({keygen:p,getPublicKey:m,getSharedSecret:E,utils:w,lengths:h,Point:s,sign:I,verify:T,recoverPublicKey:P,Signature:d,hash:r})}var Si={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Nd={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var rl=BigInt(2);function Od(s){let e=Si.p,t=BigInt(3),r=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),l=BigInt(88),u=s*s*s%e,p=u*u*s%e,m=$(p,t,e)*p%e,E=$(m,t,e)*p%e,w=$(E,rl,e)*u%e,h=$(w,n,e)*w%e,g=$(h,o,e)*h%e,b=$(g,a,e)*g%e,x=$(b,l,e)*b%e,_=$(x,a,e)*g%e,c=$(_,t,e)*p%e,f=$(c,i,e)*h%e,d=$(f,r,e)*u%e,y=$(d,rl,e);if(!Ei.eql(Ei.sqr(y),s))throw new Error("Cannot find square root");return y}var Ei=us(Si.p,{sqrt:Od}),Ud=Qc(Si,{Fp:Ei,endo:Nd}),ms=sl(Ud,os);function nl(s,e,t,r){let n=Ft.digest(t instanceof Uint8Array?t:t.subarray());if(Cr(n))return n.then(({digest:o})=>(r?.signal?.throwIfAborted(),ms.verify(e,o,s,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new js(String(o))});try{return r?.signal?.throwIfAborted(),ms.verify(e,n.digest,s,{prehash:!1,format:"der"})}catch(o){throw new js(String(o))}}var Gr=class{type="secp256k1";raw;_key;constructor(e){this._key=il(e),this.raw=ol(this._key)}toMultihash(){return Le.digest(Ve(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}verify(e,t,r){return nl(this._key,t,e,r)}};function _i(s){return new Gr(s)}function ol(s){return ms.Point.fromBytes(s).toBytes()}function il(s){try{return ms.Point.fromBytes(s),s}catch(e){throw new qt(String(e))}}function qr(s,e){let{Type:t,Data:r}=je.decode(s),n=r??new Uint8Array;switch(t){case Z.RSA:return gi(n,e);case Z.Ed25519:return Mo(n);case Z.secp256k1:return _i(n);case Z.ECDSA:return Xn(n);default:throw new Vt}}function al(s){let{Type:e,Data:t}=je.decode(s.digest),r=t??new Uint8Array;switch(e){case Z.Ed25519:return Mo(r);case Z.secp256k1:return _i(r);case Z.ECDSA:return Xn(r);default:throw new Vt}}function Ve(s){return je.encode({Type:Z[s.type],Data:s.raw})}var cl=Symbol.for("nodejs.util.inspect.custom"),Kd=114,er=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()})`}[fn]=!0;toString(){return this.string==null&&(this.string=Q.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ue.createV1(Kd,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Pe(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Pe(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[cl](){return`PeerId(${this.toString()})`}},Vr=class extends er{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Wr=class extends er{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},$r=class extends er{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},zd=2336,tr=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Le.digest(j(this.url))}[cl](){return`PeerId(${this.url})`}[fn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ue.createV1(zd,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=q(e)),e.toString()===this.toString())}};var Hd=114,ll=2336;function Ot(s,e){let t;if(s.charAt(0)==="1"||s.charAt(0)==="Q")t=Je(Q.decode(`z${s}`));else{if(s.startsWith("k51qzi5uqu5")||s.startsWith("kzwfwjn5ji4")||s.startsWith("k2k4r8")||s.startsWith("bafz"))return Gd(ue.parse(s));if(e==null)throw new X('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Je(e.decode(s))}return gs(t)}function gs(s){if(Vd(s))return new Vr({multihash:s});if(qd(s))try{let e=al(s);if(e.type==="Ed25519")return new Wr({multihash:s,publicKey:e});if(e.type==="secp256k1")return new $r({multihash:s,publicKey:e})}catch{let t=q(s.digest);return new tr(new URL(t))}throw new cr("Supplied PeerID Multihash is invalid")}function Gd(s){if(s?.multihash==null||s.version==null||s.version===1&&s.code!==Hd&&s.code!==ll)throw new ar("Supplied PeerID CID is invalid");if(s.code===ll){let e=q(s.multihash.digest);return new tr(new URL(e))}return gs(s.multihash)}function qd(s){return s.code===Le.code}function Vd(s){return s.code===Ft.code}function ul(s=0){return new Uint8Array(s)}var jr=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},bs=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Zr=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},sr=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Yr(s){return s[Symbol.asyncIterator]!=null}function hl(s,e){if(s.byteLength>e)throw new bs("Message length too long")}var Jr=s=>{let e=Be(s),t=ul(e);return Fo(s,t),Jr.bytes=e,t};Jr.bytes=0;function ys(s,e){e=e??{};let t=e.lengthEncoder??Jr,r=e?.maxDataLength??4194304;function*n(o){hl(o,r);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return Yr(s)?(async function*(){for await(let o of s)yield*n(o)})():(function*(){for(let o of s)yield*n(o)})()}ys.single=(s,e)=>{e=e??{};let t=e.lengthEncoder??Jr,r=e?.maxDataLength??4194304;return hl(s,r),new ce(t(s.byteLength),s)};var Ut;(function(s){s[s.LENGTH=0]="LENGTH",s[s.DATA=1]="DATA"})(Ut||(Ut={}));var Ii=s=>{let e=No(s);return Ii.bytes=Be(e),e};Ii.bytes=0;function rr(s,e){let t=new ce,r=Ut.LENGTH,n=-1,o=e?.lengthDecoder??Ii,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*l(){for(;t.byteLength>0;){if(r===Ut.LENGTH)try{if(n=o(t),n<0)throw new jr("Invalid message length");if(n>a)throw new bs("Message length too long");let u=o.bytes;t.consume(u),e?.onLength!=null&&e.onLength(n),r=Ut.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new Zr("Message length length too long");break}throw u}if(r===Ut.DATA){if(t.byteLength<n)break;let u=t.sublist(0,n);t.consume(n),e?.onData!=null&&e.onData(u),yield u,r=Ut.LENGTH}}}return Yr(s)?(async function*(){for await(let u of s)t.append(u),yield*l();if(t.byteLength>0)throw new sr("Unexpected end of input")})():(function*(){for(let u of s)t.append(u),yield*l();if(t.byteLength>0)throw new sr("Unexpected end of input")})()}rr.fromReader=(s,e)=>{let t=1,r=(async function*(){for(;;)try{let{done:o,value:i}=await s.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return rr(r,{...e??{},onLength:o=>{t=o}})};function at(){let s={};return s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),s}var Qr=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}},ws=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Qr(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 Qr(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 Ti=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Kt(s={}){return $d(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 $d(s,e){e=e??{};let t=e.onEnd,r=new ws,n,o,i,a=at(),l=async()=>{try{return r.isEmpty()?i?{done:!0}:await new Promise((b,x)=>{o=_=>{o=null,r.push(_);try{b(s(r))}catch(c){x(c)}return n}}):s(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=at()})}},u=b=>o!=null?o(b):(r.push(b),n),p=b=>(r=new ws,o!=null?o({error:b}):(r.push({error:b}),n)),m=b=>{if(i)return n;if(e?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:b})},E=b=>i?n:(i=!0,b!=null?p(b):u({done:!0})),w=()=>(r=new ws,E(),{done:!0}),h=b=>(E(b),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:l,return:w,throw:h,push:m,end:E,get readableLength(){return r.size},onEmpty:async b=>{let x=b?.signal;if(x?.throwIfAborted(),r.isEmpty())return;let _,c;x!=null&&(_=new Promise((f,d)=>{c=()=>{d(new Ti)},x.addEventListener("abort",c)}));try{await Promise.race([a.promise,_])}finally{c!=null&&x!=null&&x?.removeEventListener("abort",c)}}},t==null)return n;let g=n;return n={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(b){return g.throw(b),t!=null&&(t(b),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:m,end(b){return g.end(b),t!=null&&(t(b),t=void 0),n},get readableLength(){return g.readableLength},onEmpty:b=>g.onEmpty(b)},n}function jd(s){return s.reason}async function Di(s,e,t){if(e==null)return s;let r=t?.translateError??jd;if(e.aborted)return s.catch(()=>{}),Promise.reject(r(e));let n;try{return await Promise.race([s,new Promise((o,i)=>{n=()=>{i(r(e))},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Ai=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=at(),this.haveNext=at()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=at(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=at(),await Di(this.readNext.promise,t?.signal,t)}};function fl(){return new Ai}function Zd(s){return s[Symbol.asyncIterator]!=null}async function Yd(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*Xd(s){let e=new AbortController,t=fl();Yd(s,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Jd(s){for(let e of s)yield*e}function Qd(...s){let e=[];for(let t of s)Zd(t)||e.push(t);return e.length===s.length?Jd(e):Xd(s)}var dl=Qd;function nr(s,...e){if(s==null)throw new Error("Empty pipeline");if(Mi(s)){let r=s;s=()=>r.source}else if(ml(s)||pl(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]=tp(t[r]));return ep(...t)}var ep=(...s)=>{let e;for(;s.length>0;)e=s.shift()(e);return e},pl=s=>s?.[Symbol.asyncIterator]!=null,ml=s=>s?.[Symbol.iterator]!=null,Mi=s=>s==null?!1:s.sink!=null&&s.source!=null,tp=s=>e=>{let t=s.sink(e);if(t?.then!=null){let r=Kt({objectMode:!0});t.then(()=>{r.end()},i=>{r.end(i)});let n,o=s.source;if(pl(o))n=async function*(){yield*o,r.end()};else if(ml(o))n=function*(){yield*o,r.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return dl(r,n())}return s.source};var gl={maxSubscriptions:5e3,maxMessages:5e3,maxIhaveMessageIDs:5e3,maxIwantMessageIDs:5e3,maxControlMessages:5e3,maxIdontwantMessageIDs:512,maxPeerInfos:16};var ct;(function(s){let e;(function(h){let g;h.codec=()=>(g==null&&(g=ve((c,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),c.subscribe!=null&&(f.uint32(8),f.bool(c.subscribe)),c.topic!=null&&(f.uint32(18),f.string(c.topic)),d.lengthDelimited!==!1&&f.ldelim()},(c,f,d={})=>{let y={},v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{y.subscribe=c.bool();break}case 2:{y.topic=c.string();break}default:{c.skipType(S&7);break}}}return y},function*(c,f,d,y={}){let v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{yield{field:`${d}.subscribe`,value:c.bool()};break}case 2:{yield{field:`${d}.topic`,value:c.string()};break}default:{c.skipType(S&7);break}}}})),g);function b(c){return we(c,h.codec())}h.encode=b;function x(c,f){return ye(c,h.codec(),f)}h.decode=x;function _(c,f){return xe(c,h.codec(),f)}h.stream=_})(e=s.SubOpts||(s.SubOpts={}));let t;(function(h){let g;h.codec=()=>(g==null&&(g=ve((c,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),c.from!=null&&(f.uint32(10),f.bytes(c.from)),c.data!=null&&(f.uint32(18),f.bytes(c.data)),c.seqno!=null&&(f.uint32(26),f.bytes(c.seqno)),c.topic!=null&&c.topic!==""&&(f.uint32(34),f.string(c.topic)),c.signature!=null&&(f.uint32(42),f.bytes(c.signature)),c.key!=null&&(f.uint32(50),f.bytes(c.key)),d.lengthDelimited!==!1&&f.ldelim()},(c,f,d={})=>{let y={topic:""},v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{y.from=c.bytes();break}case 2:{y.data=c.bytes();break}case 3:{y.seqno=c.bytes();break}case 4:{y.topic=c.string();break}case 5:{y.signature=c.bytes();break}case 6:{y.key=c.bytes();break}default:{c.skipType(S&7);break}}}return y},function*(c,f,d,y={}){let v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{yield{field:`${d}.from`,value:c.bytes()};break}case 2:{yield{field:`${d}.data`,value:c.bytes()};break}case 3:{yield{field:`${d}.seqno`,value:c.bytes()};break}case 4:{yield{field:`${d}.topic`,value:c.string()};break}case 5:{yield{field:`${d}.signature`,value:c.bytes()};break}case 6:{yield{field:`${d}.key`,value:c.bytes()};break}default:{c.skipType(S&7);break}}}})),g);function b(c){return we(c,h.codec())}h.encode=b;function x(c,f){return ye(c,h.codec(),f)}h.decode=x;function _(c,f){return xe(c,h.codec(),f)}h.stream=_})(t=s.Message||(s.Message={}));let r;(function(h){let g;h.codec=()=>(g==null&&(g=ve((c,f,d={})=>{if(d.lengthDelimited!==!1&&f.fork(),c.ihave!=null&&c.ihave.length>0)for(let y of c.ihave)f.uint32(10),s.ControlIHave.codec().encode(y,f);if(c.iwant!=null&&c.iwant.length>0)for(let y of c.iwant)f.uint32(18),s.ControlIWant.codec().encode(y,f);if(c.graft!=null&&c.graft.length>0)for(let y of c.graft)f.uint32(26),s.ControlGraft.codec().encode(y,f);if(c.prune!=null&&c.prune.length>0)for(let y of c.prune)f.uint32(34),s.ControlPrune.codec().encode(y,f);if(c.idontwant!=null&&c.idontwant.length>0)for(let y of c.idontwant)f.uint32(42),s.ControlIDontWant.codec().encode(y,f);d.lengthDelimited!==!1&&f.ldelim()},(c,f,d={})=>{let y={ihave:[],iwant:[],graft:[],prune:[],idontwant:[]},v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{if(d.limits?.ihave!=null&&y.ihave.length===d.limits.ihave)throw new W('Decode error - repeated field "ihave" had too many elements');y.ihave.push(s.ControlIHave.codec().decode(c,c.uint32(),{limits:d.limits?.ihave$}));break}case 2:{if(d.limits?.iwant!=null&&y.iwant.length===d.limits.iwant)throw new W('Decode error - repeated field "iwant" had too many elements');y.iwant.push(s.ControlIWant.codec().decode(c,c.uint32(),{limits:d.limits?.iwant$}));break}case 3:{if(d.limits?.graft!=null&&y.graft.length===d.limits.graft)throw new W('Decode error - repeated field "graft" had too many elements');y.graft.push(s.ControlGraft.codec().decode(c,c.uint32(),{limits:d.limits?.graft$}));break}case 4:{if(d.limits?.prune!=null&&y.prune.length===d.limits.prune)throw new W('Decode error - repeated field "prune" had too many elements');y.prune.push(s.ControlPrune.codec().decode(c,c.uint32(),{limits:d.limits?.prune$}));break}case 5:{if(d.limits?.idontwant!=null&&y.idontwant.length===d.limits.idontwant)throw new W('Decode error - repeated field "idontwant" had too many elements');y.idontwant.push(s.ControlIDontWant.codec().decode(c,c.uint32(),{limits:d.limits?.idontwant$}));break}default:{c.skipType(S&7);break}}}return y},function*(c,f,d,y={}){let v={ihave:0,iwant:0,graft:0,prune:0,idontwant:0},S=f==null?c.len:c.pos+f;for(;c.pos<S;){let M=c.uint32();switch(M>>>3){case 1:{if(y.limits?.ihave!=null&&v.ihave===y.limits.ihave)throw new W('Streaming decode error - repeated field "ihave" had too many elements');for(let C of s.ControlIHave.codec().stream(c,c.uint32(),`${d}.ihave[]`,{limits:y.limits?.ihave$}))yield{...C,index:v.ihave};v.ihave++;break}case 2:{if(y.limits?.iwant!=null&&v.iwant===y.limits.iwant)throw new W('Streaming decode error - repeated field "iwant" had too many elements');for(let C of s.ControlIWant.codec().stream(c,c.uint32(),`${d}.iwant[]`,{limits:y.limits?.iwant$}))yield{...C,index:v.iwant};v.iwant++;break}case 3:{if(y.limits?.graft!=null&&v.graft===y.limits.graft)throw new W('Streaming decode error - repeated field "graft" had too many elements');for(let C of s.ControlGraft.codec().stream(c,c.uint32(),`${d}.graft[]`,{limits:y.limits?.graft$}))yield{...C,index:v.graft};v.graft++;break}case 4:{if(y.limits?.prune!=null&&v.prune===y.limits.prune)throw new W('Streaming decode error - repeated field "prune" had too many elements');for(let C of s.ControlPrune.codec().stream(c,c.uint32(),`${d}.prune[]`,{limits:y.limits?.prune$}))yield{...C,index:v.prune};v.prune++;break}case 5:{if(y.limits?.idontwant!=null&&v.idontwant===y.limits.idontwant)throw new W('Streaming decode error - repeated field "idontwant" had too many elements');for(let C of s.ControlIDontWant.codec().stream(c,c.uint32(),`${d}.idontwant[]`,{limits:y.limits?.idontwant$}))yield{...C,index:v.idontwant};v.idontwant++;break}default:{c.skipType(M&7);break}}}})),g);function b(c){return we(c,h.codec())}h.encode=b;function x(c,f){return ye(c,h.codec(),f)}h.decode=x;function _(c,f){return xe(c,h.codec(),f)}h.stream=_})(r=s.ControlMessage||(s.ControlMessage={}));let n;(function(h){let g;h.codec=()=>(g==null&&(g=ve((c,f,d={})=>{if(d.lengthDelimited!==!1&&f.fork(),c.topicID!=null&&(f.uint32(10),f.string(c.topicID)),c.messageIDs!=null&&c.messageIDs.length>0)for(let y of c.messageIDs)f.uint32(18),f.bytes(y);d.lengthDelimited!==!1&&f.ldelim()},(c,f,d={})=>{let y={messageIDs:[]},v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{y.topicID=c.string();break}case 2:{if(d.limits?.messageIDs!=null&&y.messageIDs.length===d.limits.messageIDs)throw new W('Decode error - repeated field "messageIDs" had too many elements');y.messageIDs.push(c.bytes());break}default:{c.skipType(S&7);break}}}return y},function*(c,f,d,y={}){let v={messageIDs:0},S=f==null?c.len:c.pos+f;for(;c.pos<S;){let M=c.uint32();switch(M>>>3){case 1:{yield{field:`${d}.topicID`,value:c.string()};break}case 2:{if(y.limits?.messageIDs!=null&&v.messageIDs===y.limits.messageIDs)throw new W('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:c.bytes()},v.messageIDs++;break}default:{c.skipType(M&7);break}}}})),g);function b(c){return we(c,h.codec())}h.encode=b;function x(c,f){return ye(c,h.codec(),f)}h.decode=x;function _(c,f){return xe(c,h.codec(),f)}h.stream=_})(n=s.ControlIHave||(s.ControlIHave={}));let o;(function(h){let g;h.codec=()=>(g==null&&(g=ve((c,f,d={})=>{if(d.lengthDelimited!==!1&&f.fork(),c.messageIDs!=null&&c.messageIDs.length>0)for(let y of c.messageIDs)f.uint32(10),f.bytes(y);d.lengthDelimited!==!1&&f.ldelim()},(c,f,d={})=>{let y={messageIDs:[]},v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{if(d.limits?.messageIDs!=null&&y.messageIDs.length===d.limits.messageIDs)throw new W('Decode error - repeated field "messageIDs" had too many elements');y.messageIDs.push(c.bytes());break}default:{c.skipType(S&7);break}}}return y},function*(c,f,d,y={}){let v={messageIDs:0},S=f==null?c.len:c.pos+f;for(;c.pos<S;){let M=c.uint32();switch(M>>>3){case 1:{if(y.limits?.messageIDs!=null&&v.messageIDs===y.limits.messageIDs)throw new W('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:c.bytes()},v.messageIDs++;break}default:{c.skipType(M&7);break}}}})),g);function b(c){return we(c,h.codec())}h.encode=b;function x(c,f){return ye(c,h.codec(),f)}h.decode=x;function _(c,f){return xe(c,h.codec(),f)}h.stream=_})(o=s.ControlIWant||(s.ControlIWant={}));let i;(function(h){let g;h.codec=()=>(g==null&&(g=ve((c,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),c.topicID!=null&&(f.uint32(10),f.string(c.topicID)),d.lengthDelimited!==!1&&f.ldelim()},(c,f,d={})=>{let y={},v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();S>>>3===1?y.topicID=c.string():c.skipType(S&7)}return y},function*(c,f,d,y={}){let v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();S>>>3===1?yield{field:`${d}.topicID`,value:c.string()}:c.skipType(S&7)}})),g);function b(c){return we(c,h.codec())}h.encode=b;function x(c,f){return ye(c,h.codec(),f)}h.decode=x;function _(c,f){return xe(c,h.codec(),f)}h.stream=_})(i=s.ControlGraft||(s.ControlGraft={}));let a;(function(h){let g;h.codec=()=>(g==null&&(g=ve((c,f,d={})=>{if(d.lengthDelimited!==!1&&f.fork(),c.topicID!=null&&(f.uint32(10),f.string(c.topicID)),c.peers!=null&&c.peers.length>0)for(let y of c.peers)f.uint32(18),s.PeerInfo.codec().encode(y,f);c.backoff!=null&&(f.uint32(24),f.uint64Number(c.backoff)),d.lengthDelimited!==!1&&f.ldelim()},(c,f,d={})=>{let y={peers:[]},v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{y.topicID=c.string();break}case 2:{if(d.limits?.peers!=null&&y.peers.length===d.limits.peers)throw new W('Decode error - repeated field "peers" had too many elements');y.peers.push(s.PeerInfo.codec().decode(c,c.uint32(),{limits:d.limits?.peers$}));break}case 3:{y.backoff=c.uint64Number();break}default:{c.skipType(S&7);break}}}return y},function*(c,f,d,y={}){let v={peers:0},S=f==null?c.len:c.pos+f;for(;c.pos<S;){let M=c.uint32();switch(M>>>3){case 1:{yield{field:`${d}.topicID`,value:c.string()};break}case 2:{if(y.limits?.peers!=null&&v.peers===y.limits.peers)throw new W('Streaming decode error - repeated field "peers" had too many elements');for(let C of s.PeerInfo.codec().stream(c,c.uint32(),`${d}.peers[]`,{limits:y.limits?.peers$}))yield{...C,index:v.peers};v.peers++;break}case 3:{yield{field:`${d}.backoff`,value:c.uint64Number()};break}default:{c.skipType(M&7);break}}}})),g);function b(c){return we(c,h.codec())}h.encode=b;function x(c,f){return ye(c,h.codec(),f)}h.decode=x;function _(c,f){return xe(c,h.codec(),f)}h.stream=_})(a=s.ControlPrune||(s.ControlPrune={}));let l;(function(h){let g;h.codec=()=>(g==null&&(g=ve((c,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),c.peerID!=null&&(f.uint32(10),f.bytes(c.peerID)),c.signedPeerRecord!=null&&(f.uint32(18),f.bytes(c.signedPeerRecord)),d.lengthDelimited!==!1&&f.ldelim()},(c,f,d={})=>{let y={},v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{y.peerID=c.bytes();break}case 2:{y.signedPeerRecord=c.bytes();break}default:{c.skipType(S&7);break}}}return y},function*(c,f,d,y={}){let v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{yield{field:`${d}.peerID`,value:c.bytes()};break}case 2:{yield{field:`${d}.signedPeerRecord`,value:c.bytes()};break}default:{c.skipType(S&7);break}}}})),g);function b(c){return we(c,h.codec())}h.encode=b;function x(c,f){return ye(c,h.codec(),f)}h.decode=x;function _(c,f){return xe(c,h.codec(),f)}h.stream=_})(l=s.PeerInfo||(s.PeerInfo={}));let u;(function(h){let g;h.codec=()=>(g==null&&(g=ve((c,f,d={})=>{if(d.lengthDelimited!==!1&&f.fork(),c.messageIDs!=null&&c.messageIDs.length>0)for(let y of c.messageIDs)f.uint32(10),f.bytes(y);d.lengthDelimited!==!1&&f.ldelim()},(c,f,d={})=>{let y={messageIDs:[]},v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{if(d.limits?.messageIDs!=null&&y.messageIDs.length===d.limits.messageIDs)throw new W('Decode error - repeated field "messageIDs" had too many elements');y.messageIDs.push(c.bytes());break}default:{c.skipType(S&7);break}}}return y},function*(c,f,d,y={}){let v={messageIDs:0},S=f==null?c.len:c.pos+f;for(;c.pos<S;){let M=c.uint32();switch(M>>>3){case 1:{if(y.limits?.messageIDs!=null&&v.messageIDs===y.limits.messageIDs)throw new W('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:c.bytes()},v.messageIDs++;break}default:{c.skipType(M&7);break}}}})),g);function b(c){return we(c,h.codec())}h.encode=b;function x(c,f){return ye(c,h.codec(),f)}h.decode=x;function _(c,f){return xe(c,h.codec(),f)}h.stream=_})(u=s.ControlIDontWant||(s.ControlIDontWant={}));let p;s.codec=()=>(p==null&&(p=ve((h,g,b={})=>{if(b.lengthDelimited!==!1&&g.fork(),h.subscriptions!=null&&h.subscriptions.length>0)for(let x of h.subscriptions)g.uint32(10),s.SubOpts.codec().encode(x,g);if(h.messages!=null&&h.messages.length>0)for(let x of h.messages)g.uint32(18),s.Message.codec().encode(x,g);h.control!=null&&(g.uint32(26),s.ControlMessage.codec().encode(h.control,g)),b.lengthDelimited!==!1&&g.ldelim()},(h,g,b={})=>{let x={subscriptions:[],messages:[]},_=g==null?h.len:h.pos+g;for(;h.pos<_;){let c=h.uint32();switch(c>>>3){case 1:{if(b.limits?.subscriptions!=null&&x.subscriptions.length===b.limits.subscriptions)throw new W('Decode error - repeated field "subscriptions" had too many elements');x.subscriptions.push(s.SubOpts.codec().decode(h,h.uint32(),{limits:b.limits?.subscriptions$}));break}case 2:{if(b.limits?.messages!=null&&x.messages.length===b.limits.messages)throw new W('Decode error - repeated field "messages" had too many elements');x.messages.push(s.Message.codec().decode(h,h.uint32(),{limits:b.limits?.messages$}));break}case 3:{x.control=s.ControlMessage.codec().decode(h,h.uint32(),{limits:b.limits?.control});break}default:{h.skipType(c&7);break}}}return x},function*(h,g,b,x={}){let _={subscriptions:0,messages:0},c=g==null?h.len:h.pos+g;for(;h.pos<c;){let f=h.uint32();switch(f>>>3){case 1:{if(x.limits?.subscriptions!=null&&_.subscriptions===x.limits.subscriptions)throw new W('Streaming decode error - repeated field "subscriptions" had too many elements');for(let d of s.SubOpts.codec().stream(h,h.uint32(),`${b}.subscriptions[]`,{limits:x.limits?.subscriptions$}))yield{...d,index:_.subscriptions};_.subscriptions++;break}case 2:{if(x.limits?.messages!=null&&_.messages===x.limits.messages)throw new W('Streaming decode error - repeated field "messages" had too many elements');for(let d of s.Message.codec().stream(h,h.uint32(),`${b}.messages[]`,{limits:x.limits?.messages$}))yield{...d,index:_.messages};_.messages++;break}case 3:{yield*s.ControlMessage.codec().stream(h,h.uint32(),`${b}.control`,{limits:x.limits?.control});break}default:{h.skipType(f&7);break}}}})),p);function m(h){return we(h,s.codec())}s.encode=m;function E(h,g){return ye(h,s.codec(),g)}s.decode=E;function w(h,g){return xe(h,s.codec(),g)}s.stream=w})(ct||(ct={}));var en=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 i=t.get(n.topic);i==null&&(i=[],t.set(n.topic,i)),i.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 bl;(function(s){s.StrictSign="StrictSign",s.StrictNoSign="StrictNoSign"})(bl||(bl={}));var St;(function(s){s[s.Signing=0]="Signing",s[s.Anonymous=1]="Anonymous"})(St||(St={}));var Ee;(function(s){s.Error="error",s.Ignore="ignore",s.Reject="reject",s.Blacklisted="blacklisted"})(Ee||(Ee={}));var me;(function(s){s.InvalidSignature="invalid_signature",s.InvalidSeqno="invalid_seqno",s.InvalidPeerId="invalid_peerid",s.SignaturePresent="signature_present",s.SeqnoPresent="seqno_present",s.FromPresent="from_present",s.TransformFailed="transform_failed"})(me||(me={}));var ge;(function(s){s.duplicate="duplicate",s.invalid="invalid",s.valid="valid"})(ge||(ge={}));function Pi(s){switch(s){case be.Ignore:return Ee.Ignore;case be.Reject:return Ee.Reject;default:throw new Error("Unreachable")}}var yl;(function(s){s.forward="forward",s.publish="publish"})(yl||(yl={}));var Se;(function(s){s.Fanout="fanout",s.Random="random",s.Subscribed="subscribed",s.Outbound="outbound",s.NotEnough="not_enough",s.Opportunistic="opportunistic"})(Se||(Se={}));var Ke;(function(s){s.Dc="disconnected",s.BadScore="bad_score",s.Prune="prune",s.Excess="excess"})(Ke||(Ke={}));var vs;(function(s){s.GraftBackoff="graft_backoff",s.BrokenPromise="broken_promise",s.MessageDeficit="message_deficit",s.IPColocation="IP_colocation"})(vs||(vs={}));var Es;(function(s){s.LowScore="low_score",s.MaxIhave="max_ihave",s.MaxIasked="max_iasked"})(Es||(Es={}));var xs;(function(s){s.graylist="graylist",s.publish="publish",s.gossip="gossip",s.mesh="mesh"})(xs||(xs={}));function wl(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,o){let i=this.toTopic(r);switch(n){case Se.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:i},o);break;case Se.Random:this.meshPeerInclusionEventsRandom.inc({topic:i},o);break;case Se.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:i},o);break;case Se.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:i},o);break;case Se.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:i},o);break;case Se.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:i},o);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:i},o);break}},onRemoveFromMesh(r,n,o){let i=this.toTopic(r);switch(n){case Ke.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:i},o);break;case Ke.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:i},o);break;case Ke.Prune:this.meshPeerChurnEventsPrune.inc({topic:i},o);break;case Ke.Excess:this.meshPeerChurnEventsExcess.inc({topic:i},o);break;default:this.meshPeerChurnEventsUnknown.inc({topic:i},o);break}},onReportValidation(r,n,o){if(this.asyncValidationMcacheHit.inc({hit:r!=null?"hit":"miss"}),r!=null){let i=this.toTopic(r.message.topic);switch(n){case be.Accept:this.acceptedMessagesTotal.inc({topic:i});break;case be.Ignore:this.ignoredMessagesTotal.inc({topic:i});break;case be.Reject:this.rejectedMessagesTotal.inc({topic:i});break;default:this.unknownValidationResultsTotal.inc({topic:i});break}}o!=null?this.asyncValidationDelayFromFirstSeenSec.observe((Date.now()-o)/1e3):this.asyncValidationUnknownFirstSeen.inc()},onScorePenalty(r){this.scoringPenalties.inc({penalty:r},1)},onIhaveRcv(r,n,o){let i=this.toTopic(r);this.ihaveRcvMsgids.inc({topic:i},n),this.ihaveRcvNotSeenMsgids.inc({topic:i},o)},onIwantRcv(r,n){for(let[o,i]of r){let a=this.toTopic(o);this.iwantRcvMsgids.inc({topic:a},i)}this.iwantRcvDonthaveMsgids.inc(n)},onIdontwantRcv(r,n){this.idontwantRcvMsgids.inc(r),this.idontwantRcvDonthaveMsgids.inc(n)},onForwardMsg(r,n){let o=this.toTopic(r);this.msgForwardCount.inc({topic:o},1),this.msgForwardPeers.inc({topic:o},n)},onPublishMsg(r,n,o,i,a){let l=this.toTopic(r);this.msgPublishCount.inc({topic:l},1),this.msgPublishBytes.inc({topic:l},o*i),this.msgPublishPeersByTopic.inc({topic:l},o),this.directPeersPublishedTotal.inc({topic:l},n.direct),this.floodsubPeersPublishedTotal.inc({topic:l},n.floodsub),this.meshPeersPublishedTotal.inc({topic:l},n.mesh),this.fanoutPeersPublishedTotal.inc({topic:l},n.fanout),this.msgPublishTime.observe({topic:l},a/1e3)},onMsgRecvPreValidation(r){let n=this.toTopic(r);this.msgReceivedPreValidation.inc({topic:n},1)},onMsgRecvError(r){let n=this.toTopic(r);this.msgReceivedError.inc({topic:n},1)},onPrevalidationResult(r,n){let o=this.toTopic(r);switch(n){case ge.duplicate:this.prevalidationDuplicateTotal.inc({topic:o});break;case ge.invalid:this.prevalidationInvalidTotal.inc({topic:o});break;case ge.valid:this.prevalidationValidTotal.inc({topic:o});break;default:this.prevalidationUnknownTotal.inc({topic:o});break}},onMsgRecvInvalid(r,n){let o=this.toTopic(r),i=n.reason===Ee.Error?n.error:n.reason;this.msgReceivedInvalid.inc({error:i},1),this.msgReceivedInvalidByTopic.inc({topic:o},1)},onDuplicateMsgDelivery(r,n,o){let i=this.toTopic(r);this.duplicateMsgDeliveryDelay.observe({topic:i},n/1e3),o&&this.duplicateMsgLateDelivery.inc({topic:i},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 o=r.control.ihave?.length??0,i=r.control.iwant?.length??0,a=r.control.graft?.length??0,l=r.control.prune?.length??0,u=r.control.idontwant?.length??0;o>0&&this.rpcSentIHave.inc(o),i>0&&this.rpcSentIWant.inc(i),a>0&&this.rpcSentGraft.inc(a),l>0&&this.rpcSentPrune.inc(l),u>0&&this.rpcSentIDontWant.inc(u),(o>0||i>0||a>0||l>0||u>0)&&this.rpcSentControl.inc(1)}},registerScores(r,n){let o=0,i=0,a=0,l=0;for(let u of r)u>=n.graylistThreshold&&o++,u>=n.publishThreshold&&i++,u>=n.gossipThreshold&&a++,u>=0&&l++;this.peersByScoreThreshold.set({threshold:xs.graylist},o),this.peersByScoreThreshold.set({threshold:xs.publish},i),this.peersByScoreThreshold.set({threshold:xs.gossip},a),this.peersByScoreThreshold.set({threshold:xs.mesh},l),this.score.set(r)},registerScoreWeights(r){for(let[n,o]of r.byTopic)this.scoreWeights.set({topic:n,p:"p1"},o.p1w),this.scoreWeights.set({topic:n,p:"p2"},o.p2w),this.scoreWeights.set({topic:n,p:"p3"},o.p3w),this.scoreWeights.set({topic:n,p:"p3b"},o.p3bw),this.scoreWeights.set({topic:n,p:"p4"},o.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 o=new Map;r.forEach((i,a)=>{let l=this.topicStrToLabel.get(a)??"unknown",u=o.get(l);u==null&&(u=new Set,o.set(l,u)),i.forEach(p=>u?.add(p))});for(let[i,a]of o){let l=[];a.forEach(u=>{l.push(n.get(u)??0)}),this.scorePerMesh.set({topic:i},l)}}}}var G=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var sp={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},rp={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 xl(s={}){return{...sp,...s,topics:s.topics!=null?Object.entries(s.topics).reduce((e,[t,r])=>(e[t]=np(r),e),{}):{}}}function np(s={}){return{...rp,...s}}function vl(s){for(let[e,t]of Object.entries(s.topics))try{op(t)}catch(r){throw new G(`invalid score parameters for topic ${e}: ${r.message}`)}if(s.topicScoreCap<0)throw new G("invalid topic score cap; must be positive (or 0 for no cap)");if(s.appSpecificScore===null||s.appSpecificScore===void 0)throw new G("missing application specific score function");if(s.IPColocationFactorWeight>0)throw new G("invalid IPColocationFactorWeight; must be negative (or 0 to disable)");if(s.IPColocationFactorWeight!==0&&s.IPColocationFactorThreshold<1)throw new G("invalid IPColocationFactorThreshold; must be at least 1");if(s.behaviourPenaltyWeight>0)throw new G("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)");if(s.behaviourPenaltyWeight!==0&&(s.behaviourPenaltyDecay<=0||s.behaviourPenaltyDecay>=1))throw new G("invalid BehaviourPenaltyDecay; must be between 0 and 1");if(s.decayInterval<1e3)throw new G("invalid DecayInterval; must be at least 1s");if(s.decayToZero<=0||s.decayToZero>=1)throw new G("invalid DecayToZero; must be between 0 and 1")}function op(s){if(s.topicWeight<0)throw new G("invalid topic weight; must be >= 0");if(s.timeInMeshQuantum===0)throw new G("invalid TimeInMeshQuantum; must be non zero");if(s.timeInMeshWeight<0)throw new G("invalid TimeInMeshWeight; must be positive (or 0 to disable)");if(s.timeInMeshWeight!==0&&s.timeInMeshQuantum<=0)throw new G("invalid TimeInMeshQuantum; must be positive");if(s.timeInMeshWeight!==0&&s.timeInMeshCap<=0)throw new G("invalid TimeInMeshCap; must be positive");if(s.firstMessageDeliveriesWeight<0)throw new G("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)");if(s.firstMessageDeliveriesWeight!==0&&(s.firstMessageDeliveriesDecay<=0||s.firstMessageDeliveriesDecay>=1))throw new G("invalid FirstMessageDeliveriesDecay; must be between 0 and 1");if(s.firstMessageDeliveriesWeight!==0&&s.firstMessageDeliveriesCap<=0)throw new G("invalid FirstMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight>0)throw new G("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.meshMessageDeliveriesWeight!==0&&(s.meshMessageDeliveriesDecay<=0||s.meshMessageDeliveriesDecay>=1))throw new G("invalid MeshMessageDeliveriesDecay; must be between 0 and 1");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesCap<=0)throw new G("invalid MeshMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesThreshold<=0)throw new G("invalid MeshMessageDeliveriesThreshold; must be positive");if(s.meshMessageDeliveriesWindow<0)throw new G("invalid MeshMessageDeliveriesWindow; must be non-negative");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesActivation<1e3)throw new G("invalid MeshMessageDeliveriesActivation; must be at least 1s");if(s.meshFailurePenaltyWeight>0)throw new G("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)");if(s.meshFailurePenaltyWeight!==0&&(s.meshFailurePenaltyDecay<=0||s.meshFailurePenaltyDecay>=1))throw new G("invalid MeshFailurePenaltyDecay; must be between 0 and 1");if(s.invalidMessageDeliveriesWeight>0)throw new G("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.invalidMessageDeliveriesDecay<=0||s.invalidMessageDeliveriesDecay>=1)throw new G("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1")}var ip={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function El(s={}){return{...ip,...s}}function sn(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 Sl(s,e){return sn(s,e,()=>!0)}var tn=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 _l(s,e,t,r){let n=0;Object.entries(e.topics).forEach(([i,a])=>{let l=t.topics[i];if(l===void 0)return;let u=0;if(a.inMesh){let w=a.meshTime/l.timeInMeshQuantum;w>l.timeInMeshCap&&(w=l.timeInMeshCap),u+=w*l.timeInMeshWeight}let p=a.firstMessageDeliveries;if(p>l.firstMessageDeliveriesCap&&(p=l.firstMessageDeliveriesCap),u+=p*l.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries<l.meshMessageDeliveriesThreshold){let w=l.meshMessageDeliveriesThreshold-a.meshMessageDeliveries,h=w*w;u+=h*l.meshMessageDeliveriesWeight}let m=a.meshFailurePenalty;u+=m*l.meshFailurePenaltyWeight;let E=a.invalidMessageDeliveries*a.invalidMessageDeliveries;u+=E*l.invalidMessageDeliveriesWeight,n+=u*l.topicWeight}),t.topicScoreCap>0&&n>t.topicScoreCap&&(n=t.topicScoreCap);let o=t.appSpecificScore(s);if(n+=o*t.appSpecificWeight,e.knownIPs.forEach(i=>{if(t.IPColocationFactorWhitelist.has(i))return;let a=r.get(i),l=a!=null?a.size:0;if(l>t.IPColocationFactorThreshold){let u=l-t.IPColocationFactorThreshold,p=u*u;n+=p*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let i=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=i*i;n+=a*t.behaviourPenaltyWeight}return n}var Dl=Zl(Tl(),1);var _e;(function(s){s[s.unknown=0]="unknown",s[s.valid=1]="valid",s[s.invalid=2]="invalid",s[s.ignored=3]="ignored"})(_e||(_e={}));var rn=class{records;queue;constructor(){this.records=new Map,this.queue=new Dl.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:_e.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 nn=class{params;metrics;peerStats=new Map;peerIPs=new tn(()=>new Set);scoreCache=new Map;deliveryRecords=new rn;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,r,n){this.params=e,this.metrics=t,vl(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??_l,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(([o,i])=>{let a=this.params.topics[o];a!==void 0&&(i.firstMessageDeliveries*=a.firstMessageDeliveriesDecay,i.firstMessageDeliveries<t&&(i.firstMessageDeliveries=0),i.meshMessageDeliveries*=a.meshMessageDeliveriesDecay,i.meshMessageDeliveries<t&&(i.meshMessageDeliveries=0),i.meshFailurePenalty*=a.meshFailurePenaltyDecay,i.meshFailurePenalty<t&&(i.meshFailurePenalty=0),i.invalidMessageDeliveries*=a.invalidMessageDeliveriesDecay,i.invalidMessageDeliveries<t&&(i.invalidMessageDeliveries=0),i.inMesh&&(i.meshTime=e-i.graftTime,i.meshTime>a.meshMessageDeliveriesActivation&&(i.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 o=this.computeScore(e,t,this.params,this.peerIPs),i=r+this.scoreCacheValidityMs;return n!=null?(this.metrics?.scoreCachedDelta.observe(Math.abs(o-n.score)),n.score=o,n.cacheUntil=i):this.scoreCache.set(e,{score:o,cacheUntil:i}),o}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 o=this.params.topics[r].meshMessageDeliveriesThreshold;if(n.inMesh&&n.meshMessageDeliveriesActive&&n.meshMessageDeliveries<o){let i=o-n.meshMessageDeliveries;n.meshFailurePenalty+=i*i}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 o=this.params.topics[t].meshMessageDeliveriesThreshold;if(n.meshMessageDeliveriesActive&&n.meshMessageDeliveries<o){let i=o-n.meshMessageDeliveries;n.meshFailurePenalty+=i*i}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),o=Date.now();if(n.status!==_e.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,o-n.firstSeenTsMs,_e[n.status]);return}n.status=_e.valid,n.validated=o,n.peers.forEach(i=>{i!==e.toString()&&this.markDuplicateMessageDelivery(i,r)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,r,n){switch(n){case Ee.Error:this.markInvalidMessageDelivery(e,r);return;case Ee.Blacklisted:return}let o=this.deliveryRecords.ensureRecord(t);if(o.status!==_e.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-o.firstSeenTsMs,_e[o.status]);return}if(n===Ee.Ignore){o.status=_e.ignored,o.peers.clear();return}o.status=_e.invalid,this.markInvalidMessageDelivery(e,r),o.peers.forEach(i=>{this.markInvalidMessageDelivery(i,r)}),o.peers.clear()}duplicateMessage(e,t,r){let n=this.deliveryRecords.ensureRecord(t);if(!n.peers.has(e))switch(n.status){case _e.unknown:n.peers.add(e);break;case _e.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,r,n.validated);break;case _e.invalid:this.markInvalidMessageDelivery(e,r);break;case _e.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 o=this.params.topics[t].firstMessageDeliveriesCap;n.firstMessageDeliveries=Math.min(o,n.firstMessageDeliveries+1),n.inMesh&&(o=this.params.topics[t].meshMessageDeliveriesCap,n.meshMessageDeliveries=Math.min(o,n.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,r){let n=this.peerStats.get(e);if(n!=null){let o=r!==void 0?Date.now():0,i=this.getPtopicStats(n,t);if(i!=null&&i.inMesh){let a=this.params.topics[t];if(r!==void 0){let u=o-r,p=u>a.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,u,p),p)return}let l=a.meshMessageDeliveriesCap;i.meshMessageDeliveries=Math.min(l,i.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 ap(s,e,t,r,n){let o=0,i=new Map;if(Object.entries(e.topics).forEach(([E,w])=>{let h=n.get(E)??"unknown",g=t.topics[E];if(g===void 0)return;let b=i.get(h);b==null&&(b={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},i.set(h,b));let x=0,_=0,c=0,f=0,d=0;if(w.inMesh){let M=Math.max(w.meshTime/g.timeInMeshQuantum,g.timeInMeshCap);x+=M*g.timeInMeshWeight}let y=w.firstMessageDeliveries;if(y>g.firstMessageDeliveriesCap&&(y=g.firstMessageDeliveriesCap),_+=y*g.firstMessageDeliveriesWeight,w.meshMessageDeliveriesActive&&w.meshMessageDeliveries<g.meshMessageDeliveriesThreshold){let M=g.meshMessageDeliveriesThreshold-w.meshMessageDeliveries,C=M*M;c+=C*g.meshMessageDeliveriesWeight}let v=w.meshFailurePenalty;f+=v*g.meshFailurePenaltyWeight;let S=w.invalidMessageDeliveries*w.invalidMessageDeliveries;d+=S*g.invalidMessageDeliveriesWeight,o+=(x+_+c+f+d)*g.topicWeight,b.p1w+=x,b.p2w+=_,b.p3w+=c,b.p3bw+=f,b.p4w+=d}),t.topicScoreCap>0&&o>t.topicScoreCap){o=t.topicScoreCap;let E=t.topicScoreCap/o;for(let w of i.values())w.p1w*=E,w.p2w*=E,w.p3w*=E,w.p3bw*=E,w.p4w*=E}let a=0,l=0,u=0,p=t.appSpecificScore(s);a+=p*t.appSpecificWeight,e.knownIPs.forEach(E=>{if(t.IPColocationFactorWhitelist.has(E))return;let w=r.get(E),h=w!=null?w.size:0;if(h>t.IPColocationFactorThreshold){let g=h-t.IPColocationFactorThreshold,b=g*g;l+=b*t.IPColocationFactorWeight}});let m=e.behaviourPenalty*e.behaviourPenalty;return u+=m*t.behaviourPenaltyWeight,o+=a+l+u,{byTopic:i,p5w:a,p6w:l,p7w:u,score:o}}function Al(s,e,t,r,n){let o={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let i of s){let a=e.get(i);if(a!=null){let l=ap(i,a,t,r,n);for(let[u,p]of l.byTopic){let m=o.byTopic.get(u);m==null&&(m={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},o.byTopic.set(u,m)),m.p1w.push(p.p1w),m.p2w.push(p.p2w),m.p3w.push(p.p3w),m.p3bw.push(p.p3bw),m.p4w.push(p.p4w)}o.p5w.push(l.p5w),o.p6w.push(l.p6w),o.p7w.push(l.p7w),o.score.push(l.score)}else o.p5w.push(0),o.p6w.push(0),o.p7w.push(0),o.score.push(0)}return o}function ki(s){let e=s.getComponents(),t={},r=0;return e[r]?.name==="ip6zone"&&(t.zone=`${e[r].value}`,r++),e[r]?.name==="ip4"||e[r]?.name==="ip6"||e[r]?.name==="dns"||e[r]?.name==="dns4"||e[r]?.name==="dns6"?(t.type=e[r].name,t.host=e[r].value,r++):e[r]?.name==="dnsaddr"&&(t.type=e[r].name,t.host=`_dnsaddr.${e[r].value}`,r++),(e[r]?.name==="tcp"||e[r]?.name==="udp")&&(t.protocol=e[r].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[r].value}`),r++),e[r]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[r].value}`):t.type==="ip6"&&(t.cidr=`${e[r].value}`),r++),t.type==null||t.host==null?null:(e[r]?.name==="tls"&&e[r+1]?.name==="sni"&&(t.sni=e[r+1].value,r+=2),t)}function Ml(s){let e=ki(s);if(e==null)throw new X(`Multiaddr ${s} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function Pl(s){return ki(s)!==null}var Bi=class s extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,s)}},kl=s=>s.reason??new DOMException("This operation was aborted.","AbortError");function Li(s,e){let{milliseconds:t,fallback:r,message:n,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,l,p=new Promise((m,E)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){E(kl(i));return}if(i&&(l=()=>{E(kl(i))},i.addEventListener("abort",l,{once:!0})),s.then(m,E),t===Number.POSITIVE_INFINITY)return;let w=new Bi;a=o.setTimeout.call(void 0,()=>{if(r){try{m(r())}catch(h){E(h)}return}typeof s.cancel=="function"&&s.cancel(),n===!1?m():n instanceof Error?E(n):(w.message=n??`Promise timed out after ${t} milliseconds`,E(w))},t)}).finally(()=>{p.clear(),l&&i&&i.removeEventListener("abort",l)});return p.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},p}var cp=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 lp(s,e,t){let r,n=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),l=[],{addListener:u,removeListener:p}=cp(s),m=async(...w)=>{let h=t.multiArgs?w:w[0];if(t.filter)try{if(!await t.filter(h))return}catch(g){r(),i(g);return}l.push(h),t.count===l.length&&(r(),o(l))},E=(...w)=>{r(),i(t.rejectionMultiArgs?w:w[0])};r=()=>{for(let w of a)p(w,m);for(let w of t.rejectionEvents)a.includes(w)||p(w,E)};for(let w of a)u(w,m);for(let w of t.rejectionEvents)a.includes(w)||u(w,E);t.signal&&t.signal.addEventListener("abort",()=>{E(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(l)});if(n.cancel=r,typeof t.timeout=="number"){let o=Li(n,{milliseconds:t.timeout});return o.cancel=()=>{r(),o.clear()},o}return n}function Bl(s,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let r=lp(s,e,t),n=r.then(o=>o[0]);return n.cancel=r.cancel,n}function up(s){return s?.addEventListener!=null}function hp(s){let e=Kt(),t,r=i=>{e.push(i.data)},n=()=>{e.end(),s.removeEventListener("message",r),s.removeEventListener("close",o),s.removeEventListener("remoteCloseWrite",n)},o=i=>{e.end(i.error),i.error!=null&&t?.reject(i.error),s.removeEventListener("message",r),s.removeEventListener("close",o),s.removeEventListener("remoteCloseWrite",n)};return s.addEventListener("message",r),s.addEventListener("close",o,{once:!0}),s.addEventListener("remoteCloseWrite",n,{once:!0}),{source:e,async sink(i){async function*a(){yield*i}let l=a();for(;;){t=Promise.withResolvers();let{done:u,value:p}=await Promise.race([l.next(),t.promise]);if(s.writeStatus==="closing"||s.writeStatus==="closed"||(p!=null&&(s.send(p)||await Promise.race([Bl(s,"drain",{rejectionEvents:["close"]})])),u===!0))break}await s.close()}}}function Ll(...s){let e=s.map(t=>up(t)?hp(t):t);return nr(...e)}var on=class{rawStream;constructor(e,t,r){this.rawStream=e,r.maxBufferSize!=null&&(e.maxWriteBufferLength=r.maxBufferSize),e.addEventListener("close",n=>{n.error!=null&&t(n.error)})}get protocol(){return this.rawStream.protocol}push(e){this.pushPrefixed(ys.single(e))}pushPrefixed(e){this.rawStream.send(e)}async close(e){await this.rawStream.close(e).catch(t=>{this.rawStream.abort(t)})}},an=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=Ll(this.rawStream,r=>rr(r,t))}async close(){this.closeController.abort()}};var cn=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],o=this.msgIdToStrFn(n),i=this.promises.get(o);i==null&&(i=new Map,this.promises.set(o,i));let a=Date.now();i.has(e)||(i.set(e,a+this.gossipsubIWantFollowupMs),this.metrics!=null&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(o)||this.requestMsByMsg.set(o,a)))}getBrokenPromises(){let e=Date.now(),t=new Map,r=0;return this.promises.forEach((n,o)=>{n.forEach((i,a)=>{i<e&&(t.set(a,(t.get(a)??0)+1),n.delete(a),r++)}),n.size===0&&this.promises.delete(o)}),this.metrics?.iwantPromiseBroken.inc(r),t}deliverMessage(e,t=!1){this.trackMessage(e);let r=this.promises.get(e);r!=null&&(this.promises.delete(e),this.metrics!=null&&(this.metrics.iwantPromiseResolved.inc(1),t&&this.metrics.iwantPromiseResolvedFromDuplicate.inc(1),this.metrics.iwantPromiseResolvedPeers.inc(r.size)))}rejectMessage(e,t){this.trackMessage(e),t!==Ee.Error&&this.promises.delete(e)}clear(){this.promises.clear()}prune(){let e=Date.now()-this.requestMsByMsgExpire,t=0;for(let[r,n]of this.requestMsByMsg.entries())if(n<e)this.requestMsByMsg.delete(r),t++;else break;this.metrics?.iwantMessagePruned.inc(t)}trackMessage(e){if(this.metrics!=null){let t=this.requestMsByMsg.get(e);t!==void 0&&(this.metrics.iwantPromiseDeliveryTime.observe((Date.now()-t)/1e3),this.requestMsByMsg.delete(e))}}};var Rl=j("libp2p-pubsub:"),fp=BigInt(Date.now())*1000000n;function dp(){let s=++fp,e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,s,!1),e}async function Cl(s,e,t,r){switch(s.type){case St.Signing:{let n={from:s.author.toMultihash().bytes,data:r,seqno:dp(),topic:e,signature:void 0,key:void 0},o=Rr([Rl,ct.Message.encode(n)]);n.signature=await s.privateKey.sign(o),n.key=s.key;let i={type:"signed",from:s.author,data:t,sequenceNumber:BigInt(`0x${q(n.seqno??new Uint8Array(0),"base16")}`),topic:e,signature:n.signature,key:qr(n.key)};return{raw:n,msg:i}}case St.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 Fl(s,e){switch(s){case zt:return e.signature!=null?{valid:!1,error:me.SignaturePresent}:e.seqno!=null?{valid:!1,error:me.SeqnoPresent}:e.key!=null?{valid:!1,error:me.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case _t:{if(e.seqno==null)return{valid:!1,error:me.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:me.InvalidSeqno};if(e.signature==null)return{valid:!1,error:me.InvalidSignature};if(e.from==null)return{valid:!1,error:me.InvalidPeerId};let t;try{t=gs(Je(e.from))}catch{return{valid:!1,error:me.InvalidPeerId}}let r;if(e.key!=null){if(r=qr(e.key),t.publicKey!==void 0&&!r.equals(t.publicKey))return{valid:!1,error:me.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:me.InvalidPeerId};r=t.publicKey}let n={from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0},o=Rr([Rl,ct.Message.encode(n)]);return await r.verify(o,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?qr(e.key):r}}:{valid:!1,error:me.InvalidSignature}}default:throw new Error("Unreachable")}}function ze(s=[],e){return{subscriptions:[],messages:s,control:e!==void 0?{graft:e.graft??[],prune:e.prune??[],ihave:e.ihave??[],iwant:e.iwant??[],idontwant:e.idontwant??[]}:void 0}}function Ri(s){return s.control===void 0&&(s.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),s}function Ye(s){if(s.length<=1)return s;let e=()=>Math.floor(Math.random()*Math.floor(s.length));for(let t=0;t<s.length;t++){let r=e(),n=s[t];s[t]=s[r],s[r]=n}return s}function Nl(s){return q(s,"base64")}function Ol(s,e,t){switch(s){case _t:return{type:St.Signing,author:e,key:Ve(t.publicKey),privateKey:t};case zt:return{type:St.Anonymous};default:throw new Error(`Unknown signature policy "${s}"`)}}var pp=(s,e)=>{let t=j(e.toString(16).padStart(16,"0"),"base16"),r=Ve(s),n=new Uint8Array(r.byteLength+t.length);return n.set(r,0),n.set(t,r.byteLength),n};function Ul(s){if(s.type!=="signed")throw new Error("expected signed message type");if(s.sequenceNumber==null)throw Error("missing seqno field");return pp(s.from.publicKey??s.key,s.sequenceNumber)}async function Kl(s){return Ft.encode(s.data)}function zl(s){if(Pl(s)){let e=Ml(s);switch(e.type){case"ip4":case"ip6":return e.host;default:break}}return null}var Ss=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 Me;(function(s){s[s.started=0]="started",s[s.stopped=1]="stopped"})(Me||(Me={}));var ln=class extends lr{globalSignaturePolicy;protocols=[Gt,Oi,hn];publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=Kt({objectMode:!0});direct=new Set;floodsubPeers=new Set;seenCache;acceptFromWhitelist=new Map;topics=new Map;subscriptions=new Set;mesh=new Map;fanout=new Map;fanoutLastpub=new Map;gossip=new Map;control=new Map;peerhave=new Map;iasked=new Map;iwantCounts=new Map;backoff=new Map;outbound=new Map;msgIdFn;fastMsgIdFn;msgIdToStrFn;fastMsgIdCache;publishedMessageIds;mcache;score;topicValidators=new Map;log;heartbeatTicks=0;gossipTracer;idontwantCounts=new Map;idontwants=new Map;components;directPeerInitial=null;static multicodec=Gt;opts;decodeRpcLimits;metrics;status={code:Me.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:xl(t.scoreParams),scoreThresholds:El(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=r.decodeRpcLimits??gl,this.globalSignaturePolicy=r.globalSignaturePolicy??_t,r.fallbackToFloodsub&&this.protocols.push(un),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 Ss({validityMs:r.seenTTL}),this.publishedMessageIds=new Ss({validityMs:r.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case _t:this.msgIdFn=Ul;break;case zt:this.msgIdFn=Kl;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new Ss({validityMs:r.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??Nl,this.mcache=t.messageCache??new en(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(i=>i.meshMessageDeliveriesWindow),1e3),o=wl(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:r.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:n/1e3});o.mcacheSize.addCollect(()=>{this.onScrapeMetrics(o)});for(let i of this.protocols)o.protocolsEnabled.set({protocol:i},1);this.metrics=o}else this.metrics=null;this.gossipTracer=new cn(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new nn(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:r.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnLimitedConnection=t.runOnLimitedConnection,this.allowedTopics=r.allowedTopics!=null?new Set(r.allowedTopics):null}[Symbol.toStringTag]="@libp2p/gossipsub";[Hi]=["@libp2p/pubsub"];[Gi]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===Me.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=Ol(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=Kt({objectMode:!0}),nr(this.outboundInflightQueue,async o=>{for await(let{peerId:i,connection:a}of o)await this.createOutboundStream(i,a)}).catch(o=>{this.log.error("outbound inflight queue error",o)}),await Promise.all(this.opts.directPeers.map(async o=>{await this.components.peerStore.merge(o.id,{multiaddrs:o.addrs})}));let e=this.components.registrar;await Promise.all(this.protocols.map(async o=>e.handle(o,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 o=>e.register(o,t))),n=setTimeout(this.runHeartbeat,100);this.status={code:Me.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 o=>this.connect(o)))}).catch(o=>{this.log(o)})},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!==Me.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:Me.stopped},this.opts.tagMeshPeers&&(this.removeEventListener("gossipsub:graft",this.tagMeshPeer),this.removeEventListener("gossipsub:prune",this.untagMeshPeer));let t=this.components.registrar;await Promise.all(this.protocols.map(async n=>t.unhandle(n))),e.forEach(n=>{t.unregister(n)}),this.outboundInflightQueue.end();let r=[];for(let n of this.streamsOutbound.values())r.push(n.close());this.streamsOutbound.clear();for(let n of this.streamsInbound.values())r.push(n.close());this.streamsInbound.clear(),await Promise.all(r),this.peers.clear(),this.subscriptions.clear(),this.topics.clear(),this.heartbeatTimer!=null&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.iwantCounts.clear(),this.backoff.clear(),this.outbound.clear(),this.gossipTracer.clear(),this.seenCache.clear(),this.fastMsgIdCache!=null&&this.fastMsgIdCache.clear(),this.directPeerInitial!=null&&clearTimeout(this.directPeerInitial),this.idontwantCounts.clear(),this.idontwants.clear(),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream(e,t){if(!this.isStarted())return;let r=t.remotePeer;this.addPeer(r,t.direction,t.remoteAddr),this.createInboundStream(r,e),this.outboundInflightQueue.push({peerId:r,connection:t})}onPeerConnected(e,t){this.metrics?.newConnectionCount.inc({status:t.status}),!(!this.isStarted()||t.status!=="open")&&(this.addPeer(e,t.direction,t.remoteAddr),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}async createOutboundStream(e,t){if(!this.isStarted())return;let r=e.toString();if(this.peers.has(r)&&!this.streamsOutbound.has(r))try{let n=new on(await t.newStream(this.protocols,{runOnLimitedConnection:this.runOnLimitedConnection}),i=>{this.log.error("outbound pipe error",i)},{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(r,n);let o=n.protocol;o===un&&this.floodsubPeers.add(r),this.metrics?.peersPerProtocol.inc({protocol:o},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(i=>{this.log.error(i)})),this.log("create inbound stream %s",r);let o=new an(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(r,o),this.pipePeerReadStream(e,o.source).catch(i=>{this.log(i)})}addPeer(e,t,r){let n=e.toString();if(!this.peers.has(n)){this.peers.set(n,e),this.score.addPeer(n);let o=zl(r);o!==null?this.score.addIP(n,o):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(o=>{this.log.error(o)}),n?.close().catch(o=>{this.log.error(o)}),this.streamsOutbound.delete(t),this.streamsInbound.delete(t);for(let[o,i]of this.topics)i.delete(t),i.size===0&&this.topics.delete(o);for(let[o,i]of this.mesh)i.delete(t)&&this.metrics?.onRemoveFromMesh(o,Ke.Dc,1);for(let o of this.fanout.values())o.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===Me.started}getMeshPeers(e){let t=this.mesh.get(e);return t!=null?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(t!=null?Array.from(t):[]).map(r=>this.peers.get(r)??Ot(r))}getTopics(){return Array.from(this.subscriptions)}decodeRpc(e){return ct.decode(e,{limits:{subscriptions:this.decodeRpcLimits.maxSubscriptions,messages:this.decodeRpcLimits.maxMessages,control:{ihave:this.decodeRpcLimits.maxControlMessages,ihave$:{messageIDs:this.decodeRpcLimits.maxIhaveMessageIDs},iwant:this.decodeRpcLimits.maxControlMessages,iwant$:{messageIDs:this.decodeRpcLimits.maxIwantMessageIDs},graft:this.decodeRpcLimits.maxControlMessages,prune:this.decodeRpcLimits.maxControlMessages,prune$:{peers:this.decodeRpcLimits.maxPeerInfos},idontwant:this.decodeRpcLimits.maxControlMessages,idontwant$:{messageIDs:this.decodeRpcLimits.maxIdontwantMessageIDs}}}})}async pipePeerReadStream(e,t){try{await nr(t,async r=>{for await(let n of r)try{let o=n.subarray(),i=this.decodeRpc(o);if(this.metrics?.onRpcRecv(i,o.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,i)}catch(a){this.metrics?.onRpcRecvError(),this.log(a)}else this.handleReceivedRpc(e,i).catch(a=>{this.metrics?.onRpcRecvError(),this.log(a)})}catch(o){this.metrics?.onRpcDataError(),this.log(o)}})}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,o=0,i=0,a=0,l=0;if(t.control!=null&&(t.control.ihave!=null&&(o=t.control.ihave.length),t.control.iwant!=null&&(i=t.control.iwant.length),t.control.graft!=null&&(a=t.control.graft.length),t.control.prune!=null&&(l=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${r} messages ${n} ihave ${o} iwant ${i} graft ${a} prune ${l}`),t.subscriptions!=null&&t.subscriptions.length>0){let u=[];t.subscriptions.forEach(p=>{let m=p.topic,E=p.subscribe===!0;if(m!=null){if(this.allowedTopics!=null&&!this.allowedTopics.has(m))return;this.handleReceivedSubscription(e,m,E),u.push({topic:m,subscribe:E})}}),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:u}})}for(let u of t.messages){if(this.allowedTopics!=null&&!this.allowedTopics.has(u.topic))continue;let p=this.handleReceivedMessage(e,u).catch(m=>{this.metrics?.onMsgRecvError(u.topic),this.log(m)});this.opts.awaitRpcMessageHandler&&await p}t.control!=null&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,r){this.log("subscription update from %p topic %s",e,t);let n=this.topics.get(t);r?(n==null&&(n=new Set,this.topics.set(t,n)),n.add(e.toString())):n!=null&&(n.delete(e.toString()),n.size===0&&this.topics.delete(t))}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);let r=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,r.code);let n=r.code;switch(n){case ge.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 ge.invalid:if(r.msgIdStr!=null){let o=r.msgIdStr;this.score.rejectMessage(e.toString(),o,t.topic,r.reason),this.gossipTracer.rejectMessage(o,r.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);this.metrics?.onMsgRecvInvalid(t.topic,r);return;case ge.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:ge.duplicate,msgIdStr:n};let o=await Fl(this.globalSignaturePolicy,t);if(!o.valid)return{code:ge.invalid,reason:Ee.Error,error:o.error};let i=o.message;try{this.dataTransform!=null&&(i.data=this.dataTransform.inboundTransform(t.topic,i.data))}catch(m){return this.log("Invalid message, transform failed",m),{code:ge.invalid,reason:Ee.Error,error:me.TransformFailed}}let a=await this.msgIdFn(i),l=this.msgIdToStrFn(a),u={msgId:a,msgIdStr:l};if(r!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(r,l)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(l))return{code:ge.duplicate,msgIdStr:l};this.seenCache.put(l),(t.data?.length??0)>=this.opts.idontwantMinDataSize&&this.sendIDontWants(a,t.topic,e.toString());let p=this.topicValidators.get(t.topic);if(p!=null){let m;try{m=await p(e,i)}catch(E){let w=E.code;w===Ki&&(m=be.Ignore),w===Ui?m=be.Reject:m=be.Ignore}if(m!==be.Accept)return{code:ge.invalid,reason:Pi(m),msgIdStr:l}}return{code:ge.valid,messageId:u,msg:i}}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):[],o=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&&o.length===0)return;let i=this.sendRpc(e,ze(n,{iwant:r,prune:o})),a=r[0]?.messageIDs;a!=null&&(i?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:Es.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:Es.MaxIhave}),[];let o=this.iasked.get(e)??0;if(o>=5e3)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,o),this.metrics?.ihaveRcvIgnored.inc({reason:Es.MaxIasked}),[];let i=new Map,a=0;e:for(let{topicID:p,messageIDs:m}of t){if(p==null||m==null||!this.mesh.has(p))continue;let E=0;for(let w of m){if(a>=5e3)break e;a++;let h=this.msgIdToStrFn(w);this.seenCache.has(h)||(i.set(h,w),E++)}this.metrics?.onIhaveRcv(p,m.length,E)}if(i.size===0)return[];let l=i.size;l+o>5e3&&(l=5e3-o),this.log("IHAVE: Asking for %d out of %d messages from %s",l,i.size,e);let u=Array.from(i.values());return Ye(u),u=u.slice(0,l),this.iasked.set(e,o+l),[{messageIDs:u}]}handleIWant(e,t){if(t.length===0)return[];let r=this.score.score(e);if(r<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,r),[];let n=(this.iwantCounts.get(e)??0)+1;if(this.iwantCounts.set(e,n),n>10)return this.log("IWANT: peer %s has requested too many times within this heartbeat interval; ignoring",e),[];let o=new Map,i=new Map,a=0,l=0;e:for(let{messageIDs:u}of t)if(u!=null)for(let p of u){if(l>=5e3)break e;l++;let m=this.msgIdToStrFn(p),E=this.mcache.getWithIWantCount(m,e);if(E==null){a++;continue}if(i.set(E.msg.topic,1+(i.get(E.msg.topic)??0)),E.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,p);continue}o.set(m,E.msg)}return this.metrics?.onIwantRcv(i,a),o.size===0?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",o.size,e),Array.from(o.values()))}async handleGraft(e,t){let r=[],n=this.score.score(e),o=Date.now(),i=this.opts.doPX;if(t.forEach(({topicID:l})=>{if(l==null)return;let u=this.mesh.get(l);if(u==null){i=!1;return}if(u.has(e))return;let p=this.backoff.get(l)?.get(e);if(this.direct.has(e))this.log("GRAFT: ignoring request from direct peer %s",e),r.push(l),i=!1;else if(typeof p=="number"&&o<p){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,vs.GraftBackoff),i=!1;let m=p+this.opts.graftFloodThreshold-this.opts.pruneBackoff;o<m&&this.score.addPenalty(e,1,vs.GraftBackoff),this.addBackoff(e,l),r.push(l)}else n<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,n,l),r.push(l),i=!1,this.addBackoff(e,l)):u.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(r.push(l),this.addBackoff(e,l)):(this.log("GRAFT: Add mesh link from %s in %s",e,l),this.score.graft(e,l),u.add(e),this.metrics?.onAddToMesh(l,Se.Subscribed,1));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:l,direction:"inbound"}})}),r.length===0)return[];let a=!1;return Promise.all(r.map(async l=>this.makePrune(e,l,i,a)))}async handlePrune(e,t){let r=this.score.score(e);for(let{topicID:n,backoff:o,peers:i}of t){if(n==null)continue;let a=this.mesh.get(n);if(a==null)return;this.log("PRUNE: Remove mesh link to %s in %s",e,n),this.score.prune(e,n),a.has(e)&&(a.delete(e),this.metrics?.onRemoveFromMesh(n,Ke.Prune,1)),typeof o=="number"&&o>0?this.doAddBackoff(e,n,o*1e3):this.addBackoff(e,n),i!=null&&i.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(i)),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,o=this.idontwants.get(e);o==null&&(o=new Map,this.idontwants.set(e,o));let i=0;e:for(let{messageIDs:l}of t)for(let u of l){if(r>=this.opts.idontwantMaxMessages)break e;r++;let p=this.msgIdToStrFn(u);o.set(p,this.heartbeatTicks),this.mcache.msgs.has(p)||i++}this.idontwantCounts.set(e,r);let a=r-n;this.metrics?.onIdontwantRcv(a,i)}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 o=Date.now()+r;(n.get(e)??0)<o&&n.set(e,o)}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,vs.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!==0)return;let e=Date.now();this.backoff.forEach((t,r)=>{t.forEach((n,o)=>{n+1*this.opts.heartbeatInterval<e&&t.delete(o)}),t.size===0&&this.backoff.delete(r)})}async directConnect(){let e=[];this.direct.forEach(t=>{this.streamsOutbound.has(t)||e.push(t)}),await Promise.all(e.map(async t=>this.connect(t)))}async pxConnect(e){e.length>this.opts.prunePeers&&(Ye(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async r=>{if(r.peerID==null)return;let n=gs(Je(r.peerID)),o=n.toString();if(!this.peers.has(o)){if(r.signedPeerRecord==null){t.push(o);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(o)}catch{this.log("bogus peer record obtained through px: invalid signature or not a peer record")}}})),t.length!==0&&await Promise.all(t.map(async r=>this.connect(r)))}async connect(e){this.log("Initiating connection with %s",e);let t=Ot(e),r=await this.components.connectionManager.openConnection(t);for(let n of this.protocols)for(let o of this.components.registrar.getTopologies(n))o.onConnect?.(t,r)}subscribe(e){if(this.status.code!==Me.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!==Me.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!==Me.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(o=>{!this.direct.has(o)&&this.score.score(o)>=0&&r?.has(o)!==!0&&t.add(o)}),this.metrics?.onAddToMesh(e,Se.Fanout,t.size)),t.size<this.opts.D){let o=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,Se.Random,t.size-o)}this.mesh.set(e,t),t.forEach(o=>{this.log("JOIN: Add mesh link to %s in %s",o,e),this.sendGraft(o,e)})}leave(e){if(this.status.code!==Me.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,o=this.topics.get(e);o!=null&&(this.direct.forEach(a=>{o.has(a)&&t!==a&&!(r?.has(a)??!1)&&n.add(a)}),this.floodsubPeers.forEach(a=>{o.has(a)&&t!==a&&!(r?.has(a)??!1)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&n.add(a)}));let i=this.mesh.get(e);return i!=null&&i.size>0&&i.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(o=>{this.direct.has(o)?(t.add(o),r.direct++):this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),r.floodsub++)});else{this.direct.forEach(i=>{n.has(i)&&(t.add(i),r.direct++)}),this.floodsubPeers.forEach(i=>{n.has(i)&&this.score.score(i)>=this.opts.scoreThresholds.publishThreshold&&(t.add(i),r.floodsub++)});let o=this.mesh.get(e);if(o!=null&&o.size>0)o.forEach(i=>{t.add(i),r.mesh++}),o.size<this.opts.D&&this.getRandomGossipPeers(e,this.opts.D-o.size,a=>!o.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 i=this.fanout.get(e);if(i!=null&&i.size>0)i.forEach(a=>{t.add(a),r.fanout++});else{let a=this.getRandomGossipPeers(e,this.opts.D,l=>this.score.score(l)>=this.opts.scoreThresholds.publishThreshold);a.size>0&&(this.fanout.set(e,a),a.forEach(l=>{t.add(l),r.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:r}}forwardMessage(e,t,r,n){r!=null&&this.score.deliverMessage(r,e,t.topic);let o=this.selectPeersToForward(t.topic,r,n);o.forEach(i=>{this.sendRpc(i,ze([t]))}),this.metrics?.onForwardMsg(t.topic,o.size)}async publish(e,t,r){let n=Date.now(),o=this.dataTransform!=null?this.dataTransform.outboundTransform(e,t):t;if(this.publishConfig==null)throw Error("PublishError.Uninitialized");let{raw:i,msg:a}=await Cl(this.publishConfig,e,t,o),l=await this.msgIdFn(a),u=this.msgIdToStrFn(l),p=r?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(u)){if(p)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:m,tosendCount:E}=this.selectPeersToPublish(e),w=this.opts.emitSelf&&this.subscriptions.has(e),h=r?.allowPublishToZeroTopicPeers??this.opts.allowPublishToZeroTopicPeers;if(m.size===0&&!h&&!w)throw Error("PublishError.NoPeersSubscribedToTopic");this.seenCache.put(u),this.mcache.put({msgId:l,msgIdStr:u},i,!0),this.gossipTracer.deliverMessage(u),this.publishedMessageIds.put(u);let g=r?.batchPublish??this.opts.batchPublish,b=ze([i]);if(g)this.sendRpcInBatch(m,b);else for(let _ of m)this.sendRpc(_,b)||m.delete(_);let x=Date.now()-n;return this.metrics?.onPublishMsg(e,E,m.size,i.data!=null?i.data.length:0,x),w&&(m.add(this.components.peerId.toString()),super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:u,msg:a}})),super.dispatchEvent(new CustomEvent("message",{detail:a}))),{recipients:Array.from(m.values()).map(_=>this.peers.get(_)??Ot(_))}}sendRpcInBatch(e,t){let r=ct.encode(t),n=ys.single(r);for(let o of e){let i=this.streamsOutbound.get(o);if(i==null){this.log(`Cannot send RPC to ${o} as there is no open stream to it available`),e.delete(o);continue}try{i.pushPrefixed(n)}catch(a){e.delete(o),this.log.error(`Cannot send rpc to ${o}`,a)}this.metrics?.onRpcSent(t,r.length)}}reportMessageValidationResult(e,t,r){let n;if(r===be.Accept){if(n=this.mcache.validate(e),n!=null){let{message:i,originatingPeers:a}=n;this.score.deliverMessage(t,e,i.topic),this.forwardMessage(e,n.message,t,a)}}else if(n=this.mcache.remove(e),n!=null){let i=Pi(r),{message:a,originatingPeers:l}=n;this.score.rejectMessage(t,e,a.topic,i);for(let u of l)this.score.rejectMessage(u,e,a.topic,i)}let o=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(n,r,o)}sendGraft(e,t){let n=ze([],{graft:[{topicID:t}]});this.sendRpc(e,n)}async sendPrune(e,t){let n=[await this.makePrune(e,t,this.opts.doPX,!0)],o=ze([],{prune:n});this.sendRpc(e,o)}sendIDontWants(e,t,r){let n=this.mesh.get(t);if(n==null)return;let o=new Set(n);o.delete(r);for(let a of o)this.streamsOutbound.get(a)?.protocol!==Gt&&o.delete(a);let i=ze([],{idontwant:[{messageIDs:[e]}]});this.sendRpcInBatch(o,i)}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 o=this.gossip.get(e);o!=null&&(this.piggybackGossip(e,t,o),this.gossip.delete(e));let i=ct.encode(t);try{r.push(i)}catch(a){return this.log.error(`Cannot send rpc to ${e}`,a),n!=null&&this.control.set(e,n),o!=null&&this.gossip.set(e,o),!1}if(this.metrics?.onRpcSent(t,i.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=Ri(t);for(let o of r.graft)o.topicID!=null&&(this.mesh.get(o.topicID)?.has(e)??!1)&&n.control.graft.push(o);for(let o of r.prune)o.topicID!=null&&!(this.mesh.get(o.topicID)?.has(e)??!1)&&n.control.prune.push(o)}piggybackGossip(e,t,r){let n=Ri(t);n.control.ihave=r}async sendGraftPrune(e,t,r){let n=this.opts.doPX,o=!1;for(let[i,a]of e){let l=a.map(m=>({topicID:m})),u=[],p=t.get(i);p!=null&&(u=await Promise.all(p.map(async m=>this.makePrune(i,m,n&&!(r.get(i)??!1),o))),t.delete(i)),this.sendRpc(i,ze([],{graft:l,prune:u}))}for(let[i,a]of t){let l=await Promise.all(a.map(async u=>this.makePrune(i,u,n&&!(r.get(i)??!1),o)));this.sendRpc(i,ze([],{prune:l}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[r,n]of e)this.doEmitGossip(r,n,t.get(r)??[])}doEmitGossip(e,t,r){if(r.length===0||(Ye(r),r.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",r.length),t.size===0))return;let n=this.opts.Dlazy,i=this.opts.gossipFactor*t.size,a=t;i>n&&(n=i),n>a.size?n=a.size:a=Ye(Array.from(a)).slice(0,n),a.forEach(l=>{let u=r;r.length>5e3&&(u=Ye(u.slice()).slice(0,5e3)),this.pushGossip(l,{topicID:e,messageIDs:u})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,ze([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let r=ze([],{graft:t.graft,prune:t.prune});this.sendRpc(e,r)}}pushGossip(e,t){this.log("Add gossip to %s",e);let r=this.gossip.get(e)??[];this.gossip.set(e,r.concat(t))}async makePrune(e,t,r,n){if(this.score.prune(e,t),this.streamsOutbound.get(e)?.protocol===hn)return{topicID:t,peers:[]};let o=n?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,i=o/1e3;if(this.doAddBackoff(e,t,o),!r)return{topicID:t,peers:[],backoff:i};let a=this.getRandomGossipPeers(t,this.opts.prunePeers,u=>u!==e&&this.score.score(u)>=0),l=await Promise.all(Array.from(a).map(async u=>{let p=this.peers.get(u)??Ot(u),m;try{m=await this.components.peerStore.get(p)}catch(E){if(E.name!=="NotFoundError")throw E}return{peerID:p.toMultihash().bytes,signedPeerRecord:m?.peerRecordEnvelope}}));return{topicID:t,peers:l,backoff:i}}runHeartbeat=()=>{let e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch(t=>{this.log("Error running heartbeat",t)}).finally(()=>{if(e?.(),this.status.code===Me.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:o,fanoutTTL:i}=this.opts;this.heartbeatTicks++;let a=new Map,l=h=>{let g=a.get(h);return g===void 0&&(g=this.score.score(h),a.set(h,g)),g},u=new Map,p=new Map,m=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.iwantCounts.clear(),this.applyIwantPenalties(),this.idontwantCounts.clear();for(let h of this.idontwants.values())for(let[g,b]of h)this.heartbeatTicks-b>=this.opts.mcacheLength&&h.delete(g);this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let E=new Map;this.mesh.forEach((h,g)=>{let b=this.topics.get(g),x=new Set,_=new Set;if(E.set(g,_),b!=null){let d=Ye(Array.from(b)),y=this.backoff.get(g);for(let v of d){let S=this.streamsOutbound.get(v);if(S!=null&&this.protocols.includes(S.protocol)&&!h.has(v)&&!this.direct.has(v)){let M=l(v);y?.has(v)!==!0&&M>=0&&x.add(v),M>=this.opts.scoreThresholds.gossipThreshold&&_.add(v)}}}let c=(d,y)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",d,g),this.addBackoff(d,g),h.delete(d),l(d)>=this.opts.scoreThresholds.gossipThreshold&&_.add(d),this.metrics?.onRemoveFromMesh(g,y,1);let v=p.get(d);v==null?p.set(d,[g]):v.push(g)},f=(d,y)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",d,g),this.score.graft(d,g),h.add(d),_.delete(d),this.metrics?.onAddToMesh(g,y,1);let v=u.get(d);v==null?u.set(d,[g]):v.push(g)};if(h.forEach(d=>{let y=l(d);y<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",d,y,g),c(d,Ke.BadScore),m.set(d,!0))}),h.size<t){let d=e-h.size;Sl(x,d).forEach(v=>{f(v,Se.NotEnough)})}if(h.size>r){let d=Array.from(h);d.sort((v,S)=>l(S)-l(v)),d=d.slice(0,n).concat(Ye(d.slice(n)));let y=0;if(d.slice(0,e).forEach(v=>{(this.outbound.get(v)??!1)&&y++}),y<o){let v=M=>{let C=d[M];for(let N=M;N>0;N--)d[N]=d[N-1];d[0]=C};if(y>0){let M=y;for(let C=1;C<e&&M>0;C++)(this.outbound.get(d[C])??!1)&&(v(C),M--)}let S=e-y;for(let M=e;M<d.length&&S>0;M++)(this.outbound.get(d[M])??!1)&&(v(M),S--)}d.slice(e).forEach(v=>{c(v,Ke.Excess)})}if(h.size>=t){let d=0;if(h.forEach(y=>{(this.outbound.get(y)??!1)&&d++}),d<o){let y=o-d;sn(x,y,S=>this.outbound.get(S)===!0).forEach(S=>{f(S,Se.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&h.size>1){let d=Array.from(h).sort((S,M)=>l(S)-l(M)),y=Math.floor(h.size/2),v=l(d[y]);if(v<this.opts.scoreThresholds.opportunisticGraftThreshold){let S=this.opts.opportunisticGraftPeers,M=sn(x,S,C=>l(C)>v);for(let C of M)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",C,g),f(C,Se.Opportunistic)}}});let w=Date.now();this.fanoutLastpub.forEach((h,g)=>{h+i<w&&(this.fanout.delete(g),this.fanoutLastpub.delete(g))}),this.fanout.forEach((h,g)=>{let b=this.topics.get(g);h.forEach(f=>{(!(b?.has(f)??!1)||l(f)<this.opts.scoreThresholds.publishThreshold)&&h.delete(f)});let x=this.topics.get(g),_=[],c=new Set;if(E.set(g,c),x!=null){let f=Ye(Array.from(x));for(let d of f){let y=this.streamsOutbound.get(d);if(y!=null&&this.protocols.includes(y.protocol)&&!h.has(d)&&!this.direct.has(d)){let v=l(d);v>=this.opts.scoreThresholds.publishThreshold&&_.push(d),v>=this.opts.scoreThresholds.gossipThreshold&&c.add(d)}}}if(h.size<e){let f=e-h.size;_.slice(0,f).forEach(d=>{h.add(d),c?.delete(d)})}}),this.emitGossip(E),await this.sendGraftPrune(u,p,m),this.flush(),this.mcache.shift(),this.dispatchEvent(new CustomEvent("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,r=()=>!0){let n=this.topics.get(e);if(n==null)return new Set;let o=[];return n.forEach(i=>{let a=this.streamsOutbound.get(i);a!=null&&this.protocols.includes(a.protocol)&&r(i)&&o.push(i)}),o=Ye(o),t>0&&o.length>t&&(o=o.slice(0,t)),new Set(o)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0,r=Date.now();e.connectedPeersBackoffSec.reset();for(let l of this.backoff.values()){t+=l.size;for(let[u,p]of l.entries())this.peers.has(u)&&e.connectedPeersBackoffSec.observe(Math.max(0,p-r)/1e3)}e.cacheSize.set({cache:"backoff"},t);let n=0;for(let l of this.idontwants.values())n+=l.size;e.cacheSize.set({cache:"idontwants"},n);for(let[l,u]of this.topics)e.topicPeersCount.set({topicStr:l},u.size);for(let[l,u]of this.mesh)e.meshPeerCounts.set({topicStr:l},u.size);let o=[],i=new Map;e.behaviourPenalty.reset();for(let l of this.peers.keys()){let u=this.score.score(l);o.push(u),i.set(l,u),e.behaviourPenalty.observe(this.score.peerStats.get(l)?.behaviourPenalty??0)}e.registerScores(o,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,i);let a=Al(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(a)}tagMeshPeer=e=>{let{peerId:t,topic:r}=e.detail;this.components.peerStore.merge(this.peers.get(t)??Ot(t),{tags:{[r]:{value:100}}}).catch(n=>{this.log.error("Error tagging peer %s with topic %s",t,r,n)})};untagMeshPeer=e=>{let{peerId:t,topic:r}=e.detail;this.components.peerStore.merge(this.peers.get(t)??Ot(t),{tags:{[r]:void 0}}).catch(n=>{this.log.error("Error untagging peer %s with topic %s",t,r,n)})}};var _t="StrictSign",zt="StrictNoSign",be;(function(s){s.Accept="accept",s.Ignore="ignore",s.Reject="reject"})(be||(be={}));var Gp=Gt;function qp(s={}){return e=>new ln(e,s)}return Yl(Vp);})();
2
+ "use strict";var Libp2PGossipsub=(()=>{var Gl=Object.create;var ir=Object.defineProperty;var ql=Object.getOwnPropertyDescriptor;var Vl=Object.getOwnPropertyNames;var Wl=Object.getPrototypeOf,$l=Object.prototype.hasOwnProperty;var jl=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),V=(s,e)=>{for(var t in e)ir(s,t,{get:e[t],enumerable:!0})},Ni=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Vl(e))!$l.call(s,n)&&n!==t&&ir(s,n,{get:()=>e[n],enumerable:!(r=ql(e,n))||r.enumerable});return s};var Zl=(s,e,t)=>(t=s!=null?Gl(Wl(s)):{},Ni(e||!s||!s.__esModule?ir(t,"default",{value:s,enumerable:!0}):t,s)),Yl=s=>Ni(ir({},"__esModule",{value:!0}),s);var Tl=jl((rv,Il)=>{"use strict";function Y(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))}Y.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]}};Y.prototype.get=function(e){return this.peekAt(e)};Y.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};Y.prototype.peekFront=function(){return this.peek()};Y.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(Y.prototype,"length",{get:function(){return this.size()}});Y.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};Y.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)};Y.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}};Y.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)};Y.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}};Y.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 o=this._list[t],i;if(e<r/2){for(i=e;i>0;i--)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(i=r-1-e;i>0;i--)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 o}}};Y.prototype.remove=function(e,t){var r=e,n,o=t;if(r===(r|0)&&this._head!==this._tail){var i=this.size(),a=this._list.length;if(!(r>=i||r<-i||t<1)){if(r<0&&(r+=i),t===1||!t)return n=new Array(1),n[0]=this.removeOne(r),n;if(r===0&&r+t>=i)return n=this.toArray(),this.clear(),n;r+t>i&&(t=i-r);var l;for(n=new Array(t),l=0;l<t;l++)n[l]=this._list[this._head+r+l&this._capacityMask];if(r=this._head+r&this._capacityMask,e+t===i){for(this._tail=this._tail-t+a&this._capacityMask,l=t;l>0;l--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(e===0){for(this._head=this._head+t+a&this._capacityMask,l=t-1;l>0;l--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(r<i/2){for(this._head=this._head+e+t+a&this._capacityMask,l=e;l>0;l--)this.unshift(this._list[r=r-1+a&this._capacityMask]);for(r=this._head-1+a&this._capacityMask;o>0;)this._list[r=r-1+a&this._capacityMask]=void 0,o--;e<0&&(this._tail=r)}else{for(this._tail=r,r=r+t+a&this._capacityMask,l=i-(t+e);l>0;l--)this.push(this._list[r++]);for(r=this._tail;o>0;)this._list[r=r+1+a&this._capacityMask]=void 0,o--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),n}}};Y.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 o,i,a,l=arguments.length,u=this._list.length,p=2;if(!n||r<n/2){for(i=new Array(r),o=0;o<r;o++)i[o]=this._list[this._head+o&this._capacityMask];for(t===0?(a=[],r>0&&(this._head=this._head+r+u&this._capacityMask)):(a=this.remove(r,t),this._head=this._head+r+u&this._capacityMask);l>p;)this.unshift(arguments[--l]);for(o=r;o>0;o--)this.unshift(i[o-1])}else{i=new Array(n-(r+t));var m=i.length;for(o=0;o<m;o++)i[o]=this._list[this._head+r+t+o&this._capacityMask];for(t===0?(a=[],r!=n&&(this._tail=this._head+r+u&this._capacityMask)):(a=this.remove(r,t),this._tail=this._tail-m+u&this._capacityMask);p<l;)this.push(arguments[p++]);for(o=0;o<m;o++)this.push(i[o])}return a}else return this.remove(r,t)}};Y.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0};Y.prototype.isEmpty=function(){return this._head===this._tail};Y.prototype.toArray=function(){return this._copyArray(!1)};Y.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]};Y.prototype._copyArray=function(e,t){var r=this._list,n=r.length,o=this.length;if(t=t|o,t==o&&this._head<this._tail)return this._list.slice(this._head,this._tail);var i=new Array(t),a=0,l;if(e||this._head>this._tail){for(l=this._head;l<n;l++)i[a++]=r[l];for(l=0;l<this._tail;l++)i[a++]=r[l]}else for(l=this._head;l<this._tail;l++)i[a++]=r[l];return i};Y.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};Y.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1};Y.prototype._nextPowerOf2=function(e){var t=Math.log(e)/Math.log(2),r=1<<t+1;return Math.max(r,4)};Il.exports=Y});var Vp={};V(Vp,{StrictNoSign:()=>zt,StrictSign:()=>_t,TopicValidatorResult:()=>be,gossipsub:()=>qp,multicodec:()=>Gp});var un="/floodsub/1.0.0",hn="/meshsub/1.0.0",Oi="/meshsub/1.1.0",Gt="/meshsub/1.2.0";var Ui="ERR_TOPIC_VALIDATOR_REJECT",Ki="ERR_TOPIC_VALIDATOR_IGNORE";var X=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},qt=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var ar=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},cr=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Vt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var fn=Symbol.for("@libp2p/peer-id");function Xl(s){return typeof s?.handleEvent=="function"}function Jl(s){return(s!==!0&&s!==!1&&s?.once)??!1}var lr=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,r){let n=Jl(r);super.addEventListener(e,i=>{if(n){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:l})=>l!==t),this.#e.set(i.type,a))}Xl(t)?t.handleEvent(i):t(i)},r);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:n})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),t??null,r);let n=this.#e.get(e);n!=null&&(n=n.filter(({callback:o})=>o!==t),this.#e.set(e,n))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Hi=Symbol.for("@libp2p/service-capabilities"),Gi=Symbol.for("@libp2p/service-dependencies");var bn={};V(bn,{base58btc:()=>Q,base58flickr:()=>iu});var vm=new Uint8Array(0);function qi(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 Xe(s){if(s instanceof Uint8Array&&s.constructor.name==="Uint8Array")return Tt(s);if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return Tt(new Uint8Array(s.buffer,s.byteOffset,s.byteLength));throw new Error("Unknown type, must be binary type")}function Vi(s){return new TextEncoder().encode(s)}function Wi(s){return new TextDecoder().decode(s)}function Ql(s){return s?.buffer instanceof ArrayBuffer}function Tt(s){return Ql(s)?s:s.slice()}function eu(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 o=s.charAt(n),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=n}var a=s.length,l=s.charAt(0),u=Math.log(a)/Math.log(256),p=Math.log(256)/Math.log(a);function m(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var g=0,b=0,x=0,_=h.length;x!==_&&h[x]===0;)x++,g++;for(var c=(_-x)*p+1>>>0,f=new Uint8Array(c);x!==_;){for(var d=h[x],y=0,v=c-1;(d!==0||y<b)&&v!==-1;v--,y++)d+=256*f[v]>>>0,f[v]=d%a>>>0,d=d/a>>>0;if(d!==0)throw new Error("Non-zero carry");b=y,x++}for(var S=c-b;S!==c&&f[S]===0;)S++;for(var M=l.repeat(g);S<c;++S)M+=s.charAt(f[S]);return M}function E(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var g=0;if(h[g]!==" "){for(var b=0,x=0;h[g]===l;)b++,g++;for(var _=(h.length-g)*u+1>>>0,c=new Uint8Array(_);h[g];){var f=t[h.charCodeAt(g)];if(f===255)return;for(var d=0,y=_-1;(f!==0||d<x)&&y!==-1;y--,d++)f+=a*c[y]>>>0,c[y]=f%256>>>0,f=f/256>>>0;if(f!==0)throw new Error("Non-zero carry");x=d,g++}if(h[g]!==" "){for(var v=_-x;v!==_&&c[v]===0;)v++;for(var S=new Uint8Array(b+(_-v)),M=b;v!==_;)S[M++]=c[v++];return S}}}function w(h){var g=E(h);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:m,decodeUnsafe:E,decode:w}}var tu=eu,su=tu,ji=su;var dn=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")}},pn=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 Zi(this,e)}},mn=class{decoders;constructor(e){this.decoders=e}or(e){return Zi(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 Zi(s,e){return new mn({...s.decoders??{[s.prefix]:s},...e.decoders??{[e.prefix]:e}})}var gn=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 dn(e,t,r),this.decoder=new pn(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Wt({name:s,prefix:e,encode:t,decode:r}){return new gn(s,e,t,r)}function lt({name:s,prefix:e,alphabet:t}){let{encode:r,decode:n}=ji(t,s);return Wt({prefix:e,name:s,encode:r,decode:o=>Xe(n(o))})}function ru(s,e,t,r){let n=s.length;for(;s[n-1]==="=";)--n;let o=new Uint8Array(n*t/8|0),i=0,a=0,l=0;for(let u=0;u<n;++u){let p=e[s[u]];if(p===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<t|p,i+=t,i>=8&&(i-=8,o[l++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function nu(s,e,t){let r=e[e.length-1]==="=",n=(1<<t)-1,o="",i=0,a=0;for(let l=0;l<s.length;++l)for(a=a<<8|s[l],i+=8;i>t;)i-=t,o+=e[n&a>>i];if(i!==0&&(o+=e[n&a<<t-i]),r)for(;(o.length*t&7)!==0;)o+="=";return o}function ou(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=ou(r);return Wt({prefix:e,name:s,encode(o){return nu(o,r,t)},decode(o){return ru(o,n,t,s)}})}var Q=lt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),iu=lt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var yn={};V(yn,{base32:()=>$t,base32hex:()=>uu,base32hexpad:()=>fu,base32hexpadupper:()=>du,base32hexupper:()=>hu,base32pad:()=>cu,base32padupper:()=>lu,base32upper:()=>au,base32z:()=>pu});var $t=J({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),au=J({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),cu=J({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),lu=J({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),uu=J({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),hu=J({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),fu=J({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),du=J({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),pu=J({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var wn={};V(wn,{base36:()=>Is,base36upper:()=>mu});var Is=lt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),mu=lt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var gu=Ji,Yi=128,bu=127,yu=~bu,wu=Math.pow(2,31);function Ji(s,e,t){e=e||[],t=t||0;for(var r=t;s>=wu;)e[t++]=s&255|Yi,s/=128;for(;s&yu;)e[t++]=s&255|Yi,s>>>=7;return e[t]=s|0,Ji.bytes=t-r+1,e}var xu=xn,vu=128,Xi=127;function xn(s,r){var t=0,r=r||0,n=0,o=r,i,a=s.length;do{if(o>=a)throw xn.bytes=0,new RangeError("Could not decode varint");i=s[o++],t+=n<28?(i&Xi)<<n:(i&Xi)*Math.pow(2,n),n+=7}while(i>=vu);return xn.bytes=o-r,t}var Eu=Math.pow(2,7),Su=Math.pow(2,14),_u=Math.pow(2,21),Iu=Math.pow(2,28),Tu=Math.pow(2,35),Du=Math.pow(2,42),Au=Math.pow(2,49),Mu=Math.pow(2,56),Pu=Math.pow(2,63),ku=function(s){return s<Eu?1:s<Su?2:s<_u?3:s<Iu?4:s<Tu?5:s<Du?6:s<Au?7:s<Mu?8:s<Pu?9:10},Bu={encode:gu,decode:xu,encodingLength:ku},Lu=Bu,Ts=Lu;function Ds(s,e=0){return[Ts.decode(s,e),Ts.decode.bytes]}function jt(s,e,t=0){return Ts.encode(s,e,t),e}function Zt(s){return Ts.encodingLength(s)}function He(s,e){let t=e.byteLength,r=Zt(s),n=r+Zt(t),o=new Uint8Array(n+t);return jt(s,o,0),jt(t,o,r),o.set(e,n),new Yt(s,t,e,o)}function Je(s){let e=Xe(s),[t,r]=Ds(e),[n,o]=Ds(e.subarray(r)),i=e.subarray(r+o);if(i.byteLength!==n)throw new Error("Incorrect length");return new Yt(t,n,i,e)}function Qi(s,e){if(s===e)return!0;{let t=e;return s.code===t.code&&s.size===t.size&&t.bytes instanceof Uint8Array&&qi(s.bytes,t.bytes)}}var Yt=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=Tt(r),this.bytes=Tt(n)}};function ea(s,e){let{bytes:t,version:r}=s;return r===0?Cu(t,vn(s),e??Q.encoder):Fu(t,vn(s),e??$t.encoder)}var ta=new WeakMap;function vn(s){let e=ta.get(s);if(e==null){let t=new Map;return ta.set(s,t),t}return e}var ue=class s{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=Tt(n),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==As)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Nu)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return s.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,r=He(e,t);return s.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return s.equals(this,e)}static equals(e,t){let r=t;return r!=null&&e.code===r.code&&e.version===r.version&&Qi(e.multihash,r.multihash)}toString(e){return ea(this,e)}toJSON(){return{"/":ea(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:o,bytes:i}=t;return new s(r,n,o,i??sa(r,n,o.bytes))}else if(t[Ou]===!0){let{version:r,multihash:n,code:o}=t,i=Je(n);return s.create(r,o,i)}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!==As)throw new Error(`Version 0 CID must use dag-pb (code: ${As}) block encoding`);return new s(e,t,r,r.bytes)}case 1:{let n=sa(e,t,r.bytes);return new s(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return s.create(0,As,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=Xe(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=n.subarray(t.multihashSize-t.digestSize),i=new Yt(t.multihashCode,t.digestSize,o,n);return[t.version===0?s.createV0(i):s.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,r=()=>{let[m,E]=Ds(e.subarray(t));return t+=E,m},n=r(),o=As;if(n===18?(n=0,t=0):o=r(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let i=t,a=r(),l=r(),u=t+l,p=u-i;return{version:n,codec:o,multihashCode:a,digestSize:l,multihashSize:p,size:u}}static parse(e,t){let[r,n]=Ru(e,t),o=s.decode(n);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return vn(o).set(r,e),o}};function Ru(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 $t.prefix:{let t=e??$t;return[$t.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 Cu(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 o=t.encode(s).slice(1);return e.set(r,o),o}else return n}function Fu(s,e,t){let{prefix:r}=t,n=e.get(r);if(n==null){let o=t.encode(s);return e.set(r,o),o}else return n}var As=112,Nu=18;function sa(s,e,t){let r=Zt(s),n=r+Zt(e),o=new Uint8Array(n+t.byteLength);return jt(s,o,0),jt(e,o,r),o.set(t,n),o}var Ou=Symbol.for("@ipld/js-cid/CID");var En={};V(En,{identity:()=>Le});var ra=0,Uu="identity",na=Xe;function Ku(s,e){if(e?.truncate!=null&&e.truncate!==s.byteLength){if(e.truncate<0||e.truncate>s.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${s.byteLength}`);s=s.subarray(0,e.truncate)}return He(ra,na(s))}var Le={code:ra,name:Uu,encode:na,digest:Ku};function Pe(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 zu(s){return s.buffer instanceof ArrayBuffer}function Ge(s){return zu(s)?s:s.slice()}async function oa(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 o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,Ge(e),Ge(t.subarray()));return r?.signal?.throwIfAborted(),o}function Qe(s=0){return new Uint8Array(s)}function Ms(s=0){return new Uint8Array(s)}function Sn(s,e){e==null&&(e=s.reduce((n,o)=>n+o.length,0));let t=Ms(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}function ia(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}var ca=Symbol.for("@achingbrain/uint8arraylist");function aa(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 hr(s){return!!s?.[ca]}var ce=class s{bufs;length;[ca]=!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(hr(r)){t+=r.byteLength;for(let n of r.bufs)this.bufs.push(n)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else if(hr(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=aa(this.bufs,e);return t.buf[t.index]}set(e,t){let r=aa(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(hr(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 Sn(r,n)}subarray(e,t){let{bufs:r,length:n}=this._subList(e,t);return r.length===1?r[0]:Sn(r,n)}sublist(e,t){let{bufs:r,length:n}=this._subList(e,t),o=new s;return o.length=n,o.bufs=r,o}_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 o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=n,l=a+i.byteLength;if(n=l,e>=l)continue;let u=e>=a&&e<l,p=t>a&&t<=l;if(u&&p){if(e===a&&t===l){r.push(i);break}let m=e-a;r.push(i.subarray(m,m+(t-e)));break}if(u){if(e===0){r.push(i);continue}r.push(i.subarray(e-a));continue}if(p){if(t===l){r.push(i);break}r.push(i.subarray(0,t-a));break}r.push(i)}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!hr(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 o=256,i=new Int32Array(o);for(let m=0;m<o;m++)i[m]=-1;for(let m=0;m<n;m++)i[r[m]]=m;let a=i,l=this.byteLength-r.byteLength,u=r.byteLength-1,p;for(let m=t;m<=l;m+=p){p=0;for(let E=u;E>=0;E--){let w=this.get(m+E);if(r[E]!==w){p=Math.max(1,E-a[w]);break}}if(p===0)return m}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let r=Ms(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=Qe(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=Qe(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=Qe(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=Ms(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=Qe(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=Qe(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=Qe(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=Qe(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=Qe(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(!ia(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,o)=>n+o.byteLength,0)),r.length=t,r}};var _n={};V(_n,{base10:()=>Hu});var Hu=lt({prefix:"9",name:"base10",alphabet:"0123456789"});var In={};V(In,{base16:()=>Gu,base16upper:()=>qu});var Gu=J({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),qu=J({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Tn={};V(Tn,{base2:()=>Vu});var Vu=J({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Dn={};V(Dn,{base256emoji:()=>Yu});var la=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}"),Wu=la.reduce((s,e,t)=>(s[t]=e,s),[]),$u=la.reduce((s,e,t)=>{let r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return s[r]=t,s},[]);function ju(s){return s.reduce((e,t)=>(e+=Wu[t],e),"")}function Zu(s){let e=[];for(let t of s){let r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);let n=$u[r];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Yu=Wt({prefix:"\u{1F680}",name:"base256emoji",encode:ju,decode:Zu});var An={};V(An,{base64:()=>Xu,base64pad:()=>Ju,base64url:()=>Qu,base64urlpad:()=>eh});var Xu=J({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ju=J({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Qu=J({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),eh=J({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Mn={};V(Mn,{base8:()=>th});var th=J({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Pn={};V(Pn,{identity:()=>sh});var sh=Wt({prefix:"\0",name:"identity",encode:s=>Wi(s),decode:s=>Vi(s)});var cg=new TextEncoder,lg=new TextDecoder;var Ln={};V(Ln,{sha256:()=>Dt,sha512:()=>ih});var oh=20;function Bn({name:s,code:e,encode:t,minDigestLength:r,maxDigestLength:n}){return new kn(s,e,t,r,n)}var kn=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,r,n,o){this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??oh,this.maxDigestLength=o}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?ua(r,this.code,t?.truncate):r.then(n=>ua(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ua(s,e,t){if(t!=null&&t!==s.byteLength){if(t>s.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${s.byteLength}`);s=s.subarray(0,t)}return He(e,s)}function fa(s){return async e=>new Uint8Array(await crypto.subtle.digest(s,e))}var Dt=Bn({name:"sha2-256",code:18,encode:fa("SHA-256")}),ih=Bn({name:"sha2-512",code:19,encode:fa("SHA-512")});var Rn={...Pn,...Tn,...Mn,..._n,...In,...yn,...wn,...bn,...An,...Dn},vg={...Ln,...En};function fr(s=0){return new Uint8Array(s)}function pa(s,e,t,r){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:r}}}var da=pa("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),Cn=pa("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=fr(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),ah={utf8:da,"utf-8":da,hex:Rn.base16,latin1:Cn,ascii:Cn,binary:Cn,...Rn},dr=ah;function j(s,e="utf8"){let t=dr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${s}`)}function q(s,e="utf8"){let t=dr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(s).substring(1)}var ch=parseInt("11111",2),Fn=parseInt("10000000",2),lh=parseInt("01111111",2),ma={0:Ps,1:Ps,2:uh,3:dh,4:ph,5:fh,6:hh,16:Ps,22:Ps,48:Ps};function et(s,e={offset:0}){let t=s[e.offset]&ch;if(e.offset++,ma[t]!=null)return ma[t](s,e);throw new Error("No decoder for tag "+t)}function ks(s,e){let t=0;if((s[e.offset]&Fn)===Fn){let r=s[e.offset]&lh,n="0x";e.offset++;for(let o=0;o<r;o++,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 Ps(s,e){ks(s,e);let t=[];for(;!(e.offset>=s.byteLength);){let r=et(s,e);if(r===null)break;t.push(r)}return t}function uh(s,e){let t=ks(s,e),r=e.offset,n=e.offset+t,o=[];for(let i=r;i<n;i++)i===r&&s[i]===0||o.push(s[i]);return e.offset+=t,Uint8Array.from(o)}function hh(s,e){let t=ks(s,e),r=e.offset+t,n=s[e.offset];e.offset++;let o=0,i=0;n<40?(o=0,i=n):n<80?(o=1,i=n-40):(o=2,i=n-80);let a=`${o}.${i}`,l=[];for(;e.offset<r;){let u=s[e.offset];if(e.offset++,l.push(u&127),u<128){l.reverse();let p=0;for(let m=0;m<l.length;m++)p+=l[m]<<m*7;a+=`.${p}`,l=[]}}return a}function fh(s,e){return e.offset++,null}function dh(s,e){let t=ks(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 ph(s,e){let t=ks(s,e),r=s.subarray(e.offset,e.offset+t);return e.offset+=t,r}function mh(s){let e=s.toString(16);e.length%2===1&&(e="0"+e);let t=new ce;for(let r=0;r<e.length;r+=2)t.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return t}function Nn(s){if(s.byteLength<128)return Uint8Array.from([s.byteLength]);let e=mh(s.byteLength);return new ce(Uint8Array.from([e.byteLength|Fn]),e)}function Te(s){let e=new ce,t=128;return(s.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(s),new ce(Uint8Array.from([2]),Nn(e),e)}function pr(s){let e=Uint8Array.from([0]),t=new ce(e,s);return new ce(Uint8Array.from([3]),Nn(t),t)}function ht(s,e=48){let t=new ce;for(let r of s)t.append(r);return new ce(Uint8Array.from([e]),Nn(t),t)}var gh=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),bh=Uint8Array.from([6,5,43,129,4,0,34]),yh=Uint8Array.from([6,5,43,129,4,0,35]),wh={ext:!0,kty:"EC",crv:"P-256"},xh={ext:!0,kty:"EC",crv:"P-384"},vh={ext:!0,kty:"EC",crv:"P-521"},On=32,Un=48,Kn=66;function zn(s){let e=et(s);return ga(e)}function ga(s){let e=s[1][1][0],t=1,r,n;if(e.byteLength===On*2+1)return r=q(e.subarray(t,t+On),"base64url"),n=q(e.subarray(t+On),"base64url"),new Xt({...wh,key_ops:["verify"],x:r,y:n});if(e.byteLength===Un*2+1)return r=q(e.subarray(t,t+Un),"base64url"),n=q(e.subarray(t+Un),"base64url"),new Xt({...xh,key_ops:["verify"],x:r,y:n});if(e.byteLength===Kn*2+1)return r=q(e.subarray(t,t+Kn),"base64url"),n=q(e.subarray(t+Kn),"base64url"),new Xt({...vh,key_ops:["verify"],x:r,y:n});throw new X(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function ba(s){return ht([Te(Uint8Array.from([1])),ht([Eh(s.crv)],160),ht([pr(new ce(Uint8Array.from([4]),j(s.x??"","base64url"),j(s.y??"","base64url")))],161)]).subarray()}function Eh(s){if(s==="P-256")return gh;if(s==="P-384")return bh;if(s==="P-521")return yh;throw new X(`Invalid curve ${s}`)}var Xt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=ba(this.jwk)),this._raw}toMultihash(){return Le.digest(qe(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}async verify(e,t,r){return oa(this.jwk,t,e,r)}};function Hn(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in s&&s.BYTES_PER_ELEMENT===1}function ft(s,e=""){if(typeof s!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof s}`)}if(!Number.isSafeInteger(s)||s<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${s}`)}}function De(s,e,t=""){let r=Hn(s),n=s?.length,o=e!==void 0;if(!r||o&&n!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",l=r?`length=${n}`:`type=${typeof s}`,u=i+"expected Uint8Array"+a+", got "+l;throw r?new RangeError(u):new TypeError(u)}return s}function mr(s){if(typeof s!="function"||typeof s.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(ft(s.outputLen),ft(s.blockLen),s.outputLen<1)throw new Error('"outputLen" must be >= 1');if(s.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Jt(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 gr(s,e){De(s,void 0,"digestInto() output");let t=e.outputLen;if(s.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function st(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function br(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Re(s,e){return s<<32-e|s>>>e}var wa=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Sh=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function yr(s){if(De(s),wa)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=Sh[s[t]];return e}var tt={_0:48,_9:57,A:65,F:70,a:97,f:102};function ya(s){if(s>=tt._0&&s<=tt._9)return s-tt._0;if(s>=tt.A&&s<=tt.F)return s-(tt.A-10);if(s>=tt.a&&s<=tt.f)return s-(tt.a-10)}function Bs(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);if(wa)try{return Uint8Array.fromHex(s)}catch(n){throw n instanceof SyntaxError?new RangeError(n.message):n}let e=s.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let n=0,o=0;n<t;n++,o+=2){let i=ya(s.charCodeAt(o)),a=ya(s.charCodeAt(o+1));if(i===void 0||a===void 0){let l=s[o]+s[o+1];throw new RangeError('hex string expected, got non-hex character "'+l+'" at index '+o)}r[n]=i*16+a}return r}function Gn(...s){let e=0;for(let r=0;r<s.length;r++){let n=s[r];De(n),e+=n.length}let t=new Uint8Array(e);for(let r=0,n=0;r<s.length;r++){let o=s[r];t.set(o,n),n+=o.length}return t}function qn(s,e={}){let t=(n,o)=>s(o).update(n).digest(),r=s(void 0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.canXOF=r.canXOF,t.create=n=>s(n),Object.assign(t,e),Object.freeze(t)}function xa(s=32){ft(s,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(s>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${s}`);return e.getRandomValues(new Uint8Array(s))}var Vn=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function va(s,e,t){return s&e^~s&t}function Ea(s,e,t){return s&e^s&t^e&t}var Ls=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=br(this.buffer)}update(e){Jt(this),De(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(n-this.pos,o-i);if(a===n){let l=br(e);for(;n<=o-i;i+=n)this.process(l,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Jt(this),gr(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;t[i++]=128,st(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(r,0),i=0);for(let m=i;m<n;m++)t[m]=0;r.setBigUint64(n-8,BigInt(this.length*8),o),this.process(r,0);let a=br(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=l/4,p=this.get();if(u>p.length)throw new Error("_sha2: outputLen bigger than state");for(let m=0;m<u;m++)a.setUint32(4*m,p[m],o)}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:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=a,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}},rt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var he=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var wr=BigInt(4294967295),Sa=BigInt(32);function _h(s,e=!1){return e?{h:Number(s&wr),l:Number(s>>Sa&wr)}:{h:Number(s>>Sa&wr)|0,l:Number(s&wr)|0}}function _a(s,e=!1){let t=s.length,r=new Uint32Array(t),n=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=_h(s[o],e);[r[o],n[o]]=[i,a]}return[r,n]}var Wn=(s,e,t)=>s>>>t,$n=(s,e,t)=>s<<32-t|e>>>t,At=(s,e,t)=>s>>>t|e<<32-t,Mt=(s,e,t)=>s<<32-t|e>>>t,Rs=(s,e,t)=>s<<64-t|e>>>t-32,Cs=(s,e,t)=>s>>>t-32|e<<64-t;function Ve(s,e,t,r){let n=(e>>>0)+(r>>>0);return{h:s+t+(n/2**32|0)|0,l:n|0}}var Ia=(s,e,t)=>(s>>>0)+(e>>>0)+(t>>>0),Ta=(s,e,t,r)=>e+t+r+(s/2**32|0)|0,Da=(s,e,t,r)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0),Aa=(s,e,t,r,n)=>e+t+r+n+(s/2**32|0)|0,Ma=(s,e,t,r,n)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Pa=(s,e,t,r,n,o)=>e+t+r+n+o+(s/2**32|0)|0;var Th=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]),dt=new Uint32Array(64),jn=class extends Ls{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:a,H:l}=this;return[e,t,r,n,o,i,a,l]}set(e,t,r,n,o,i,a,l){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=l|0}process(e,t){for(let m=0;m<16;m++,t+=4)dt[m]=e.getUint32(t,!1);for(let m=16;m<64;m++){let E=dt[m-15],w=dt[m-2],h=Re(E,7)^Re(E,18)^E>>>3,g=Re(w,17)^Re(w,19)^w>>>10;dt[m]=g+dt[m-7]+h+dt[m-16]|0}let{A:r,B:n,C:o,D:i,E:a,F:l,G:u,H:p}=this;for(let m=0;m<64;m++){let E=Re(a,6)^Re(a,11)^Re(a,25),w=p+E+va(a,l,u)+Th[m]+dt[m]|0,g=(Re(r,2)^Re(r,13)^Re(r,22))+Ea(r,n,o)|0;p=u,u=l,l=a,a=i+w|0,i=o,o=n,n=r,r=w+g|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,l=l+this.F|0,u=u+this.G|0,p=p+this.H|0,this.set(r,n,o,i,a,l,u,p)}roundClean(){st(dt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),st(this.buffer)}},Zn=class extends jn{A=rt[0]|0;B=rt[1]|0;C=rt[2]|0;D=rt[3]|0;E=rt[4]|0;F=rt[5]|0;G=rt[6]|0;H=rt[7]|0;constructor(){super(32)}};var ka=_a(["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))),Dh=ka[0],Ah=ka[1],pt=new Uint32Array(80),mt=new Uint32Array(80),Yn=class extends Ls{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:o,Cl:i,Dh:a,Dl:l,Eh:u,El:p,Fh:m,Fl:E,Gh:w,Gl:h,Hh:g,Hl:b}=this;return[e,t,r,n,o,i,a,l,u,p,m,E,w,h,g,b]}set(e,t,r,n,o,i,a,l,u,p,m,E,w,h,g,b){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=n|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=l|0,this.Eh=u|0,this.El=p|0,this.Fh=m|0,this.Fl=E|0,this.Gh=w|0,this.Gl=h|0,this.Hh=g|0,this.Hl=b|0}process(e,t){for(let c=0;c<16;c++,t+=4)pt[c]=e.getUint32(t),mt[c]=e.getUint32(t+=4);for(let c=16;c<80;c++){let f=pt[c-15]|0,d=mt[c-15]|0,y=At(f,d,1)^At(f,d,8)^Wn(f,d,7),v=Mt(f,d,1)^Mt(f,d,8)^$n(f,d,7),S=pt[c-2]|0,M=mt[c-2]|0,C=At(S,M,19)^Rs(S,M,61)^Wn(S,M,6),N=Mt(S,M,19)^Cs(S,M,61)^$n(S,M,6),I=Da(v,N,mt[c-7],mt[c-16]),T=Aa(I,y,C,pt[c-7],pt[c-16]);pt[c]=T|0,mt[c]=I|0}let{Ah:r,Al:n,Bh:o,Bl:i,Ch:a,Cl:l,Dh:u,Dl:p,Eh:m,El:E,Fh:w,Fl:h,Gh:g,Gl:b,Hh:x,Hl:_}=this;for(let c=0;c<80;c++){let f=At(m,E,14)^At(m,E,18)^Rs(m,E,41),d=Mt(m,E,14)^Mt(m,E,18)^Cs(m,E,41),y=m&w^~m&g,v=E&h^~E&b,S=Ma(_,d,v,Ah[c],mt[c]),M=Pa(S,x,f,y,Dh[c],pt[c]),C=S|0,N=At(r,n,28)^Rs(r,n,34)^Rs(r,n,39),I=Mt(r,n,28)^Cs(r,n,34)^Cs(r,n,39),T=r&o^r&a^o&a,P=n&i^n&l^i&l;x=g|0,_=b|0,g=w|0,b=h|0,w=m|0,h=E|0,{h:m,l:E}=Ve(u|0,p|0,M|0,C|0),u=a|0,p=l|0,a=o|0,l=i|0,o=r|0,i=n|0;let A=Ia(C,I,P);r=Ta(A,M,N,T),n=A|0}({h:r,l:n}=Ve(this.Ah|0,this.Al|0,r|0,n|0)),{h:o,l:i}=Ve(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l}=Ve(this.Ch|0,this.Cl|0,a|0,l|0),{h:u,l:p}=Ve(this.Dh|0,this.Dl|0,u|0,p|0),{h:m,l:E}=Ve(this.Eh|0,this.El|0,m|0,E|0),{h:w,l:h}=Ve(this.Fh|0,this.Fl|0,w|0,h|0),{h:g,l:b}=Ve(this.Gh|0,this.Gl|0,g|0,b|0),{h:x,l:_}=Ve(this.Hh|0,this.Hl|0,x|0,_|0),this.set(r,n,o,i,a,l,u,p,m,E,w,h,g,b,x,_)}roundClean(){st(pt,mt)}destroy(){this.destroyed=!0,st(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Xn=class extends Yn{Ah=he[0]|0;Al=he[1]|0;Bh=he[2]|0;Bl=he[3]|0;Ch=he[4]|0;Cl=he[5]|0;Dh=he[6]|0;Dl=he[7]|0;Eh=he[8]|0;El=he[9]|0;Fh=he[10]|0;Fl=he[11]|0;Gh=he[12]|0;Gl=he[13]|0;Hh=he[14]|0;Hl=he[15]|0;constructor(){super(64)}};var Qt=qn(()=>new Zn,Vn(1));var xr=qn(()=>new Xn,Vn(3));var K=(s,e,t)=>De(s,e,t),Qn=ft,es=yr,oe=(...s)=>Gn(...s),ts=s=>Bs(s),Pt=Hn,Fs=s=>xa(s),Er=BigInt(0),Jn=BigInt(1);function Ce(s,e=""){if(typeof s!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof s)}return s}function Sr(s){if(typeof s=="bigint"){if(!vr(s))throw new RangeError("positive bigint expected, got "+s)}else Qn(s);return s}function Fe(s,e=""){if(typeof s!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof s)}if(!Number.isSafeInteger(s)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+s)}}function Ns(s){let e=Sr(s).toString(16);return e.length&1?"0"+e:e}function Ba(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);return s===""?Er:BigInt("0x"+s)}function kt(s){return Ba(yr(s))}function We(s){return Ba(yr(Os(De(s)).reverse()))}function _r(s,e){if(ft(e),e===0)throw new RangeError("zero length");s=Sr(s);let t=s.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Bs(t.padStart(e*2,"0"))}function eo(s,e){return _r(s,e).reverse()}function La(s,e){if(s=K(s),e=K(e),s.length!==e.length)return!1;let t=0;for(let r=0;r<s.length;r++)t|=s[r]^e[r];return t===0}function Os(s){return Uint8Array.from(K(s))}function Ir(s){if(typeof s!="string")throw new TypeError("ascii string expected, got "+typeof s);return Uint8Array.from(s,(e,t)=>{let r=e.charCodeAt(0);if(e.length!==1||r>127)throw new RangeError(`string contains non-ASCII character "${s[t]}" with code ${r} at position ${t}`);return r})}var vr=s=>typeof s=="bigint"&&Er<=s;function Mh(s,e,t){return vr(s)&&vr(e)&&vr(t)&&e<=s&&s<t}function ss(s,e,t,r){if(!Mh(e,t,r))throw new RangeError("expected valid "+s+": "+t+" <= n < "+r+", got "+e)}function rs(s){if(s<Er)throw new Error("expected non-negative bigint, got "+s);let e;for(e=0;s>Er;s>>=Jn,e+=1);return e}var Us=s=>(Jn<<BigInt(s))-Jn;function Ra(s,e,t){if(ft(s,"hashLen"),ft(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let r=b=>new Uint8Array(b),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,l=r(s),u=r(s),p=0,m=()=>{l.fill(1),u.fill(0),p=0},E=(...b)=>t(u,oe(l,...b)),w=(b=n)=>{u=E(o,b),l=E(),b.length!==0&&(u=E(i,b),l=E())},h=()=>{if(p++>=a)throw new Error("drbg: tried max amount of iterations");let b=0,x=[];for(;b<e;){l=E();let _=l.slice();x.push(_),b+=l.length}return oe(...x)};return(b,x)=>{m(),w(b);let _;for(;(_=x(h()))===void 0;)w();return m(),_}}function Ne(s,e={},t={}){if(Object.prototype.toString.call(s)!=="[object Object]")throw new TypeError("expected valid options object");function r(o,i,a){if(!a&&i!=="function"&&!Object.hasOwn(s,o))throw new TypeError(`param "${o}" is invalid: expected own property`);let l=s[o];if(a&&l===void 0)return;let u=typeof l;if(u!==i||l===null)throw new TypeError(`param "${o}" is invalid: expected ${i}, got ${u}`)}let n=(o,i)=>Object.entries(o).forEach(([a,l])=>r(a,l,i));n(e,!1),n(t,!0)}var to=()=>{throw new Error("not implemented")};var fe=BigInt(0),ee=BigInt(1),Bt=BigInt(2),Oa=BigInt(3),Ua=BigInt(4),Ka=BigInt(5),Ph=BigInt(7),za=BigInt(8),kh=BigInt(9),Ha=BigInt(16);function re(s,e){if(e<=fe)throw new Error("mod: expected positive modulus, got "+e);let t=s%e;return t>=fe?t:e+t}function $(s,e,t){if(e<fe)throw new Error("pow2: expected non-negative exponent, got "+e);let r=s;for(;e-- >fe;)r*=r,r%=t;return r}function Ca(s,e){if(s===fe)throw new Error("invert: expected non-zero number");if(e<=fe)throw new Error("invert: expected positive modulus, got "+e);let t=re(s,e),r=e,n=fe,o=ee,i=ee,a=fe;for(;t!==fe;){let u=r/t,p=r-t*u,m=n-i*u,E=o-a*u;r=t,t=p,n=i,o=a,i=m,a=E}if(r!==ee)throw new Error("invert: does not exist");return re(n,e)}function so(s,e,t){let r=s;if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function Ga(s,e){let t=s,r=(t.ORDER+ee)/Ua,n=t.pow(e,r);return so(t,n,e),n}function Bh(s,e){let t=s,r=(t.ORDER-Ka)/za,n=t.mul(e,Bt),o=t.pow(n,r),i=t.mul(e,o),a=t.mul(t.mul(i,Bt),o),l=t.mul(i,t.sub(a,t.ONE));return so(t,l,e),l}function Lh(s){let e=ns(s),t=qa(s),r=t(e,e.neg(e.ONE)),n=t(e,r),o=t(e,e.neg(r)),i=(s+Ph)/Ha;return((a,l)=>{let u=a,p=u.pow(l,i),m=u.mul(p,r),E=u.mul(p,n),w=u.mul(p,o),h=u.eql(u.sqr(m),l),g=u.eql(u.sqr(E),l);p=u.cmov(p,m,h),m=u.cmov(w,E,g);let b=u.eql(u.sqr(m),l),x=u.cmov(p,m,b);return so(u,x,l),x})}function qa(s){if(s<Oa)throw new Error("sqrt is not defined for small field");let e=s-ee,t=0;for(;e%Bt===fe;)e/=Bt,t++;let r=Bt,n=ns(s);for(;Fa(n,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Ga;let o=n.pow(r,e),i=(e+ee)/Bt;return function(l,u){let p=l;if(p.is0(u))return u;if(Fa(p,u)!==1)throw new Error("Cannot find square root");let m=t,E=p.mul(p.ONE,o),w=p.pow(u,e),h=p.pow(u,i);for(;!p.eql(w,p.ONE);){if(p.is0(w))return p.ZERO;let g=1,b=p.sqr(w);for(;!p.eql(b,p.ONE);)if(g++,b=p.sqr(b),g===m)throw new Error("Cannot find square root");let x=ee<<BigInt(m-g-1),_=p.pow(E,x);m=g,E=p.sqr(_),w=p.mul(w,E),h=p.mul(h,_)}return h}}function Rh(s){return s%Ua===Oa?Ga:s%za===Ka?Bh:s%Ha===kh?Lh(s):qa(s)}var nt=(s,e)=>(re(s,e)&ee)===ee,Ch=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ro(s){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=Ch.reduce((r,n)=>(r[n]="function",r),e);if(Ne(s,t),Fe(s.BYTES,"BYTES"),Fe(s.BITS,"BITS"),s.BYTES<1||s.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(s.ORDER<=ee)throw new Error("invalid field: expected ORDER > 1, got "+s.ORDER);return s}function Fh(s,e,t){let r=s;if(t<fe)throw new Error("invalid exponent, negatives unsupported");if(t===fe)return r.ONE;if(t===ee)return e;let n=r.ONE,o=e;for(;t>fe;)t&ee&&(n=r.mul(n,o)),o=r.sqr(o),t>>=ee;return n}function Ks(s,e,t=!1){let r=s,n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((a,l,u)=>r.is0(l)?a:(n[u]=a,r.mul(a,l)),r.ONE),i=r.inv(o);return e.reduceRight((a,l,u)=>r.is0(l)?a:(n[u]=r.mul(a,n[u]),r.mul(a,l)),i),n}function Fa(s,e){let t=s,r=(t.ORDER-ee)/Bt,n=t.pow(e,r),o=t.eql(n,t.ONE),i=t.eql(n,t.ZERO),a=t.eql(n,t.neg(t.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function Nh(s,e){if(e!==void 0&&Qn(e),s<=fe)throw new Error("invalid n length: expected positive n, got "+s);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=rs(s);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let r=e!==void 0?e:t,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var Na=new WeakMap,Tr=class{ORDER;BITS;BYTES;isLE;ZERO=fe;ONE=ee;_lengths;_mod;constructor(e,t={}){if(e<=ee)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:n,nByteLength:o}=Nh(e,r);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,Object.freeze(this)}create(e){return re(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return fe<=e&&e<this.ORDER}is0(e){return e===fe}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ee)===ee}neg(e){return re(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return re(e*e,this.ORDER)}add(e,t){return re(e+t,this.ORDER)}sub(e,t){return re(e-t,this.ORDER)}mul(e,t){return re(e*t,this.ORDER)}pow(e,t){return Fh(this,e,t)}div(e,t){return re(e*Ca(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 Ca(e,this.ORDER)}sqrt(e){let t=Na.get(this);return t||Na.set(this,t=Rh(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?eo(e,this.BYTES):_r(e,this.BYTES)}fromBytes(e,t=!1){K(e);let{_lengths:r,BYTES:n,isLE:o,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let u=new Uint8Array(n);u.set(e,o?0:u.length-e.length),e=u}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=o?We(e):kt(e);if(a&&(l=re(l,i)),!t&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return Ks(this,e)}cmov(e,t,r){return Ce(r,"condition"),r?t:e}};Object.freeze(Tr.prototype);function ns(s,e={}){return new Tr(s,e)}function Va(s){if(typeof s!="bigint")throw new Error("field order must be bigint");if(s<=ee)throw new Error("field order must be greater than 1");let e=rs(s-ee);return Math.ceil(e/8)}function no(s){let e=Va(s);return e+Math.ceil(e/2)}function oo(s,e,t=!1){K(s);let r=s.length,n=Va(e),o=Math.max(no(e),16);if(r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);let i=t?We(s):kt(s),a=re(i,e-ee)+ee;return t?eo(a,n):_r(a,n)}var os=BigInt(0),Lt=BigInt(1);function zs(s,e){let t=e.negate();return s?t:e}function Rt(s,e){let t=Ks(s.Fp,e.map(r=>r.Z));return e.map((r,n)=>s.fromAffine(r.toAffine(t[n])))}function Za(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function io(s,e){Za(s,e);let t=Math.ceil(e/s)+1,r=2**(s-1),n=2**s,o=Us(s),i=BigInt(s);return{windows:t,windowSize:r,mask:o,maxNumber:n,shiftBy:i}}function Wa(s,e,t){let{windowSize:r,mask:n,maxNumber:o,shiftBy:i}=t,a=Number(s&n),l=s>>i;a>r&&(a-=o,l+=Lt);let u=e*r,p=u+Math.abs(a)-1,m=a===0,E=a<0,w=e%2!==0;return{nextN:l,offset:p,isZero:m,isNeg:E,isNegF:w,offsetF:u}}var ao=new WeakMap,Ya=new WeakMap;function co(s){return Ya.get(s)||1}function $a(s){if(s!==os)throw new Error("invalid wNAF")}var is=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>os;)t&Lt&&(r=r.add(n)),n=n.double(),t>>=Lt;return r}precomputeWindow(e,t){let{windows:r,windowSize:n}=io(t,this.bits),o=[],i=e,a=i;for(let l=0;l<r;l++){a=i,o.push(a);for(let u=1;u<n;u++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE,i=io(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:l,offset:u,isZero:p,isNeg:m,isNegF:E,offsetF:w}=Wa(r,a,i);r=l,p?o=o.add(zs(E,t[w])):n=n.add(zs(m,t[u]))}return $a(r),{p:n,f:o}}wNAFUnsafe(e,t,r,n=this.ZERO){let o=io(e,this.bits);for(let i=0;i<o.windows&&r!==os;i++){let{nextN:a,offset:l,isZero:u,isNeg:p}=Wa(r,i,o);if(r=a,!u){let m=t[l];n=n.add(p?m.negate():m)}}return $a(r),n}getPrecomputes(e,t,r){let n=ao.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(n=r(n)),ao.set(t,n))),n}cached(e,t,r){let n=co(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){let o=co(e);return o===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,n)}createCache(e,t){Za(t,this.bits),Ya.set(e,t),ao.delete(e)}hasCache(e){return co(e)!==1}};function Xa(s,e,t,r){let n=e,o=s.ZERO,i=s.ZERO;for(;t>os||r>os;)t&Lt&&(o=o.add(n)),r&Lt&&(i=i.add(n)),n=n.double(),t>>=Lt,r>>=Lt;return{p1:o,p2:i}}function ja(s,e,t){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ro(e),e}else return ns(s,{isLE:t})}function Dr(s,e,t={},r){if(r===void 0&&(r=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(let l of["p","n","h"]){let u=e[l];if(!(typeof u=="bigint"&&u>os))throw new Error(`CURVE.${l} must be positive bigint`)}let n=ja(e.p,t.Fp,r),o=ja(e.n,t.Fn,r),a=["Gx","Gy","a",s==="weierstrass"?"b":"d"];for(let l of a)if(!n.isValid(e[l]))throw new Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:o}}function Ar(s,e){return function(r){let n=s(r);return{secretKey:n,publicKey:e(n)}}}var gt=BigInt(0),le=BigInt(1),lo=BigInt(2),Oh=BigInt(8);function Uh(s,e,t,r){let n=s.sqr(t),o=s.sqr(r),i=s.add(s.mul(e.a,n),o),a=s.add(s.ONE,s.mul(e.d,s.mul(n,o)));return s.eql(i,a)}function Ja(s,e={}){let t=e,r=Dr("edwards",s,t,t.FpFnLE),{Fp:n,Fn:o}=r,i=r.CURVE,{h:a}=i;Ne(t,{},{uvRatio:"function"});let l=lo<<BigInt(o.BYTES*8)-le,u=g=>n.create(g),p=t.uvRatio===void 0?(g,b)=>{try{return{isValid:!0,value:n.sqrt(n.div(g,b))}}catch{return{isValid:!1,value:gt}}}:t.uvRatio;if(!Uh(n,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function m(g,b,x=!1){let _=x?le:gt;return ss("coordinate "+g,b,_,l),b}function E(g){if(!(g instanceof w))throw new Error("EdwardsPoint expected")}class w{static BASE=new w(i.Gx,i.Gy,le,u(i.Gx*i.Gy));static ZERO=new w(gt,le,le,gt);static Fp=n;static Fn=o;X;Y;Z;T;constructor(b,x,_,c){this.X=m("x",b),this.Y=m("y",x),this.Z=m("z",_,!0),this.T=m("t",c),Object.freeze(this)}static CURVE(){return i}static fromAffine(b){if(b instanceof w)throw new Error("extended point not allowed");let{x,y:_}=b||{};return m("x",x),m("y",_),new w(x,_,le,u(x*_))}static fromBytes(b,x=!1){let _=n.BYTES,{a:c,d:f}=i;b=Os(K(b,_,"point")),Ce(x,"zip215");let d=Os(b),y=b[_-1];d[_-1]=y&-129;let v=We(d),S=x?l:n.ORDER;ss("point.y",v,gt,S);let M=u(v*v),C=u(M-le),N=u(f*M-c),{isValid:I,value:T}=p(C,N);if(!I)throw new Error("bad point: invalid y coordinate");let P=(T&le)===le,A=(y&128)!==0;if(!x&&T===gt&&A)throw new Error("bad point: x=0 and x_0=1");return A!==P&&(T=u(-T)),w.fromAffine({x:T,y:v})}static fromHex(b,x=!1){return w.fromBytes(ts(b),x)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,x=!0){return h.createCache(this,b),x||this.multiply(lo),this}assertValidity(){let b=this,{a:x,d:_}=i;if(b.is0())throw new Error("bad point: ZERO");let{X:c,Y:f,Z:d,T:y}=b,v=u(c*c),S=u(f*f),M=u(d*d),C=u(M*M),N=u(v*x),I=u(M*u(N+S)),T=u(C+u(_*u(v*S)));if(I!==T)throw new Error("bad point: equation left != right (1)");let P=u(c*f),A=u(d*y);if(P!==A)throw new Error("bad point: equation left != right (2)")}equals(b){E(b);let{X:x,Y:_,Z:c}=this,{X:f,Y:d,Z:y}=b,v=u(x*y),S=u(f*c),M=u(_*y),C=u(d*c);return v===S&&M===C}is0(){return this.equals(w.ZERO)}negate(){return new w(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:b}=i,{X:x,Y:_,Z:c}=this,f=u(x*x),d=u(_*_),y=u(lo*u(c*c)),v=u(b*f),S=x+_,M=u(u(S*S)-f-d),C=v+d,N=C-y,I=v-d,T=u(M*N),P=u(C*I),A=u(M*I),D=u(N*C);return new w(T,P,D,A)}add(b){E(b);let{a:x,d:_}=i,{X:c,Y:f,Z:d,T:y}=this,{X:v,Y:S,Z:M,T:C}=b,N=u(c*v),I=u(f*S),T=u(y*_*C),P=u(d*M),A=u((c+f)*(v+S)-N-I),D=P-T,k=P+T,L=u(I-x*N),B=u(A*D),R=u(k*L),F=u(A*L),U=u(D*k);return new w(B,R,U,F)}subtract(b){return E(b),this.add(b.negate())}multiply(b){if(!o.isValidNot0(b))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:x,f:_}=h.cached(this,b,c=>Rt(w,c));return Rt(w,[x,_])[0]}multiplyUnsafe(b){if(!o.isValid(b))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return b===gt?w.ZERO:this.is0()||b===le?this:h.unsafe(this,b,x=>Rt(w,x))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return h.unsafe(this,i.n).is0()}toAffine(b){let x=this,_=b,{X:c,Y:f,Z:d}=x,y=x.is0();_==null&&(_=y?Oh:n.inv(d));let v=u(c*_),S=u(f*_),M=n.mul(d,_);if(y)return{x:gt,y:le};if(M!==le)throw new Error("invZ was invalid");return{x:v,y:S}}clearCofactor(){return a===le?this:this.multiplyUnsafe(a)}toBytes(){let{x:b,y:x}=this.toAffine(),_=n.toBytes(x);return _[_.length-1]|=b&le?128:0,_}toHex(){return es(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let h=new is(w,o.BITS);return o.BITS>=8&&w.BASE.precompute(8),Object.freeze(w.prototype),Object.freeze(w),w}var Mr=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){to()}static fromHex(e){to()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return es(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function Qa(s,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let r=e,n=t;Ne(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:o}=n,{BASE:i,Fp:a,Fn:l}=s,u=r.outputLen,p=2*a.BYTES;if(u!==void 0&&(Fe(u,"hash.outputLen"),u!==p))throw new Error(`hash.outputLen must be ${p}, got ${u}`);let m=n.randomBytes===void 0?Fs:n.randomBytes,E=n.adjustScalarBytes===void 0?I=>I:n.adjustScalarBytes,w=n.domain===void 0?(I,T,P)=>{if(Ce(P,"phflag"),T.length||P)throw new Error("Contexts/pre-hash are not supported");return I}:n.domain;function h(I){return l.create(We(I))}function g(I){let T=v.secretKey;K(I,v.secretKey,"secretKey");let P=K(r(I),2*T,"hashedSecretKey"),A=E(P.slice(0,T)),D=P.slice(T,2*T),k=h(A);return{head:A,prefix:D,scalar:k}}function b(I){let{head:T,prefix:P,scalar:A}=g(I),D=i.multiply(A),k=D.toBytes();return{head:T,prefix:P,scalar:A,point:D,pointBytes:k}}function x(I){return b(I).pointBytes}function _(I=Uint8Array.of(),...T){let P=oe(...T);return h(r(w(P,K(I,void 0,"context"),!!o)))}function c(I,T,P={}){I=K(I,void 0,"message"),o&&(I=o(I));let{prefix:A,scalar:D,pointBytes:k}=b(T),L=_(P.context,A,I),B=i.multiply(L).toBytes(),R=_(P.context,B,k,I),F=l.create(L+R*D);if(!l.isValid(F))throw new Error("sign failed: invalid s");let U=oe(B,l.toBytes(F));return K(U,v.signature,"result")}let f={zip215:n.zip215};function d(I,T,P,A=f){let{context:D}=A,k=A.zip215===void 0?!!f.zip215:A.zip215,L=v.signature;I=K(I,L,"signature"),T=K(T,void 0,"message"),P=K(P,v.publicKey,"publicKey"),k!==void 0&&Ce(k,"zip215"),o&&(T=o(T));let B=L/2,R=I.subarray(0,B),F=We(I.subarray(B,L)),U,z,O;try{U=s.fromBytes(P,k),z=s.fromBytes(R,k),O=i.multiplyUnsafe(F)}catch{return!1}if(!k&&U.isSmallOrder())return!1;let ne=_(D,R,P,T);return z.add(U.multiplyUnsafe(ne)).subtract(O).clearCofactor().is0()}let y=a.BYTES,v={secretKey:y,publicKey:y,signature:2*y,seed:y};function S(I){return I=I===void 0?m(v.seed):I,K(I,v.seed,"seed")}function M(I){return Pt(I)&&I.length===v.secretKey}function C(I,T){try{return!!s.fromBytes(I,T===void 0?f.zip215:T)}catch{return!1}}let N={getExtendedPublicKey:b,randomSecretKey:S,isValidSecretKey:M,isValidPublicKey:C,toMontgomery(I){let{y:T}=s.fromBytes(I),P=v.publicKey,A=P===32;if(!A&&P!==57)throw new Error("only defined for 25519 and 448");let D=A?a.div(le+T,le-T):a.div(T-le,T+le);return a.toBytes(D)},toMontgomerySecret(I){let T=v.secretKey;K(I,T);let P=r(I.subarray(0,T));return E(P).subarray(0,T)}};return Object.freeze(v),Object.freeze(N),Object.freeze({keygen:Ar(S,x),getPublicKey:x,sign:c,verify:d,utils:N,Point:s,lengths:v})}function Hs(s,e){if(Fe(s),Fe(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(s<0||s>2**(8*e)-1)throw new Error("invalid I2OSP input: "+s);let t=Array.from({length:e}).fill(0);for(let r=e-1;r>=0;r--)t[r]=s&255,s>>>=8;return new Uint8Array(t)}function Kh(s,e){let t=new Uint8Array(s.length);for(let r=0;r<s.length;r++)t[r]=s[r]^e[r];return t}function zh(s){if(!Pt(s)&&typeof s!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof s=="string"?Ir(s):s;if(e.length===0)throw new Error("DST must be non-empty");return e}function uo(s,e,t,r){K(s),Fe(t),e=zh(e),e.length>255&&(e=r(oe(Ir("H2C-OVERSIZE-DST-"),e)));let{outputLen:n,blockLen:o}=r,i=Math.ceil(t/n);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=oe(e,Hs(e.length,1)),l=new Uint8Array(o),u=Hs(t,2),p=new Array(i),m=r(oe(l,s,u,Hs(0,1),a));p[0]=r(oe(m,Hs(1,1),a));for(let w=1;w<i;w++){let h=[Kh(m,p[w-1]),Hs(w+1,1),a];p[w]=r(oe(...h))}return oe(...p).slice(0,t)}var ec="HashToScalar-";var Hh=BigInt(0),ot=BigInt(1),tc=BigInt(2);var Gh=BigInt(5),qh=BigInt(8),as=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),mo={p:as,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:qh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Vh(s){let e=BigInt(10),t=BigInt(20),r=BigInt(40),n=BigInt(80),o=as,a=s*s%o*s%o,l=$(a,tc,o)*a%o,u=$(l,ot,o)*s%o,p=$(u,Gh,o)*u%o,m=$(p,e,o)*p%o,E=$(m,t,o)*m%o,w=$(E,r,o)*E%o,h=$(w,n,o)*w%o,g=$(h,n,o)*w%o,b=$(g,e,o)*p%o;return{pow_p_5_8:$(b,tc,o)*s%o,b2:a}}function Wh(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}var ho=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function go(s,e){let t=as,r=re(e*e*e,t),n=re(r*r*e,t),o=Vh(s*n).pow_p_5_8,i=re(s*r*o,t),a=re(e*i*i,t),l=i,u=re(i*ho,t),p=a===s,m=a===re(-s,t),E=a===re(-s*ho,t);return p&&(i=l),(m||E)&&(i=u),nt(i,t)&&(i=re(-i,t)),{isValid:p||m,value:i}}var yt=Ja(mo,{uvRatio:go}),bt=yt.Fp,nc=yt.Fn;function $h(s){return Qa(yt,xr,Object.assign({adjustScalarBytes:Wh,zip215:!0},s))}var oc=$h({});var fo=ho,jh=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Zh=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Yh=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Xh=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),sc=s=>go(ot,s),Jh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),po=s=>bt.create(We(s)&Jh);function rc(s){let{d:e}=mo,t=as,r=x=>bt.create(x),n=r(fo*s*s),o=r((n+ot)*Yh),i=BigInt(-1),a=r((i-e*n)*r(n+e)),{isValid:l,value:u}=go(o,a),p=r(u*s);nt(p,t)||(p=r(-p)),l||(u=p),l||(i=n);let m=r(i*(n-ot)*Xh-a),E=u*u,w=r((u+u)*a),h=r(m*jh),g=r(ot-E),b=r(ot+E);return new yt(r(w*b),r(g*h),r(h*b),r(w*g))}var wt=class s extends Mr{static BASE=new s(yt.BASE);static ZERO=new s(yt.ZERO);static Fp=bt;static Fn=nc;constructor(e){super(e)}static fromAffine(e){return new s(yt.fromAffine(e))}assertSame(e){if(!(e instanceof s))throw new Error("RistrettoPoint expected")}init(e){return new s(e)}static fromBytes(e){De(e,32);let{a:t,d:r}=mo,n=as,o=f=>bt.create(f),i=po(e);if(!La(bt.toBytes(i),e)||nt(i,n))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),l=o(ot+t*a),u=o(ot-t*a),p=o(l*l),m=o(u*u),E=o(t*r*p-m),{isValid:w,value:h}=sc(o(E*m)),g=o(h*u),b=o(h*g*E),x=o((i+i)*g);nt(x,n)&&(x=o(-x));let _=o(l*b),c=o(x*_);if(!w||nt(c,n)||_===Hh)throw new Error("invalid ristretto255 encoding 2");return new s(new yt(x,_,ot,c))}static fromHex(e){return s.fromBytes(Bs(e))}toBytes(){let{X:e,Y:t,Z:r,T:n}=this.ep,o=as,i=b=>bt.create(b),a=i(i(r+t)*i(r-t)),l=i(e*t),u=i(l*l),{value:p}=sc(i(a*u)),m=i(p*a),E=i(p*l),w=i(m*E*n),h;if(nt(n*w,o)){let b=i(t*fo),x=i(e*fo);e=b,t=x,h=i(m*Zh)}else h=E;nt(e*w,o)&&(t=i(-t));let g=i((r-t)*h);return nt(g,o)&&(g=i(-g)),bt.toBytes(g)}equals(e){this.assertSame(e);let{X:t,Y:r}=this.ep,{X:n,Y:o}=e.ep,i=u=>bt.create(u),a=i(t*o)===i(r*n),l=i(r*o)===i(t*n);return a||l}is0(){return this.equals(s.ZERO)}};Object.freeze(wt.BASE);Object.freeze(wt.ZERO);Object.freeze(wt.prototype);Object.freeze(wt);var Qh=Object.freeze({Point:wt,hashToCurve(s,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,r=uo(s,t,64,xr);return Qh.deriveToCurve(r)},hashToScalar(s,e={DST:ec}){let t=uo(s,e.DST,64,xr);return nc.create(We(t))},deriveToCurve(s){De(s,64);let e=po(s.subarray(0,32)),t=rc(e),r=po(s.subarray(32,64)),n=rc(r);return new wt(t.add(n))}});var Gs=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Pr=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var ke={get(s=globalThis){let e=s.crypto;if(e?.subtle==null)throw new Pr("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var kr=32;var bo,ef=(async()=>{try{return await ke.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function tf(s,e,t){if(s.buffer instanceof ArrayBuffer){let r=await ke.get().subtle.importKey("raw",s.buffer,{name:"Ed25519"},!1,["verify"]);return await ke.get().subtle.verify({name:"Ed25519"},r,Ge(e),Ge(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function sf(s,e,t){return oc.verify(e,t instanceof Uint8Array?t:t.subarray(),s)}async function ic(s,e,t){return bo==null&&(bo=await ef),bo?tf(s,e,t):sf(s,e,t)}function rf(s){return s?.buffer instanceof ArrayBuffer}function cc(s){if(rf(s))return s;let e=s.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Br(s,e){e==null&&(e=s.reduce((n,o)=>n+o.length,0));let t=fr(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return cc(t)}function Lr(s){return s==null?!1:typeof s.then=="function"&&typeof s.catch=="function"&&typeof s.finally=="function"}var Rr=class{type="Ed25519";raw;constructor(e){this.raw=yo(e,kr)}toMultihash(){return Le.digest(qe(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();let n=ic(this.raw,t,e);return Lr(n)?n.then(o=>(r?.signal?.throwIfAborted(),o)):n}};function wo(s){return s=yo(s,kr),new Rr(s)}function yo(s,e){if(s=Uint8Array.from(s??[]),s.length!==e)throw new X(`Key must be a Uint8Array of length ${e}, got ${s.length}`);return s}function lc(s=0){return new Uint8Array(s)}var of=Math.pow(2,7),af=Math.pow(2,14),cf=Math.pow(2,21),xo=Math.pow(2,28),vo=Math.pow(2,35),Eo=Math.pow(2,42),So=Math.pow(2,49),H=128,de=127;function Be(s){if(s<of)return 1;if(s<af)return 2;if(s<cf)return 3;if(s<xo)return 4;if(s<vo)return 5;if(s<Eo)return 6;if(s<So)return 7;if(Number.MAX_SAFE_INTEGER!=null&&s>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function _o(s,e,t=0){switch(Be(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 lf(s,e,t=0){switch(Be(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 Io(s,e){let t=s[e],r=0;if(r+=t&de,t<H||(t=s[e+1],r+=(t&de)<<7,t<H)||(t=s[e+2],r+=(t&de)<<14,t<H)||(t=s[e+3],r+=(t&de)<<21,t<H)||(t=s[e+4],r+=(t&de)*xo,t<H)||(t=s[e+5],r+=(t&de)*vo,t<H)||(t=s[e+6],r+=(t&de)*Eo,t<H)||(t=s[e+7],r+=(t&de)*So,t<H))return r;throw new RangeError("Could not decode varint")}function uf(s,e){let t=s.get(e),r=0;if(r+=t&de,t<H||(t=s.get(e+1),r+=(t&de)<<7,t<H)||(t=s.get(e+2),r+=(t&de)<<14,t<H)||(t=s.get(e+3),r+=(t&de)<<21,t<H)||(t=s.get(e+4),r+=(t&de)*xo,t<H)||(t=s.get(e+5),r+=(t&de)*vo,t<H)||(t=s.get(e+6),r+=(t&de)*Eo,t<H)||(t=s.get(e+7),r+=(t&de)*So,t<H))return r;throw new RangeError("Could not decode varint")}function To(s,e,t=0){return e==null&&(e=lc(Be(s))),e instanceof Uint8Array?_o(s,e,t):lf(s,e,t)}function Do(s,e=0){return s instanceof Uint8Array?Io(s,e):uf(s,e)}var Mo=new Float32Array([-0]),xt=new Uint8Array(Mo.buffer);function uc(s,e,t){Mo[0]=s,e[t]=xt[0],e[t+1]=xt[1],e[t+2]=xt[2],e[t+3]=xt[3]}function hc(s,e){return xt[0]=s[e],xt[1]=s[e+1],xt[2]=s[e+2],xt[3]=s[e+3],Mo[0]}var Po=new Float64Array([-0]),pe=new Uint8Array(Po.buffer);function fc(s,e,t){Po[0]=s,e[t]=pe[0],e[t+1]=pe[1],e[t+2]=pe[2],e[t+3]=pe[3],e[t+4]=pe[4],e[t+5]=pe[5],e[t+6]=pe[6],e[t+7]=pe[7]}function dc(s,e){return pe[0]=s[e],pe[1]=s[e+1],pe[2]=s[e+2],pe[3]=s[e+3],pe[4]=s[e+4],pe[5]=s[e+5],pe[6]=s[e+6],pe[7]=s[e+7],Po[0]}var hf=BigInt(Number.MAX_SAFE_INTEGER),ff=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 Ct;if(e<hf&&e>ff)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>pc&&(n=0n,++r>pc&&(r=0n))),new s(Number(n),Number(r))}static fromNumber(e){if(e===0)return Ct;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):Ct}},Ct=new Ae(0,0);Ct.toBigInt=function(){return 0n};Ct.zzEncode=Ct.zzDecode=function(){return this};Ct.length=function(){return 1};var pc=4294967296n;function mc(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 gc(s,e,t){if(t-e<1)return"";let n,o=[],i=0,a;for(;e<t;)a=s[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(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,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(s[e++]&63)<<6|s[e++]&63,i>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,o)),i=0);return n!=null?(i>0&&n.push(String.fromCharCode.apply(String,o.slice(0,i))),n.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function ko(s,e,t){let r=t,n,o;for(let i=0;i<s.length;++i)n=s.charCodeAt(i),n<128?e[t++]=n:n<2048?(e[t++]=n>>6|192,e[t++]=n&63|128):(n&64512)===55296&&((o=s.charCodeAt(i+1))&64512)===56320?(n=65536+((n&1023)<<10)+(o&1023),++i,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 Oe(s,e){return RangeError(`index out of range: ${s.pos} + ${e??1} > ${s.len}`)}function Cr(s,e){return(s[e-4]|s[e-3]<<8|s[e-2]<<16|s[e-1]<<24)>>>0}var Bo=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,Oe(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 Oe(this,4);return Cr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Oe(this,4);return Cr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Oe(this,4);let e=hc(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Oe(this,4);let e=dc(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 Oe(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){let e=this.bytes();return gc(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Oe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Oe(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 Oe(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 Oe(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 Oe(this,8);let e=Cr(this.buf,this.pos+=4),t=Cr(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=Io(this.buf,this.pos);return this.pos+=Be(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 qs(s){return new Bo(s instanceof Uint8Array?s:s.subarray())}function ye(s,e,t){let r=qs(s);return e.decode(r,void 0,t)}function Ft(s=0){return new Uint8Array(s)}var No={};V(No,{base10:()=>wf});var d0=new Uint8Array(0);function yc(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 it(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 wc(s){return new TextEncoder().encode(s)}function xc(s){return new TextDecoder().decode(s)}function df(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 o=s.charAt(n),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=n}var a=s.length,l=s.charAt(0),u=Math.log(a)/Math.log(256),p=Math.log(256)/Math.log(a);function m(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var g=0,b=0,x=0,_=h.length;x!==_&&h[x]===0;)x++,g++;for(var c=(_-x)*p+1>>>0,f=new Uint8Array(c);x!==_;){for(var d=h[x],y=0,v=c-1;(d!==0||y<b)&&v!==-1;v--,y++)d+=256*f[v]>>>0,f[v]=d%a>>>0,d=d/a>>>0;if(d!==0)throw new Error("Non-zero carry");b=y,x++}for(var S=c-b;S!==c&&f[S]===0;)S++;for(var M=l.repeat(g);S<c;++S)M+=s.charAt(f[S]);return M}function E(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var g=0;if(h[g]!==" "){for(var b=0,x=0;h[g]===l;)b++,g++;for(var _=(h.length-g)*u+1>>>0,c=new Uint8Array(_);h[g];){var f=t[h.charCodeAt(g)];if(f===255)return;for(var d=0,y=_-1;(f!==0||d<x)&&y!==-1;y--,d++)f+=a*c[y]>>>0,c[y]=f%256>>>0,f=f/256>>>0;if(f!==0)throw new Error("Non-zero carry");x=d,g++}if(h[g]!==" "){for(var v=_-x;v!==_&&c[v]===0;)v++;for(var S=new Uint8Array(b+(_-v)),M=b;v!==_;)S[M++]=c[v++];return S}}}function w(h){var g=E(h);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:m,decodeUnsafe:E,decode:w}}var pf=df,mf=pf,Ec=mf;var Lo=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")}},Ro=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 Sc(this,e)}},Co=class{decoders;constructor(e){this.decoders=e}or(e){return Sc(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 Sc(s,e){return new Co({...s.decoders??{[s.prefix]:s},...e.decoders??{[e.prefix]:e}})}var Fo=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 Lo(e,t,r),this.decoder=new Ro(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function cs({name:s,prefix:e,encode:t,decode:r}){return new Fo(s,e,t,r)}function vt({name:s,prefix:e,alphabet:t}){let{encode:r,decode:n}=Ec(t,s);return cs({prefix:e,name:s,encode:r,decode:o=>it(n(o))})}function gf(s,e,t,r){let n=s.length;for(;s[n-1]==="=";)--n;let o=new Uint8Array(n*t/8|0),i=0,a=0,l=0;for(let u=0;u<n;++u){let p=e[s[u]];if(p===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<t|p,i+=t,i>=8&&(i-=8,o[l++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function bf(s,e,t){let r=e[e.length-1]==="=",n=(1<<t)-1,o="",i=0,a=0;for(let l=0;l<s.length;++l)for(a=a<<8|s[l],i+=8;i>t;)i-=t,o+=e[n&a>>i];if(i!==0&&(o+=e[n&a<<t-i]),r)for(;(o.length*t&7)!==0;)o+="=";return o}function yf(s){let e={};for(let t=0;t<s.length;++t)e[s[t]]=t;return e}function te({name:s,prefix:e,bitsPerChar:t,alphabet:r}){let n=yf(r);return cs({prefix:e,name:s,encode(o){return bf(o,r,t)},decode(o){return gf(o,n,t,s)}})}var wf=vt({prefix:"9",name:"base10",alphabet:"0123456789"});var Oo={};V(Oo,{base16:()=>xf,base16upper:()=>vf});var xf=te({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),vf=te({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Uo={};V(Uo,{base2:()=>Ef});var Ef=te({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ko={};V(Ko,{base256emoji:()=>Df});var _c=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}"),Sf=_c.reduce((s,e,t)=>(s[t]=e,s),[]),_f=_c.reduce((s,e,t)=>{let r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return s[r]=t,s},[]);function If(s){return s.reduce((e,t)=>(e+=Sf[t],e),"")}function Tf(s){let e=[];for(let t of s){let r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);let n=_f[r];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Df=cs({prefix:"\u{1F680}",name:"base256emoji",encode:If,decode:Tf});var zo={};V(zo,{base32:()=>ls,base32hex:()=>kf,base32hexpad:()=>Lf,base32hexpadupper:()=>Rf,base32hexupper:()=>Bf,base32pad:()=>Mf,base32padupper:()=>Pf,base32upper:()=>Af,base32z:()=>Cf});var ls=te({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Af=te({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Mf=te({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Pf=te({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),kf=te({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Bf=te({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Lf=te({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Rf=te({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Cf=te({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ho={};V(Ho,{base36:()=>Vs,base36upper:()=>Ff});var Vs=vt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ff=vt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Go={};V(Go,{base58btc:()=>$e,base58flickr:()=>Nf});var $e=vt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Nf=vt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var qo={};V(qo,{base64:()=>Of,base64pad:()=>Uf,base64url:()=>Kf,base64urlpad:()=>zf});var Of=te({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Uf=te({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Kf=te({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zf=te({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Vo={};V(Vo,{base8:()=>Hf});var Hf=te({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Wo={};V(Wo,{identity:()=>Gf});var Gf=cs({prefix:"\0",name:"identity",encode:s=>xc(s),decode:s=>wc(s)});var M0=new TextEncoder,P0=new TextDecoder;var jo={};V(jo,{identity:()=>fd});var Wf=Dc,Ic=128,$f=127,jf=~$f,Zf=Math.pow(2,31);function Dc(s,e,t){e=e||[],t=t||0;for(var r=t;s>=Zf;)e[t++]=s&255|Ic,s/=128;for(;s&jf;)e[t++]=s&255|Ic,s>>>=7;return e[t]=s|0,Dc.bytes=t-r+1,e}var Yf=$o,Xf=128,Tc=127;function $o(s,r){var t=0,r=r||0,n=0,o=r,i,a=s.length;do{if(o>=a)throw $o.bytes=0,new RangeError("Could not decode varint");i=s[o++],t+=n<28?(i&Tc)<<n:(i&Tc)*Math.pow(2,n),n+=7}while(i>=Xf);return $o.bytes=o-r,t}var Jf=Math.pow(2,7),Qf=Math.pow(2,14),ed=Math.pow(2,21),td=Math.pow(2,28),sd=Math.pow(2,35),rd=Math.pow(2,42),nd=Math.pow(2,49),od=Math.pow(2,56),id=Math.pow(2,63),ad=function(s){return s<Jf?1:s<Qf?2:s<ed?3:s<td?4:s<sd?5:s<rd?6:s<nd?7:s<od?8:s<id?9:10},cd={encode:Wf,decode:Yf,encodingLength:ad},ld=cd,Ws=ld;function $s(s,e=0){return[Ws.decode(s,e),Ws.decode.bytes]}function us(s,e,t=0){return Ws.encode(s,e,t),e}function hs(s){return Ws.encodingLength(s)}function ds(s,e){let t=e.byteLength,r=hs(s),n=r+hs(t),o=new Uint8Array(n+t);return us(s,o,0),us(t,o,r),o.set(e,n),new fs(s,t,e,o)}function Ac(s){let e=it(s),[t,r]=$s(e),[n,o]=$s(e.subarray(r)),i=e.subarray(r+o);if(i.byteLength!==n)throw new Error("Incorrect length");return new fs(t,n,i,e)}function Mc(s,e){if(s===e)return!0;{let t=e;return s.code===t.code&&s.size===t.size&&t.bytes instanceof Uint8Array&&yc(s.bytes,t.bytes)}}var fs=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}};var Pc=0,ud="identity",kc=it;function hd(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 ds(Pc,kc(s))}var fd={code:Pc,name:ud,encode:kc,digest:hd};var Xo={};V(Xo,{sha256:()=>pd,sha512:()=>md});var dd=20;function Yo({name:s,code:e,encode:t,minDigestLength:r,maxDigestLength:n}){return new Zo(s,e,t,r,n)}var Zo=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,r,n,o){this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??dd,this.maxDigestLength=o}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?Bc(r,this.code,t?.truncate):r.then(n=>Bc(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Bc(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 ds(e,s)}function Rc(s){return async e=>new Uint8Array(await crypto.subtle.digest(s,e))}var pd=Yo({name:"sha2-256",code:18,encode:Rc("SHA-256")}),md=Yo({name:"sha2-512",code:19,encode:Rc("SHA-512")});function Cc(s,e){let{bytes:t,version:r}=s;return r===0?bd(t,Jo(s),e??$e.encoder):yd(t,Jo(s),e??ls.encoder)}var Fc=new WeakMap;function Jo(s){let e=Fc.get(s);if(e==null){let t=new Map;return Fc.set(s,t),t}return e}var Nr=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!==Zs)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==wd)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=ds(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&&Mc(e.multihash,r.multihash)}toString(e){return Cc(this,e)}toJSON(){return{"/":Cc(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:o,bytes:i}=t;return new s(r,n,o,i??Nc(r,n,o.bytes))}else if(t[xd]===!0){let{version:r,multihash:n,code:o}=t,i=Ac(n);return s.create(r,o,i)}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!==Zs)throw new Error(`Version 0 CID must use dag-pb (code: ${Zs}) block encoding`);return new s(e,t,r,r.bytes)}case 1:{let n=Nc(e,t,r.bytes);return new s(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return s.create(0,Zs,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=it(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=n.subarray(t.multihashSize-t.digestSize),i=new fs(t.multihashCode,t.digestSize,o,n);return[t.version===0?s.createV0(i):s.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,r=()=>{let[m,E]=$s(e.subarray(t));return t+=E,m},n=r(),o=Zs;if(n===18?(n=0,t=0):o=r(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let i=t,a=r(),l=r(),u=t+l,p=u-i;return{version:n,codec:o,multihashCode:a,digestSize:l,multihashSize:p,size:u}}static parse(e,t){let[r,n]=gd(e,t),o=s.decode(n);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Jo(o).set(r,e),o}};function gd(s,e){switch(s[0]){case"Q":{let t=e??$e;return[$e.prefix,t.decode(`${$e.prefix}${s}`)]}case $e.prefix:{let t=e??$e;return[$e.prefix,t.decode(s)]}case ls.prefix:{let t=e??ls;return[ls.prefix,t.decode(s)]}case Vs.prefix:{let t=e??Vs;return[Vs.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 bd(s,e,t){let{prefix:r}=t;if(r!==$e.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let n=e.get(r);if(n==null){let o=t.encode(s).slice(1);return e.set(r,o),o}else return n}function yd(s,e,t){let{prefix:r}=t,n=e.get(r);if(n==null){let o=t.encode(s);return e.set(r,o),o}else return n}var Zs=112,wd=18;function Nc(s,e,t){let r=hs(s),n=r+hs(e),o=new Uint8Array(n+t.byteLength);return us(s,o,0),us(e,o,r),o.set(t,n),o}var xd=Symbol.for("@ipld/js-cid/CID");var Qo={...Wo,...Uo,...Vo,...No,...Oo,...zo,...Ho,...Go,...qo,...Ko},J0={...Xo,...jo};function Uc(s,e,t,r){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:r}}}var Oc=Uc("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),ei=Uc("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=Ft(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),vd={utf8:Oc,"utf-8":Oc,hex:Qo.base16,latin1:ei,ascii:ei,binary:ei,...Qo},Kc=vd;function zc(s,e="utf8"){let t=Kc[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${s}`)}function ti(s){let e=s??8192,t=e>>>1,r,n=e;return function(i){if(i<1||i>t)return Ft(i);n+i>e&&(r=Ft(e),n=0);let a=r.subarray(n,n+=i);return(n&7)!==0&&(n=(n|7)+1),a}}var Nt=class{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}};function si(){}var ni=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Ed=ti();function Sd(s){return globalThis.Buffer!=null?Ft(s):Ed(s)}var Xs=class{len;head;tail;states;constructor(){this.len=0,this.head=new Nt(si,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new Nt(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new oi((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(Or,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(Or,t.length(),t)}uint64Number(e){return this._push(_o,Be(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(Or,t.length(),t)}sint64Number(e){let t=Ae.fromNumber(e).zzEncode();return this._push(Or,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(ri,1,e?1:0)}fixed32(e){return this._push(Ys,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ae.fromBigInt(e);return this._push(Ys,4,t.lo)._push(Ys,4,t.hi)}fixed64Number(e){let t=Ae.fromNumber(e);return this._push(Ys,4,t.lo)._push(Ys,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(uc,4,e)}double(e){return this._push(fc,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(ri,1,0):this.uint32(t)._push(Id,t,e)}string(e){let t=mc(e);return t!==0?this.uint32(t)._push(ko,t,e):this._push(ri,1,0)}fork(){return this.states=new ni(this),this.head=this.tail=new Nt(si,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 Nt(si,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=Sd(this.len),r=0;for(;e!=null;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}};function ri(s,e,t){e[t]=s&255}function _d(s,e,t){for(;s>127;)e[t++]=s&127|128,s>>>=7;e[t]=s}var oi=class extends Nt{next;constructor(e,t){super(_d,e,t),this.next=void 0}};function Or(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 Ys(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 Id(s,e,t){e.set(s,t)}globalThis.Buffer!=null&&(Xs.prototype.bytes=function(s){let e=s.length>>>0;return this.uint32(e),e>0&&this._push(Td,e,s),this},Xs.prototype.string=function(s){let e=globalThis.Buffer.byteLength(s);return this.uint32(e),e>0&&this._push(Dd,e,s),this});function Td(s,e,t){e.set(s,t)}function Dd(s,e,t){s.length<40?ko(s,e,t):e.utf8Write!=null?e.utf8Write(s,t):e.set(zc(s),t)}function ii(){return new Xs}function we(s,e){let t=ii();return e.encode(s,t,{lengthDelimited:!1}),t.finish()}function*xe(s,e,t){let r=qs(s);yield*e.stream(r,void 0,"$",t)}var Ur={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Kr(s,e,t,r,n){return{name:s,type:e,encode:t,decode:r,stream:n}}function ai(s){function e(o){if(s[o.toString()]==null)throw new Error("Invalid enum value");return s[o]}let t=function(i,a){let l=e(i);a.int32(l)},r=function(i){let a=i.int32();return e(a)},n=function*(i){let a=i.int32();yield e(a)};return Kr("enum",Ur.VARINT,t,r,n)}function ve(s,e,t){return Kr("message",Ur.LENGTH_DELIMITED,s,e,t)}var W=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var Z;(function(s){s.RSA="RSA",s.Ed25519="Ed25519",s.secp256k1="secp256k1",s.ECDSA="ECDSA"})(Z||(Z={}));var ci;(function(s){s[s.RSA=0]="RSA",s[s.Ed25519=1]="Ed25519",s[s.secp256k1=2]="secp256k1",s[s.ECDSA=3]="ECDSA"})(ci||(ci={}));(function(s){s.codec=()=>ai(ci)})(Z||(Z={}));var je;(function(s){let e;s.codec=()=>(e==null&&(e=ve((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),Z.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let l={},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let p=o.uint32();switch(p>>>3){case 1:{l.Type=Z.codec().decode(o);break}case 2:{l.Data=o.bytes();break}default:{o.skipType(p&7);break}}}return l},function*(o,i,a,l={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let p=o.uint32();switch(p>>>3){case 1:{yield{field:`${a}.Type`,value:Z.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(p&7);break}}}})),e);function t(o){return we(o,s.codec())}s.encode=t;function r(o,i){return ye(o,s.codec(),i)}s.decode=r;function n(o,i){return xe(o,s.codec(),i)}s.stream=n})(je||(je={}));var li;(function(s){let e;s.codec=()=>(e==null&&(e=ve((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),Z.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let l={},u=i==null?o.len:o.pos+i;for(;o.pos<u;){let p=o.uint32();switch(p>>>3){case 1:{l.Type=Z.codec().decode(o);break}case 2:{l.Data=o.bytes();break}default:{o.skipType(p&7);break}}}return l},function*(o,i,a,l={}){let u=i==null?o.len:o.pos+i;for(;o.pos<u;){let p=o.uint32();switch(p>>>3){case 1:{yield{field:`${a}.Type`,value:Z.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(p&7);break}}}})),e);function t(o){return we(o,s.codec())}s.encode=t;function r(o,i){return ye(o,s.codec(),i)}s.decode=r;function n(o,i){return xe(o,s.codec(),i)}s.stream=n})(li||(li={}));var Qs={};V(Qs,{MAX_RSA_KEY_SIZE:()=>ui,generateRSAKeyPair:()=>Wc,jwkToJWKKeyPair:()=>$c,jwkToPkcs1:()=>kd,jwkToPkix:()=>pi,jwkToRSAPrivateKey:()=>yi,pkcs1MessageToJwk:()=>fi,pkcs1MessageToRSAPrivateKey:()=>mi,pkcs1ToJwk:()=>Pd,pkcs1ToRSAPrivateKey:()=>Vc,pkixMessageToJwk:()=>di,pkixMessageToRSAPublicKey:()=>bi,pkixToJwk:()=>Bd,pkixToRSAPublicKey:()=>gi});var ps=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Qs.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ue.createV1(114,this._multihash)}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}verify(e,t,r){return qc(this.jwk,t,e,r)}},Js=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Qs.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}sign(e,t){return Gc(this.jwk,e,t)}};var ui=8192,hi=18,Ad=1062,Md=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Pd(s){let e=et(s);return fi(e)}function fi(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 kd(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 X("JWK was missing components");return ht([Te(Uint8Array.from([0])),Te(j(s.n,"base64url")),Te(j(s.e,"base64url")),Te(j(s.d,"base64url")),Te(j(s.p,"base64url")),Te(j(s.q,"base64url")),Te(j(s.dp,"base64url")),Te(j(s.dq,"base64url")),Te(j(s.qi,"base64url"))]).subarray()}function Bd(s){let e=et(s,{offset:0});return di(e)}function di(s){let e=et(s[1],{offset:0});return{kty:"RSA",n:q(e[0],"base64url"),e:q(e[1],"base64url")}}function pi(s){if(s.n==null||s.e==null)throw new X("JWK was missing components");return ht([Md,pr(ht([Te(j(s.n,"base64url")),Te(j(s.e,"base64url"))]))]).subarray()}function Vc(s){let e=et(s);return mi(e)}function mi(s){let e=fi(s);return yi(e)}function gi(s,e){if(s.byteLength>=Ad)throw new qt("Key size is too large");let t=et(s,{offset:0});return bi(t,s,e)}function bi(s,e,t){let r=di(s);if(t==null){let n=Qt(je.encode({Type:Z.RSA,Data:e}));t=He(hi,n)}return new ps(r,t)}function yi(s){if(Zc(s)>ui)throw new X("Key size is too large");let e=$c(s),t=Qt(je.encode({Type:Z.RSA,Data:pi(e.publicKey)})),r=He(hi,t);return new Js(e.privateKey,new ps(e.publicKey,r))}async function Wc(s){if(s>ui)throw new X("Key size is too large");let e=await jc(s),t=Qt(je.encode({Type:Z.RSA,Data:pi(e.publicKey)})),r=He(hi,t);return new Js(e.privateKey,new ps(e.publicKey,r))}function $c(s){if(s==null)throw new X("Missing key parameter");return{privateKey:s,publicKey:{kty:s.kty,n:s.n,e:s.e}}}async function jc(s,e){let t=await ke.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:s,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let r=await Ld(t,e);return{privateKey:r[0],publicKey:r[1]}}async function Gc(s,e,t){let r=await ke.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let n=await ke.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,Ge(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(n,0,n.byteLength)}async function qc(s,e,t,r){let n=await ke.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();let o=await ke.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,Ge(e),Ge(t instanceof Uint8Array?t:t.subarray()));return r?.signal?.throwIfAborted(),o}async function Ld(s,e){if(s.privateKey==null||s.publicKey==null)throw new X("Private and public key are required");let t=await Promise.all([ke.get().subtle.exportKey("jwk",s.privateKey),ke.get().subtle.exportKey("jwk",s.publicKey)]);return e?.signal?.throwIfAborted(),t}function Zc(s){if(s.kty!=="RSA")throw new X("invalid key type");if(s.n==null)throw new X("invalid key modulus");return j(s.n,"base64url").length*8}var zr=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(mr(e),De(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 o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),st(n)}update(e){return Jt(this),this.iHash.update(e),this}digestInto(e){Jt(this),gr(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:n,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,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()}},Yc=(()=>{let s=((e,t,r)=>new zr(e,t).update(r).digest());return s.create=(e,t)=>new zr(e,t),s})();var Xc=(s,e)=>(s+(s>=0?e:-e)/Jc)/e;function Rd(s,e,t){ss("scalar",s,Ze,t);let[[r,n],[o,i]]=e,a=Xc(i*s,t),l=Xc(-n*s,t),u=s-a*r-l*o,p=-a*n-l*i,m=u<Ze,E=p<Ze;m&&(u=-u),E&&(p=-p);let w=Us(Math.ceil(rs(t)/2))+Et;if(u<Ze||u>=w||p<Ze||p>=w)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:m,k1:u,k2neg:E,k2:p}}function xi(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function wi(s,e){Ne(s);let t={};for(let r of Object.keys(e))t[r]=s[r]===void 0?e[r]:s[r];return Ce(t.lowS,"lowS"),Ce(t.prehash,"prehash"),t.format!==void 0&&xi(t.format),t}var vi=class extends Error{constructor(e=""){super(e)}},Ue={Err:vi,_tlv:{encode:(s,e)=>{let{Err:t}=Ue;if(Fe(s,"tag"),s<0||s>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let r=e.length/2,n=Ns(r);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let o=r>127?Ns(n.length/2|128):"";return Ns(s)+o+n+e},decode(s,e){let{Err:t}=Ue;e=K(e,void 0,"DER data");let r=0;if(s<0||s>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[r++]!==s)throw new t("tlv.decode: wrong tlv");let n=e[r++],o=!!(n&128),i=0;if(!o)i=n;else{let l=n&127;if(!l)throw new t("tlv.decode(long): indefinite length not supported");if(l>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(r,r+l);if(u.length!==l)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let p of u)i=i<<8|p;if(r+=l,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+i)}}},_int:{encode(s){let{Err:e}=Ue;if(Sr(s),s<Ze)throw new e("integer: negative integers are not allowed");let t=Ns(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}=Ue;if(s.length<1)throw new e("invalid signature integer: empty");if(s[0]&128)throw new e("invalid signature integer: negative");if(s.length>1&&s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return kt(s)}},toSig(s){let{Err:e,_int:t,_tlv:r}=Ue,n=K(s,void 0,"signature"),{v:o,l:i}=r.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l}=r.decode(2,o),{v:u,l:p}=r.decode(2,l);if(p.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(s){let{_tlv:e,_int:t}=Ue,r=e.encode(2,t.encode(s.r)),n=e.encode(2,t.encode(s.s)),o=r+n;return e.encode(48,o)}};Object.freeze(Ue._tlv);Object.freeze(Ue._int);Object.freeze(Ue);var Ze=BigInt(0),Et=BigInt(1),Jc=BigInt(2),Hr=BigInt(3),Cd=BigInt(4);function Qc(s,e={}){let t=Dr("weierstrass",s,e),r=t.Fp,n=t.Fn,o=t.CURVE,{h:i,n:a}=o;Ne(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:l,allowInfinityPoint:u}=e;if(l&&(!r.is0(o.a)||typeof l.beta!="bigint"||!Array.isArray(l.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let p=tl(r,n);function m(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function E(N,I,T){if(u&&I.is0())return Uint8Array.of(0);let{x:P,y:A}=I.toAffine(),D=r.toBytes(P);if(Ce(T,"isCompressed"),T){m();let k=!r.isOdd(A);return oe(el(k),D)}else return oe(Uint8Array.of(4),D,r.toBytes(A))}function w(N){K(N,void 0,"Point");let{publicKey:I,publicKeyUncompressed:T}=p,P=N.length,A=N[0],D=N.subarray(1);if(u&&P===1&&A===0)return{x:r.ZERO,y:r.ZERO};if(P===I&&(A===2||A===3)){let k=r.fromBytes(D);if(!r.isValid(k))throw new Error("bad point: is not on curve, wrong x");let L=b(k),B;try{B=r.sqrt(L)}catch(U){let z=U instanceof Error?": "+U.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}m();let R=r.isOdd(B);return(A&1)===1!==R&&(B=r.neg(B)),{x:k,y:B}}else if(P===T&&A===4){let k=r.BYTES,L=r.fromBytes(D.subarray(0,k)),B=r.fromBytes(D.subarray(k,k*2));if(!x(L,B))throw new Error("bad point: is not on curve");return{x:L,y:B}}else throw new Error(`bad point: got length ${P}, expected compressed=${I} or uncompressed=${T}`)}let h=e.toBytes===void 0?E:e.toBytes,g=e.fromBytes===void 0?w:e.fromBytes;function b(N){let I=r.sqr(N),T=r.mul(I,N);return r.add(r.add(T,r.mul(N,o.a)),o.b)}function x(N,I){let T=r.sqr(I),P=b(N);return r.eql(T,P)}if(!x(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let _=r.mul(r.pow(o.a,Hr),Cd),c=r.mul(r.sqr(o.b),BigInt(27));if(r.is0(r.add(_,c)))throw new Error("bad curve params: a or b");function f(N,I,T=!1){if(!r.isValid(I)||T&&r.is0(I))throw new Error(`bad point coordinate ${N}`);return I}function d(N){if(!(N instanceof S))throw new Error("Weierstrass Point expected")}function y(N){if(!l||!l.basises)throw new Error("no endo");return Rd(N,l.basises,n.ORDER)}function v(N,I,T,P,A){return T=new S(r.mul(T.X,N),T.Y,T.Z),I=zs(P,I),T=zs(A,T),I.add(T)}class S{static BASE=new S(o.Gx,o.Gy,r.ONE);static ZERO=new S(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=n;X;Y;Z;constructor(I,T,P){this.X=f("x",I),this.Y=f("y",T,!0),this.Z=f("z",P),Object.freeze(this)}static CURVE(){return o}static fromAffine(I){let{x:T,y:P}=I||{};if(!I||!r.isValid(T)||!r.isValid(P))throw new Error("invalid affine point");if(I instanceof S)throw new Error("projective point not allowed");return r.is0(T)&&r.is0(P)?S.ZERO:new S(T,P,r.ONE)}static fromBytes(I){let T=S.fromAffine(g(K(I,void 0,"point")));return T.assertValidity(),T}static fromHex(I){return S.fromBytes(ts(I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,T=!0){return C.createCache(this,I),T||this.multiply(Hr),this}assertValidity(){let I=this;if(I.is0()){if(e.allowInfinityPoint&&r.is0(I.X)&&r.eql(I.Y,r.ONE)&&r.is0(I.Z))return;throw new Error("bad point: ZERO")}let{x:T,y:P}=I.toAffine();if(!r.isValid(T)||!r.isValid(P))throw new Error("bad point: x or y not field elements");if(!x(T,P))throw new Error("bad point: equation left != right");if(!I.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:I}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(I)}equals(I){d(I);let{X:T,Y:P,Z:A}=this,{X:D,Y:k,Z:L}=I,B=r.eql(r.mul(T,L),r.mul(D,A)),R=r.eql(r.mul(P,L),r.mul(k,A));return B&&R}negate(){return new S(this.X,r.neg(this.Y),this.Z)}double(){let{a:I,b:T}=o,P=r.mul(T,Hr),{X:A,Y:D,Z:k}=this,L=r.ZERO,B=r.ZERO,R=r.ZERO,F=r.mul(A,A),U=r.mul(D,D),z=r.mul(k,k),O=r.mul(A,D);return O=r.add(O,O),R=r.mul(A,k),R=r.add(R,R),L=r.mul(I,R),B=r.mul(P,z),B=r.add(L,B),L=r.sub(U,B),B=r.add(U,B),B=r.mul(L,B),L=r.mul(O,L),R=r.mul(P,R),z=r.mul(I,z),O=r.sub(F,z),O=r.mul(I,O),O=r.add(O,R),R=r.add(F,F),F=r.add(R,F),F=r.add(F,z),F=r.mul(F,O),B=r.add(B,F),z=r.mul(D,k),z=r.add(z,z),F=r.mul(z,O),L=r.sub(L,F),R=r.mul(z,U),R=r.add(R,R),R=r.add(R,R),new S(L,B,R)}add(I){d(I);let{X:T,Y:P,Z:A}=this,{X:D,Y:k,Z:L}=I,B=r.ZERO,R=r.ZERO,F=r.ZERO,U=o.a,z=r.mul(o.b,Hr),O=r.mul(T,D),ne=r.mul(P,k),ie=r.mul(A,L),ae=r.add(T,P),se=r.add(D,k);ae=r.mul(ae,se),se=r.add(O,ne),ae=r.sub(ae,se),se=r.add(T,A);let Ie=r.add(D,L);return se=r.mul(se,Ie),Ie=r.add(O,ie),se=r.sub(se,Ie),Ie=r.add(P,A),B=r.add(k,L),Ie=r.mul(Ie,B),B=r.add(ne,ie),Ie=r.sub(Ie,B),F=r.mul(U,se),B=r.mul(z,ie),F=r.add(B,F),B=r.sub(ne,F),F=r.add(ne,F),R=r.mul(B,F),ne=r.add(O,O),ne=r.add(ne,O),ie=r.mul(U,ie),se=r.mul(z,se),ne=r.add(ne,ie),ie=r.sub(O,ie),ie=r.mul(U,ie),se=r.add(se,ie),O=r.mul(ne,se),R=r.add(R,O),O=r.mul(Ie,se),B=r.mul(ae,B),B=r.sub(B,O),O=r.mul(ae,ne),F=r.mul(Ie,F),F=r.add(F,O),new S(B,R,F)}subtract(I){return d(I),this.add(I.negate())}is0(){return this.equals(S.ZERO)}multiply(I){let{endo:T}=e;if(!n.isValidNot0(I))throw new RangeError("invalid scalar: out of range");let P,A,D=k=>C.cached(this,k,L=>Rt(S,L));if(T){let{k1neg:k,k1:L,k2neg:B,k2:R}=y(I),{p:F,f:U}=D(L),{p:z,f:O}=D(R);A=U.add(O),P=v(T.beta,F,z,k,B)}else{let{p:k,f:L}=D(I);P=k,A=L}return Rt(S,[P,A])[0]}multiplyUnsafe(I){let{endo:T}=e,P=this,A=I;if(!n.isValid(A))throw new RangeError("invalid scalar: out of range");if(A===Ze||P.is0())return S.ZERO;if(A===Et)return P;if(C.hasCache(this))return this.multiply(A);if(T){let{k1neg:D,k1:k,k2neg:L,k2:B}=y(A),{p1:R,p2:F}=Xa(S,P,k,B);return v(T.beta,R,F,D,L)}else return C.unsafe(P,A)}toAffine(I){let T=this,P=I,{X:A,Y:D,Z:k}=T;if(r.eql(k,r.ONE))return{x:A,y:D};let L=T.is0();P==null&&(P=L?r.ONE:r.inv(k));let B=r.mul(A,P),R=r.mul(D,P),F=r.mul(k,P);if(L)return{x:r.ZERO,y:r.ZERO};if(!r.eql(F,r.ONE))throw new Error("invZ was invalid");return{x:B,y:R}}isTorsionFree(){let{isTorsionFree:I}=e;return i===Et?!0:I?I(S,this):C.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:I}=e;return i===Et?this:I?I(S,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Et?this.is0():this.clearCofactor().is0()}toBytes(I=!0){return Ce(I,"isCompressed"),this.assertValidity(),h(S,this,I)}toHex(I=!0){return es(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let M=n.BITS,C=new is(S,e.endo?Math.ceil(M/2):M);return M>=8&&S.BASE.precompute(8),Object.freeze(S.prototype),Object.freeze(S),S}function el(s){return Uint8Array.of(s?2:3)}function tl(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Fd(s,e={}){let{Fn:t}=s,r=e.randomBytes===void 0?Fs:e.randomBytes,n=Object.assign(tl(s.Fp,t),{seed:Math.max(no(t.ORDER),16)});function o(w){try{let h=t.fromBytes(w);return t.isValidNot0(h)}catch{return!1}}function i(w,h){let{publicKey:g,publicKeyUncompressed:b}=n;try{let x=w.length;return h===!0&&x!==g||h===!1&&x!==b?!1:!!s.fromBytes(w)}catch{return!1}}function a(w){return w=w===void 0?r(n.seed):w,oo(K(w,n.seed,"seed"),t.ORDER)}function l(w,h=!0){return s.BASE.multiply(t.fromBytes(w)).toBytes(h)}function u(w){let{secretKey:h,publicKey:g,publicKeyUncompressed:b}=n,x=t._lengths;if(!Pt(w))return;let _=K(w,void 0,"key").length,c=_===g||_===b,f=_===h||!!x?.includes(_);if(!(c&&f))return c}function p(w,h,g=!0){if(u(w)===!0)throw new Error("first arg must be private key");if(u(h)===!1)throw new Error("second arg must be public key");let b=t.fromBytes(w);return s.fromBytes(h).multiply(b).toBytes(g)}let m={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},E=Ar(a,l);return Object.freeze(m),Object.freeze(n),Object.freeze({getPublicKey:l,getSharedSecret:p,keygen:E,Point:s,utils:m,lengths:n})}function sl(s,e,t={}){let r=e;mr(r),Ne(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes===void 0?Fs:t.randomBytes,o=t.hmac===void 0?(A,D)=>Yc(r,A,D):t.hmac,{Fp:i,Fn:a}=s,{ORDER:l,BITS:u}=a,{keygen:p,getPublicKey:m,getSharedSecret:E,utils:w,lengths:h}=Fd(s,t),g={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},b=l*Jc+Et<i.ORDER;function x(A){let D=l>>Et;return A>D}function _(A,D){if(!a.isValidNot0(D))throw new Error(`invalid signature ${A}: out of range 1..Point.Fn.ORDER`);return D}function c(){if(b)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function f(A,D){xi(D);let k=h.signature,L=D==="compact"?k:D==="recovered"?k+1:void 0;return K(A,L)}class d{r;s;recovery;constructor(D,k,L){if(this.r=_("r",D),this.s=_("s",k),L!=null){if(c(),![0,1,2,3].includes(L))throw new Error("invalid recovery id");this.recovery=L}Object.freeze(this)}static fromBytes(D,k=g.format){f(D,k);let L;if(k==="der"){let{r:U,s:z}=Ue.toSig(K(D));return new d(U,z)}k==="recovered"&&(L=D[0],k="compact",D=D.subarray(1));let B=h.signature/2,R=D.subarray(0,B),F=D.subarray(B,B*2);return new d(a.fromBytes(R),a.fromBytes(F),L)}static fromHex(D,k){return this.fromBytes(ts(D),k)}assertRecovery(){let{recovery:D}=this;if(D==null)throw new Error("invalid recovery id: must be present");return D}addRecoveryBit(D){return new d(this.r,this.s,D)}recoverPublicKey(D){let{r:k,s:L}=this,B=this.assertRecovery(),R=B===2||B===3?k+l:k;if(!i.isValid(R))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let F=i.toBytes(R),U=s.fromBytes(oe(el((B&1)===0),F)),z=a.inv(R),O=v(K(D,void 0,"msgHash")),ne=a.create(-O*z),ie=a.create(L*z),ae=s.BASE.multiplyUnsafe(ne).add(U.multiplyUnsafe(ie));if(ae.is0())throw new Error("invalid recovery: point at infinify");return ae.assertValidity(),ae}hasHighS(){return x(this.s)}toBytes(D=g.format){if(xi(D),D==="der")return ts(Ue.hexFromSig(this));let{r:k,s:L}=this,B=a.toBytes(k),R=a.toBytes(L);return D==="recovered"?(c(),oe(Uint8Array.of(this.assertRecovery()),B,R)):oe(B,R)}toHex(D){return es(this.toBytes(D))}}Object.freeze(d.prototype),Object.freeze(d);let y=t.bits2int===void 0?function(D){if(D.length>8192)throw new Error("input is too large");let k=kt(D),L=D.length*8-u;return L>0?k>>BigInt(L):k}:t.bits2int,v=t.bits2int_modN===void 0?function(D){return a.create(y(D))}:t.bits2int_modN,S=Us(u);function M(A){return ss("num < 2^"+u,A,Ze,S),a.toBytes(A)}function C(A,D){return K(A,void 0,"message"),D?K(r(A),void 0,"prehashed message"):A}function N(A,D,k){let{lowS:L,prehash:B,extraEntropy:R}=wi(k,g);A=C(A,B);let F=v(A),U=a.fromBytes(D);if(!a.isValidNot0(U))throw new Error("invalid private key");let z=[M(U),M(F)];if(R!=null&&R!==!1){let ae=R===!0?n(h.secretKey):R;z.push(K(ae,void 0,"extraEntropy"))}let O=oe(...z),ne=F;function ie(ae){let se=y(ae);if(!a.isValidNot0(se))return;let Ie=a.inv(se),Ht=s.BASE.multiply(se).toAffine(),_s=a.create(Ht.x);if(_s===Ze)return;let or=a.create(Ie*a.create(ne+_s*U));if(or===Ze)return;let Ci=(Ht.x===_s?0:2)|Number(Ht.y&Et),Fi=or;return L&&x(or)&&(Fi=a.neg(or),Ci^=1),new d(_s,Fi,b?void 0:Ci)}return{seed:O,k2sig:ie}}function I(A,D,k={}){let{seed:L,k2sig:B}=N(A,D,k);return Ra(r.outputLen,a.BYTES,o)(L,B).toBytes(k.format)}function T(A,D,k,L={}){let{lowS:B,prehash:R,format:F}=wi(L,g);if(k=K(k,void 0,"publicKey"),D=C(D,R),!Pt(A)){let U=A instanceof d?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+U)}f(A,F);try{let U=d.fromBytes(A,F),z=s.fromBytes(k);if(B&&U.hasHighS())return!1;let{r:O,s:ne}=U,ie=v(D),ae=a.inv(ne),se=a.create(ie*ae),Ie=a.create(O*ae),Ht=s.BASE.multiplyUnsafe(se).add(z.multiplyUnsafe(Ie));return Ht.is0()?!1:a.create(Ht.x)===O}catch{return!1}}function P(A,D,k={}){let{prehash:L}=wi(k,g);return D=C(D,L),d.fromBytes(A,"recovered").recoverPublicKey(D).toBytes()}return Object.freeze({keygen:p,getPublicKey:m,getSharedSecret:E,utils:w,lengths:h,Point:s,sign:I,verify:T,recoverPublicKey:P,Signature:d,hash:r})}var Si={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Nd={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var rl=BigInt(2);function Od(s){let e=Si.p,t=BigInt(3),r=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),l=BigInt(88),u=s*s*s%e,p=u*u*s%e,m=$(p,t,e)*p%e,E=$(m,t,e)*p%e,w=$(E,rl,e)*u%e,h=$(w,n,e)*w%e,g=$(h,o,e)*h%e,b=$(g,a,e)*g%e,x=$(b,l,e)*b%e,_=$(x,a,e)*g%e,c=$(_,t,e)*p%e,f=$(c,i,e)*h%e,d=$(f,r,e)*u%e,y=$(d,rl,e);if(!Ei.eql(Ei.sqr(y),s))throw new Error("Cannot find square root");return y}var Ei=ns(Si.p,{sqrt:Od}),Ud=Qc(Si,{Fp:Ei,endo:Nd}),ms=sl(Ud,Qt);function nl(s,e,t,r){let n=Dt.digest(t instanceof Uint8Array?t:t.subarray());if(Lr(n))return n.then(({digest:o})=>(r?.signal?.throwIfAborted(),ms.verify(e,o,s,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new Gs(String(o))});try{return r?.signal?.throwIfAborted(),ms.verify(e,n.digest,s,{prehash:!1,format:"der"})}catch(o){throw new Gs(String(o))}}var Gr=class{type="secp256k1";raw;_key;constructor(e){this._key=il(e),this.raw=ol(this._key)}toMultihash(){return Le.digest(qe(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}verify(e,t,r){return nl(this._key,t,e,r)}};function _i(s){return new Gr(s)}function ol(s){return ms.Point.fromBytes(s).toBytes()}function il(s){try{return ms.Point.fromBytes(s),s}catch(e){throw new qt(String(e))}}function qr(s,e){let{Type:t,Data:r}=je.decode(s),n=r??new Uint8Array;switch(t){case Z.RSA:return gi(n,e);case Z.Ed25519:return wo(n);case Z.secp256k1:return _i(n);case Z.ECDSA:return zn(n);default:throw new Vt}}function al(s){let{Type:e,Data:t}=je.decode(s.digest),r=t??new Uint8Array;switch(e){case Z.Ed25519:return wo(r);case Z.secp256k1:return _i(r);case Z.ECDSA:return zn(r);default:throw new Vt}}function qe(s){return je.encode({Type:Z[s.type],Data:s.raw})}var cl=Symbol.for("nodejs.util.inspect.custom"),Kd=114,er=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()})`}[fn]=!0;toString(){return this.string==null&&(this.string=Q.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ue.createV1(Kd,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Pe(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Pe(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[cl](){return`PeerId(${this.toString()})`}},Vr=class extends er{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Wr=class extends er{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},$r=class extends er{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},zd=2336,tr=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Le.digest(j(this.url))}[cl](){return`PeerId(${this.url})`}[fn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ue.createV1(zd,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=q(e)),e.toString()===this.toString())}};var Hd=114,ll=2336;function Ot(s,e){let t;if(s.charAt(0)==="1"||s.charAt(0)==="Q")t=Je(Q.decode(`z${s}`));else{if(s.startsWith("k51qzi5uqu5")||s.startsWith("kzwfwjn5ji4")||s.startsWith("k2k4r8")||s.startsWith("bafz"))return Gd(ue.parse(s));if(e==null)throw new X('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Je(e.decode(s))}return gs(t)}function gs(s){if(Vd(s))return new Vr({multihash:s});if(qd(s))try{let e=al(s);if(e.type==="Ed25519")return new Wr({multihash:s,publicKey:e});if(e.type==="secp256k1")return new $r({multihash:s,publicKey:e})}catch{let t=q(s.digest);return new tr(new URL(t))}throw new cr("Supplied PeerID Multihash is invalid")}function Gd(s){if(s?.multihash==null||s.version==null||s.version===1&&s.code!==Hd&&s.code!==ll)throw new ar("Supplied PeerID CID is invalid");if(s.code===ll){let e=q(s.multihash.digest);return new tr(new URL(e))}return gs(s.multihash)}function qd(s){return s.code===Le.code}function Vd(s){return s.code===Dt.code}function ul(s=0){return new Uint8Array(s)}var jr=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},bs=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Zr=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},sr=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Yr(s){return s[Symbol.asyncIterator]!=null}function hl(s,e){if(s.byteLength>e)throw new bs("Message length too long")}var Jr=s=>{let e=Be(s),t=ul(e);return To(s,t),Jr.bytes=e,t};Jr.bytes=0;function ys(s,e){e=e??{};let t=e.lengthEncoder??Jr,r=e?.maxDataLength??4194304;function*n(o){hl(o,r);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return Yr(s)?(async function*(){for await(let o of s)yield*n(o)})():(function*(){for(let o of s)yield*n(o)})()}ys.single=(s,e)=>{e=e??{};let t=e.lengthEncoder??Jr,r=e?.maxDataLength??4194304;return hl(s,r),new ce(t(s.byteLength),s)};var Ut;(function(s){s[s.LENGTH=0]="LENGTH",s[s.DATA=1]="DATA"})(Ut||(Ut={}));var Ii=s=>{let e=Do(s);return Ii.bytes=Be(e),e};Ii.bytes=0;function rr(s,e){let t=new ce,r=Ut.LENGTH,n=-1,o=e?.lengthDecoder??Ii,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*l(){for(;t.byteLength>0;){if(r===Ut.LENGTH)try{if(n=o(t),n<0)throw new jr("Invalid message length");if(n>a)throw new bs("Message length too long");let u=o.bytes;t.consume(u),e?.onLength!=null&&e.onLength(n),r=Ut.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new Zr("Message length length too long");break}throw u}if(r===Ut.DATA){if(t.byteLength<n)break;let u=t.sublist(0,n);t.consume(n),e?.onData!=null&&e.onData(u),yield u,r=Ut.LENGTH}}}return Yr(s)?(async function*(){for await(let u of s)t.append(u),yield*l();if(t.byteLength>0)throw new sr("Unexpected end of input")})():(function*(){for(let u of s)t.append(u),yield*l();if(t.byteLength>0)throw new sr("Unexpected end of input")})()}rr.fromReader=(s,e)=>{let t=1,r=(async function*(){for(;;)try{let{done:o,value:i}=await s.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return rr(r,{...e??{},onLength:o=>{t=o}})};function at(){let s={};return s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),s}var Qr=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}},ws=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Qr(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 Qr(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 Ti=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Kt(s={}){return $d(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 $d(s,e){e=e??{};let t=e.onEnd,r=new ws,n,o,i,a=at(),l=async()=>{try{return r.isEmpty()?i?{done:!0}:await new Promise((b,x)=>{o=_=>{o=null,r.push(_);try{b(s(r))}catch(c){x(c)}return n}}):s(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=at()})}},u=b=>o!=null?o(b):(r.push(b),n),p=b=>(r=new ws,o!=null?o({error:b}):(r.push({error:b}),n)),m=b=>{if(i)return n;if(e?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:b})},E=b=>i?n:(i=!0,b!=null?p(b):u({done:!0})),w=()=>(r=new ws,E(),{done:!0}),h=b=>(E(b),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:l,return:w,throw:h,push:m,end:E,get readableLength(){return r.size},onEmpty:async b=>{let x=b?.signal;if(x?.throwIfAborted(),r.isEmpty())return;let _,c;x!=null&&(_=new Promise((f,d)=>{c=()=>{d(new Ti)},x.addEventListener("abort",c)}));try{await Promise.race([a.promise,_])}finally{c!=null&&x!=null&&x?.removeEventListener("abort",c)}}},t==null)return n;let g=n;return n={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(b){return g.throw(b),t!=null&&(t(b),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:m,end(b){return g.end(b),t!=null&&(t(b),t=void 0),n},get readableLength(){return g.readableLength},onEmpty:b=>g.onEmpty(b)},n}function jd(s){return s.reason}async function Di(s,e,t){if(e==null)return s;let r=t?.translateError??jd;if(e.aborted)return s.catch(()=>{}),Promise.reject(r(e));let n;try{return await Promise.race([s,new Promise((o,i)=>{n=()=>{i(r(e))},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Ai=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=at(),this.haveNext=at()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=at(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=at(),await Di(this.readNext.promise,t?.signal,t)}};function fl(){return new Ai}function Zd(s){return s[Symbol.asyncIterator]!=null}async function Yd(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*Xd(s){let e=new AbortController,t=fl();Yd(s,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Jd(s){for(let e of s)yield*e}function Qd(...s){let e=[];for(let t of s)Zd(t)||e.push(t);return e.length===s.length?Jd(e):Xd(s)}var dl=Qd;function nr(s,...e){if(s==null)throw new Error("Empty pipeline");if(Mi(s)){let r=s;s=()=>r.source}else if(ml(s)||pl(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]=tp(t[r]));return ep(...t)}var ep=(...s)=>{let e;for(;s.length>0;)e=s.shift()(e);return e},pl=s=>s?.[Symbol.asyncIterator]!=null,ml=s=>s?.[Symbol.iterator]!=null,Mi=s=>s==null?!1:s.sink!=null&&s.source!=null,tp=s=>e=>{let t=s.sink(e);if(t?.then!=null){let r=Kt({objectMode:!0});t.then(()=>{r.end()},i=>{r.end(i)});let n,o=s.source;if(pl(o))n=async function*(){yield*o,r.end()};else if(ml(o))n=function*(){yield*o,r.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return dl(r,n())}return s.source};var gl={maxSubscriptions:5e3,maxMessages:5e3,maxIhaveMessageIDs:5e3,maxIwantMessageIDs:5e3,maxControlMessages:5e3,maxIdontwantMessageIDs:512,maxPeerInfos:16};var ct;(function(s){let e;(function(h){let g;h.codec=()=>(g==null&&(g=ve((c,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),c.subscribe!=null&&(f.uint32(8),f.bool(c.subscribe)),c.topic!=null&&(f.uint32(18),f.string(c.topic)),d.lengthDelimited!==!1&&f.ldelim()},(c,f,d={})=>{let y={},v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{y.subscribe=c.bool();break}case 2:{y.topic=c.string();break}default:{c.skipType(S&7);break}}}return y},function*(c,f,d,y={}){let v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{yield{field:`${d}.subscribe`,value:c.bool()};break}case 2:{yield{field:`${d}.topic`,value:c.string()};break}default:{c.skipType(S&7);break}}}})),g);function b(c){return we(c,h.codec())}h.encode=b;function x(c,f){return ye(c,h.codec(),f)}h.decode=x;function _(c,f){return xe(c,h.codec(),f)}h.stream=_})(e=s.SubOpts||(s.SubOpts={}));let t;(function(h){let g;h.codec=()=>(g==null&&(g=ve((c,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),c.from!=null&&(f.uint32(10),f.bytes(c.from)),c.data!=null&&(f.uint32(18),f.bytes(c.data)),c.seqno!=null&&(f.uint32(26),f.bytes(c.seqno)),c.topic!=null&&c.topic!==""&&(f.uint32(34),f.string(c.topic)),c.signature!=null&&(f.uint32(42),f.bytes(c.signature)),c.key!=null&&(f.uint32(50),f.bytes(c.key)),d.lengthDelimited!==!1&&f.ldelim()},(c,f,d={})=>{let y={topic:""},v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{y.from=c.bytes();break}case 2:{y.data=c.bytes();break}case 3:{y.seqno=c.bytes();break}case 4:{y.topic=c.string();break}case 5:{y.signature=c.bytes();break}case 6:{y.key=c.bytes();break}default:{c.skipType(S&7);break}}}return y},function*(c,f,d,y={}){let v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{yield{field:`${d}.from`,value:c.bytes()};break}case 2:{yield{field:`${d}.data`,value:c.bytes()};break}case 3:{yield{field:`${d}.seqno`,value:c.bytes()};break}case 4:{yield{field:`${d}.topic`,value:c.string()};break}case 5:{yield{field:`${d}.signature`,value:c.bytes()};break}case 6:{yield{field:`${d}.key`,value:c.bytes()};break}default:{c.skipType(S&7);break}}}})),g);function b(c){return we(c,h.codec())}h.encode=b;function x(c,f){return ye(c,h.codec(),f)}h.decode=x;function _(c,f){return xe(c,h.codec(),f)}h.stream=_})(t=s.Message||(s.Message={}));let r;(function(h){let g;h.codec=()=>(g==null&&(g=ve((c,f,d={})=>{if(d.lengthDelimited!==!1&&f.fork(),c.ihave!=null&&c.ihave.length>0)for(let y of c.ihave)f.uint32(10),s.ControlIHave.codec().encode(y,f);if(c.iwant!=null&&c.iwant.length>0)for(let y of c.iwant)f.uint32(18),s.ControlIWant.codec().encode(y,f);if(c.graft!=null&&c.graft.length>0)for(let y of c.graft)f.uint32(26),s.ControlGraft.codec().encode(y,f);if(c.prune!=null&&c.prune.length>0)for(let y of c.prune)f.uint32(34),s.ControlPrune.codec().encode(y,f);if(c.idontwant!=null&&c.idontwant.length>0)for(let y of c.idontwant)f.uint32(42),s.ControlIDontWant.codec().encode(y,f);d.lengthDelimited!==!1&&f.ldelim()},(c,f,d={})=>{let y={ihave:[],iwant:[],graft:[],prune:[],idontwant:[]},v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{if(d.limits?.ihave!=null&&y.ihave.length===d.limits.ihave)throw new W('Decode error - repeated field "ihave" had too many elements');y.ihave.push(s.ControlIHave.codec().decode(c,c.uint32(),{limits:d.limits?.ihave$}));break}case 2:{if(d.limits?.iwant!=null&&y.iwant.length===d.limits.iwant)throw new W('Decode error - repeated field "iwant" had too many elements');y.iwant.push(s.ControlIWant.codec().decode(c,c.uint32(),{limits:d.limits?.iwant$}));break}case 3:{if(d.limits?.graft!=null&&y.graft.length===d.limits.graft)throw new W('Decode error - repeated field "graft" had too many elements');y.graft.push(s.ControlGraft.codec().decode(c,c.uint32(),{limits:d.limits?.graft$}));break}case 4:{if(d.limits?.prune!=null&&y.prune.length===d.limits.prune)throw new W('Decode error - repeated field "prune" had too many elements');y.prune.push(s.ControlPrune.codec().decode(c,c.uint32(),{limits:d.limits?.prune$}));break}case 5:{if(d.limits?.idontwant!=null&&y.idontwant.length===d.limits.idontwant)throw new W('Decode error - repeated field "idontwant" had too many elements');y.idontwant.push(s.ControlIDontWant.codec().decode(c,c.uint32(),{limits:d.limits?.idontwant$}));break}default:{c.skipType(S&7);break}}}return y},function*(c,f,d,y={}){let v={ihave:0,iwant:0,graft:0,prune:0,idontwant:0},S=f==null?c.len:c.pos+f;for(;c.pos<S;){let M=c.uint32();switch(M>>>3){case 1:{if(y.limits?.ihave!=null&&v.ihave===y.limits.ihave)throw new W('Streaming decode error - repeated field "ihave" had too many elements');for(let C of s.ControlIHave.codec().stream(c,c.uint32(),`${d}.ihave[]`,{limits:y.limits?.ihave$}))yield{...C,index:v.ihave};v.ihave++;break}case 2:{if(y.limits?.iwant!=null&&v.iwant===y.limits.iwant)throw new W('Streaming decode error - repeated field "iwant" had too many elements');for(let C of s.ControlIWant.codec().stream(c,c.uint32(),`${d}.iwant[]`,{limits:y.limits?.iwant$}))yield{...C,index:v.iwant};v.iwant++;break}case 3:{if(y.limits?.graft!=null&&v.graft===y.limits.graft)throw new W('Streaming decode error - repeated field "graft" had too many elements');for(let C of s.ControlGraft.codec().stream(c,c.uint32(),`${d}.graft[]`,{limits:y.limits?.graft$}))yield{...C,index:v.graft};v.graft++;break}case 4:{if(y.limits?.prune!=null&&v.prune===y.limits.prune)throw new W('Streaming decode error - repeated field "prune" had too many elements');for(let C of s.ControlPrune.codec().stream(c,c.uint32(),`${d}.prune[]`,{limits:y.limits?.prune$}))yield{...C,index:v.prune};v.prune++;break}case 5:{if(y.limits?.idontwant!=null&&v.idontwant===y.limits.idontwant)throw new W('Streaming decode error - repeated field "idontwant" had too many elements');for(let C of s.ControlIDontWant.codec().stream(c,c.uint32(),`${d}.idontwant[]`,{limits:y.limits?.idontwant$}))yield{...C,index:v.idontwant};v.idontwant++;break}default:{c.skipType(M&7);break}}}})),g);function b(c){return we(c,h.codec())}h.encode=b;function x(c,f){return ye(c,h.codec(),f)}h.decode=x;function _(c,f){return xe(c,h.codec(),f)}h.stream=_})(r=s.ControlMessage||(s.ControlMessage={}));let n;(function(h){let g;h.codec=()=>(g==null&&(g=ve((c,f,d={})=>{if(d.lengthDelimited!==!1&&f.fork(),c.topicID!=null&&(f.uint32(10),f.string(c.topicID)),c.messageIDs!=null&&c.messageIDs.length>0)for(let y of c.messageIDs)f.uint32(18),f.bytes(y);d.lengthDelimited!==!1&&f.ldelim()},(c,f,d={})=>{let y={messageIDs:[]},v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{y.topicID=c.string();break}case 2:{if(d.limits?.messageIDs!=null&&y.messageIDs.length===d.limits.messageIDs)throw new W('Decode error - repeated field "messageIDs" had too many elements');y.messageIDs.push(c.bytes());break}default:{c.skipType(S&7);break}}}return y},function*(c,f,d,y={}){let v={messageIDs:0},S=f==null?c.len:c.pos+f;for(;c.pos<S;){let M=c.uint32();switch(M>>>3){case 1:{yield{field:`${d}.topicID`,value:c.string()};break}case 2:{if(y.limits?.messageIDs!=null&&v.messageIDs===y.limits.messageIDs)throw new W('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:c.bytes()},v.messageIDs++;break}default:{c.skipType(M&7);break}}}})),g);function b(c){return we(c,h.codec())}h.encode=b;function x(c,f){return ye(c,h.codec(),f)}h.decode=x;function _(c,f){return xe(c,h.codec(),f)}h.stream=_})(n=s.ControlIHave||(s.ControlIHave={}));let o;(function(h){let g;h.codec=()=>(g==null&&(g=ve((c,f,d={})=>{if(d.lengthDelimited!==!1&&f.fork(),c.messageIDs!=null&&c.messageIDs.length>0)for(let y of c.messageIDs)f.uint32(10),f.bytes(y);d.lengthDelimited!==!1&&f.ldelim()},(c,f,d={})=>{let y={messageIDs:[]},v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{if(d.limits?.messageIDs!=null&&y.messageIDs.length===d.limits.messageIDs)throw new W('Decode error - repeated field "messageIDs" had too many elements');y.messageIDs.push(c.bytes());break}default:{c.skipType(S&7);break}}}return y},function*(c,f,d,y={}){let v={messageIDs:0},S=f==null?c.len:c.pos+f;for(;c.pos<S;){let M=c.uint32();switch(M>>>3){case 1:{if(y.limits?.messageIDs!=null&&v.messageIDs===y.limits.messageIDs)throw new W('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:c.bytes()},v.messageIDs++;break}default:{c.skipType(M&7);break}}}})),g);function b(c){return we(c,h.codec())}h.encode=b;function x(c,f){return ye(c,h.codec(),f)}h.decode=x;function _(c,f){return xe(c,h.codec(),f)}h.stream=_})(o=s.ControlIWant||(s.ControlIWant={}));let i;(function(h){let g;h.codec=()=>(g==null&&(g=ve((c,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),c.topicID!=null&&(f.uint32(10),f.string(c.topicID)),d.lengthDelimited!==!1&&f.ldelim()},(c,f,d={})=>{let y={},v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();S>>>3===1?y.topicID=c.string():c.skipType(S&7)}return y},function*(c,f,d,y={}){let v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();S>>>3===1?yield{field:`${d}.topicID`,value:c.string()}:c.skipType(S&7)}})),g);function b(c){return we(c,h.codec())}h.encode=b;function x(c,f){return ye(c,h.codec(),f)}h.decode=x;function _(c,f){return xe(c,h.codec(),f)}h.stream=_})(i=s.ControlGraft||(s.ControlGraft={}));let a;(function(h){let g;h.codec=()=>(g==null&&(g=ve((c,f,d={})=>{if(d.lengthDelimited!==!1&&f.fork(),c.topicID!=null&&(f.uint32(10),f.string(c.topicID)),c.peers!=null&&c.peers.length>0)for(let y of c.peers)f.uint32(18),s.PeerInfo.codec().encode(y,f);c.backoff!=null&&(f.uint32(24),f.uint64Number(c.backoff)),d.lengthDelimited!==!1&&f.ldelim()},(c,f,d={})=>{let y={peers:[]},v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{y.topicID=c.string();break}case 2:{if(d.limits?.peers!=null&&y.peers.length===d.limits.peers)throw new W('Decode error - repeated field "peers" had too many elements');y.peers.push(s.PeerInfo.codec().decode(c,c.uint32(),{limits:d.limits?.peers$}));break}case 3:{y.backoff=c.uint64Number();break}default:{c.skipType(S&7);break}}}return y},function*(c,f,d,y={}){let v={peers:0},S=f==null?c.len:c.pos+f;for(;c.pos<S;){let M=c.uint32();switch(M>>>3){case 1:{yield{field:`${d}.topicID`,value:c.string()};break}case 2:{if(y.limits?.peers!=null&&v.peers===y.limits.peers)throw new W('Streaming decode error - repeated field "peers" had too many elements');for(let C of s.PeerInfo.codec().stream(c,c.uint32(),`${d}.peers[]`,{limits:y.limits?.peers$}))yield{...C,index:v.peers};v.peers++;break}case 3:{yield{field:`${d}.backoff`,value:c.uint64Number()};break}default:{c.skipType(M&7);break}}}})),g);function b(c){return we(c,h.codec())}h.encode=b;function x(c,f){return ye(c,h.codec(),f)}h.decode=x;function _(c,f){return xe(c,h.codec(),f)}h.stream=_})(a=s.ControlPrune||(s.ControlPrune={}));let l;(function(h){let g;h.codec=()=>(g==null&&(g=ve((c,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),c.peerID!=null&&(f.uint32(10),f.bytes(c.peerID)),c.signedPeerRecord!=null&&(f.uint32(18),f.bytes(c.signedPeerRecord)),d.lengthDelimited!==!1&&f.ldelim()},(c,f,d={})=>{let y={},v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{y.peerID=c.bytes();break}case 2:{y.signedPeerRecord=c.bytes();break}default:{c.skipType(S&7);break}}}return y},function*(c,f,d,y={}){let v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{yield{field:`${d}.peerID`,value:c.bytes()};break}case 2:{yield{field:`${d}.signedPeerRecord`,value:c.bytes()};break}default:{c.skipType(S&7);break}}}})),g);function b(c){return we(c,h.codec())}h.encode=b;function x(c,f){return ye(c,h.codec(),f)}h.decode=x;function _(c,f){return xe(c,h.codec(),f)}h.stream=_})(l=s.PeerInfo||(s.PeerInfo={}));let u;(function(h){let g;h.codec=()=>(g==null&&(g=ve((c,f,d={})=>{if(d.lengthDelimited!==!1&&f.fork(),c.messageIDs!=null&&c.messageIDs.length>0)for(let y of c.messageIDs)f.uint32(10),f.bytes(y);d.lengthDelimited!==!1&&f.ldelim()},(c,f,d={})=>{let y={messageIDs:[]},v=f==null?c.len:c.pos+f;for(;c.pos<v;){let S=c.uint32();switch(S>>>3){case 1:{if(d.limits?.messageIDs!=null&&y.messageIDs.length===d.limits.messageIDs)throw new W('Decode error - repeated field "messageIDs" had too many elements');y.messageIDs.push(c.bytes());break}default:{c.skipType(S&7);break}}}return y},function*(c,f,d,y={}){let v={messageIDs:0},S=f==null?c.len:c.pos+f;for(;c.pos<S;){let M=c.uint32();switch(M>>>3){case 1:{if(y.limits?.messageIDs!=null&&v.messageIDs===y.limits.messageIDs)throw new W('Streaming decode error - repeated field "messageIDs" had too many elements');yield{field:`${d}.messageIDs[]`,index:v.messageIDs,value:c.bytes()},v.messageIDs++;break}default:{c.skipType(M&7);break}}}})),g);function b(c){return we(c,h.codec())}h.encode=b;function x(c,f){return ye(c,h.codec(),f)}h.decode=x;function _(c,f){return xe(c,h.codec(),f)}h.stream=_})(u=s.ControlIDontWant||(s.ControlIDontWant={}));let p;s.codec=()=>(p==null&&(p=ve((h,g,b={})=>{if(b.lengthDelimited!==!1&&g.fork(),h.subscriptions!=null&&h.subscriptions.length>0)for(let x of h.subscriptions)g.uint32(10),s.SubOpts.codec().encode(x,g);if(h.messages!=null&&h.messages.length>0)for(let x of h.messages)g.uint32(18),s.Message.codec().encode(x,g);h.control!=null&&(g.uint32(26),s.ControlMessage.codec().encode(h.control,g)),b.lengthDelimited!==!1&&g.ldelim()},(h,g,b={})=>{let x={subscriptions:[],messages:[]},_=g==null?h.len:h.pos+g;for(;h.pos<_;){let c=h.uint32();switch(c>>>3){case 1:{if(b.limits?.subscriptions!=null&&x.subscriptions.length===b.limits.subscriptions)throw new W('Decode error - repeated field "subscriptions" had too many elements');x.subscriptions.push(s.SubOpts.codec().decode(h,h.uint32(),{limits:b.limits?.subscriptions$}));break}case 2:{if(b.limits?.messages!=null&&x.messages.length===b.limits.messages)throw new W('Decode error - repeated field "messages" had too many elements');x.messages.push(s.Message.codec().decode(h,h.uint32(),{limits:b.limits?.messages$}));break}case 3:{x.control=s.ControlMessage.codec().decode(h,h.uint32(),{limits:b.limits?.control});break}default:{h.skipType(c&7);break}}}return x},function*(h,g,b,x={}){let _={subscriptions:0,messages:0},c=g==null?h.len:h.pos+g;for(;h.pos<c;){let f=h.uint32();switch(f>>>3){case 1:{if(x.limits?.subscriptions!=null&&_.subscriptions===x.limits.subscriptions)throw new W('Streaming decode error - repeated field "subscriptions" had too many elements');for(let d of s.SubOpts.codec().stream(h,h.uint32(),`${b}.subscriptions[]`,{limits:x.limits?.subscriptions$}))yield{...d,index:_.subscriptions};_.subscriptions++;break}case 2:{if(x.limits?.messages!=null&&_.messages===x.limits.messages)throw new W('Streaming decode error - repeated field "messages" had too many elements');for(let d of s.Message.codec().stream(h,h.uint32(),`${b}.messages[]`,{limits:x.limits?.messages$}))yield{...d,index:_.messages};_.messages++;break}case 3:{yield*s.ControlMessage.codec().stream(h,h.uint32(),`${b}.control`,{limits:x.limits?.control});break}default:{h.skipType(f&7);break}}}})),p);function m(h){return we(h,s.codec())}s.encode=m;function E(h,g){return ye(h,s.codec(),g)}s.decode=E;function w(h,g){return xe(h,s.codec(),g)}s.stream=w})(ct||(ct={}));var en=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 i=t.get(n.topic);i==null&&(i=[],t.set(n.topic,i)),i.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 bl;(function(s){s.StrictSign="StrictSign",s.StrictNoSign="StrictNoSign"})(bl||(bl={}));var St;(function(s){s[s.Signing=0]="Signing",s[s.Anonymous=1]="Anonymous"})(St||(St={}));var Ee;(function(s){s.Error="error",s.Ignore="ignore",s.Reject="reject",s.Blacklisted="blacklisted"})(Ee||(Ee={}));var me;(function(s){s.InvalidSignature="invalid_signature",s.InvalidSeqno="invalid_seqno",s.InvalidPeerId="invalid_peerid",s.SignaturePresent="signature_present",s.SeqnoPresent="seqno_present",s.FromPresent="from_present",s.TransformFailed="transform_failed"})(me||(me={}));var ge;(function(s){s.duplicate="duplicate",s.invalid="invalid",s.valid="valid"})(ge||(ge={}));function Pi(s){switch(s){case be.Ignore:return Ee.Ignore;case be.Reject:return Ee.Reject;default:throw new Error("Unreachable")}}var yl;(function(s){s.forward="forward",s.publish="publish"})(yl||(yl={}));var Se;(function(s){s.Fanout="fanout",s.Random="random",s.Subscribed="subscribed",s.Outbound="outbound",s.NotEnough="not_enough",s.Opportunistic="opportunistic"})(Se||(Se={}));var Ke;(function(s){s.Dc="disconnected",s.BadScore="bad_score",s.Prune="prune",s.Excess="excess"})(Ke||(Ke={}));var vs;(function(s){s.GraftBackoff="graft_backoff",s.BrokenPromise="broken_promise",s.MessageDeficit="message_deficit",s.IPColocation="IP_colocation"})(vs||(vs={}));var Es;(function(s){s.LowScore="low_score",s.MaxIhave="max_ihave",s.MaxIasked="max_iasked"})(Es||(Es={}));var xs;(function(s){s.graylist="graylist",s.publish="publish",s.gossip="gossip",s.mesh="mesh"})(xs||(xs={}));function wl(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,o){let i=this.toTopic(r);switch(n){case Se.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:i},o);break;case Se.Random:this.meshPeerInclusionEventsRandom.inc({topic:i},o);break;case Se.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:i},o);break;case Se.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:i},o);break;case Se.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:i},o);break;case Se.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:i},o);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:i},o);break}},onRemoveFromMesh(r,n,o){let i=this.toTopic(r);switch(n){case Ke.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:i},o);break;case Ke.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:i},o);break;case Ke.Prune:this.meshPeerChurnEventsPrune.inc({topic:i},o);break;case Ke.Excess:this.meshPeerChurnEventsExcess.inc({topic:i},o);break;default:this.meshPeerChurnEventsUnknown.inc({topic:i},o);break}},onReportValidation(r,n,o){if(this.asyncValidationMcacheHit.inc({hit:r!=null?"hit":"miss"}),r!=null){let i=this.toTopic(r.message.topic);switch(n){case be.Accept:this.acceptedMessagesTotal.inc({topic:i});break;case be.Ignore:this.ignoredMessagesTotal.inc({topic:i});break;case be.Reject:this.rejectedMessagesTotal.inc({topic:i});break;default:this.unknownValidationResultsTotal.inc({topic:i});break}}o!=null?this.asyncValidationDelayFromFirstSeenSec.observe((Date.now()-o)/1e3):this.asyncValidationUnknownFirstSeen.inc()},onScorePenalty(r){this.scoringPenalties.inc({penalty:r},1)},onIhaveRcv(r,n,o){let i=this.toTopic(r);this.ihaveRcvMsgids.inc({topic:i},n),this.ihaveRcvNotSeenMsgids.inc({topic:i},o)},onIwantRcv(r,n){for(let[o,i]of r){let a=this.toTopic(o);this.iwantRcvMsgids.inc({topic:a},i)}this.iwantRcvDonthaveMsgids.inc(n)},onIdontwantRcv(r,n){this.idontwantRcvMsgids.inc(r),this.idontwantRcvDonthaveMsgids.inc(n)},onForwardMsg(r,n){let o=this.toTopic(r);this.msgForwardCount.inc({topic:o},1),this.msgForwardPeers.inc({topic:o},n)},onPublishMsg(r,n,o,i,a){let l=this.toTopic(r);this.msgPublishCount.inc({topic:l},1),this.msgPublishBytes.inc({topic:l},o*i),this.msgPublishPeersByTopic.inc({topic:l},o),this.directPeersPublishedTotal.inc({topic:l},n.direct),this.floodsubPeersPublishedTotal.inc({topic:l},n.floodsub),this.meshPeersPublishedTotal.inc({topic:l},n.mesh),this.fanoutPeersPublishedTotal.inc({topic:l},n.fanout),this.msgPublishTime.observe({topic:l},a/1e3)},onMsgRecvPreValidation(r){let n=this.toTopic(r);this.msgReceivedPreValidation.inc({topic:n},1)},onMsgRecvError(r){let n=this.toTopic(r);this.msgReceivedError.inc({topic:n},1)},onPrevalidationResult(r,n){let o=this.toTopic(r);switch(n){case ge.duplicate:this.prevalidationDuplicateTotal.inc({topic:o});break;case ge.invalid:this.prevalidationInvalidTotal.inc({topic:o});break;case ge.valid:this.prevalidationValidTotal.inc({topic:o});break;default:this.prevalidationUnknownTotal.inc({topic:o});break}},onMsgRecvInvalid(r,n){let o=this.toTopic(r),i=n.reason===Ee.Error?n.error:n.reason;this.msgReceivedInvalid.inc({error:i},1),this.msgReceivedInvalidByTopic.inc({topic:o},1)},onDuplicateMsgDelivery(r,n,o){let i=this.toTopic(r);this.duplicateMsgDeliveryDelay.observe({topic:i},n/1e3),o&&this.duplicateMsgLateDelivery.inc({topic:i},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 o=r.control.ihave?.length??0,i=r.control.iwant?.length??0,a=r.control.graft?.length??0,l=r.control.prune?.length??0,u=r.control.idontwant?.length??0;o>0&&this.rpcSentIHave.inc(o),i>0&&this.rpcSentIWant.inc(i),a>0&&this.rpcSentGraft.inc(a),l>0&&this.rpcSentPrune.inc(l),u>0&&this.rpcSentIDontWant.inc(u),(o>0||i>0||a>0||l>0||u>0)&&this.rpcSentControl.inc(1)}},registerScores(r,n){let o=0,i=0,a=0,l=0;for(let u of r)u>=n.graylistThreshold&&o++,u>=n.publishThreshold&&i++,u>=n.gossipThreshold&&a++,u>=0&&l++;this.peersByScoreThreshold.set({threshold:xs.graylist},o),this.peersByScoreThreshold.set({threshold:xs.publish},i),this.peersByScoreThreshold.set({threshold:xs.gossip},a),this.peersByScoreThreshold.set({threshold:xs.mesh},l),this.score.set(r)},registerScoreWeights(r){for(let[n,o]of r.byTopic)this.scoreWeights.set({topic:n,p:"p1"},o.p1w),this.scoreWeights.set({topic:n,p:"p2"},o.p2w),this.scoreWeights.set({topic:n,p:"p3"},o.p3w),this.scoreWeights.set({topic:n,p:"p3b"},o.p3bw),this.scoreWeights.set({topic:n,p:"p4"},o.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 o=new Map;r.forEach((i,a)=>{let l=this.topicStrToLabel.get(a)??"unknown",u=o.get(l);u==null&&(u=new Set,o.set(l,u)),i.forEach(p=>u?.add(p))});for(let[i,a]of o){let l=[];a.forEach(u=>{l.push(n.get(u)??0)}),this.scorePerMesh.set({topic:i},l)}}}}var G=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var sp={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},rp={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 xl(s={}){return{...sp,...s,topics:s.topics!=null?Object.entries(s.topics).reduce((e,[t,r])=>(e[t]=np(r),e),{}):{}}}function np(s={}){return{...rp,...s}}function vl(s){for(let[e,t]of Object.entries(s.topics))try{op(t)}catch(r){throw new G(`invalid score parameters for topic ${e}: ${r.message}`)}if(s.topicScoreCap<0)throw new G("invalid topic score cap; must be positive (or 0 for no cap)");if(s.appSpecificScore===null||s.appSpecificScore===void 0)throw new G("missing application specific score function");if(s.IPColocationFactorWeight>0)throw new G("invalid IPColocationFactorWeight; must be negative (or 0 to disable)");if(s.IPColocationFactorWeight!==0&&s.IPColocationFactorThreshold<1)throw new G("invalid IPColocationFactorThreshold; must be at least 1");if(s.behaviourPenaltyWeight>0)throw new G("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)");if(s.behaviourPenaltyWeight!==0&&(s.behaviourPenaltyDecay<=0||s.behaviourPenaltyDecay>=1))throw new G("invalid BehaviourPenaltyDecay; must be between 0 and 1");if(s.decayInterval<1e3)throw new G("invalid DecayInterval; must be at least 1s");if(s.decayToZero<=0||s.decayToZero>=1)throw new G("invalid DecayToZero; must be between 0 and 1")}function op(s){if(s.topicWeight<0)throw new G("invalid topic weight; must be >= 0");if(s.timeInMeshQuantum===0)throw new G("invalid TimeInMeshQuantum; must be non zero");if(s.timeInMeshWeight<0)throw new G("invalid TimeInMeshWeight; must be positive (or 0 to disable)");if(s.timeInMeshWeight!==0&&s.timeInMeshQuantum<=0)throw new G("invalid TimeInMeshQuantum; must be positive");if(s.timeInMeshWeight!==0&&s.timeInMeshCap<=0)throw new G("invalid TimeInMeshCap; must be positive");if(s.firstMessageDeliveriesWeight<0)throw new G("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)");if(s.firstMessageDeliveriesWeight!==0&&(s.firstMessageDeliveriesDecay<=0||s.firstMessageDeliveriesDecay>=1))throw new G("invalid FirstMessageDeliveriesDecay; must be between 0 and 1");if(s.firstMessageDeliveriesWeight!==0&&s.firstMessageDeliveriesCap<=0)throw new G("invalid FirstMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight>0)throw new G("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.meshMessageDeliveriesWeight!==0&&(s.meshMessageDeliveriesDecay<=0||s.meshMessageDeliveriesDecay>=1))throw new G("invalid MeshMessageDeliveriesDecay; must be between 0 and 1");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesCap<=0)throw new G("invalid MeshMessageDeliveriesCap; must be positive");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesThreshold<=0)throw new G("invalid MeshMessageDeliveriesThreshold; must be positive");if(s.meshMessageDeliveriesWindow<0)throw new G("invalid MeshMessageDeliveriesWindow; must be non-negative");if(s.meshMessageDeliveriesWeight!==0&&s.meshMessageDeliveriesActivation<1e3)throw new G("invalid MeshMessageDeliveriesActivation; must be at least 1s");if(s.meshFailurePenaltyWeight>0)throw new G("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)");if(s.meshFailurePenaltyWeight!==0&&(s.meshFailurePenaltyDecay<=0||s.meshFailurePenaltyDecay>=1))throw new G("invalid MeshFailurePenaltyDecay; must be between 0 and 1");if(s.invalidMessageDeliveriesWeight>0)throw new G("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)");if(s.invalidMessageDeliveriesDecay<=0||s.invalidMessageDeliveriesDecay>=1)throw new G("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1")}var ip={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function El(s={}){return{...ip,...s}}function sn(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 Sl(s,e){return sn(s,e,()=>!0)}var tn=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 _l(s,e,t,r){let n=0;Object.entries(e.topics).forEach(([i,a])=>{let l=t.topics[i];if(l===void 0)return;let u=0;if(a.inMesh){let w=a.meshTime/l.timeInMeshQuantum;w>l.timeInMeshCap&&(w=l.timeInMeshCap),u+=w*l.timeInMeshWeight}let p=a.firstMessageDeliveries;if(p>l.firstMessageDeliveriesCap&&(p=l.firstMessageDeliveriesCap),u+=p*l.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries<l.meshMessageDeliveriesThreshold){let w=l.meshMessageDeliveriesThreshold-a.meshMessageDeliveries,h=w*w;u+=h*l.meshMessageDeliveriesWeight}let m=a.meshFailurePenalty;u+=m*l.meshFailurePenaltyWeight;let E=a.invalidMessageDeliveries*a.invalidMessageDeliveries;u+=E*l.invalidMessageDeliveriesWeight,n+=u*l.topicWeight}),t.topicScoreCap>0&&n>t.topicScoreCap&&(n=t.topicScoreCap);let o=t.appSpecificScore(s);if(n+=o*t.appSpecificWeight,e.knownIPs.forEach(i=>{if(t.IPColocationFactorWhitelist.has(i))return;let a=r.get(i),l=a!=null?a.size:0;if(l>t.IPColocationFactorThreshold){let u=l-t.IPColocationFactorThreshold,p=u*u;n+=p*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let i=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=i*i;n+=a*t.behaviourPenaltyWeight}return n}var Dl=Zl(Tl(),1);var _e;(function(s){s[s.unknown=0]="unknown",s[s.valid=1]="valid",s[s.invalid=2]="invalid",s[s.ignored=3]="ignored"})(_e||(_e={}));var rn=class{records;queue;constructor(){this.records=new Map,this.queue=new Dl.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:_e.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 nn=class{params;metrics;peerStats=new Map;peerIPs=new tn(()=>new Set);scoreCache=new Map;deliveryRecords=new rn;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,r,n){this.params=e,this.metrics=t,vl(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??_l,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(([o,i])=>{let a=this.params.topics[o];a!==void 0&&(i.firstMessageDeliveries*=a.firstMessageDeliveriesDecay,i.firstMessageDeliveries<t&&(i.firstMessageDeliveries=0),i.meshMessageDeliveries*=a.meshMessageDeliveriesDecay,i.meshMessageDeliveries<t&&(i.meshMessageDeliveries=0),i.meshFailurePenalty*=a.meshFailurePenaltyDecay,i.meshFailurePenalty<t&&(i.meshFailurePenalty=0),i.invalidMessageDeliveries*=a.invalidMessageDeliveriesDecay,i.invalidMessageDeliveries<t&&(i.invalidMessageDeliveries=0),i.inMesh&&(i.meshTime=e-i.graftTime,i.meshTime>a.meshMessageDeliveriesActivation&&(i.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 o=this.computeScore(e,t,this.params,this.peerIPs),i=r+this.scoreCacheValidityMs;return n!=null?(this.metrics?.scoreCachedDelta.observe(Math.abs(o-n.score)),n.score=o,n.cacheUntil=i):this.scoreCache.set(e,{score:o,cacheUntil:i}),o}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 o=this.params.topics[r].meshMessageDeliveriesThreshold;if(n.inMesh&&n.meshMessageDeliveriesActive&&n.meshMessageDeliveries<o){let i=o-n.meshMessageDeliveries;n.meshFailurePenalty+=i*i}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 o=this.params.topics[t].meshMessageDeliveriesThreshold;if(n.meshMessageDeliveriesActive&&n.meshMessageDeliveries<o){let i=o-n.meshMessageDeliveries;n.meshFailurePenalty+=i*i}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),o=Date.now();if(n.status!==_e.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,o-n.firstSeenTsMs,_e[n.status]);return}n.status=_e.valid,n.validated=o,n.peers.forEach(i=>{i!==e.toString()&&this.markDuplicateMessageDelivery(i,r)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,r,n){switch(n){case Ee.Error:this.markInvalidMessageDelivery(e,r);return;case Ee.Blacklisted:return}let o=this.deliveryRecords.ensureRecord(t);if(o.status!==_e.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-o.firstSeenTsMs,_e[o.status]);return}if(n===Ee.Ignore){o.status=_e.ignored,o.peers.clear();return}o.status=_e.invalid,this.markInvalidMessageDelivery(e,r),o.peers.forEach(i=>{this.markInvalidMessageDelivery(i,r)}),o.peers.clear()}duplicateMessage(e,t,r){let n=this.deliveryRecords.ensureRecord(t);if(!n.peers.has(e))switch(n.status){case _e.unknown:n.peers.add(e);break;case _e.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,r,n.validated);break;case _e.invalid:this.markInvalidMessageDelivery(e,r);break;case _e.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 o=this.params.topics[t].firstMessageDeliveriesCap;n.firstMessageDeliveries=Math.min(o,n.firstMessageDeliveries+1),n.inMesh&&(o=this.params.topics[t].meshMessageDeliveriesCap,n.meshMessageDeliveries=Math.min(o,n.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,r){let n=this.peerStats.get(e);if(n!=null){let o=r!==void 0?Date.now():0,i=this.getPtopicStats(n,t);if(i!=null&&i.inMesh){let a=this.params.topics[t];if(r!==void 0){let u=o-r,p=u>a.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,u,p),p)return}let l=a.meshMessageDeliveriesCap;i.meshMessageDeliveries=Math.min(l,i.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 ap(s,e,t,r,n){let o=0,i=new Map;if(Object.entries(e.topics).forEach(([E,w])=>{let h=n.get(E)??"unknown",g=t.topics[E];if(g===void 0)return;let b=i.get(h);b==null&&(b={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},i.set(h,b));let x=0,_=0,c=0,f=0,d=0;if(w.inMesh){let M=Math.max(w.meshTime/g.timeInMeshQuantum,g.timeInMeshCap);x+=M*g.timeInMeshWeight}let y=w.firstMessageDeliveries;if(y>g.firstMessageDeliveriesCap&&(y=g.firstMessageDeliveriesCap),_+=y*g.firstMessageDeliveriesWeight,w.meshMessageDeliveriesActive&&w.meshMessageDeliveries<g.meshMessageDeliveriesThreshold){let M=g.meshMessageDeliveriesThreshold-w.meshMessageDeliveries,C=M*M;c+=C*g.meshMessageDeliveriesWeight}let v=w.meshFailurePenalty;f+=v*g.meshFailurePenaltyWeight;let S=w.invalidMessageDeliveries*w.invalidMessageDeliveries;d+=S*g.invalidMessageDeliveriesWeight,o+=(x+_+c+f+d)*g.topicWeight,b.p1w+=x,b.p2w+=_,b.p3w+=c,b.p3bw+=f,b.p4w+=d}),t.topicScoreCap>0&&o>t.topicScoreCap){o=t.topicScoreCap;let E=t.topicScoreCap/o;for(let w of i.values())w.p1w*=E,w.p2w*=E,w.p3w*=E,w.p3bw*=E,w.p4w*=E}let a=0,l=0,u=0,p=t.appSpecificScore(s);a+=p*t.appSpecificWeight,e.knownIPs.forEach(E=>{if(t.IPColocationFactorWhitelist.has(E))return;let w=r.get(E),h=w!=null?w.size:0;if(h>t.IPColocationFactorThreshold){let g=h-t.IPColocationFactorThreshold,b=g*g;l+=b*t.IPColocationFactorWeight}});let m=e.behaviourPenalty*e.behaviourPenalty;return u+=m*t.behaviourPenaltyWeight,o+=a+l+u,{byTopic:i,p5w:a,p6w:l,p7w:u,score:o}}function Al(s,e,t,r,n){let o={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let i of s){let a=e.get(i);if(a!=null){let l=ap(i,a,t,r,n);for(let[u,p]of l.byTopic){let m=o.byTopic.get(u);m==null&&(m={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},o.byTopic.set(u,m)),m.p1w.push(p.p1w),m.p2w.push(p.p2w),m.p3w.push(p.p3w),m.p3bw.push(p.p3bw),m.p4w.push(p.p4w)}o.p5w.push(l.p5w),o.p6w.push(l.p6w),o.p7w.push(l.p7w),o.score.push(l.score)}else o.p5w.push(0),o.p6w.push(0),o.p7w.push(0),o.score.push(0)}return o}function ki(s){let e=s.getComponents(),t={},r=0;return e[r]?.name==="ip6zone"&&(t.zone=`${e[r].value}`,r++),e[r]?.name==="ip4"||e[r]?.name==="ip6"||e[r]?.name==="dns"||e[r]?.name==="dns4"||e[r]?.name==="dns6"?(t.type=e[r].name,t.host=e[r].value,r++):e[r]?.name==="dnsaddr"&&(t.type=e[r].name,t.host=`_dnsaddr.${e[r].value}`,r++),(e[r]?.name==="tcp"||e[r]?.name==="udp")&&(t.protocol=e[r].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[r].value}`),r++),e[r]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[r].value}`):t.type==="ip6"&&(t.cidr=`${e[r].value}`),r++),t.type==null||t.host==null?null:(e[r]?.name==="tls"&&e[r+1]?.name==="sni"&&(t.sni=e[r+1].value,r+=2),t)}function Ml(s){let e=ki(s);if(e==null)throw new X(`Multiaddr ${s} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function Pl(s){return ki(s)!==null}var Bi=class s extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,s)}},kl=s=>s.reason??new DOMException("This operation was aborted.","AbortError");function Li(s,e){let{milliseconds:t,fallback:r,message:n,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,l,p=new Promise((m,E)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){E(kl(i));return}if(i&&(l=()=>{E(kl(i))},i.addEventListener("abort",l,{once:!0})),s.then(m,E),t===Number.POSITIVE_INFINITY)return;let w=new Bi;a=o.setTimeout.call(void 0,()=>{if(r){try{m(r())}catch(h){E(h)}return}typeof s.cancel=="function"&&s.cancel(),n===!1?m():n instanceof Error?E(n):(w.message=n??`Promise timed out after ${t} milliseconds`,E(w))},t)}).finally(()=>{p.clear(),l&&i&&i.removeEventListener("abort",l)});return p.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},p}var cp=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 lp(s,e,t){let r,n=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),l=[],{addListener:u,removeListener:p}=cp(s),m=async(...w)=>{let h=t.multiArgs?w:w[0];if(t.filter)try{if(!await t.filter(h))return}catch(g){r(),i(g);return}l.push(h),t.count===l.length&&(r(),o(l))},E=(...w)=>{r(),i(t.rejectionMultiArgs?w:w[0])};r=()=>{for(let w of a)p(w,m);for(let w of t.rejectionEvents)a.includes(w)||p(w,E)};for(let w of a)u(w,m);for(let w of t.rejectionEvents)a.includes(w)||u(w,E);t.signal&&t.signal.addEventListener("abort",()=>{E(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(l)});if(n.cancel=r,typeof t.timeout=="number"){let o=Li(n,{milliseconds:t.timeout});return o.cancel=()=>{r(),o.clear()},o}return n}function Bl(s,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let r=lp(s,e,t),n=r.then(o=>o[0]);return n.cancel=r.cancel,n}function up(s){return s?.addEventListener!=null}function hp(s){let e=Kt(),t,r=i=>{e.push(i.data)},n=()=>{e.end(),s.removeEventListener("message",r),s.removeEventListener("close",o),s.removeEventListener("remoteCloseWrite",n)},o=i=>{e.end(i.error),i.error!=null&&t?.reject(i.error),s.removeEventListener("message",r),s.removeEventListener("close",o),s.removeEventListener("remoteCloseWrite",n)};return s.addEventListener("message",r),s.addEventListener("close",o,{once:!0}),s.addEventListener("remoteCloseWrite",n,{once:!0}),{source:e,async sink(i){async function*a(){yield*i}let l=a();for(;;){t=Promise.withResolvers();let{done:u,value:p}=await Promise.race([l.next(),t.promise]);if(s.writeStatus==="closing"||s.writeStatus==="closed"||(p!=null&&(s.send(p)||await Promise.race([Bl(s,"drain",{rejectionEvents:["close"]})])),u===!0))break}await s.close()}}}function Ll(...s){let e=s.map(t=>up(t)?hp(t):t);return nr(...e)}var on=class{rawStream;constructor(e,t,r){this.rawStream=e,r.maxBufferSize!=null&&(e.maxWriteBufferLength=r.maxBufferSize),e.addEventListener("close",n=>{n.error!=null&&t(n.error)})}get protocol(){return this.rawStream.protocol}push(e){this.pushPrefixed(ys.single(e))}pushPrefixed(e){this.rawStream.send(e)}async close(e){await this.rawStream.close(e).catch(t=>{this.rawStream.abort(t)})}},an=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=Ll(this.rawStream,r=>rr(r,t))}async close(){this.closeController.abort()}};var cn=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],o=this.msgIdToStrFn(n),i=this.promises.get(o);i==null&&(i=new Map,this.promises.set(o,i));let a=Date.now();i.has(e)||(i.set(e,a+this.gossipsubIWantFollowupMs),this.metrics!=null&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(o)||this.requestMsByMsg.set(o,a)))}getBrokenPromises(){let e=Date.now(),t=new Map,r=0;return this.promises.forEach((n,o)=>{n.forEach((i,a)=>{i<e&&(t.set(a,(t.get(a)??0)+1),n.delete(a),r++)}),n.size===0&&this.promises.delete(o)}),this.metrics?.iwantPromiseBroken.inc(r),t}deliverMessage(e,t=!1){this.trackMessage(e);let r=this.promises.get(e);r!=null&&(this.promises.delete(e),this.metrics!=null&&(this.metrics.iwantPromiseResolved.inc(1),t&&this.metrics.iwantPromiseResolvedFromDuplicate.inc(1),this.metrics.iwantPromiseResolvedPeers.inc(r.size)))}rejectMessage(e,t){this.trackMessage(e),t!==Ee.Error&&this.promises.delete(e)}clear(){this.promises.clear()}prune(){let e=Date.now()-this.requestMsByMsgExpire,t=0;for(let[r,n]of this.requestMsByMsg.entries())if(n<e)this.requestMsByMsg.delete(r),t++;else break;this.metrics?.iwantMessagePruned.inc(t)}trackMessage(e){if(this.metrics!=null){let t=this.requestMsByMsg.get(e);t!==void 0&&(this.metrics.iwantPromiseDeliveryTime.observe((Date.now()-t)/1e3),this.requestMsByMsg.delete(e))}}};var Rl=j("libp2p-pubsub:"),fp=BigInt(Date.now())*1000000n;function dp(){let s=++fp,e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,s,!1),e}async function Cl(s,e,t,r){switch(s.type){case St.Signing:{let n={from:s.author.toMultihash().bytes,data:r,seqno:dp(),topic:e,signature:void 0,key:void 0},o=Br([Rl,ct.Message.encode(n)]);n.signature=await s.privateKey.sign(o),n.key=s.key;let i={type:"signed",from:s.author,data:t,sequenceNumber:BigInt(`0x${q(n.seqno??new Uint8Array(0),"base16")}`),topic:e,signature:n.signature,key:qr(n.key)};return{raw:n,msg:i}}case St.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 Fl(s,e){switch(s){case zt:return e.signature!=null?{valid:!1,error:me.SignaturePresent}:e.seqno!=null?{valid:!1,error:me.SeqnoPresent}:e.key!=null?{valid:!1,error:me.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case _t:{if(e.seqno==null)return{valid:!1,error:me.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:me.InvalidSeqno};if(e.signature==null)return{valid:!1,error:me.InvalidSignature};if(e.from==null)return{valid:!1,error:me.InvalidPeerId};let t;try{t=gs(Je(e.from))}catch{return{valid:!1,error:me.InvalidPeerId}}let r;if(e.key!=null){if(r=qr(e.key),t.publicKey!==void 0&&!r.equals(t.publicKey))return{valid:!1,error:me.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:me.InvalidPeerId};r=t.publicKey}let n={from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0},o=Br([Rl,ct.Message.encode(n)]);return await r.verify(o,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?qr(e.key):r}}:{valid:!1,error:me.InvalidSignature}}default:throw new Error("Unreachable")}}function ze(s=[],e){return{subscriptions:[],messages:s,control:e!==void 0?{graft:e.graft??[],prune:e.prune??[],ihave:e.ihave??[],iwant:e.iwant??[],idontwant:e.idontwant??[]}:void 0}}function Ri(s){return s.control===void 0&&(s.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),s}function Ye(s){if(s.length<=1)return s;let e=()=>Math.floor(Math.random()*Math.floor(s.length));for(let t=0;t<s.length;t++){let r=e(),n=s[t];s[t]=s[r],s[r]=n}return s}function Nl(s){return q(s,"base64")}function Ol(s,e,t){switch(s){case _t:return{type:St.Signing,author:e,key:qe(t.publicKey),privateKey:t};case zt:return{type:St.Anonymous};default:throw new Error(`Unknown signature policy "${s}"`)}}var pp=(s,e)=>{let t=j(e.toString(16).padStart(16,"0"),"base16"),r=qe(s),n=new Uint8Array(r.byteLength+t.length);return n.set(r,0),n.set(t,r.byteLength),n};function Ul(s){if(s.type!=="signed")throw new Error("expected signed message type");if(s.sequenceNumber==null)throw Error("missing seqno field");return pp(s.from.publicKey??s.key,s.sequenceNumber)}async function Kl(s){return Dt.encode(s.data)}function zl(s){if(Pl(s)){let e=Ml(s);switch(e.type){case"ip4":case"ip6":return e.host;default:break}}return null}var Ss=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 Me;(function(s){s[s.started=0]="started",s[s.stopped=1]="stopped"})(Me||(Me={}));var ln=class extends lr{globalSignaturePolicy;protocols=[Gt,Oi,hn];publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=Kt({objectMode:!0});direct=new Set;floodsubPeers=new Set;seenCache;acceptFromWhitelist=new Map;topics=new Map;subscriptions=new Set;mesh=new Map;fanout=new Map;fanoutLastpub=new Map;gossip=new Map;control=new Map;peerhave=new Map;iasked=new Map;iwantCounts=new Map;backoff=new Map;outbound=new Map;msgIdFn;fastMsgIdFn;msgIdToStrFn;fastMsgIdCache;publishedMessageIds;mcache;score;topicValidators=new Map;log;heartbeatTicks=0;gossipTracer;idontwantCounts=new Map;idontwants=new Map;components;directPeerInitial=null;static multicodec=Gt;opts;decodeRpcLimits;metrics;status={code:Me.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:xl(t.scoreParams),scoreThresholds:El(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=r.decodeRpcLimits??gl,this.globalSignaturePolicy=r.globalSignaturePolicy??_t,r.fallbackToFloodsub&&this.protocols.push(un),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 Ss({validityMs:r.seenTTL}),this.publishedMessageIds=new Ss({validityMs:r.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case _t:this.msgIdFn=Ul;break;case zt:this.msgIdFn=Kl;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new Ss({validityMs:r.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??Nl,this.mcache=t.messageCache??new en(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(i=>i.meshMessageDeliveriesWindow),1e3),o=wl(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:r.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:n/1e3});o.mcacheSize.addCollect(()=>{this.onScrapeMetrics(o)});for(let i of this.protocols)o.protocolsEnabled.set({protocol:i},1);this.metrics=o}else this.metrics=null;this.gossipTracer=new cn(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new nn(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:r.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnLimitedConnection=t.runOnLimitedConnection,this.allowedTopics=r.allowedTopics!=null?new Set(r.allowedTopics):null}[Symbol.toStringTag]="@libp2p/gossipsub";[Hi]=["@libp2p/pubsub"];[Gi]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===Me.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=Ol(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=Kt({objectMode:!0}),nr(this.outboundInflightQueue,async o=>{for await(let{peerId:i,connection:a}of o)await this.createOutboundStream(i,a)}).catch(o=>{this.log.error("outbound inflight queue error",o)}),await Promise.all(this.opts.directPeers.map(async o=>{await this.components.peerStore.merge(o.id,{multiaddrs:o.addrs})}));let e=this.components.registrar;await Promise.all(this.protocols.map(async o=>e.handle(o,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 o=>e.register(o,t))),n=setTimeout(this.runHeartbeat,100);this.status={code:Me.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 o=>this.connect(o)))}).catch(o=>{this.log(o)})},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!==Me.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:Me.stopped},this.opts.tagMeshPeers&&(this.removeEventListener("gossipsub:graft",this.tagMeshPeer),this.removeEventListener("gossipsub:prune",this.untagMeshPeer));let t=this.components.registrar;await Promise.all(this.protocols.map(async n=>t.unhandle(n))),e.forEach(n=>{t.unregister(n)}),this.outboundInflightQueue.end();let r=[];for(let n of this.streamsOutbound.values())r.push(n.close());this.streamsOutbound.clear();for(let n of this.streamsInbound.values())r.push(n.close());this.streamsInbound.clear(),await Promise.all(r),this.peers.clear(),this.subscriptions.clear(),this.topics.clear(),this.heartbeatTimer!=null&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.iwantCounts.clear(),this.backoff.clear(),this.outbound.clear(),this.gossipTracer.clear(),this.seenCache.clear(),this.fastMsgIdCache!=null&&this.fastMsgIdCache.clear(),this.directPeerInitial!=null&&clearTimeout(this.directPeerInitial),this.idontwantCounts.clear(),this.idontwants.clear(),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream(e,t){if(!this.isStarted())return;let r=t.remotePeer;this.addPeer(r,t.direction,t.remoteAddr),this.createInboundStream(r,e),this.outboundInflightQueue.push({peerId:r,connection:t})}onPeerConnected(e,t){this.metrics?.newConnectionCount.inc({status:t.status}),!(!this.isStarted()||t.status!=="open")&&(this.addPeer(e,t.direction,t.remoteAddr),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}async createOutboundStream(e,t){if(!this.isStarted())return;let r=e.toString();if(this.peers.has(r)&&!this.streamsOutbound.has(r))try{let n=await t.newStream(this.protocols,{runOnLimitedConnection:this.runOnLimitedConnection}),o=new on(n,a=>{this.log.error("outbound pipe error",a)},{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(r,o);let i=o.protocol;i===un&&this.floodsubPeers.add(r),this.metrics?.peersPerProtocol.inc({protocol:i},1),n.addEventListener("close",()=>{this.streamsOutbound.get(r)===o&&(this.streamsOutbound.delete(r),this.floodsubPeers.delete(r),this.metrics?.peersPerProtocol.inc({protocol:i},-1))},{once:!0}),this.subscriptions.size>0&&(this.log("send subscriptions to",r),this.sendSubscriptions(r,Array.from(this.subscriptions),!0))}catch(n){this.log.error("createOutboundStream error",n)}}createInboundStream(e,t){if(!this.isStarted())return;let r=e.toString();if(!this.peers.has(r))return;let n=this.streamsInbound.get(r);n!==void 0&&(this.log("replacing existing inbound steam %s",r),n.close().catch(i=>{this.log.error(i)})),this.log("create inbound stream %s",r);let o=new an(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(r,o),this.pipePeerReadStream(e,o.source).catch(i=>{this.log(i)})}addPeer(e,t,r){let n=e.toString();if(!this.peers.has(n)){this.peers.set(n,e),this.score.addPeer(n);let o=zl(r);o!==null?this.score.addIP(n,o):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(o=>{this.log.error(o)}),n?.close().catch(o=>{this.log.error(o)}),this.streamsOutbound.delete(t),this.streamsInbound.delete(t);for(let[o,i]of this.topics)i.delete(t),i.size===0&&this.topics.delete(o);for(let[o,i]of this.mesh)i.delete(t)&&this.metrics?.onRemoveFromMesh(o,Ke.Dc,1);for(let o of this.fanout.values())o.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===Me.started}getMeshPeers(e){let t=this.mesh.get(e);return t!=null?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(t!=null?Array.from(t):[]).map(r=>this.peers.get(r)??Ot(r))}getTopics(){return Array.from(this.subscriptions)}decodeRpc(e){return ct.decode(e,{limits:{subscriptions:this.decodeRpcLimits.maxSubscriptions,messages:this.decodeRpcLimits.maxMessages,control:{ihave:this.decodeRpcLimits.maxControlMessages,ihave$:{messageIDs:this.decodeRpcLimits.maxIhaveMessageIDs},iwant:this.decodeRpcLimits.maxControlMessages,iwant$:{messageIDs:this.decodeRpcLimits.maxIwantMessageIDs},graft:this.decodeRpcLimits.maxControlMessages,prune:this.decodeRpcLimits.maxControlMessages,prune$:{peers:this.decodeRpcLimits.maxPeerInfos},idontwant:this.decodeRpcLimits.maxControlMessages,idontwant$:{messageIDs:this.decodeRpcLimits.maxIdontwantMessageIDs}}}})}async pipePeerReadStream(e,t){try{await nr(t,async r=>{for await(let n of r)try{let o=n.subarray(),i=this.decodeRpc(o);if(this.metrics?.onRpcRecv(i,o.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,i)}catch(a){this.metrics?.onRpcRecvError(),this.log(a)}else this.handleReceivedRpc(e,i).catch(a=>{this.metrics?.onRpcRecvError(),this.log(a)})}catch(o){this.metrics?.onRpcDataError(),this.log(o)}})}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,o=0,i=0,a=0,l=0;if(t.control!=null&&(t.control.ihave!=null&&(o=t.control.ihave.length),t.control.iwant!=null&&(i=t.control.iwant.length),t.control.graft!=null&&(a=t.control.graft.length),t.control.prune!=null&&(l=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${r} messages ${n} ihave ${o} iwant ${i} graft ${a} prune ${l}`),t.subscriptions!=null&&t.subscriptions.length>0){let u=[];t.subscriptions.forEach(p=>{let m=p.topic,E=p.subscribe===!0;if(m!=null){if(this.allowedTopics!=null&&!this.allowedTopics.has(m))return;this.handleReceivedSubscription(e,m,E),u.push({topic:m,subscribe:E})}}),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:u}})}for(let u of t.messages){if(this.allowedTopics!=null&&!this.allowedTopics.has(u.topic))continue;let p=this.handleReceivedMessage(e,u).catch(m=>{this.metrics?.onMsgRecvError(u.topic),this.log(m)});this.opts.awaitRpcMessageHandler&&await p}t.control!=null&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,r){this.log("subscription update from %p topic %s",e,t);let n=this.topics.get(t);r?(n==null&&(n=new Set,this.topics.set(t,n)),n.add(e.toString())):n!=null&&(n.delete(e.toString()),n.size===0&&this.topics.delete(t))}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);let r=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,r.code);let n=r.code;switch(n){case ge.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 ge.invalid:if(r.msgIdStr!=null){let o=r.msgIdStr;this.score.rejectMessage(e.toString(),o,t.topic,r.reason),this.gossipTracer.rejectMessage(o,r.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);this.metrics?.onMsgRecvInvalid(t.topic,r);return;case ge.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:ge.duplicate,msgIdStr:n};let o=await Fl(this.globalSignaturePolicy,t);if(!o.valid)return{code:ge.invalid,reason:Ee.Error,error:o.error};let i=o.message;try{this.dataTransform!=null&&(i.data=this.dataTransform.inboundTransform(t.topic,i.data))}catch(m){return this.log("Invalid message, transform failed",m),{code:ge.invalid,reason:Ee.Error,error:me.TransformFailed}}let a=await this.msgIdFn(i),l=this.msgIdToStrFn(a),u={msgId:a,msgIdStr:l};if(r!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(r,l)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(l))return{code:ge.duplicate,msgIdStr:l};this.seenCache.put(l),(t.data?.length??0)>=this.opts.idontwantMinDataSize&&this.sendIDontWants(a,t.topic,e.toString());let p=this.topicValidators.get(t.topic);if(p!=null){let m;try{m=await p(e,i)}catch(E){let w=E.code;w===Ki&&(m=be.Ignore),w===Ui?m=be.Reject:m=be.Ignore}if(m!==be.Accept)return{code:ge.invalid,reason:Pi(m),msgIdStr:l}}return{code:ge.valid,messageId:u,msg:i}}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):[],o=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&&o.length===0)return;let i=this.sendRpc(e,ze(n,{iwant:r,prune:o})),a=r[0]?.messageIDs;a!=null&&(i?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:Es.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:Es.MaxIhave}),[];let o=this.iasked.get(e)??0;if(o>=5e3)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,o),this.metrics?.ihaveRcvIgnored.inc({reason:Es.MaxIasked}),[];let i=new Map,a=0;e:for(let{topicID:p,messageIDs:m}of t){if(p==null||m==null||!this.mesh.has(p))continue;let E=0;for(let w of m){if(a>=5e3)break e;a++;let h=this.msgIdToStrFn(w);this.seenCache.has(h)||(i.set(h,w),E++)}this.metrics?.onIhaveRcv(p,m.length,E)}if(i.size===0)return[];let l=i.size;l+o>5e3&&(l=5e3-o),this.log("IHAVE: Asking for %d out of %d messages from %s",l,i.size,e);let u=Array.from(i.values());return Ye(u),u=u.slice(0,l),this.iasked.set(e,o+l),[{messageIDs:u}]}handleIWant(e,t){if(t.length===0)return[];let r=this.score.score(e);if(r<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,r),[];let n=(this.iwantCounts.get(e)??0)+1;if(this.iwantCounts.set(e,n),n>10)return this.log("IWANT: peer %s has requested too many times within this heartbeat interval; ignoring",e),[];let o=new Map,i=new Map,a=0,l=0;e:for(let{messageIDs:u}of t)if(u!=null)for(let p of u){if(l>=5e3)break e;l++;let m=this.msgIdToStrFn(p),E=this.mcache.getWithIWantCount(m,e);if(E==null){a++;continue}if(i.set(E.msg.topic,1+(i.get(E.msg.topic)??0)),E.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,p);continue}o.set(m,E.msg)}return this.metrics?.onIwantRcv(i,a),o.size===0?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",o.size,e),Array.from(o.values()))}async handleGraft(e,t){let r=[],n=this.score.score(e),o=Date.now(),i=this.opts.doPX;if(t.forEach(({topicID:l})=>{if(l==null)return;let u=this.mesh.get(l);if(u==null){i=!1;return}if(u.has(e))return;let p=this.backoff.get(l)?.get(e);if(this.direct.has(e))this.log("GRAFT: ignoring request from direct peer %s",e),r.push(l),i=!1;else if(typeof p=="number"&&o<p){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,vs.GraftBackoff),i=!1;let m=p+this.opts.graftFloodThreshold-this.opts.pruneBackoff;o<m&&this.score.addPenalty(e,1,vs.GraftBackoff),this.addBackoff(e,l),r.push(l)}else n<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,n,l),r.push(l),i=!1,this.addBackoff(e,l)):u.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(r.push(l),this.addBackoff(e,l)):(this.log("GRAFT: Add mesh link from %s in %s",e,l),this.score.graft(e,l),u.add(e),this.metrics?.onAddToMesh(l,Se.Subscribed,1));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:l,direction:"inbound"}})}),r.length===0)return[];let a=!1;return Promise.all(r.map(async l=>this.makePrune(e,l,i,a)))}async handlePrune(e,t){let r=this.score.score(e);for(let{topicID:n,backoff:o,peers:i}of t){if(n==null)continue;let a=this.mesh.get(n);if(a==null)return;this.log("PRUNE: Remove mesh link to %s in %s",e,n),this.score.prune(e,n),a.has(e)&&(a.delete(e),this.metrics?.onRemoveFromMesh(n,Ke.Prune,1)),typeof o=="number"&&o>0?this.doAddBackoff(e,n,o*1e3):this.addBackoff(e,n),i!=null&&i.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(i)),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,o=this.idontwants.get(e);o==null&&(o=new Map,this.idontwants.set(e,o));let i=0;e:for(let{messageIDs:l}of t)for(let u of l){if(r>=this.opts.idontwantMaxMessages)break e;r++;let p=this.msgIdToStrFn(u);o.set(p,this.heartbeatTicks),this.mcache.msgs.has(p)||i++}this.idontwantCounts.set(e,r);let a=r-n;this.metrics?.onIdontwantRcv(a,i)}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 o=Date.now()+r;(n.get(e)??0)<o&&n.set(e,o)}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,vs.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!==0)return;let e=Date.now();this.backoff.forEach((t,r)=>{t.forEach((n,o)=>{n+1*this.opts.heartbeatInterval<e&&t.delete(o)}),t.size===0&&this.backoff.delete(r)})}async directConnect(){let e=[];this.direct.forEach(t=>{this.streamsOutbound.has(t)||e.push(t)}),await Promise.all(e.map(async t=>this.connect(t)))}async pxConnect(e){e.length>this.opts.prunePeers&&(Ye(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async r=>{if(r.peerID==null)return;let n=gs(Je(r.peerID)),o=n.toString();if(!this.peers.has(o)){if(r.signedPeerRecord==null){t.push(o);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(o)}catch{this.log("bogus peer record obtained through px: invalid signature or not a peer record")}}})),t.length!==0&&await Promise.all(t.map(async r=>this.connect(r)))}async connect(e){this.log("Initiating connection with %s",e);let t=Ot(e),r=await this.components.connectionManager.openConnection(t);for(let n of this.protocols)for(let o of this.components.registrar.getTopologies(n))o.onConnect?.(t,r)}subscribe(e){if(this.status.code!==Me.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!==Me.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!==Me.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(o=>{!this.direct.has(o)&&this.score.score(o)>=0&&r?.has(o)!==!0&&t.add(o)}),this.metrics?.onAddToMesh(e,Se.Fanout,t.size)),t.size<this.opts.D){let o=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,Se.Random,t.size-o)}this.mesh.set(e,t),t.forEach(o=>{this.log("JOIN: Add mesh link to %s in %s",o,e),this.sendGraft(o,e)})}leave(e){if(this.status.code!==Me.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,o=this.topics.get(e);o!=null&&(this.direct.forEach(a=>{o.has(a)&&t!==a&&!(r?.has(a)??!1)&&n.add(a)}),this.floodsubPeers.forEach(a=>{o.has(a)&&t!==a&&!(r?.has(a)??!1)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&n.add(a)}));let i=this.mesh.get(e);return i!=null&&i.size>0&&i.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(o=>{this.direct.has(o)?(t.add(o),r.direct++):this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),r.floodsub++)});else{this.direct.forEach(i=>{n.has(i)&&(t.add(i),r.direct++)}),this.floodsubPeers.forEach(i=>{n.has(i)&&this.score.score(i)>=this.opts.scoreThresholds.publishThreshold&&(t.add(i),r.floodsub++)});let o=this.mesh.get(e);if(o!=null&&o.size>0)o.forEach(i=>{t.add(i),r.mesh++}),o.size<this.opts.D&&this.getRandomGossipPeers(e,this.opts.D-o.size,a=>!o.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 i=this.fanout.get(e);if(i!=null&&i.size>0)i.forEach(a=>{t.add(a),r.fanout++});else{let a=this.getRandomGossipPeers(e,this.opts.D,l=>this.score.score(l)>=this.opts.scoreThresholds.publishThreshold);a.size>0&&(this.fanout.set(e,a),a.forEach(l=>{t.add(l),r.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:r}}forwardMessage(e,t,r,n){r!=null&&this.score.deliverMessage(r,e,t.topic);let o=this.selectPeersToForward(t.topic,r,n);o.forEach(i=>{this.sendRpc(i,ze([t]))}),this.metrics?.onForwardMsg(t.topic,o.size)}async publish(e,t,r){let n=Date.now(),o=this.dataTransform!=null?this.dataTransform.outboundTransform(e,t):t;if(this.publishConfig==null)throw Error("PublishError.Uninitialized");let{raw:i,msg:a}=await Cl(this.publishConfig,e,t,o),l=await this.msgIdFn(a),u=this.msgIdToStrFn(l),p=r?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(u)){if(p)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:m,tosendCount:E}=this.selectPeersToPublish(e),w=this.opts.emitSelf&&this.subscriptions.has(e),h=r?.allowPublishToZeroTopicPeers??this.opts.allowPublishToZeroTopicPeers;if(m.size===0&&!h&&!w)throw Error("PublishError.NoPeersSubscribedToTopic");this.seenCache.put(u),this.mcache.put({msgId:l,msgIdStr:u},i,!0),this.gossipTracer.deliverMessage(u),this.publishedMessageIds.put(u);let g=r?.batchPublish??this.opts.batchPublish,b=ze([i]);if(g)this.sendRpcInBatch(m,b);else for(let _ of m)this.sendRpc(_,b)||m.delete(_);let x=Date.now()-n;return this.metrics?.onPublishMsg(e,E,m.size,i.data!=null?i.data.length:0,x),w&&(m.add(this.components.peerId.toString()),super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:u,msg:a}})),super.dispatchEvent(new CustomEvent("message",{detail:a}))),{recipients:Array.from(m.values()).map(_=>this.peers.get(_)??Ot(_))}}sendRpcInBatch(e,t){let r=ct.encode(t),n=ys.single(r);for(let o of e){let i=this.streamsOutbound.get(o);if(i==null){this.log(`Cannot send RPC to ${o} as there is no open stream to it available`),e.delete(o);continue}try{i.pushPrefixed(n)}catch(a){e.delete(o),this.log.error(`Cannot send rpc to ${o}`,a)}this.metrics?.onRpcSent(t,r.length)}}reportMessageValidationResult(e,t,r){let n;if(r===be.Accept){if(n=this.mcache.validate(e),n!=null){let{message:i,originatingPeers:a}=n;this.score.deliverMessage(t,e,i.topic),this.forwardMessage(e,n.message,t,a)}}else if(n=this.mcache.remove(e),n!=null){let i=Pi(r),{message:a,originatingPeers:l}=n;this.score.rejectMessage(t,e,a.topic,i);for(let u of l)this.score.rejectMessage(u,e,a.topic,i)}let o=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(n,r,o)}sendGraft(e,t){let n=ze([],{graft:[{topicID:t}]});this.sendRpc(e,n)}async sendPrune(e,t){let n=[await this.makePrune(e,t,this.opts.doPX,!0)],o=ze([],{prune:n});this.sendRpc(e,o)}sendIDontWants(e,t,r){let n=this.mesh.get(t);if(n==null)return;let o=new Set(n);o.delete(r);for(let a of o)this.streamsOutbound.get(a)?.protocol!==Gt&&o.delete(a);let i=ze([],{idontwant:[{messageIDs:[e]}]});this.sendRpcInBatch(o,i)}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 o=this.gossip.get(e);o!=null&&(this.piggybackGossip(e,t,o),this.gossip.delete(e));let i=ct.encode(t);try{r.push(i)}catch(a){return this.log.error(`Cannot send rpc to ${e}`,a),n!=null&&this.control.set(e,n),o!=null&&this.gossip.set(e,o),!1}if(this.metrics?.onRpcSent(t,i.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=Ri(t);for(let o of r.graft)o.topicID!=null&&(this.mesh.get(o.topicID)?.has(e)??!1)&&n.control.graft.push(o);for(let o of r.prune)o.topicID!=null&&!(this.mesh.get(o.topicID)?.has(e)??!1)&&n.control.prune.push(o)}piggybackGossip(e,t,r){let n=Ri(t);n.control.ihave=r}async sendGraftPrune(e,t,r){let n=this.opts.doPX,o=!1;for(let[i,a]of e){let l=a.map(m=>({topicID:m})),u=[],p=t.get(i);p!=null&&(u=await Promise.all(p.map(async m=>this.makePrune(i,m,n&&!(r.get(i)??!1),o))),t.delete(i)),this.sendRpc(i,ze([],{graft:l,prune:u}))}for(let[i,a]of t){let l=await Promise.all(a.map(async u=>this.makePrune(i,u,n&&!(r.get(i)??!1),o)));this.sendRpc(i,ze([],{prune:l}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[r,n]of e)this.doEmitGossip(r,n,t.get(r)??[])}doEmitGossip(e,t,r){if(r.length===0||(Ye(r),r.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",r.length),t.size===0))return;let n=this.opts.Dlazy,i=this.opts.gossipFactor*t.size,a=t;i>n&&(n=i),n>a.size?n=a.size:a=Ye(Array.from(a)).slice(0,n),a.forEach(l=>{let u=r;r.length>5e3&&(u=Ye(u.slice()).slice(0,5e3)),this.pushGossip(l,{topicID:e,messageIDs:u})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,ze([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let r=ze([],{graft:t.graft,prune:t.prune});this.sendRpc(e,r)}}pushGossip(e,t){this.log("Add gossip to %s",e);let r=this.gossip.get(e)??[];this.gossip.set(e,r.concat(t))}async makePrune(e,t,r,n){if(this.score.prune(e,t),this.streamsOutbound.get(e)?.protocol===hn)return{topicID:t,peers:[]};let o=n?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,i=o/1e3;if(this.doAddBackoff(e,t,o),!r)return{topicID:t,peers:[],backoff:i};let a=this.getRandomGossipPeers(t,this.opts.prunePeers,u=>u!==e&&this.score.score(u)>=0),l=await Promise.all(Array.from(a).map(async u=>{let p=this.peers.get(u)??Ot(u),m;try{m=await this.components.peerStore.get(p)}catch(E){if(E.name!=="NotFoundError")throw E}return{peerID:p.toMultihash().bytes,signedPeerRecord:m?.peerRecordEnvelope}}));return{topicID:t,peers:l,backoff:i}}runHeartbeat=()=>{let e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch(t=>{this.log("Error running heartbeat",t)}).finally(()=>{if(e?.(),this.status.code===Me.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:o,fanoutTTL:i}=this.opts;this.heartbeatTicks++;let a=new Map,l=h=>{let g=a.get(h);return g===void 0&&(g=this.score.score(h),a.set(h,g)),g},u=new Map,p=new Map,m=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.iwantCounts.clear(),this.applyIwantPenalties(),this.idontwantCounts.clear();for(let h of this.idontwants.values())for(let[g,b]of h)this.heartbeatTicks-b>=this.opts.mcacheLength&&h.delete(g);this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let E=new Map;this.mesh.forEach((h,g)=>{let b=this.topics.get(g),x=new Set,_=new Set;if(E.set(g,_),b!=null){let d=Ye(Array.from(b)),y=this.backoff.get(g);for(let v of d){let S=this.streamsOutbound.get(v);if(S!=null&&this.protocols.includes(S.protocol)&&!h.has(v)&&!this.direct.has(v)){let M=l(v);y?.has(v)!==!0&&M>=0&&x.add(v),M>=this.opts.scoreThresholds.gossipThreshold&&_.add(v)}}}let c=(d,y)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",d,g),this.addBackoff(d,g),h.delete(d),l(d)>=this.opts.scoreThresholds.gossipThreshold&&_.add(d),this.metrics?.onRemoveFromMesh(g,y,1);let v=p.get(d);v==null?p.set(d,[g]):v.push(g)},f=(d,y)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",d,g),this.score.graft(d,g),h.add(d),_.delete(d),this.metrics?.onAddToMesh(g,y,1);let v=u.get(d);v==null?u.set(d,[g]):v.push(g)};if(h.forEach(d=>{let y=l(d);y<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",d,y,g),c(d,Ke.BadScore),m.set(d,!0))}),h.size<t){let d=e-h.size;Sl(x,d).forEach(v=>{f(v,Se.NotEnough)})}if(h.size>r){let d=Array.from(h);d.sort((v,S)=>l(S)-l(v)),d=d.slice(0,n).concat(Ye(d.slice(n)));let y=0;if(d.slice(0,e).forEach(v=>{(this.outbound.get(v)??!1)&&y++}),y<o){let v=M=>{let C=d[M];for(let N=M;N>0;N--)d[N]=d[N-1];d[0]=C};if(y>0){let M=y;for(let C=1;C<e&&M>0;C++)(this.outbound.get(d[C])??!1)&&(v(C),M--)}let S=e-y;for(let M=e;M<d.length&&S>0;M++)(this.outbound.get(d[M])??!1)&&(v(M),S--)}d.slice(e).forEach(v=>{c(v,Ke.Excess)})}if(h.size>=t){let d=0;if(h.forEach(y=>{(this.outbound.get(y)??!1)&&d++}),d<o){let y=o-d;sn(x,y,S=>this.outbound.get(S)===!0).forEach(S=>{f(S,Se.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&h.size>1){let d=Array.from(h).sort((S,M)=>l(S)-l(M)),y=Math.floor(h.size/2),v=l(d[y]);if(v<this.opts.scoreThresholds.opportunisticGraftThreshold){let S=this.opts.opportunisticGraftPeers,M=sn(x,S,C=>l(C)>v);for(let C of M)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",C,g),f(C,Se.Opportunistic)}}});let w=Date.now();this.fanoutLastpub.forEach((h,g)=>{h+i<w&&(this.fanout.delete(g),this.fanoutLastpub.delete(g))}),this.fanout.forEach((h,g)=>{let b=this.topics.get(g);h.forEach(f=>{(!(b?.has(f)??!1)||l(f)<this.opts.scoreThresholds.publishThreshold)&&h.delete(f)});let x=this.topics.get(g),_=[],c=new Set;if(E.set(g,c),x!=null){let f=Ye(Array.from(x));for(let d of f){let y=this.streamsOutbound.get(d);if(y!=null&&this.protocols.includes(y.protocol)&&!h.has(d)&&!this.direct.has(d)){let v=l(d);v>=this.opts.scoreThresholds.publishThreshold&&_.push(d),v>=this.opts.scoreThresholds.gossipThreshold&&c.add(d)}}}if(h.size<e){let f=e-h.size;_.slice(0,f).forEach(d=>{h.add(d),c?.delete(d)})}}),this.emitGossip(E),await this.sendGraftPrune(u,p,m),this.flush(),this.mcache.shift(),this.dispatchEvent(new CustomEvent("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,r=()=>!0){let n=this.topics.get(e);if(n==null)return new Set;let o=[];return n.forEach(i=>{let a=this.streamsOutbound.get(i);a!=null&&this.protocols.includes(a.protocol)&&r(i)&&o.push(i)}),o=Ye(o),t>0&&o.length>t&&(o=o.slice(0,t)),new Set(o)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0,r=Date.now();e.connectedPeersBackoffSec.reset();for(let l of this.backoff.values()){t+=l.size;for(let[u,p]of l.entries())this.peers.has(u)&&e.connectedPeersBackoffSec.observe(Math.max(0,p-r)/1e3)}e.cacheSize.set({cache:"backoff"},t);let n=0;for(let l of this.idontwants.values())n+=l.size;e.cacheSize.set({cache:"idontwants"},n);for(let[l,u]of this.topics)e.topicPeersCount.set({topicStr:l},u.size);for(let[l,u]of this.mesh)e.meshPeerCounts.set({topicStr:l},u.size);let o=[],i=new Map;e.behaviourPenalty.reset();for(let l of this.peers.keys()){let u=this.score.score(l);o.push(u),i.set(l,u),e.behaviourPenalty.observe(this.score.peerStats.get(l)?.behaviourPenalty??0)}e.registerScores(o,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,i);let a=Al(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(a)}tagMeshPeer=e=>{let{peerId:t,topic:r}=e.detail;this.components.peerStore.merge(this.peers.get(t)??Ot(t),{tags:{[r]:{value:100}}}).catch(n=>{this.log.error("Error tagging peer %s with topic %s",t,r,n)})};untagMeshPeer=e=>{let{peerId:t,topic:r}=e.detail;this.components.peerStore.merge(this.peers.get(t)??Ot(t),{tags:{[r]:void 0}}).catch(n=>{this.log.error("Error untagging peer %s with topic %s",t,r,n)})}};var _t="StrictSign",zt="StrictNoSign",be;(function(s){s.Accept="accept",s.Ignore="ignore",s.Reject="reject"})(be||(be={}));var Gp=Gt;function qp(s={}){return e=>new ln(e,s)}return Yl(Vp);})();
3
3
  /*! Bundled license information:
4
4
 
5
5
  @noble/curves/utils.js: