@libp2p/gossipsub 15.0.23 → 16.0.0-5b8813abc
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/README.md +5 -6
- package/dist/index.min.js +1 -1
- package/dist/index.min.js.map +4 -4
- package/dist/src/constants.d.ts +4 -0
- package/dist/src/constants.d.ts.map +1 -1
- package/dist/src/constants.js +4 -0
- package/dist/src/constants.js.map +1 -1
- package/dist/src/gossipsub.d.ts +7 -1
- package/dist/src/gossipsub.d.ts.map +1 -1
- package/dist/src/gossipsub.js +65 -31
- package/dist/src/gossipsub.js.map +1 -1
- package/dist/src/message/decodeRpc.d.ts.map +1 -1
- package/dist/src/message/decodeRpc.js +8 -7
- package/dist/src/message/decodeRpc.js.map +1 -1
- package/dist/src/score/message-deliveries.js +1 -1
- package/dist/src/score/peer-score-params.js +1 -1
- package/dist/src/score/peer-score-thresholds.js +1 -1
- package/dist/src/score/peer-score.d.ts +4 -4
- package/dist/src/score/peer-score.js +2 -2
- package/dist/src/score/peer-stats.d.ts +1 -1
- package/dist/src/utils/buildRawMessage.d.ts +4 -4
- package/dist/src/utils/buildRawMessage.d.ts.map +1 -1
- package/dist/src/utils/buildRawMessage.js +2 -2
- package/dist/src/utils/create-gossip-rpc.d.ts +1 -1
- package/dist/src/utils/msgIdFn.d.ts +1 -1
- package/dist/src/utils/publishConfig.d.ts +1 -1
- package/dist/src/utils/publishConfig.js +1 -1
- package/package.json +17 -16
- package/src/constants.ts +5 -0
- package/src/gossipsub.ts +70 -31
- package/src/message/decodeRpc.ts +8 -7
- package/src/score/message-deliveries.ts +1 -1
- package/src/score/peer-score-params.ts +1 -1
- package/src/score/peer-score-thresholds.ts +1 -1
- package/src/score/peer-score.ts +4 -4
- package/src/score/peer-stats.ts +1 -1
- package/src/utils/buildRawMessage.ts +3 -3
- package/src/utils/create-gossip-rpc.ts +1 -1
- package/src/utils/msgIdFn.ts +1 -1
- package/src/utils/publishConfig.ts +2 -2
- package/dist/typedoc-urls.json +0 -195
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 Tc=Object.create;var Gs=Object.defineProperty;var Dc=Object.getOwnPropertyDescriptor;var Ac=Object.getOwnPropertyNames;var Mc=Object.getPrototypeOf,Pc=Object.prototype.hasOwnProperty;var kc=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Ie=(s,e)=>{for(var t in e)Gs(s,t,{get:e[t],enumerable:!0})},$o=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ac(e))!Pc.call(s,n)&&n!==t&&Gs(s,n,{get:()=>e[n],enumerable:!(r=Dc(e,n))||r.enumerable});return s};var Bc=(s,e,t)=>(t=s!=null?Tc(Mc(s)):{},$o(e||!s||!s.__esModule?Gs(t,"default",{value:s,enumerable:!0}):t,s)),Rc=s=>$o(Gs({},"__esModule",{value:!0}),s);var lc=kc((_0,cc)=>{"use strict";function Z(s,t){var t=t||{};this._capacity=t.capacity,this._head=0,this._tail=0,Array.isArray(s)?this._fromArray(s):(this._capacityMask=3,this._list=new Array(4))}Z.prototype.peekAt=function(e){var t=e;if(t===(t|0)){var r=this.size();if(!(t>=r||t<-r))return t<0&&(t+=r),t=this._head+t&this._capacityMask,this._list[t]}};Z.prototype.get=function(e){return this.peekAt(e)};Z.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};Z.prototype.peekFront=function(){return this.peek()};Z.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(Z.prototype,"length",{get:function(){return this.size()}});Z.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};Z.prototype.unshift=function(e){if(arguments.length===0)return this.size();var t=this._list.length;return this._head=this._head-1+t&this._capacityMask,this._list[this._head]=e,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.pop(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};Z.prototype.shift=function(){var e=this._head;if(e!==this._tail){var t=this._list[e];return this._list[e]=void 0,this._head=e+1&this._capacityMask,e<2&&this._tail>1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}};Z.prototype.push=function(e){if(arguments.length===0)return this.size();var t=this._tail;return this._list[t]=e,this._tail=t+1&this._capacityMask,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.shift(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};Z.prototype.pop=function(){var e=this._tail;if(e!==this._head){var t=this._list.length;this._tail=e-1+t&this._capacityMask;var r=this._list[this._tail];return this._list[this._tail]=void 0,this._head<2&&e>1e4&&e<=t>>>2&&this._shrinkArray(),r}};Z.prototype.removeOne=function(e){var t=e;if(t===(t|0)&&this._head!==this._tail){var r=this.size(),n=this._list.length;if(!(t>=r||t<-r)){t<0&&(t+=r),t=this._head+t&this._capacityMask;var 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}}};Z.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}}};Z.prototype.splice=function(e,t){var r=e;if(r===(r|0)){var n=this.size();if(r<0&&(r+=n),!(r>n))if(arguments.length>2){var 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)}};Z.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0};Z.prototype.isEmpty=function(){return this._head===this._tail};Z.prototype.toArray=function(){return this._copyArray(!1)};Z.prototype._fromArray=function(e){var t=e.length,r=this._nextPowerOf2(t);this._list=new Array(r),this._capacityMask=r-1,this._tail=t;for(var n=0;n<t;n++)this._list[n]=e[n]};Z.prototype._copyArray=function(e,t){var r=this._list,n=r.length,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};Z.prototype._growArray=function(){if(this._head!=0){var e=this._copyArray(!0,this._list.length<<1);this._tail=this._list.length,this._head=0,this._list=e}else this._tail=this._list.length,this._list.length<<=1;this._capacityMask=this._capacityMask<<1|1};Z.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1};Z.prototype._nextPowerOf2=function(e){var t=Math.log(e)/Math.log(2),r=1<<t+1;return Math.max(r,4)};cc.exports=Z});var mf={};Ie(mf,{StrictNoSign:()=>Ct,StrictSign:()=>xt,TopicValidatorResult:()=>ge,gossipsub:()=>pf,multicodec:()=>df});var Hr="/floodsub/1.0.0",Gr="/meshsub/1.0.0",jo="/meshsub/1.1.0",Nt="/meshsub/1.2.0";var Zo="ERR_TOPIC_VALIDATOR_REJECT",Yo="ERR_TOPIC_VALIDATOR_IGNORE";var Y=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Ot=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var qs=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Vs=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Ut=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var qr=Symbol.for("@libp2p/peer-id");function Lc(s){return typeof s?.handleEvent=="function"}function Cc(s){return(s!==!0&&s!==!1&&s?.once)??!1}var Ws=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,r){let n=Cc(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))}Lc(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 Jo=Symbol.for("@libp2p/service-capabilities"),Qo=Symbol.for("@libp2p/service-dependencies");var Zr={};Ie(Zr,{base58btc:()=>J,base58flickr:()=>Hc});var Vf=new Uint8Array(0);function ei(s,e){if(s===e)return!0;if(s.byteLength!==e.byteLength)return!1;for(let t=0;t<s.byteLength;t++)if(s[t]!==e[t])return!1;return!0}function Ze(s){if(s instanceof Uint8Array&&s.constructor.name==="Uint8Array")return s;if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return new Uint8Array(s.buffer,s.byteOffset,s.byteLength);throw new Error("Unknown type, must be binary type")}function ti(s){return new TextEncoder().encode(s)}function si(s){return new TextDecoder().decode(s)}function Fc(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 b=0,g=0,x=0,I=h.length;x!==I&&h[x]===0;)x++,b++;for(var c=(I-x)*p+1>>>0,f=new Uint8Array(c);x!==I;){for(var d=h[x],y=0,v=c-1;(d!==0||y<g)&&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");g=y,x++}for(var S=c-g;S!==c&&f[S]===0;)S++;for(var k=l.repeat(b);S<c;++S)k+=s.charAt(f[S]);return k}function E(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var b=0;if(h[b]!==" "){for(var g=0,x=0;h[b]===l;)g++,b++;for(var I=(h.length-b)*u+1>>>0,c=new Uint8Array(I);h[b];){var f=t[h.charCodeAt(b)];if(f===255)return;for(var d=0,y=I-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,b++}if(h[b]!==" "){for(var v=I-x;v!==I&&c[v]===0;)v++;for(var S=new Uint8Array(g+(I-v)),k=g;v!==I;)S[k++]=c[v++];return S}}}function w(h){var b=E(h);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:m,decodeUnsafe:E,decode:w}}var Nc=Fc,Oc=Nc,ni=Oc;var Vr=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")}},Wr=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 oi(this,e)}},$r=class{decoders;constructor(e){this.decoders=e}or(e){return oi(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 oi(s,e){return new $r({...s.decoders??{[s.prefix]:s},...e.decoders??{[e.prefix]:e}})}var jr=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 Vr(e,t,r),this.decoder=new Wr(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Kt({name:s,prefix:e,encode:t,decode:r}){return new jr(s,e,t,r)}function it({name:s,prefix:e,alphabet:t}){let{encode:r,decode:n}=ni(t,s);return Kt({prefix:e,name:s,encode:r,decode:o=>Ze(n(o))})}function Uc(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 Kc(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 zc(s){let e={};for(let t=0;t<s.length;++t)e[s[t]]=t;return e}function X({name:s,prefix:e,bitsPerChar:t,alphabet:r}){let n=zc(r);return Kt({prefix:e,name:s,encode(o){return Kc(o,r,t)},decode(o){return Uc(o,n,t,s)}})}var J=it({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Hc=it({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Yr={};Ie(Yr,{base32:()=>zt,base32hex:()=>Wc,base32hexpad:()=>jc,base32hexpadupper:()=>Zc,base32hexupper:()=>$c,base32pad:()=>qc,base32padupper:()=>Vc,base32upper:()=>Gc,base32z:()=>Yc});var zt=X({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Gc=X({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),qc=X({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Vc=X({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Wc=X({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),$c=X({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),jc=X({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Zc=X({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Yc=X({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Xr={};Ie(Xr,{base36:()=>ps,base36upper:()=>Xc});var ps=it({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Xc=it({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Jc=ci,ii=128,Qc=127,el=~Qc,tl=Math.pow(2,31);function ci(s,e,t){e=e||[],t=t||0;for(var r=t;s>=tl;)e[t++]=s&255|ii,s/=128;for(;s⪙)e[t++]=s&255|ii,s>>>=7;return e[t]=s|0,ci.bytes=t-r+1,e}var sl=Jr,rl=128,ai=127;function Jr(s,r){var t=0,r=r||0,n=0,o=r,i,a=s.length;do{if(o>=a)throw Jr.bytes=0,new RangeError("Could not decode varint");i=s[o++],t+=n<28?(i&ai)<<n:(i&ai)*Math.pow(2,n),n+=7}while(i>=rl);return Jr.bytes=o-r,t}var nl=Math.pow(2,7),ol=Math.pow(2,14),il=Math.pow(2,21),al=Math.pow(2,28),cl=Math.pow(2,35),ll=Math.pow(2,42),ul=Math.pow(2,49),hl=Math.pow(2,56),fl=Math.pow(2,63),dl=function(s){return s<nl?1:s<ol?2:s<il?3:s<al?4:s<cl?5:s<ll?6:s<ul?7:s<hl?8:s<fl?9:10},pl={encode:Jc,decode:sl,encodingLength:dl},ml=pl,ms=ml;function gs(s,e=0){return[ms.decode(s,e),ms.decode.bytes]}function Ht(s,e,t=0){return ms.encode(s,e,t),e}function Gt(s){return ms.encodingLength(s)}function He(s,e){let t=e.byteLength,r=Gt(s),n=r+Gt(t),o=new Uint8Array(n+t);return Ht(s,o,0),Ht(t,o,r),o.set(e,n),new qt(s,t,e,o)}function Ye(s){let e=Ze(s),[t,r]=gs(e),[n,o]=gs(e.subarray(r)),i=e.subarray(r+o);if(i.byteLength!==n)throw new Error("Incorrect length");return new qt(t,n,i,e)}function li(s,e){if(s===e)return!0;{let t=e;return s.code===t.code&&s.size===t.size&&t.bytes instanceof Uint8Array&&ei(s.bytes,t.bytes)}}var qt=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}};function ui(s,e){let{bytes:t,version:r}=s;return r===0?bl(t,Qr(s),e??J.encoder):yl(t,Qr(s),e??zt.encoder)}var hi=new WeakMap;function Qr(s){let e=hi.get(s);if(e==null){let t=new Map;return hi.set(s,t),t}return e}var ce=class s{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=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!==bs)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==wl)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&&li(e.multihash,r.multihash)}toString(e){return ui(this,e)}toJSON(){return{"/":ui(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??fi(r,n,o.bytes))}else if(t[xl]===!0){let{version:r,multihash:n,code:o}=t,i=Ye(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!==bs)throw new Error(`Version 0 CID must use dag-pb (code: ${bs}) block encoding`);return new s(e,t,r,r.bytes)}case 1:{let n=fi(e,t,r.bytes);return new s(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return s.create(0,bs,e)}static createV1(e,t){return s.create(1,e,t)}static decode(e){let[t,r]=s.decodeFirst(e);if(r.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=s.inspectBytes(e),r=t.size-t.multihashSize,n=Ze(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 qt(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]=gs(e.subarray(t));return t+=E,m},n=r(),o=bs;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]=gl(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 Qr(o).set(r,e),o}};function gl(s,e){switch(s[0]){case"Q":{let t=e??J;return[J.prefix,t.decode(`${J.prefix}${s}`)]}case J.prefix:{let t=e??J;return[J.prefix,t.decode(s)]}case zt.prefix:{let t=e??zt;return[zt.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 bl(s,e,t){let{prefix:r}=t;if(r!==J.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let n=e.get(r);if(n==null){let o=t.encode(s).slice(1);return e.set(r,o),o}else return n}function yl(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 bs=112,wl=18;function fi(s,e,t){let r=Gt(s),n=r+Gt(e),o=new Uint8Array(n+t.byteLength);return Ht(s,o,0),Ht(e,o,r),o.set(t,n),o}var xl=Symbol.for("@ipld/js-cid/CID");var en={};Ie(en,{identity:()=>Re});var di=0,vl="identity",pi=Ze;function El(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(di,pi(s))}var Re={code:di,name:vl,encode:pi,digest:El};function Te(s,e){if(s===e)return!0;if(s.byteLength!==e.byteLength)return!1;for(let t=0;t<s.byteLength;t++)if(s[t]!==e[t])return!1;return!0}async function mi(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,e,t.subarray());return r?.signal?.throwIfAborted(),o}function Xe(s=0){return new Uint8Array(s)}function he(s=0){return new Uint8Array(s)}function vt(s,e){e==null&&(e=s.reduce((n,o)=>n+o.length,0));let t=he(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var bi=Symbol.for("@achingbrain/uint8arraylist");function gi(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 js(s){return!!s?.[bi]}var ie=class s{bufs;length;[bi]=!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(js(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(js(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=gi(this.bufs,e);return t.buf[t.index]}set(e,t){let r=gi(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(js(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 vt(r,n)}subarray(e,t){let{bufs:r,length:n}=this._subList(e,t);return r.length===1?r[0]:vt(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(!js(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=he(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){let n=Xe(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){let n=Xe(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){let n=Xe(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let r=he(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){let n=Xe(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){let n=Xe(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){let n=Xe(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){let n=Xe(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){let n=Xe(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(e==null||!(e instanceof s)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Te(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let r=new s;return r.bufs=e,t==null&&(t=e.reduce((n,o)=>n+o.byteLength,0)),r.length=t,r}};var tn={};Ie(tn,{base10:()=>Sl});var Sl=it({prefix:"9",name:"base10",alphabet:"0123456789"});var sn={};Ie(sn,{base16:()=>_l,base16upper:()=>Il});var _l=X({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Il=X({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var rn={};Ie(rn,{base2:()=>Tl});var Tl=X({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var nn={};Ie(nn,{base256emoji:()=>kl});var yi=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}"),Dl=yi.reduce((s,e,t)=>(s[t]=e,s),[]),Al=yi.reduce((s,e,t)=>{let r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return s[r]=t,s},[]);function Ml(s){return s.reduce((e,t)=>(e+=Dl[t],e),"")}function Pl(s){let e=[];for(let t of s){let r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);let n=Al[r];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var kl=Kt({prefix:"\u{1F680}",name:"base256emoji",encode:Ml,decode:Pl});var on={};Ie(on,{base64:()=>Bl,base64pad:()=>Rl,base64url:()=>Ll,base64urlpad:()=>Cl});var Bl=X({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Rl=X({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ll=X({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Cl=X({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var an={};Ie(an,{base8:()=>Fl});var Fl=X({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var cn={};Ie(cn,{identity:()=>Nl});var Nl=Kt({prefix:"\0",name:"identity",encode:s=>si(s),decode:s=>ti(s)});var Md=new TextEncoder,Pd=new TextDecoder;var hn={};Ie(hn,{sha256:()=>Et,sha512:()=>zl});var Kl=20;function un({name:s,code:e,encode:t,minDigestLength:r,maxDigestLength:n}){return new ln(s,e,t,r,n)}var ln=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,r,n,o){this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??Kl,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?wi(r,this.code,t?.truncate):r.then(n=>wi(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function wi(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 vi(s){return async e=>new Uint8Array(await crypto.subtle.digest(s,e))}var Et=un({name:"sha2-256",code:18,encode:vi("SHA-256")}),zl=un({name:"sha2-512",code:19,encode:vi("SHA-512")});var fn={...cn,...rn,...an,...tn,...sn,...Yr,...Xr,...Zr,...on,...nn},Hd={...hn,...en};function Si(s,e,t,r){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:r}}}var Ei=Si("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),dn=Si("ascii","a",s=>{let e="a";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return e},s=>{s=s.substring(1);let e=he(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),Hl={utf8:Ei,"utf-8":Ei,hex:fn.base16,latin1:dn,ascii:dn,binary:dn,...fn},Zs=Hl;function V(s,e="utf8"){let t=Zs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${s}`)}function q(s,e="utf8"){let t=Zs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(s).substring(1)}var Gl=parseInt("11111",2),pn=parseInt("10000000",2),ql=parseInt("01111111",2),_i={0:ys,1:ys,2:Vl,3:jl,4:Zl,5:$l,6:Wl,16:ys,22:ys,48:ys};function Je(s,e={offset:0}){let t=s[e.offset]&Gl;if(e.offset++,_i[t]!=null)return _i[t](s,e);throw new Error("No decoder for tag "+t)}function ws(s,e){let t=0;if((s[e.offset]&pn)===pn){let r=s[e.offset]&ql,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 ys(s,e){ws(s,e);let t=[];for(;!(e.offset>=s.byteLength);){let r=Je(s,e);if(r===null)break;t.push(r)}return t}function Vl(s,e){let t=ws(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 Wl(s,e){let t=ws(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 $l(s,e){return e.offset++,null}function jl(s,e){let t=ws(s,e),r=s[e.offset];e.offset++;let n=s.subarray(e.offset,e.offset+t-1);if(e.offset+=t,r!==0)throw new Error("Unused bits in bit string is unimplemented");return n}function Zl(s,e){let t=ws(s,e),r=s.subarray(e.offset,e.offset+t);return e.offset+=t,r}function Yl(s){let e=s.toString(16);e.length%2===1&&(e="0"+e);let t=new ie;for(let r=0;r<e.length;r+=2)t.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return t}function mn(s){if(s.byteLength<128)return Uint8Array.from([s.byteLength]);let e=Yl(s.byteLength);return new ie(Uint8Array.from([e.byteLength|pn]),e)}function De(s){let e=new ie,t=128;return(s.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(s),new ie(Uint8Array.from([2]),mn(e),e)}function Ys(s){let e=Uint8Array.from([0]),t=new ie(e,s);return new ie(Uint8Array.from([3]),mn(t),t)}function ct(s,e=48){let t=new ie;for(let r of s)t.append(r);return new ie(Uint8Array.from([e]),mn(t),t)}var Xl=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Jl=Uint8Array.from([6,5,43,129,4,0,34]),Ql=Uint8Array.from([6,5,43,129,4,0,35]),eu={ext:!0,kty:"EC",crv:"P-256"},tu={ext:!0,kty:"EC",crv:"P-384"},su={ext:!0,kty:"EC",crv:"P-521"},gn=32,bn=48,yn=66;function wn(s){let e=Je(s);return Ii(e)}function Ii(s){let e=s[1][1][0],t=1,r,n;if(e.byteLength===gn*2+1)return r=q(e.subarray(t,t+gn),"base64url"),n=q(e.subarray(t+gn),"base64url"),new Vt({...eu,key_ops:["verify"],x:r,y:n});if(e.byteLength===bn*2+1)return r=q(e.subarray(t,t+bn),"base64url"),n=q(e.subarray(t+bn),"base64url"),new Vt({...tu,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 Vt({...su,key_ops:["verify"],x:r,y:n});throw new Y(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Ti(s){return ct([De(Uint8Array.from([1])),ct([ru(s.crv)],160),ct([Ys(new ie(Uint8Array.from([4]),V(s.x??"","base64url"),V(s.y??"","base64url")))],161)]).subarray()}function ru(s){if(s==="P-256")return Xl;if(s==="P-384")return Jl;if(s==="P-521")return Ql;throw new Y(`Invalid curve ${s}`)}var Vt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Ti(this.jwk)),this._raw}toMultihash(){return Re.digest(Ge(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Te(this.raw,e.raw)}async verify(e,t,r){return mi(this.jwk,t,e,r)}};function xn(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in s&&s.BYTES_PER_ELEMENT===1}function lt(s,e=""){if(typeof s!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof s}`)}if(!Number.isSafeInteger(s)||s<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${s}`)}}function Ae(s,e,t=""){let r=xn(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 Xs(s){if(typeof s!="function"||typeof s.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(lt(s.outputLen),lt(s.blockLen),s.outputLen<1)throw new Error('"outputLen" must be >= 1');if(s.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Wt(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 Js(s,e){Ae(s,void 0,"digestInto() output");let t=e.outputLen;if(s.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function et(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Qs(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Le(s,e){return s<<32-e|s>>>e}var Ai=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",nu=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function er(s){if(Ae(s),Ai)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=nu[s[t]];return e}var Qe={_0:48,_9:57,A:65,F:70,a:97,f:102};function Di(s){if(s>=Qe._0&&s<=Qe._9)return s-Qe._0;if(s>=Qe.A&&s<=Qe.F)return s-(Qe.A-10);if(s>=Qe.a&&s<=Qe.f)return s-(Qe.a-10)}function xs(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);if(Ai)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=Di(s.charCodeAt(o)),a=Di(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 vn(...s){let e=0;for(let r=0;r<s.length;r++){let n=s[r];Ae(n),e+=n.length}let t=new Uint8Array(e);for(let r=0,n=0;r<s.length;r++){let o=s[r];t.set(o,n),n+=o.length}return t}function En(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 Mi(s=32){lt(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 Sn=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function Pi(s,e,t){return s&e^~s&t}function ki(s,e,t){return s&e^s&t^e&t}var vs=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Qs(this.buffer)}update(e){Wt(this),Ae(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=Qs(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){Wt(this),Js(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;t[i++]=128,et(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=Qs(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()}},tt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var le=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var tr=BigInt(4294967295),Bi=BigInt(32);function ou(s,e=!1){return e?{h:Number(s&tr),l:Number(s>>Bi&tr)}:{h:Number(s>>Bi&tr)|0,l:Number(s&tr)|0}}function Ri(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}=ou(s[o],e);[r[o],n[o]]=[i,a]}return[r,n]}var _n=(s,e,t)=>s>>>t,In=(s,e,t)=>s<<32-t|e>>>t,St=(s,e,t)=>s>>>t|e<<32-t,_t=(s,e,t)=>s<<32-t|e>>>t,Es=(s,e,t)=>s<<64-t|e>>>t-32,Ss=(s,e,t)=>s>>>t-32|e<<64-t;function qe(s,e,t,r){let n=(e>>>0)+(r>>>0);return{h:s+t+(n/2**32|0)|0,l:n|0}}var Li=(s,e,t)=>(s>>>0)+(e>>>0)+(t>>>0),Ci=(s,e,t,r)=>e+t+r+(s/2**32|0)|0,Fi=(s,e,t,r)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0),Ni=(s,e,t,r,n)=>e+t+r+n+(s/2**32|0)|0,Oi=(s,e,t,r,n)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Ui=(s,e,t,r,n,o)=>e+t+r+n+o+(s/2**32|0)|0;var au=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]),ut=new Uint32Array(64),Tn=class extends vs{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)ut[m]=e.getUint32(t,!1);for(let m=16;m<64;m++){let E=ut[m-15],w=ut[m-2],h=Le(E,7)^Le(E,18)^E>>>3,b=Le(w,17)^Le(w,19)^w>>>10;ut[m]=b+ut[m-7]+h+ut[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=Le(a,6)^Le(a,11)^Le(a,25),w=p+E+Pi(a,l,u)+au[m]+ut[m]|0,b=(Le(r,2)^Le(r,13)^Le(r,22))+ki(r,n,o)|0;p=u,u=l,l=a,a=i+w|0,i=o,o=n,n=r,r=w+b|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(){et(ut)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),et(this.buffer)}},Dn=class extends Tn{A=tt[0]|0;B=tt[1]|0;C=tt[2]|0;D=tt[3]|0;E=tt[4]|0;F=tt[5]|0;G=tt[6]|0;H=tt[7]|0;constructor(){super(32)}};var Ki=Ri(["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))),cu=Ki[0],lu=Ki[1],ht=new Uint32Array(80),ft=new Uint32Array(80),An=class extends vs{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:b,Hl:g}=this;return[e,t,r,n,o,i,a,l,u,p,m,E,w,h,b,g]}set(e,t,r,n,o,i,a,l,u,p,m,E,w,h,b,g){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=b|0,this.Hl=g|0}process(e,t){for(let c=0;c<16;c++,t+=4)ht[c]=e.getUint32(t),ft[c]=e.getUint32(t+=4);for(let c=16;c<80;c++){let f=ht[c-15]|0,d=ft[c-15]|0,y=St(f,d,1)^St(f,d,8)^_n(f,d,7),v=_t(f,d,1)^_t(f,d,8)^In(f,d,7),S=ht[c-2]|0,k=ft[c-2]|0,C=St(S,k,19)^Es(S,k,61)^_n(S,k,6),N=_t(S,k,19)^Ss(S,k,61)^In(S,k,6),_=Fi(v,N,ft[c-7],ft[c-16]),T=Ni(_,y,C,ht[c-7],ht[c-16]);ht[c]=T|0,ft[c]=_|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:b,Gl:g,Hh:x,Hl:I}=this;for(let c=0;c<80;c++){let f=St(m,E,14)^St(m,E,18)^Es(m,E,41),d=_t(m,E,14)^_t(m,E,18)^Ss(m,E,41),y=m&w^~m&b,v=E&h^~E&g,S=Oi(I,d,v,lu[c],ft[c]),k=Ui(S,x,f,y,cu[c],ht[c]),C=S|0,N=St(r,n,28)^Es(r,n,34)^Es(r,n,39),_=_t(r,n,28)^Ss(r,n,34)^Ss(r,n,39),T=r&o^r&a^o&a,M=n&i^n&l^i&l;x=b|0,I=g|0,b=w|0,g=h|0,w=m|0,h=E|0,{h:m,l:E}=qe(u|0,p|0,k|0,C|0),u=a|0,p=l|0,a=o|0,l=i|0,o=r|0,i=n|0;let A=Li(C,_,M);r=Ci(A,k,N,T),n=A|0}({h:r,l:n}=qe(this.Ah|0,this.Al|0,r|0,n|0)),{h:o,l:i}=qe(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l}=qe(this.Ch|0,this.Cl|0,a|0,l|0),{h:u,l:p}=qe(this.Dh|0,this.Dl|0,u|0,p|0),{h:m,l:E}=qe(this.Eh|0,this.El|0,m|0,E|0),{h:w,l:h}=qe(this.Fh|0,this.Fl|0,w|0,h|0),{h:b,l:g}=qe(this.Gh|0,this.Gl|0,b|0,g|0),{h:x,l:I}=qe(this.Hh|0,this.Hl|0,x|0,I|0),this.set(r,n,o,i,a,l,u,p,m,E,w,h,b,g,x,I)}roundClean(){et(ht,ft)}destroy(){this.destroyed=!0,et(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Mn=class extends An{Ah=le[0]|0;Al=le[1]|0;Bh=le[2]|0;Bl=le[3]|0;Ch=le[4]|0;Cl=le[5]|0;Dh=le[6]|0;Dl=le[7]|0;Eh=le[8]|0;El=le[9]|0;Fh=le[10]|0;Fl=le[11]|0;Gh=le[12]|0;Gl=le[13]|0;Hh=le[14]|0;Hl=le[15]|0;constructor(){super(64)}};var $t=En(()=>new Dn,Sn(1));var sr=En(()=>new Mn,Sn(3));var K=(s,e,t)=>Ae(s,e,t),kn=lt,jt=er,re=(...s)=>vn(...s),Zt=s=>xs(s),It=xn,_s=s=>Mi(s),nr=BigInt(0),Pn=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 or(s){if(typeof s=="bigint"){if(!rr(s))throw new RangeError("positive bigint expected, got "+s)}else kn(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 Is(s){let e=or(s).toString(16);return e.length&1?"0"+e:e}function zi(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);return s===""?nr:BigInt("0x"+s)}function Tt(s){return zi(er(s))}function Ve(s){return zi(er(Ts(Ae(s)).reverse()))}function ir(s,e){if(lt(e),e===0)throw new RangeError("zero length");s=or(s);let t=s.toString(16);if(t.length>e*2)throw new RangeError("number too large");return xs(t.padStart(e*2,"0"))}function Bn(s,e){return ir(s,e).reverse()}function Hi(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 Ts(s){return Uint8Array.from(K(s))}function ar(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 rr=s=>typeof s=="bigint"&&nr<=s;function uu(s,e,t){return rr(s)&&rr(e)&&rr(t)&&e<=s&&s<t}function Yt(s,e,t,r){if(!uu(e,t,r))throw new RangeError("expected valid "+s+": "+t+" <= n < "+r+", got "+e)}function Xt(s){if(s<nr)throw new Error("expected non-negative bigint, got "+s);let e;for(e=0;s>nr;s>>=Pn,e+=1);return e}var Ds=s=>(Pn<<BigInt(s))-Pn;function Gi(s,e,t){if(lt(s,"hashLen"),lt(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let r=g=>new Uint8Array(g),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=(...g)=>t(u,re(l,...g)),w=(g=n)=>{u=E(o,g),l=E(),g.length!==0&&(u=E(i,g),l=E())},h=()=>{if(p++>=a)throw new Error("drbg: tried max amount of iterations");let g=0,x=[];for(;g<e;){l=E();let I=l.slice();x.push(I),g+=l.length}return re(...x)};return(g,x)=>{m(),w(g);let I;for(;(I=x(h()))===void 0;)w();return m(),I}}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 Rn=()=>{throw new Error("not implemented")};var ue=BigInt(0),Q=BigInt(1),Dt=BigInt(2),$i=BigInt(3),ji=BigInt(4),Zi=BigInt(5),hu=BigInt(7),Yi=BigInt(8),fu=BigInt(9),Xi=BigInt(16);function te(s,e){if(e<=ue)throw new Error("mod: expected positive modulus, got "+e);let t=s%e;return t>=ue?t:e+t}function $(s,e,t){if(e<ue)throw new Error("pow2: expected non-negative exponent, got "+e);let r=s;for(;e-- >ue;)r*=r,r%=t;return r}function qi(s,e){if(s===ue)throw new Error("invert: expected non-zero number");if(e<=ue)throw new Error("invert: expected positive modulus, got "+e);let t=te(s,e),r=e,n=ue,o=Q,i=Q,a=ue;for(;t!==ue;){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!==Q)throw new Error("invert: does not exist");return te(n,e)}function Ln(s,e,t){let r=s;if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function Ji(s,e){let t=s,r=(t.ORDER+Q)/ji,n=t.pow(e,r);return Ln(t,n,e),n}function du(s,e){let t=s,r=(t.ORDER-Zi)/Yi,n=t.mul(e,Dt),o=t.pow(n,r),i=t.mul(e,o),a=t.mul(t.mul(i,Dt),o),l=t.mul(i,t.sub(a,t.ONE));return Ln(t,l,e),l}function pu(s){let e=Jt(s),t=Qi(s),r=t(e,e.neg(e.ONE)),n=t(e,r),o=t(e,e.neg(r)),i=(s+hu)/Xi;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),b=u.eql(u.sqr(E),l);p=u.cmov(p,m,h),m=u.cmov(w,E,b);let g=u.eql(u.sqr(m),l),x=u.cmov(p,m,g);return Ln(u,x,l),x})}function Qi(s){if(s<$i)throw new Error("sqrt is not defined for small field");let e=s-Q,t=0;for(;e%Dt===ue;)e/=Dt,t++;let r=Dt,n=Jt(s);for(;Vi(n,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Ji;let o=n.pow(r,e),i=(e+Q)/Dt;return function(l,u){let p=l;if(p.is0(u))return u;if(Vi(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 b=1,g=p.sqr(w);for(;!p.eql(g,p.ONE);)if(b++,g=p.sqr(g),b===m)throw new Error("Cannot find square root");let x=Q<<BigInt(m-b-1),I=p.pow(E,x);m=b,E=p.sqr(I),w=p.mul(w,E),h=p.mul(h,I)}return h}}function mu(s){return s%ji===$i?Ji:s%Yi===Zi?du:s%Xi===fu?pu(s):Qi(s)}var st=(s,e)=>(te(s,e)&Q)===Q,gu=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Cn(s){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=gu.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<=Q)throw new Error("invalid field: expected ORDER > 1, got "+s.ORDER);return s}function bu(s,e,t){let r=s;if(t<ue)throw new Error("invalid exponent, negatives unsupported");if(t===ue)return r.ONE;if(t===Q)return e;let n=r.ONE,o=e;for(;t>ue;)t&Q&&(n=r.mul(n,o)),o=r.sqr(o),t>>=Q;return n}function As(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 Vi(s,e){let t=s,r=(t.ORDER-Q)/Dt,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 yu(s,e){if(e!==void 0&&kn(e),s<=ue)throw new Error("invalid n length: expected positive n, got "+s);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Xt(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 Wi=new WeakMap,cr=class{ORDER;BITS;BYTES;isLE;ZERO=ue;ONE=Q;_lengths;_mod;constructor(e,t={}){if(e<=Q)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:n,nByteLength:o}=yu(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 te(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return ue<=e&&e<this.ORDER}is0(e){return e===ue}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Q)===Q}neg(e){return te(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return te(e*e,this.ORDER)}add(e,t){return te(e+t,this.ORDER)}sub(e,t){return te(e-t,this.ORDER)}mul(e,t){return te(e*t,this.ORDER)}pow(e,t){return bu(this,e,t)}div(e,t){return te(e*qi(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 qi(e,this.ORDER)}sqrt(e){let t=Wi.get(this);return t||Wi.set(this,t=mu(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Bn(e,this.BYTES):ir(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?Ve(e):Tt(e);if(a&&(l=te(l,i)),!t&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return As(this,e)}cmov(e,t,r){return Ce(r,"condition"),r?t:e}};Object.freeze(cr.prototype);function Jt(s,e={}){return new cr(s,e)}function ea(s){if(typeof s!="bigint")throw new Error("field order must be bigint");if(s<=Q)throw new Error("field order must be greater than 1");let e=Xt(s-Q);return Math.ceil(e/8)}function Fn(s){let e=ea(s);return e+Math.ceil(e/2)}function Nn(s,e,t=!1){K(s);let r=s.length,n=ea(e),o=Math.max(Fn(e),16);if(r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);let i=t?Ve(s):Tt(s),a=te(i,e-Q)+Q;return t?Bn(a,n):ir(a,n)}var Qt=BigInt(0),At=BigInt(1);function Ms(s,e){let t=e.negate();return s?t:e}function Mt(s,e){let t=As(s.Fp,e.map(r=>r.Z));return e.map((r,n)=>s.fromAffine(r.toAffine(t[n])))}function na(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function On(s,e){na(s,e);let t=Math.ceil(e/s)+1,r=2**(s-1),n=2**s,o=Ds(s),i=BigInt(s);return{windows:t,windowSize:r,mask:o,maxNumber:n,shiftBy:i}}function ta(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+=At);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 Un=new WeakMap,oa=new WeakMap;function Kn(s){return oa.get(s)||1}function sa(s){if(s!==Qt)throw new Error("invalid wNAF")}var es=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>Qt;)t&At&&(r=r.add(n)),n=n.double(),t>>=At;return r}precomputeWindow(e,t){let{windows:r,windowSize:n}=On(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=On(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:l,offset:u,isZero:p,isNeg:m,isNegF:E,offsetF:w}=ta(r,a,i);r=l,p?o=o.add(Ms(E,t[w])):n=n.add(Ms(m,t[u]))}return sa(r),{p:n,f:o}}wNAFUnsafe(e,t,r,n=this.ZERO){let o=On(e,this.bits);for(let i=0;i<o.windows&&r!==Qt;i++){let{nextN:a,offset:l,isZero:u,isNeg:p}=ta(r,i,o);if(r=a,!u){let m=t[l];n=n.add(p?m.negate():m)}}return sa(r),n}getPrecomputes(e,t,r){let n=Un.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(n=r(n)),Un.set(t,n))),n}cached(e,t,r){let n=Kn(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){let o=Kn(e);return o===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,n)}createCache(e,t){na(t,this.bits),oa.set(e,t),Un.delete(e)}hasCache(e){return Kn(e)!==1}};function ia(s,e,t,r){let n=e,o=s.ZERO,i=s.ZERO;for(;t>Qt||r>Qt;)t&At&&(o=o.add(n)),r&At&&(i=i.add(n)),n=n.double(),t>>=At,r>>=At;return{p1:o,p2:i}}function ra(s,e,t){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Cn(e),e}else return Jt(s,{isLE:t})}function lr(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>Qt))throw new Error(`CURVE.${l} must be positive bigint`)}let n=ra(e.p,t.Fp,r),o=ra(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 ur(s,e){return function(r){let n=s(r);return{secretKey:n,publicKey:e(n)}}}var dt=BigInt(0),ae=BigInt(1),zn=BigInt(2),wu=BigInt(8);function xu(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 aa(s,e={}){let t=e,r=lr("edwards",s,t,t.FpFnLE),{Fp:n,Fn:o}=r,i=r.CURVE,{h:a}=i;Ne(t,{},{uvRatio:"function"});let l=zn<<BigInt(o.BYTES*8)-ae,u=b=>n.create(b),p=t.uvRatio===void 0?(b,g)=>{try{return{isValid:!0,value:n.sqrt(n.div(b,g))}}catch{return{isValid:!1,value:dt}}}:t.uvRatio;if(!xu(n,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function m(b,g,x=!1){let I=x?ae:dt;return Yt("coordinate "+b,g,I,l),g}function E(b){if(!(b instanceof w))throw new Error("EdwardsPoint expected")}class w{static BASE=new w(i.Gx,i.Gy,ae,u(i.Gx*i.Gy));static ZERO=new w(dt,ae,ae,dt);static Fp=n;static Fn=o;X;Y;Z;T;constructor(g,x,I,c){this.X=m("x",g),this.Y=m("y",x),this.Z=m("z",I,!0),this.T=m("t",c),Object.freeze(this)}static CURVE(){return i}static fromAffine(g){if(g instanceof w)throw new Error("extended point not allowed");let{x,y:I}=g||{};return m("x",x),m("y",I),new w(x,I,ae,u(x*I))}static fromBytes(g,x=!1){let I=n.BYTES,{a:c,d:f}=i;g=Ts(K(g,I,"point")),Ce(x,"zip215");let d=Ts(g),y=g[I-1];d[I-1]=y&-129;let v=Ve(d),S=x?l:n.ORDER;Yt("point.y",v,dt,S);let k=u(v*v),C=u(k-ae),N=u(f*k-c),{isValid:_,value:T}=p(C,N);if(!_)throw new Error("bad point: invalid y coordinate");let M=(T&ae)===ae,A=(y&128)!==0;if(!x&&T===dt&&A)throw new Error("bad point: x=0 and x_0=1");return A!==M&&(T=u(-T)),w.fromAffine({x:T,y:v})}static fromHex(g,x=!1){return w.fromBytes(Zt(g),x)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,x=!0){return h.createCache(this,g),x||this.multiply(zn),this}assertValidity(){let g=this,{a:x,d:I}=i;if(g.is0())throw new Error("bad point: ZERO");let{X:c,Y:f,Z:d,T:y}=g,v=u(c*c),S=u(f*f),k=u(d*d),C=u(k*k),N=u(v*x),_=u(k*u(N+S)),T=u(C+u(I*u(v*S)));if(_!==T)throw new Error("bad point: equation left != right (1)");let M=u(c*f),A=u(d*y);if(M!==A)throw new Error("bad point: equation left != right (2)")}equals(g){E(g);let{X:x,Y:I,Z:c}=this,{X:f,Y:d,Z:y}=g,v=u(x*y),S=u(f*c),k=u(I*y),C=u(d*c);return v===S&&k===C}is0(){return this.equals(w.ZERO)}negate(){return new w(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:g}=i,{X:x,Y:I,Z:c}=this,f=u(x*x),d=u(I*I),y=u(zn*u(c*c)),v=u(g*f),S=x+I,k=u(u(S*S)-f-d),C=v+d,N=C-y,_=v-d,T=u(k*N),M=u(C*_),A=u(k*_),D=u(N*C);return new w(T,M,D,A)}add(g){E(g);let{a:x,d:I}=i,{X:c,Y:f,Z:d,T:y}=this,{X:v,Y:S,Z:k,T:C}=g,N=u(c*v),_=u(f*S),T=u(y*I*C),M=u(d*k),A=u((c+f)*(v+S)-N-_),D=M-T,P=M+T,R=u(_-x*N),B=u(A*D),L=u(P*R),F=u(A*R),U=u(D*P);return new w(B,L,U,F)}subtract(g){return E(g),this.add(g.negate())}multiply(g){if(!o.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:x,f:I}=h.cached(this,g,c=>Mt(w,c));return Mt(w,[x,I])[0]}multiplyUnsafe(g){if(!o.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===dt?w.ZERO:this.is0()||g===ae?this:h.unsafe(this,g,x=>Mt(w,x))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return h.unsafe(this,i.n).is0()}toAffine(g){let x=this,I=g,{X:c,Y:f,Z:d}=x,y=x.is0();I==null&&(I=y?wu:n.inv(d));let v=u(c*I),S=u(f*I),k=n.mul(d,I);if(y)return{x:dt,y:ae};if(k!==ae)throw new Error("invZ was invalid");return{x:v,y:S}}clearCofactor(){return a===ae?this:this.multiplyUnsafe(a)}toBytes(){let{x:g,y:x}=this.toAffine(),I=n.toBytes(x);return I[I.length-1]|=g&ae?128:0,I}toHex(){return jt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let h=new es(w,o.BITS);return o.BITS>=8&&w.BASE.precompute(8),Object.freeze(w.prototype),Object.freeze(w),w}var hr=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Rn()}static fromHex(e){Rn()}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 jt(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 ca(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?_s:n.randomBytes,E=n.adjustScalarBytes===void 0?_=>_:n.adjustScalarBytes,w=n.domain===void 0?(_,T,M)=>{if(Ce(M,"phflag"),T.length||M)throw new Error("Contexts/pre-hash are not supported");return _}:n.domain;function h(_){return l.create(Ve(_))}function b(_){let T=v.secretKey;K(_,v.secretKey,"secretKey");let M=K(r(_),2*T,"hashedSecretKey"),A=E(M.slice(0,T)),D=M.slice(T,2*T),P=h(A);return{head:A,prefix:D,scalar:P}}function g(_){let{head:T,prefix:M,scalar:A}=b(_),D=i.multiply(A),P=D.toBytes();return{head:T,prefix:M,scalar:A,point:D,pointBytes:P}}function x(_){return g(_).pointBytes}function I(_=Uint8Array.of(),...T){let M=re(...T);return h(r(w(M,K(_,void 0,"context"),!!o)))}function c(_,T,M={}){_=K(_,void 0,"message"),o&&(_=o(_));let{prefix:A,scalar:D,pointBytes:P}=g(T),R=I(M.context,A,_),B=i.multiply(R).toBytes(),L=I(M.context,B,P,_),F=l.create(R+L*D);if(!l.isValid(F))throw new Error("sign failed: invalid s");let U=re(B,l.toBytes(F));return K(U,v.signature,"result")}let f={zip215:n.zip215};function d(_,T,M,A=f){let{context:D}=A,P=A.zip215===void 0?!!f.zip215:A.zip215,R=v.signature;_=K(_,R,"signature"),T=K(T,void 0,"message"),M=K(M,v.publicKey,"publicKey"),P!==void 0&&Ce(P,"zip215"),o&&(T=o(T));let B=R/2,L=_.subarray(0,B),F=Ve(_.subarray(B,R)),U,z,O;try{U=s.fromBytes(M,P),z=s.fromBytes(L,P),O=i.multiplyUnsafe(F)}catch{return!1}if(!P&&U.isSmallOrder())return!1;let se=I(D,L,M,T);return z.add(U.multiplyUnsafe(se)).subtract(O).clearCofactor().is0()}let y=a.BYTES,v={secretKey:y,publicKey:y,signature:2*y,seed:y};function S(_){return _=_===void 0?m(v.seed):_,K(_,v.seed,"seed")}function k(_){return It(_)&&_.length===v.secretKey}function C(_,T){try{return!!s.fromBytes(_,T===void 0?f.zip215:T)}catch{return!1}}let N={getExtendedPublicKey:g,randomSecretKey:S,isValidSecretKey:k,isValidPublicKey:C,toMontgomery(_){let{y:T}=s.fromBytes(_),M=v.publicKey,A=M===32;if(!A&&M!==57)throw new Error("only defined for 25519 and 448");let D=A?a.div(ae+T,ae-T):a.div(T-ae,T+ae);return a.toBytes(D)},toMontgomerySecret(_){let T=v.secretKey;K(_,T);let M=r(_.subarray(0,T));return E(M).subarray(0,T)}};return Object.freeze(v),Object.freeze(N),Object.freeze({keygen:ur(S,x),getPublicKey:x,sign:c,verify:d,utils:N,Point:s,lengths:v})}function Ps(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 vu(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 Eu(s){if(!It(s)&&typeof s!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof s=="string"?ar(s):s;if(e.length===0)throw new Error("DST must be non-empty");return e}function Hn(s,e,t,r){K(s),Fe(t),e=Eu(e),e.length>255&&(e=r(re(ar("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=re(e,Ps(e.length,1)),l=new Uint8Array(o),u=Ps(t,2),p=new Array(i),m=r(re(l,s,u,Ps(0,1),a));p[0]=r(re(m,Ps(1,1),a));for(let w=1;w<i;w++){let h=[vu(m,p[w-1]),Ps(w+1,1),a];p[w]=r(re(...h))}return re(...p).slice(0,t)}var la="HashToScalar-";var Su=BigInt(0),rt=BigInt(1),ua=BigInt(2);var _u=BigInt(5),Iu=BigInt(8),ts=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Wn={p:ts,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Iu,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Tu(s){let e=BigInt(10),t=BigInt(20),r=BigInt(40),n=BigInt(80),o=ts,a=s*s%o*s%o,l=$(a,ua,o)*a%o,u=$(l,rt,o)*s%o,p=$(u,_u,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,b=$(h,n,o)*w%o,g=$(b,e,o)*p%o;return{pow_p_5_8:$(g,ua,o)*s%o,b2:a}}function Du(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}var Gn=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function $n(s,e){let t=ts,r=te(e*e*e,t),n=te(r*r*e,t),o=Tu(s*n).pow_p_5_8,i=te(s*r*o,t),a=te(e*i*i,t),l=i,u=te(i*Gn,t),p=a===s,m=a===te(-s,t),E=a===te(-s*Gn,t);return p&&(i=l),(m||E)&&(i=u),st(i,t)&&(i=te(-i,t)),{isValid:p||m,value:i}}var mt=aa(Wn,{uvRatio:$n}),pt=mt.Fp,da=mt.Fn;function Au(s){return ca(mt,sr,Object.assign({adjustScalarBytes:Du,zip215:!0},s))}var pa=Au({});var qn=Gn,Mu=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Pu=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),ku=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Bu=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),ha=s=>$n(rt,s),Ru=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Vn=s=>pt.create(Ve(s)&Ru);function fa(s){let{d:e}=Wn,t=ts,r=x=>pt.create(x),n=r(qn*s*s),o=r((n+rt)*ku),i=BigInt(-1),a=r((i-e*n)*r(n+e)),{isValid:l,value:u}=$n(o,a),p=r(u*s);st(p,t)||(p=r(-p)),l||(u=p),l||(i=n);let m=r(i*(n-rt)*Bu-a),E=u*u,w=r((u+u)*a),h=r(m*Mu),b=r(rt-E),g=r(rt+E);return new mt(r(w*g),r(b*h),r(h*g),r(w*b))}var gt=class s extends hr{static BASE=new s(mt.BASE);static ZERO=new s(mt.ZERO);static Fp=pt;static Fn=da;constructor(e){super(e)}static fromAffine(e){return new s(mt.fromAffine(e))}assertSame(e){if(!(e instanceof s))throw new Error("RistrettoPoint expected")}init(e){return new s(e)}static fromBytes(e){Ae(e,32);let{a:t,d:r}=Wn,n=ts,o=f=>pt.create(f),i=Vn(e);if(!Hi(pt.toBytes(i),e)||st(i,n))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),l=o(rt+t*a),u=o(rt-t*a),p=o(l*l),m=o(u*u),E=o(t*r*p-m),{isValid:w,value:h}=ha(o(E*m)),b=o(h*u),g=o(h*b*E),x=o((i+i)*b);st(x,n)&&(x=o(-x));let I=o(l*g),c=o(x*I);if(!w||st(c,n)||I===Su)throw new Error("invalid ristretto255 encoding 2");return new s(new mt(x,I,rt,c))}static fromHex(e){return s.fromBytes(xs(e))}toBytes(){let{X:e,Y:t,Z:r,T:n}=this.ep,o=ts,i=g=>pt.create(g),a=i(i(r+t)*i(r-t)),l=i(e*t),u=i(l*l),{value:p}=ha(i(a*u)),m=i(p*a),E=i(p*l),w=i(m*E*n),h;if(st(n*w,o)){let g=i(t*qn),x=i(e*qn);e=g,t=x,h=i(m*Pu)}else h=E;st(e*w,o)&&(t=i(-t));let b=i((r-t)*h);return st(b,o)&&(b=i(-b)),pt.toBytes(b)}equals(e){this.assertSame(e);let{X:t,Y:r}=this.ep,{X:n,Y:o}=e.ep,i=u=>pt.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(gt.BASE);Object.freeze(gt.ZERO);Object.freeze(gt.prototype);Object.freeze(gt);var Lu=Object.freeze({Point:gt,hashToCurve(s,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,r=Hn(s,t,64,sr);return Lu.deriveToCurve(r)},hashToScalar(s,e={DST:la}){let t=Hn(s,e.DST,64,sr);return da.create(Ve(t))},deriveToCurve(s){Ae(s,64);let e=Vn(s.subarray(0,32)),t=fa(e),r=Vn(s.subarray(32,64)),n=fa(r);return new gt(t.add(n))}});var ks=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},fr=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var ma={get(s=globalThis){let e=s.crypto;if(e?.subtle==null)throw new fr("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 ke=ma;var dr=32;var jn,Cu=(async()=>{try{return await ke.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Fu(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,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Nu(s,e,t){return pa.verify(e,t instanceof Uint8Array?t:t.subarray(),s)}async function ga(s,e,t){return jn==null&&(jn=await Cu),jn?Fu(s,e,t):Nu(s,e,t)}function pr(s){return s==null?!1:typeof s.then=="function"&&typeof s.catch=="function"&&typeof s.finally=="function"}var mr=class{type="Ed25519";raw;constructor(e){this.raw=Zn(e,dr)}toMultihash(){return Re.digest(Ge(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Te(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();let n=ga(this.raw,t,e);return pr(n)?n.then(o=>(r?.signal?.throwIfAborted(),o)):n}};function Yn(s){return s=Zn(s,dr),new mr(s)}function Zn(s,e){if(s=Uint8Array.from(s??[]),s.length!==e)throw new Y(`Key must be a Uint8Array of length ${e}, got ${s.length}`);return s}var Uu=Math.pow(2,7),Ku=Math.pow(2,14),zu=Math.pow(2,21),Xn=Math.pow(2,28),Jn=Math.pow(2,35),Qn=Math.pow(2,42),eo=Math.pow(2,49),H=128,fe=127;function Be(s){if(s<Uu)return 1;if(s<Ku)return 2;if(s<zu)return 3;if(s<Xn)return 4;if(s<Jn)return 5;if(s<Qn)return 6;if(s<eo)return 7;if(Number.MAX_SAFE_INTEGER!=null&&s>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function to(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 Hu(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 so(s,e){let t=s[e],r=0;if(r+=t&fe,t<H||(t=s[e+1],r+=(t&fe)<<7,t<H)||(t=s[e+2],r+=(t&fe)<<14,t<H)||(t=s[e+3],r+=(t&fe)<<21,t<H)||(t=s[e+4],r+=(t&fe)*Xn,t<H)||(t=s[e+5],r+=(t&fe)*Jn,t<H)||(t=s[e+6],r+=(t&fe)*Qn,t<H)||(t=s[e+7],r+=(t&fe)*eo,t<H))return r;throw new RangeError("Could not decode varint")}function Gu(s,e){let t=s.get(e),r=0;if(r+=t&fe,t<H||(t=s.get(e+1),r+=(t&fe)<<7,t<H)||(t=s.get(e+2),r+=(t&fe)<<14,t<H)||(t=s.get(e+3),r+=(t&fe)<<21,t<H)||(t=s.get(e+4),r+=(t&fe)*Xn,t<H)||(t=s.get(e+5),r+=(t&fe)*Jn,t<H)||(t=s.get(e+6),r+=(t&fe)*Qn,t<H)||(t=s.get(e+7),r+=(t&fe)*eo,t<H))return r;throw new RangeError("Could not decode varint")}function ro(s,e,t=0){return e==null&&(e=he(Be(s))),e instanceof Uint8Array?to(s,e,t):Hu(s,e,t)}function no(s,e=0){return s instanceof Uint8Array?so(s,e):Gu(s,e)}var io=new Float32Array([-0]),bt=new Uint8Array(io.buffer);function ya(s,e,t){io[0]=s,e[t]=bt[0],e[t+1]=bt[1],e[t+2]=bt[2],e[t+3]=bt[3]}function wa(s,e){return bt[0]=s[e],bt[1]=s[e+1],bt[2]=s[e+2],bt[3]=s[e+3],io[0]}var ao=new Float64Array([-0]),de=new Uint8Array(ao.buffer);function xa(s,e,t){ao[0]=s,e[t]=de[0],e[t+1]=de[1],e[t+2]=de[2],e[t+3]=de[3],e[t+4]=de[4],e[t+5]=de[5],e[t+6]=de[6],e[t+7]=de[7]}function va(s,e){return de[0]=s[e],de[1]=s[e+1],de[2]=s[e+2],de[3]=s[e+3],de[4]=s[e+4],de[5]=s[e+5],de[6]=s[e+6],de[7]=s[e+7],ao[0]}var qu=BigInt(Number.MAX_SAFE_INTEGER),Vu=BigInt(Number.MIN_SAFE_INTEGER),Me=class s{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,r=~this.hi>>>0;return t===0&&(r=r+1>>>0),-(t+r*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,r=~this.hi>>>0;return t===0&&(r=r+1>>>0),-(BigInt(t)+(BigInt(r)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(e===0n)return Pt;if(e<qu&&e>Vu)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>Ea&&(n=0n,++r>Ea&&(r=0n))),new s(Number(n),Number(r))}static fromNumber(e){if(e===0)return Pt;let t=e<0;t&&(e=-e);let r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new s(r,n)}static from(e){return typeof e=="number"?s.fromNumber(e):typeof e=="bigint"?s.fromBigInt(e):typeof e=="string"?s.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new s(e.low>>>0,e.high>>>0):Pt}},Pt=new Me(0,0);Pt.toBigInt=function(){return 0n};Pt.zzEncode=Pt.zzDecode=function(){return this};Pt.length=function(){return 1};var Ea=4294967296n;function Sa(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 _a(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 co(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 gr(s,e){return(s[e-4]|s[e-3]<<8|s[e-2]<<16|s[e-1]<<24)>>>0}var lo=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 gr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Oe(this,4);return gr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Oe(this,4);let e=wa(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Oe(this,4);let e=va(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 _a(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 Me(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw 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=gr(this.buf,this.pos+=4),t=gr(this.buf,this.pos+=4);return new Me(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=so(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 Bs(s){return new lo(s instanceof Uint8Array?s:s.subarray())}function be(s,e,t){let r=Bs(s);return e.decode(r,void 0,t)}function uo(s){let e=s??8192,t=e>>>1,r,n=e;return function(i){if(i<1||i>t)return he(i);n+i>e&&(r=he(e),n=0);let a=r.subarray(n,n+=i);return(n&7)!==0&&(n=(n|7)+1),a}}var kt=class{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}};function ho(){}var po=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Wu=uo();function $u(s){return globalThis.Buffer!=null?he(s):Wu(s)}var Ls=class{len;head;tail;states;constructor(){this.len=0,this.head=new kt(ho,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new kt(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new mo((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(br,10,Me.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Me.fromBigInt(e);return this._push(br,t.length(),t)}uint64Number(e){return this._push(to,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=Me.fromBigInt(e).zzEncode();return this._push(br,t.length(),t)}sint64Number(e){let t=Me.fromNumber(e).zzEncode();return this._push(br,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(fo,1,e?1:0)}fixed32(e){return this._push(Rs,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Me.fromBigInt(e);return this._push(Rs,4,t.lo)._push(Rs,4,t.hi)}fixed64Number(e){let t=Me.fromNumber(e);return this._push(Rs,4,t.lo)._push(Rs,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(ya,4,e)}double(e){return this._push(xa,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(fo,1,0):this.uint32(t)._push(Zu,t,e)}string(e){let t=Sa(e);return t!==0?this.uint32(t)._push(co,t,e):this._push(fo,1,0)}fork(){return this.states=new po(this),this.head=this.tail=new kt(ho,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 kt(ho,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=$u(this.len),r=0;for(;e!=null;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}};function fo(s,e,t){e[t]=s&255}function ju(s,e,t){for(;s>127;)e[t++]=s&127|128,s>>>=7;e[t]=s}var mo=class extends kt{next;constructor(e,t){super(ju,e,t),this.next=void 0}};function br(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 Rs(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 Zu(s,e,t){e.set(s,t)}globalThis.Buffer!=null&&(Ls.prototype.bytes=function(s){let e=s.length>>>0;return this.uint32(e),e>0&&this._push(Yu,e,s),this},Ls.prototype.string=function(s){let e=globalThis.Buffer.byteLength(s);return this.uint32(e),e>0&&this._push(Xu,e,s),this});function Yu(s,e,t){e.set(s,t)}function Xu(s,e,t){s.length<40?co(s,e,t):e.utf8Write!=null?e.utf8Write(s,t):e.set(V(s),t)}function go(){return new Ls}function ye(s,e){let t=go();return e.encode(s,t,{lengthDelimited:!1}),t.finish()}function*we(s,e,t){let r=Bs(s);yield*e.stream(r,void 0,"$",t)}var yr={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function wr(s,e,t,r,n){return{name:s,type:e,encode:t,decode:r,stream:n}}function bo(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 wr("enum",yr.VARINT,t,r,n)}function xe(s,e,t){return wr("message",yr.LENGTH_DELIMITED,s,e,t)}var W=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var j;(function(s){s.RSA="RSA",s.Ed25519="Ed25519",s.secp256k1="secp256k1",s.ECDSA="ECDSA"})(j||(j={}));var yo;(function(s){s[s.RSA=0]="RSA",s[s.Ed25519=1]="Ed25519",s[s.secp256k1=2]="secp256k1",s[s.ECDSA=3]="ECDSA"})(yo||(yo={}));(function(s){s.codec=()=>bo(yo)})(j||(j={}));var We;(function(s){let e;s.codec=()=>(e==null&&(e=xe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),j.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=j.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:j.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 ye(o,s.codec())}s.encode=t;function r(o,i){return be(o,s.codec(),i)}s.decode=r;function n(o,i){return we(o,s.codec(),i)}s.stream=n})(We||(We={}));var wo;(function(s){let e;s.codec=()=>(e==null&&(e=xe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),j.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=j.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:j.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 ye(o,s.codec())}s.encode=t;function r(o,i){return be(o,s.codec(),i)}s.decode=r;function n(o,i){return we(o,s.codec(),i)}s.stream=n})(wo||(wo={}));var Fs={};Ie(Fs,{MAX_RSA_KEY_SIZE:()=>xo,generateRSAKeyPair:()=>Pa,jwkToJWKKeyPair:()=>ka,jwkToPkcs1:()=>th,jwkToPkix:()=>_o,jwkToRSAPrivateKey:()=>Ao,pkcs1MessageToJwk:()=>Eo,pkcs1MessageToRSAPrivateKey:()=>Io,pkcs1ToJwk:()=>eh,pkcs1ToRSAPrivateKey:()=>Ma,pkixMessageToJwk:()=>So,pkixMessageToRSAPublicKey:()=>Do,pkixToJwk:()=>sh,pkixToRSAPublicKey:()=>To});var ss=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Fs.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ce.createV1(114,this._multihash)}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Te(this.raw,e.raw)}verify(e,t,r){return Aa(this.jwk,t,e,r)}},Cs=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Fs.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Te(this.raw,e.raw)}sign(e,t){return Da(this.jwk,e,t)}};var xo=8192,vo=18,Ju=1062,Qu=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function eh(s){let e=Je(s);return Eo(e)}function Eo(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 th(s){if(s.n==null||s.e==null||s.d==null||s.p==null||s.q==null||s.dp==null||s.dq==null||s.qi==null)throw new Y("JWK was missing components");return ct([De(Uint8Array.from([0])),De(V(s.n,"base64url")),De(V(s.e,"base64url")),De(V(s.d,"base64url")),De(V(s.p,"base64url")),De(V(s.q,"base64url")),De(V(s.dp,"base64url")),De(V(s.dq,"base64url")),De(V(s.qi,"base64url"))]).subarray()}function sh(s){let e=Je(s,{offset:0});return So(e)}function So(s){let e=Je(s[1],{offset:0});return{kty:"RSA",n:q(e[0],"base64url"),e:q(e[1],"base64url")}}function _o(s){if(s.n==null||s.e==null)throw new Y("JWK was missing components");return ct([Qu,Ys(ct([De(V(s.n,"base64url")),De(V(s.e,"base64url"))]))]).subarray()}function Ma(s){let e=Je(s);return Io(e)}function Io(s){let e=Eo(s);return Ao(e)}function To(s,e){if(s.byteLength>=Ju)throw new Ot("Key size is too large");let t=Je(s,{offset:0});return Do(t,s,e)}function Do(s,e,t){let r=So(s);if(t==null){let n=$t(We.encode({Type:j.RSA,Data:e}));t=He(vo,n)}return new ss(r,t)}function Ao(s){if(Ra(s)>xo)throw new Y("Key size is too large");let e=ka(s),t=$t(We.encode({Type:j.RSA,Data:_o(e.publicKey)})),r=He(vo,t);return new Cs(e.privateKey,new ss(e.publicKey,r))}async function Pa(s){if(s>xo)throw new Y("Key size is too large");let e=await Ba(s),t=$t(We.encode({Type:j.RSA,Data:_o(e.publicKey)})),r=He(vo,t);return new Cs(e.privateKey,new ss(e.publicKey,r))}function ka(s){if(s==null)throw new Y("Missing key parameter");return{privateKey:s,publicKey:{kty:s.kty,n:s.n,e:s.e}}}async function Ba(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 rh(t,e);return{privateKey:r[0],publicKey:r[1]}}async function Da(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,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(n,0,n.byteLength)}async function Aa(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,e,t instanceof Uint8Array?t:t.subarray());return r?.signal?.throwIfAborted(),o}async function rh(s,e){if(s.privateKey==null||s.publicKey==null)throw new Y("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 Ra(s){if(s.kty!=="RSA")throw new Y("invalid key type");if(s.n==null)throw new Y("invalid key modulus");return V(s.n,"base64url").length*8}var xr=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Xs(e),Ae(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,n=new Uint8Array(r);n.set(t.length>r?e.create().update(t).digest():t);for(let 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),et(n)}update(e){return Wt(this),this.iHash.update(e),this}digestInto(e){Wt(this),Js(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()}},La=(()=>{let s=((e,t,r)=>new xr(e,t).update(r).digest());return s.create=(e,t)=>new xr(e,t),s})();var Ca=(s,e)=>(s+(s>=0?e:-e)/Fa)/e;function nh(s,e,t){Yt("scalar",s,$e,t);let[[r,n],[o,i]]=e,a=Ca(i*s,t),l=Ca(-n*s,t),u=s-a*r-l*o,p=-a*n-l*i,m=u<$e,E=p<$e;m&&(u=-u),E&&(p=-p);let w=Ds(Math.ceil(Xt(t)/2))+yt;if(u<$e||u>=w||p<$e||p>=w)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:m,k1:u,k2neg:E,k2:p}}function Po(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function Mo(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&&Po(t.format),t}var ko=class extends Error{constructor(e=""){super(e)}},Ue={Err:ko,_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=Is(r);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let o=r>127?Is(n.length/2|128):"";return Is(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(or(s),s<$e)throw new e("integer: negative integers are not allowed");let t=Is(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 Tt(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 $e=BigInt(0),yt=BigInt(1),Fa=BigInt(2),vr=BigInt(3),oh=BigInt(4);function Na(s,e={}){let t=lr("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=Ua(r,n);function m(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function E(N,_,T){if(u&&_.is0())return Uint8Array.of(0);let{x:M,y:A}=_.toAffine(),D=r.toBytes(M);if(Ce(T,"isCompressed"),T){m();let P=!r.isOdd(A);return re(Oa(P),D)}else return re(Uint8Array.of(4),D,r.toBytes(A))}function w(N){K(N,void 0,"Point");let{publicKey:_,publicKeyUncompressed:T}=p,M=N.length,A=N[0],D=N.subarray(1);if(u&&M===1&&A===0)return{x:r.ZERO,y:r.ZERO};if(M===_&&(A===2||A===3)){let P=r.fromBytes(D);if(!r.isValid(P))throw new Error("bad point: is not on curve, wrong x");let R=g(P),B;try{B=r.sqrt(R)}catch(U){let z=U instanceof Error?": "+U.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}m();let L=r.isOdd(B);return(A&1)===1!==L&&(B=r.neg(B)),{x:P,y:B}}else if(M===T&&A===4){let P=r.BYTES,R=r.fromBytes(D.subarray(0,P)),B=r.fromBytes(D.subarray(P,P*2));if(!x(R,B))throw new Error("bad point: is not on curve");return{x:R,y:B}}else throw new Error(`bad point: got length ${M}, expected compressed=${_} or uncompressed=${T}`)}let h=e.toBytes===void 0?E:e.toBytes,b=e.fromBytes===void 0?w:e.fromBytes;function g(N){let _=r.sqr(N),T=r.mul(_,N);return r.add(r.add(T,r.mul(N,o.a)),o.b)}function x(N,_){let T=r.sqr(_),M=g(N);return r.eql(T,M)}if(!x(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let I=r.mul(r.pow(o.a,vr),oh),c=r.mul(r.sqr(o.b),BigInt(27));if(r.is0(r.add(I,c)))throw new Error("bad curve params: a or b");function f(N,_,T=!1){if(!r.isValid(_)||T&&r.is0(_))throw new Error(`bad point coordinate ${N}`);return _}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 nh(N,l.basises,n.ORDER)}function v(N,_,T,M,A){return T=new S(r.mul(T.X,N),T.Y,T.Z),_=Ms(M,_),T=Ms(A,T),_.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(_,T,M){this.X=f("x",_),this.Y=f("y",T,!0),this.Z=f("z",M),Object.freeze(this)}static CURVE(){return o}static fromAffine(_){let{x:T,y:M}=_||{};if(!_||!r.isValid(T)||!r.isValid(M))throw new Error("invalid affine point");if(_ instanceof S)throw new Error("projective point not allowed");return r.is0(T)&&r.is0(M)?S.ZERO:new S(T,M,r.ONE)}static fromBytes(_){let T=S.fromAffine(b(K(_,void 0,"point")));return T.assertValidity(),T}static fromHex(_){return S.fromBytes(Zt(_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,T=!0){return C.createCache(this,_),T||this.multiply(vr),this}assertValidity(){let _=this;if(_.is0()){if(e.allowInfinityPoint&&r.is0(_.X)&&r.eql(_.Y,r.ONE)&&r.is0(_.Z))return;throw new Error("bad point: ZERO")}let{x:T,y:M}=_.toAffine();if(!r.isValid(T)||!r.isValid(M))throw new Error("bad point: x or y not field elements");if(!x(T,M))throw new Error("bad point: equation left != right");if(!_.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:_}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(_)}equals(_){d(_);let{X:T,Y:M,Z:A}=this,{X:D,Y:P,Z:R}=_,B=r.eql(r.mul(T,R),r.mul(D,A)),L=r.eql(r.mul(M,R),r.mul(P,A));return B&&L}negate(){return new S(this.X,r.neg(this.Y),this.Z)}double(){let{a:_,b:T}=o,M=r.mul(T,vr),{X:A,Y:D,Z:P}=this,R=r.ZERO,B=r.ZERO,L=r.ZERO,F=r.mul(A,A),U=r.mul(D,D),z=r.mul(P,P),O=r.mul(A,D);return O=r.add(O,O),L=r.mul(A,P),L=r.add(L,L),R=r.mul(_,L),B=r.mul(M,z),B=r.add(R,B),R=r.sub(U,B),B=r.add(U,B),B=r.mul(R,B),R=r.mul(O,R),L=r.mul(M,L),z=r.mul(_,z),O=r.sub(F,z),O=r.mul(_,O),O=r.add(O,L),L=r.add(F,F),F=r.add(L,F),F=r.add(F,z),F=r.mul(F,O),B=r.add(B,F),z=r.mul(D,P),z=r.add(z,z),F=r.mul(z,O),R=r.sub(R,F),L=r.mul(z,U),L=r.add(L,L),L=r.add(L,L),new S(R,B,L)}add(_){d(_);let{X:T,Y:M,Z:A}=this,{X:D,Y:P,Z:R}=_,B=r.ZERO,L=r.ZERO,F=r.ZERO,U=o.a,z=r.mul(o.b,vr),O=r.mul(T,D),se=r.mul(M,P),ne=r.mul(A,R),oe=r.add(T,M),ee=r.add(D,P);oe=r.mul(oe,ee),ee=r.add(O,se),oe=r.sub(oe,ee),ee=r.add(T,A);let _e=r.add(D,R);return ee=r.mul(ee,_e),_e=r.add(O,ne),ee=r.sub(ee,_e),_e=r.add(M,A),B=r.add(P,R),_e=r.mul(_e,B),B=r.add(se,ne),_e=r.sub(_e,B),F=r.mul(U,ee),B=r.mul(z,ne),F=r.add(B,F),B=r.sub(se,F),F=r.add(se,F),L=r.mul(B,F),se=r.add(O,O),se=r.add(se,O),ne=r.mul(U,ne),ee=r.mul(z,ee),se=r.add(se,ne),ne=r.sub(O,ne),ne=r.mul(U,ne),ee=r.add(ee,ne),O=r.mul(se,ee),L=r.add(L,O),O=r.mul(_e,ee),B=r.mul(oe,B),B=r.sub(B,O),O=r.mul(oe,se),F=r.mul(_e,F),F=r.add(F,O),new S(B,L,F)}subtract(_){return d(_),this.add(_.negate())}is0(){return this.equals(S.ZERO)}multiply(_){let{endo:T}=e;if(!n.isValidNot0(_))throw new RangeError("invalid scalar: out of range");let M,A,D=P=>C.cached(this,P,R=>Mt(S,R));if(T){let{k1neg:P,k1:R,k2neg:B,k2:L}=y(_),{p:F,f:U}=D(R),{p:z,f:O}=D(L);A=U.add(O),M=v(T.beta,F,z,P,B)}else{let{p:P,f:R}=D(_);M=P,A=R}return Mt(S,[M,A])[0]}multiplyUnsafe(_){let{endo:T}=e,M=this,A=_;if(!n.isValid(A))throw new RangeError("invalid scalar: out of range");if(A===$e||M.is0())return S.ZERO;if(A===yt)return M;if(C.hasCache(this))return this.multiply(A);if(T){let{k1neg:D,k1:P,k2neg:R,k2:B}=y(A),{p1:L,p2:F}=ia(S,M,P,B);return v(T.beta,L,F,D,R)}else return C.unsafe(M,A)}toAffine(_){let T=this,M=_,{X:A,Y:D,Z:P}=T;if(r.eql(P,r.ONE))return{x:A,y:D};let R=T.is0();M==null&&(M=R?r.ONE:r.inv(P));let B=r.mul(A,M),L=r.mul(D,M),F=r.mul(P,M);if(R)return{x:r.ZERO,y:r.ZERO};if(!r.eql(F,r.ONE))throw new Error("invZ was invalid");return{x:B,y:L}}isTorsionFree(){let{isTorsionFree:_}=e;return i===yt?!0:_?_(S,this):C.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:_}=e;return i===yt?this:_?_(S,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===yt?this.is0():this.clearCofactor().is0()}toBytes(_=!0){return Ce(_,"isCompressed"),this.assertValidity(),h(S,this,_)}toHex(_=!0){return jt(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let k=n.BITS,C=new es(S,e.endo?Math.ceil(k/2):k);return k>=8&&S.BASE.precompute(8),Object.freeze(S.prototype),Object.freeze(S),S}function Oa(s){return Uint8Array.of(s?2:3)}function Ua(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function ih(s,e={}){let{Fn:t}=s,r=e.randomBytes===void 0?_s:e.randomBytes,n=Object.assign(Ua(s.Fp,t),{seed:Math.max(Fn(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:b,publicKeyUncompressed:g}=n;try{let x=w.length;return h===!0&&x!==b||h===!1&&x!==g?!1:!!s.fromBytes(w)}catch{return!1}}function a(w){return w=w===void 0?r(n.seed):w,Nn(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:b,publicKeyUncompressed:g}=n,x=t._lengths;if(!It(w))return;let I=K(w,void 0,"key").length,c=I===b||I===g,f=I===h||!!x?.includes(I);if(!(c&&f))return c}function p(w,h,b=!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 g=t.fromBytes(w);return s.fromBytes(h).multiply(g).toBytes(b)}let m={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},E=ur(a,l);return Object.freeze(m),Object.freeze(n),Object.freeze({getPublicKey:l,getSharedSecret:p,keygen:E,Point:s,utils:m,lengths:n})}function Ka(s,e,t={}){let r=e;Xs(r),Ne(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes===void 0?_s:t.randomBytes,o=t.hmac===void 0?(A,D)=>La(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}=ih(s,t),b={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},g=l*Fa+yt<i.ORDER;function x(A){let D=l>>yt;return A>D}function I(A,D){if(!a.isValidNot0(D))throw new Error(`invalid signature ${A}: out of range 1..Point.Fn.ORDER`);return D}function c(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function f(A,D){Po(D);let P=h.signature,R=D==="compact"?P:D==="recovered"?P+1:void 0;return K(A,R)}class d{r;s;recovery;constructor(D,P,R){if(this.r=I("r",D),this.s=I("s",P),R!=null){if(c(),![0,1,2,3].includes(R))throw new Error("invalid recovery id");this.recovery=R}Object.freeze(this)}static fromBytes(D,P=b.format){f(D,P);let R;if(P==="der"){let{r:U,s:z}=Ue.toSig(K(D));return new d(U,z)}P==="recovered"&&(R=D[0],P="compact",D=D.subarray(1));let B=h.signature/2,L=D.subarray(0,B),F=D.subarray(B,B*2);return new d(a.fromBytes(L),a.fromBytes(F),R)}static fromHex(D,P){return this.fromBytes(Zt(D),P)}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:P,s:R}=this,B=this.assertRecovery(),L=B===2||B===3?P+l:P;if(!i.isValid(L))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let F=i.toBytes(L),U=s.fromBytes(re(Oa((B&1)===0),F)),z=a.inv(L),O=v(K(D,void 0,"msgHash")),se=a.create(-O*z),ne=a.create(R*z),oe=s.BASE.multiplyUnsafe(se).add(U.multiplyUnsafe(ne));if(oe.is0())throw new Error("invalid recovery: point at infinify");return oe.assertValidity(),oe}hasHighS(){return x(this.s)}toBytes(D=b.format){if(Po(D),D==="der")return Zt(Ue.hexFromSig(this));let{r:P,s:R}=this,B=a.toBytes(P),L=a.toBytes(R);return D==="recovered"?(c(),re(Uint8Array.of(this.assertRecovery()),B,L)):re(B,L)}toHex(D){return jt(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 P=Tt(D),R=D.length*8-u;return R>0?P>>BigInt(R):P}:t.bits2int,v=t.bits2int_modN===void 0?function(D){return a.create(y(D))}:t.bits2int_modN,S=Ds(u);function k(A){return Yt("num < 2^"+u,A,$e,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,P){let{lowS:R,prehash:B,extraEntropy:L}=Mo(P,b);A=C(A,B);let F=v(A),U=a.fromBytes(D);if(!a.isValidNot0(U))throw new Error("invalid private key");let z=[k(U),k(F)];if(L!=null&&L!==!1){let oe=L===!0?n(h.secretKey):L;z.push(K(oe,void 0,"extraEntropy"))}let O=re(...z),se=F;function ne(oe){let ee=y(oe);if(!a.isValidNot0(ee))return;let _e=a.inv(ee),Ft=s.BASE.multiply(ee).toAffine(),ds=a.create(Ft.x);if(ds===$e)return;let Hs=a.create(_e*a.create(se+ds*U));if(Hs===$e)return;let Vo=(Ft.x===ds?0:2)|Number(Ft.y&yt),Wo=Hs;return R&&x(Hs)&&(Wo=a.neg(Hs),Vo^=1),new d(ds,Wo,g?void 0:Vo)}return{seed:O,k2sig:ne}}function _(A,D,P={}){let{seed:R,k2sig:B}=N(A,D,P);return Gi(r.outputLen,a.BYTES,o)(R,B).toBytes(P.format)}function T(A,D,P,R={}){let{lowS:B,prehash:L,format:F}=Mo(R,b);if(P=K(P,void 0,"publicKey"),D=C(D,L),!It(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(P);if(B&&U.hasHighS())return!1;let{r:O,s:se}=U,ne=v(D),oe=a.inv(se),ee=a.create(ne*oe),_e=a.create(O*oe),Ft=s.BASE.multiplyUnsafe(ee).add(z.multiplyUnsafe(_e));return Ft.is0()?!1:a.create(Ft.x)===O}catch{return!1}}function M(A,D,P={}){let{prehash:R}=Mo(P,b);return D=C(D,R),d.fromBytes(A,"recovered").recoverPublicKey(D).toBytes()}return Object.freeze({keygen:p,getPublicKey:m,getSharedSecret:E,utils:w,lengths:h,Point:s,sign:_,verify:T,recoverPublicKey:M,Signature:d,hash:r})}var Ro={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},ah={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var za=BigInt(2);function ch(s){let e=Ro.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,za,e)*u%e,h=$(w,n,e)*w%e,b=$(h,o,e)*h%e,g=$(b,a,e)*b%e,x=$(g,l,e)*g%e,I=$(x,a,e)*b%e,c=$(I,t,e)*p%e,f=$(c,i,e)*h%e,d=$(f,r,e)*u%e,y=$(d,za,e);if(!Bo.eql(Bo.sqr(y),s))throw new Error("Cannot find square root");return y}var Bo=Jt(Ro.p,{sqrt:ch}),lh=Na(Ro,{Fp:Bo,endo:ah}),rs=Ka(lh,$t);function Ha(s,e,t,r){let n=Et.digest(t instanceof Uint8Array?t:t.subarray());if(pr(n))return n.then(({digest:o})=>(r?.signal?.throwIfAborted(),rs.verify(e,o,s,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new ks(String(o))});try{return r?.signal?.throwIfAborted(),rs.verify(e,n.digest,s,{prehash:!1,format:"der"})}catch(o){throw new ks(String(o))}}var Er=class{type="secp256k1";raw;_key;constructor(e){this._key=qa(e),this.raw=Ga(this._key)}toMultihash(){return Re.digest(Ge(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Te(this.raw,e.raw)}verify(e,t,r){return Ha(this._key,t,e,r)}};function Lo(s){return new Er(s)}function Ga(s){return rs.Point.fromBytes(s).toBytes()}function qa(s){try{return rs.Point.fromBytes(s),s}catch(e){throw new Ot(String(e))}}function Sr(s,e){let{Type:t,Data:r}=We.decode(s),n=r??new Uint8Array;switch(t){case j.RSA:return To(n,e);case j.Ed25519:return Yn(n);case j.secp256k1:return Lo(n);case j.ECDSA:return wn(n);default:throw new Ut}}function Va(s){let{Type:e,Data:t}=We.decode(s.digest),r=t??new Uint8Array;switch(e){case j.Ed25519:return Yn(r);case j.secp256k1:return Lo(r);case j.ECDSA:return wn(r);default:throw new Ut}}function Ge(s){return We.encode({Type:j[s.type],Data:s.raw})}var Wa=Symbol.for("nodejs.util.inspect.custom"),uh=114,Ns=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()})`}[qr]=!0;toString(){return this.string==null&&(this.string=J.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ce.createV1(uh,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Te(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Te(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Wa](){return`PeerId(${this.toString()})`}},_r=class extends Ns{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Ir=class extends Ns{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Tr=class extends Ns{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},hh=2336,Os=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Re.digest(V(this.url))}[Wa](){return`PeerId(${this.url})`}[qr]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ce.createV1(hh,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=q(e)),e.toString()===this.toString())}};var fh=114,$a=2336;function Bt(s,e){let t;if(s.charAt(0)==="1"||s.charAt(0)==="Q")t=Ye(J.decode(`z${s}`));else{if(s.startsWith("k51qzi5uqu5")||s.startsWith("kzwfwjn5ji4")||s.startsWith("k2k4r8")||s.startsWith("bafz"))return dh(ce.parse(s));if(e==null)throw new Y('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ye(e.decode(s))}return ns(t)}function ns(s){if(mh(s))return new _r({multihash:s});if(ph(s))try{let e=Va(s);if(e.type==="Ed25519")return new Ir({multihash:s,publicKey:e});if(e.type==="secp256k1")return new Tr({multihash:s,publicKey:e})}catch{let t=q(s.digest);return new Os(new URL(t))}throw new Vs("Supplied PeerID Multihash is invalid")}function dh(s){if(s?.multihash==null||s.version==null||s.version===1&&s.code!==fh&&s.code!==$a)throw new qs("Supplied PeerID CID is invalid");if(s.code===$a){let e=q(s.multihash.digest);return new Os(new URL(e))}return ns(s.multihash)}function ph(s){return s.code===Re.code}function mh(s){return s.code===Et.code}var Dr=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},os=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ar=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Us=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Mr(s){return s[Symbol.asyncIterator]!=null}function ja(s,e){if(s.byteLength>e)throw new os("Message length too long")}var kr=s=>{let e=Be(s),t=he(e);return ro(s,t),kr.bytes=e,t};kr.bytes=0;function is(s,e){e=e??{};let t=e.lengthEncoder??kr,r=e?.maxDataLength??4194304;function*n(o){ja(o,r);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return Mr(s)?(async function*(){for await(let o of s)yield*n(o)})():(function*(){for(let o of s)yield*n(o)})()}is.single=(s,e)=>{e=e??{};let t=e.lengthEncoder??kr,r=e?.maxDataLength??4194304;return ja(s,r),new ie(t(s.byteLength),s)};var Rt;(function(s){s[s.LENGTH=0]="LENGTH",s[s.DATA=1]="DATA"})(Rt||(Rt={}));var Co=s=>{let e=no(s);return Co.bytes=Be(e),e};Co.bytes=0;function Ks(s,e){let t=new ie,r=Rt.LENGTH,n=-1,o=e?.lengthDecoder??Co,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*l(){for(;t.byteLength>0;){if(r===Rt.LENGTH)try{if(n=o(t),n<0)throw new Dr("Invalid message length");if(n>a)throw new os("Message length too long");let u=o.bytes;t.consume(u),e?.onLength!=null&&e.onLength(n),r=Rt.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new Ar("Message length length too long");break}throw u}if(r===Rt.DATA){if(t.byteLength<n)break;let u=t.sublist(0,n);t.consume(n),e?.onData!=null&&e.onData(u),yield u,r=Rt.LENGTH}}}return Mr(s)?(async function*(){for await(let u of s)t.append(u),yield*l();if(t.byteLength>0)throw new Us("Unexpected end of input")})():(function*(){for(let u of s)t.append(u),yield*l();if(t.byteLength>0)throw new Us("Unexpected end of input")})()}Ks.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 Ks(r,{...e??{},onLength:o=>{t=o}})};function nt(){let s={};return s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),s}var Br=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}},as=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Br(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 Br(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 Fo=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Lt(s={}){return bh(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 bh(s,e){e=e??{};let t=e.onEnd,r=new as,n,o,i,a=nt(),l=async()=>{try{return r.isEmpty()?i?{done:!0}:await new Promise((g,x)=>{o=I=>{o=null,r.push(I);try{g(s(r))}catch(c){x(c)}return n}}):s(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=nt()})}},u=g=>o!=null?o(g):(r.push(g),n),p=g=>(r=new as,o!=null?o({error:g}):(r.push({error:g}),n)),m=g=>{if(i)return n;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:g})},E=g=>i?n:(i=!0,g!=null?p(g):u({done:!0})),w=()=>(r=new as,E(),{done:!0}),h=g=>(E(g),{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 g=>{let x=g?.signal;if(x?.throwIfAborted(),r.isEmpty())return;let I,c;x!=null&&(I=new Promise((f,d)=>{c=()=>{d(new Fo)},x.addEventListener("abort",c)}));try{await Promise.race([a.promise,I])}finally{c!=null&&x!=null&&x?.removeEventListener("abort",c)}}},t==null)return n;let b=n;return n={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(g){return b.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return b.return(),t!=null&&(t(),t=void 0),{done:!0}},push:m,end(g){return b.end(g),t!=null&&(t(g),t=void 0),n},get readableLength(){return b.readableLength},onEmpty:g=>b.onEmpty(g)},n}function yh(s){return s.reason}async function No(s,e,t){if(e==null)return s;let r=t?.translateError??yh;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 Oo=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=nt(),this.haveNext=nt()}[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=nt(),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=nt(),await No(this.readNext.promise,t?.signal,t)}};function Za(){return new Oo}function wh(s){return s[Symbol.asyncIterator]!=null}async function xh(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*vh(s){let e=new AbortController,t=Za();xh(s,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Eh(s){for(let e of s)yield*e}function Sh(...s){let e=[];for(let t of s)wh(t)||e.push(t);return e.length===s.length?Eh(e):vh(s)}var Ya=Sh;function zs(s,...e){if(s==null)throw new Error("Empty pipeline");if(Uo(s)){let r=s;s=()=>r.source}else if(Ja(s)||Xa(s)){let r=s;s=()=>r}let t=[s,...e];if(t.length>1&&Uo(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++)Uo(t[r])&&(t[r]=Ih(t[r]));return _h(...t)}var _h=(...s)=>{let e;for(;s.length>0;)e=s.shift()(e);return e},Xa=s=>s?.[Symbol.asyncIterator]!=null,Ja=s=>s?.[Symbol.iterator]!=null,Uo=s=>s==null?!1:s.sink!=null&&s.source!=null,Ih=s=>e=>{let t=s.sink(e);if(t?.then!=null){let r=Lt({objectMode:!0});t.then(()=>{r.end()},i=>{r.end(i)});let n,o=s.source;if(Xa(o))n=async function*(){yield*o,r.end()};else if(Ja(o))n=function*(){yield*o,r.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Ya(r,n())}return s.source};var Qa={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxIdontwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};var ot;(function(s){let e;(function(h){let b;h.codec=()=>(b==null&&(b=xe((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}}}})),b);function g(c){return ye(c,h.codec())}h.encode=g;function x(c,f){return be(c,h.codec(),f)}h.decode=x;function I(c,f){return we(c,h.codec(),f)}h.stream=I})(e=s.SubOpts||(s.SubOpts={}));let t;(function(h){let b;h.codec=()=>(b==null&&(b=xe((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}}}})),b);function g(c){return ye(c,h.codec())}h.encode=g;function x(c,f){return be(c,h.codec(),f)}h.decode=x;function I(c,f){return we(c,h.codec(),f)}h.stream=I})(t=s.Message||(s.Message={}));let r;(function(h){let b;h.codec=()=>(b==null&&(b=xe((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 k=c.uint32();switch(k>>>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(k&7);break}}}})),b);function g(c){return ye(c,h.codec())}h.encode=g;function x(c,f){return be(c,h.codec(),f)}h.decode=x;function I(c,f){return we(c,h.codec(),f)}h.stream=I})(r=s.ControlMessage||(s.ControlMessage={}));let n;(function(h){let b;h.codec=()=>(b==null&&(b=xe((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 k=c.uint32();switch(k>>>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(k&7);break}}}})),b);function g(c){return ye(c,h.codec())}h.encode=g;function x(c,f){return be(c,h.codec(),f)}h.decode=x;function I(c,f){return we(c,h.codec(),f)}h.stream=I})(n=s.ControlIHave||(s.ControlIHave={}));let o;(function(h){let b;h.codec=()=>(b==null&&(b=xe((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 k=c.uint32();switch(k>>>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(k&7);break}}}})),b);function g(c){return ye(c,h.codec())}h.encode=g;function x(c,f){return be(c,h.codec(),f)}h.decode=x;function I(c,f){return we(c,h.codec(),f)}h.stream=I})(o=s.ControlIWant||(s.ControlIWant={}));let i;(function(h){let b;h.codec=()=>(b==null&&(b=xe((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)}})),b);function g(c){return ye(c,h.codec())}h.encode=g;function x(c,f){return be(c,h.codec(),f)}h.decode=x;function I(c,f){return we(c,h.codec(),f)}h.stream=I})(i=s.ControlGraft||(s.ControlGraft={}));let a;(function(h){let b;h.codec=()=>(b==null&&(b=xe((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 k=c.uint32();switch(k>>>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(k&7);break}}}})),b);function g(c){return ye(c,h.codec())}h.encode=g;function x(c,f){return be(c,h.codec(),f)}h.decode=x;function I(c,f){return we(c,h.codec(),f)}h.stream=I})(a=s.ControlPrune||(s.ControlPrune={}));let l;(function(h){let b;h.codec=()=>(b==null&&(b=xe((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}}}})),b);function g(c){return ye(c,h.codec())}h.encode=g;function x(c,f){return be(c,h.codec(),f)}h.decode=x;function I(c,f){return we(c,h.codec(),f)}h.stream=I})(l=s.PeerInfo||(s.PeerInfo={}));let u;(function(h){let b;h.codec=()=>(b==null&&(b=xe((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 k=c.uint32();switch(k>>>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(k&7);break}}}})),b);function g(c){return ye(c,h.codec())}h.encode=g;function x(c,f){return be(c,h.codec(),f)}h.decode=x;function I(c,f){return we(c,h.codec(),f)}h.stream=I})(u=s.ControlIDontWant||(s.ControlIDontWant={}));let p;s.codec=()=>(p==null&&(p=xe((h,b,g={})=>{if(g.lengthDelimited!==!1&&b.fork(),h.subscriptions!=null&&h.subscriptions.length>0)for(let x of h.subscriptions)b.uint32(10),s.SubOpts.codec().encode(x,b);if(h.messages!=null&&h.messages.length>0)for(let x of h.messages)b.uint32(18),s.Message.codec().encode(x,b);h.control!=null&&(b.uint32(26),s.ControlMessage.codec().encode(h.control,b)),g.lengthDelimited!==!1&&b.ldelim()},(h,b,g={})=>{let x={subscriptions:[],messages:[]},I=b==null?h.len:h.pos+b;for(;h.pos<I;){let c=h.uint32();switch(c>>>3){case 1:{if(g.limits?.subscriptions!=null&&x.subscriptions.length===g.limits.subscriptions)throw new W('Decode error - repeated field "subscriptions" had too many elements');x.subscriptions.push(s.SubOpts.codec().decode(h,h.uint32(),{limits:g.limits?.subscriptions$}));break}case 2:{if(g.limits?.messages!=null&&x.messages.length===g.limits.messages)throw new W('Decode error - repeated field "messages" had too many elements');x.messages.push(s.Message.codec().decode(h,h.uint32(),{limits:g.limits?.messages$}));break}case 3:{x.control=s.ControlMessage.codec().decode(h,h.uint32(),{limits:g.limits?.control});break}default:{h.skipType(c&7);break}}}return x},function*(h,b,g,x={}){let I={subscriptions:0,messages:0},c=b==null?h.len:h.pos+b;for(;h.pos<c;){let f=h.uint32();switch(f>>>3){case 1:{if(x.limits?.subscriptions!=null&&I.subscriptions===x.limits.subscriptions)throw new W('Streaming decode error - repeated field "subscriptions" had too many elements');for(let d of s.SubOpts.codec().stream(h,h.uint32(),`${g}.subscriptions[]`,{limits:x.limits?.subscriptions$}))yield{...d,index:I.subscriptions};I.subscriptions++;break}case 2:{if(x.limits?.messages!=null&&I.messages===x.limits.messages)throw new W('Streaming decode error - repeated field "messages" had too many elements');for(let d of s.Message.codec().stream(h,h.uint32(),`${g}.messages[]`,{limits:x.limits?.messages$}))yield{...d,index:I.messages};I.messages++;break}case 3:{yield*s.ControlMessage.codec().stream(h,h.uint32(),`${g}.control`,{limits:x.limits?.control});break}default:{h.skipType(f&7);break}}}})),p);function m(h){return ye(h,s.codec())}s.encode=m;function E(h,b){return be(h,s.codec(),b)}s.decode=E;function w(h,b){return we(h,s.codec(),b)}s.stream=w})(ot||(ot={}));var Rr=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 ec;(function(s){s.StrictSign="StrictSign",s.StrictNoSign="StrictNoSign"})(ec||(ec={}));var wt;(function(s){s[s.Signing=0]="Signing",s[s.Anonymous=1]="Anonymous"})(wt||(wt={}));var ve;(function(s){s.Error="error",s.Ignore="ignore",s.Reject="reject",s.Blacklisted="blacklisted"})(ve||(ve={}));var pe;(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"})(pe||(pe={}));var me;(function(s){s.duplicate="duplicate",s.invalid="invalid",s.valid="valid"})(me||(me={}));function Ko(s){switch(s){case ge.Ignore:return ve.Ignore;case ge.Reject:return ve.Reject;default:throw new Error("Unreachable")}}var tc;(function(s){s.forward="forward",s.publish="publish"})(tc||(tc={}));var Ee;(function(s){s.Fanout="fanout",s.Random="random",s.Subscribed="subscribed",s.Outbound="outbound",s.NotEnough="not_enough",s.Opportunistic="opportunistic"})(Ee||(Ee={}));var Ke;(function(s){s.Dc="disconnected",s.BadScore="bad_score",s.Prune="prune",s.Excess="excess"})(Ke||(Ke={}));var ls;(function(s){s.GraftBackoff="graft_backoff",s.BrokenPromise="broken_promise",s.MessageDeficit="message_deficit",s.IPColocation="IP_colocation"})(ls||(ls={}));var us;(function(s){s.LowScore="low_score",s.MaxIhave="max_ihave",s.MaxIasked="max_iasked"})(us||(us={}));var cs;(function(s){s.graylist="graylist",s.publish="publish",s.gossip="gossip",s.mesh="mesh"})(cs||(cs={}));function sc(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 Ee.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:i},o);break;case Ee.Random:this.meshPeerInclusionEventsRandom.inc({topic:i},o);break;case Ee.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:i},o);break;case Ee.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:i},o);break;case Ee.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:i},o);break;case Ee.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 ge.Accept:this.acceptedMessagesTotal.inc({topic:i});break;case ge.Ignore:this.ignoredMessagesTotal.inc({topic:i});break;case ge.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 me.duplicate:this.prevalidationDuplicateTotal.inc({topic:o});break;case me.invalid:this.prevalidationInvalidTotal.inc({topic:o});break;case me.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===ve.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:cs.graylist},o),this.peersByScoreThreshold.set({threshold:cs.publish},i),this.peersByScoreThreshold.set({threshold:cs.gossip},a),this.peersByScoreThreshold.set({threshold:cs.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 Th={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},Dh={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 rc(s={}){return{...Th,...s,topics:s.topics!=null?Object.entries(s.topics).reduce((e,[t,r])=>(e[t]=Ah(r),e),{}):{}}}function Ah(s={}){return{...Dh,...s}}function nc(s){for(let[e,t]of Object.entries(s.topics))try{Mh(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 Mh(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 Ph={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function oc(s={}){return{...Ph,...s}}function Cr(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 ic(s,e){return Cr(s,e,()=>!0)}var Lr=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 ac(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 uc=Bc(lc(),1);var Se;(function(s){s[s.unknown=0]="unknown",s[s.valid=1]="valid",s[s.invalid=2]="invalid",s[s.ignored=3]="ignored"})(Se||(Se={}));var Fr=class{records;queue;constructor(){this.records=new Map,this.queue=new uc.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:Se.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let r={msgId:e,expire:Date.now()+12e4};return this.queue.push(r),t}gc(){let e=Date.now(),t=this.queue.peekFront();for(;t!=null&&t.expire<e;)this.records.delete(t.msgId),this.queue.shift(),t=this.queue.peekFront()}clear(){this.records.clear(),this.queue.clear()}};var Nr=class{params;metrics;peerStats=new Map;peerIPs=new Lr(()=>new Set);scoreCache=new Map;deliveryRecords=new Fr;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,r,n){this.params=e,this.metrics=t,nc(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??ac,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!==Se.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,o-n.firstSeenTsMs,Se[n.status]);return}n.status=Se.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 ve.Error:this.markInvalidMessageDelivery(e,r);return;case ve.Blacklisted:return}let o=this.deliveryRecords.ensureRecord(t);if(o.status!==Se.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-o.firstSeenTsMs,Se[o.status]);return}if(n===ve.Ignore){o.status=Se.ignored,o.peers.clear();return}o.status=Se.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 Se.unknown:n.peers.add(e);break;case Se.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,r,n.validated);break;case Se.invalid:this.markInvalidMessageDelivery(e,r);break;case Se.ignored:break}}markInvalidMessageDelivery(e,t){let r=this.peerStats.get(e);if(r!=null){let n=this.getPtopicStats(r,t);n!=null&&(n.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){let r=this.peerStats.get(e);if(r!=null){let n=this.getPtopicStats(r,t);if(n!=null){let 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 kh(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",b=t.topics[E];if(b===void 0)return;let g=i.get(h);g==null&&(g={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},i.set(h,g));let x=0,I=0,c=0,f=0,d=0;if(w.inMesh){let k=Math.max(w.meshTime/b.timeInMeshQuantum,b.timeInMeshCap);x+=k*b.timeInMeshWeight}let y=w.firstMessageDeliveries;if(y>b.firstMessageDeliveriesCap&&(y=b.firstMessageDeliveriesCap),I+=y*b.firstMessageDeliveriesWeight,w.meshMessageDeliveriesActive&&w.meshMessageDeliveries<b.meshMessageDeliveriesThreshold){let k=b.meshMessageDeliveriesThreshold-w.meshMessageDeliveries,C=k*k;c+=C*b.meshMessageDeliveriesWeight}let v=w.meshFailurePenalty;f+=v*b.meshFailurePenaltyWeight;let S=w.invalidMessageDeliveries*w.invalidMessageDeliveries;d+=S*b.invalidMessageDeliveriesWeight,o+=(x+I+c+f+d)*b.topicWeight,g.p1w+=x,g.p2w+=I,g.p3w+=c,g.p3bw+=f,g.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 b=h-t.IPColocationFactorThreshold,g=b*b;l+=g*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 hc(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=kh(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 zo(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 fc(s){let e=zo(s);if(e==null)throw new Y(`Multiaddr ${s} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function dc(s){return zo(s)!==null}var Ho=class s extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,s)}},pc=s=>s.reason??new DOMException("This operation was aborted.","AbortError");function Go(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(pc(i));return}if(i&&(l=()=>{E(pc(i))},i.addEventListener("abort",l,{once:!0})),s.then(m,E),t===Number.POSITIVE_INFINITY)return;let w=new Ho;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 Bh=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 Rh(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}=Bh(s),m=async(...w)=>{let h=t.multiArgs?w:w[0];if(t.filter)try{if(!await t.filter(h))return}catch(b){r(),i(b);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=Go(n,{milliseconds:t.timeout});return o.cancel=()=>{r(),o.clear()},o}return n}function mc(s,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let r=Rh(s,e,t),n=r.then(o=>o[0]);return n.cancel=r.cancel,n}function Lh(s){return s?.addEventListener!=null}function Ch(s){let e=Lt(),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([mc(s,"drain",{rejectionEvents:["close"]})])),u===!0))break}await s.close()}}}function gc(...s){let e=s.map(t=>Lh(t)?Ch(t):t);return zs(...e)}var Or=class{rawStream;constructor(e,t,r){this.rawStream=e,r.maxBufferSize!=null&&(e.maxWriteBufferLength=r.maxBufferSize),e.addEventListener("close",n=>{n.error!=null&&t(n.error)})}get protocol(){return this.rawStream.protocol}push(e){this.pushPrefixed(is.single(e))}pushPrefixed(e){this.rawStream.send(e)}async close(e){await this.rawStream.close(e).catch(t=>{this.rawStream.abort(t)})}},Ur=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=gc(this.rawStream,r=>Ks(r,t))}async close(){this.closeController.abort()}};var Kr=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!==ve.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 bc=V("libp2p-pubsub:"),Fh=BigInt(Date.now())*1000000n;function Nh(){let s=++Fh,e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,s,!1),e}async function yc(s,e,t,r){switch(s.type){case wt.Signing:{let n={from:s.author.toMultihash().bytes,data:r,seqno:Nh(),topic:e,signature:void 0,key:void 0},o=vt([bc,ot.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:Sr(n.key)};return{raw:n,msg:i}}case wt.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 wc(s,e){switch(s){case Ct:return e.signature!=null?{valid:!1,error:pe.SignaturePresent}:e.seqno!=null?{valid:!1,error:pe.SeqnoPresent}:e.key!=null?{valid:!1,error:pe.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case xt:{if(e.seqno==null)return{valid:!1,error:pe.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:pe.InvalidSeqno};if(e.signature==null)return{valid:!1,error:pe.InvalidSignature};if(e.from==null)return{valid:!1,error:pe.InvalidPeerId};let t;try{t=ns(Ye(e.from))}catch{return{valid:!1,error:pe.InvalidPeerId}}let r;if(e.key!=null){if(r=Sr(e.key),t.publicKey!==void 0&&!r.equals(t.publicKey))return{valid:!1,error:pe.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:pe.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=vt([bc,ot.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?Sr(e.key):r}}:{valid:!1,error:pe.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 qo(s){return s.control===void 0&&(s.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),s}function je(s){if(s.length<=1)return s;let e=()=>Math.floor(Math.random()*Math.floor(s.length));for(let t=0;t<s.length;t++){let r=e(),n=s[t];s[t]=s[r],s[r]=n}return s}function xc(s){return q(s,"base64")}function vc(s,e,t){switch(s){case xt:return{type:wt.Signing,author:e,key:Ge(t.publicKey),privateKey:t};case Ct:return{type:wt.Anonymous};default:throw new Error(`Unknown signature policy "${s}"`)}}var Oh=(s,e)=>{let t=V(e.toString(16).padStart(16,"0"),"base16"),r=Ge(s),n=new Uint8Array(r.byteLength+t.length);return n.set(r,0),n.set(t,r.byteLength),n};function Ec(s){if(s.type!=="signed")throw new Error("expected signed message type");if(s.sequenceNumber==null)throw Error("missing seqno field");return Oh(s.from.publicKey??s.key,s.sequenceNumber)}async function Sc(s){return Et.encode(s.data)}function _c(s){if(dc(s)){let e=fc(s);switch(e.type){case"ip4":case"ip6":return e.host;default:break}}return null}var hs=class{entries=new Map;validityMs;constructor(e){this.validityMs=e.validityMs}get size(){return this.entries.size}put(e,t){return this.entries.has(e)?!0:(this.entries.set(e,{value:t,validUntilMs:Date.now()+this.validityMs}),!1)}prune(){let e=Date.now();for(let[t,r]of this.entries.entries())if(r.validUntilMs<e)this.entries.delete(t);else break}has(e){return this.entries.has(e)}get(e){let t=this.entries.get(e);return t!=null&&t.validUntilMs>=Date.now()?t.value:void 0}clear(){this.entries.clear()}};var Pe;(function(s){s[s.started=0]="started",s[s.stopped=1]="stopped"})(Pe||(Pe={}));var zr=class extends Ws{globalSignaturePolicy;protocols=[Nt,jo,Gr];publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=Lt({objectMode:!0});direct=new Set;floodsubPeers=new Set;seenCache;acceptFromWhitelist=new Map;topics=new Map;subscriptions=new Set;mesh=new Map;fanout=new Map;fanoutLastpub=new Map;gossip=new Map;control=new Map;peerhave=new Map;iasked=new Map;backoff=new Map;outbound=new Map;msgIdFn;fastMsgIdFn;msgIdToStrFn;fastMsgIdCache;publishedMessageIds;mcache;score;topicValidators=new Map;log;heartbeatTicks=0;gossipTracer;idontwantCounts=new Map;idontwants=new Map;components;directPeerInitial=null;static multicodec=Nt;opts;decodeRpcLimits;metrics;status={code:Pe.stopped};maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;allowedTopics;heartbeatTimer=null;constructor(e,t={}){super();let r={fallbackToFloodsub:!0,floodPublish:!0,batchPublish:!1,tagMeshPeers:!0,doPX:!1,directPeers:[],D:6,Dlo:4,Dhi:12,Dscore:4,Dout:2,Dlazy:6,heartbeatInterval:1e3,fanoutTTL:6e4,mcacheLength:5,mcacheGossip:3,seenTTL:12e4,gossipsubIWantFollowupMs:3e3,prunePeers:16,pruneBackoff:6e4,unsubcribeBackoff:1e4,graftFloodThreshold:1e4,opportunisticGraftPeers:2,opportunisticGraftTicks:60,directConnectTicks:300,gossipFactor:.25,idontwantMinDataSize:512,idontwantMaxMessages:512,...t,scoreParams:rc(t.scoreParams),scoreThresholds:oc(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=r.decodeRpcLimits??Qa,this.globalSignaturePolicy=r.globalSignaturePolicy??xt,r.fallbackToFloodsub&&this.protocols.push(Hr),this.log=e.logger.forComponent(r.debugName??"libp2p:gossipsub"),this.opts=r,this.direct=new Set(r.directPeers.map(n=>n.id.toString())),this.seenCache=new hs({validityMs:r.seenTTL}),this.publishedMessageIds=new hs({validityMs:r.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case xt:this.msgIdFn=Ec;break;case Ct:this.msgIdFn=Sc;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new hs({validityMs:r.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??xc,this.mcache=t.messageCache??new Rr(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=sc(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 Kr(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new Nr(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:r.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnLimitedConnection=t.runOnLimitedConnection,this.allowedTopics=r.allowedTopics!=null?new Set(r.allowedTopics):null}[Symbol.toStringTag]="@chainsafe/libp2p-gossipsub";[Jo]=["@libp2p/pubsub"];[Qo]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===Pe.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=vc(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=Lt({objectMode:!0}),zs(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:Pe.started,registrarTopologyIds:r,heartbeatTimeout:n,hearbeatStartMs:Date.now()+100},this.score.start(),this.directPeerInitial=setTimeout(()=>{Promise.resolve().then(async()=>{await Promise.all(Array.from(this.direct).map(async 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!==Pe.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:Pe.stopped},this.opts.tagMeshPeers&&(this.removeEventListener("gossipsub:graft",this.tagMeshPeer),this.removeEventListener("gossipsub:prune",this.untagMeshPeer));let t=this.components.registrar;await Promise.all(this.protocols.map(async n=>t.unhandle(n))),e.forEach(n=>{t.unregister(n)}),this.outboundInflightQueue.end();let r=[];for(let n of this.streamsOutbound.values())r.push(n.close());this.streamsOutbound.clear();for(let n of this.streamsInbound.values())r.push(n.close());this.streamsInbound.clear(),await Promise.all(r),this.peers.clear(),this.subscriptions.clear(),this.topics.clear(),this.heartbeatTimer!=null&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.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 Or(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===Hr&&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 Ur(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=_c(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===Pe.started}getMeshPeers(e){let t=this.mesh.get(e);return t!=null?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(t!=null?Array.from(t):[]).map(r=>this.peers.get(r)??Bt(r))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await zs(t,async r=>{for await(let n of r)try{let o=n.subarray(),i=ot.decode(o,{limits:{subscriptions:this.decodeRpcLimits.maxSubscriptions,messages:this.decodeRpcLimits.maxMessages,control$:{ihave:this.decodeRpcLimits.maxIhaveMessageIDs,iwant:this.decodeRpcLimits.maxIwantMessageIDs,graft:this.decodeRpcLimits.maxControlMessages,prune:this.decodeRpcLimits.maxControlMessages,prune$:{peers:this.decodeRpcLimits.maxPeerInfos},idontwant:this.decodeRpcLimits.maxControlMessages,idontwant$:{messageIDs:this.decodeRpcLimits.maxIdontwantMessageIDs}}}});if(this.metrics?.onRpcRecv(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 me.duplicate:this.score.duplicateMessage(e.toString(),r.msgIdStr,t.topic),this.gossipTracer.deliverMessage(r.msgIdStr,!0),this.mcache.observeDuplicate(r.msgIdStr,e.toString());return;case me.invalid:if(r.msgIdStr!=null){let 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 me.valid:this.score.validateMessage(r.messageId.msgIdStr),this.gossipTracer.deliverMessage(r.messageId.msgIdStr),this.mcache.put(r.messageId,t,!this.opts.asyncValidation),this.subscriptions.has(t.topic)&&(!this.components.peerId.equals(e)||this.opts.emitSelf)&&(super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:e,msgId:r.messageId.msgIdStr,msg:r.msg}})),super.dispatchEvent(new CustomEvent("message",{detail:r.msg}))),this.opts.asyncValidation||this.forwardMessage(r.messageId.msgIdStr,t,e.toString());break;default:throw new Error(`Invalid validation result: ${n}`)}}async validateReceivedMessage(e,t){let r=this.fastMsgIdFn?.(t),n=r!==void 0?this.fastMsgIdCache?.get(r):void 0;if(n!=null)return{code:me.duplicate,msgIdStr:n};let o=await wc(this.globalSignaturePolicy,t);if(!o.valid)return{code:me.invalid,reason:ve.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:me.invalid,reason:ve.Error,error:pe.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:me.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===Yo&&(m=ge.Ignore),w===Zo?m=ge.Reject:m=ge.Ignore}if(m!==ge.Accept)return{code:me.invalid,reason:Ko(m),msgIdStr:l}}return{code:me.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:us.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:us.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:us.MaxIasked}),[];let i=new Map;if(t.forEach(({topicID:u,messageIDs:p})=>{if(u==null||p==null||!this.mesh.has(u))return;let m=0;p.forEach(E=>{let w=this.msgIdToStrFn(E);this.seenCache.has(w)||(i.set(w,E),m++)}),this.metrics?.onIhaveRcv(u,p.length,m)}),i.size===0)return[];let a=i.size;a+o>5e3&&(a=5e3-o),this.log("IHAVE: Asking for %d out of %d messages from %s",a,i.size,e);let l=Array.from(i.values());return je(l),l=l.slice(0,a),this.iasked.set(e,o+a),[{messageIDs:l}]}handleIWant(e,t){if(t.length===0)return[];let r=this.score.score(e);if(r<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,r),[];let n=new Map,o=new Map,i=0;return t.forEach(({messageIDs:a})=>{a?.forEach(l=>{let u=this.msgIdToStrFn(l),p=this.mcache.getWithIWantCount(u,e);if(p==null){i++;return}if(o.set(p.msg.topic,1+(o.get(p.msg.topic)??0)),p.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,l);return}n.set(u,p.msg)})}),this.metrics?.onIwantRcv(o,i),n.size===0?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",n.size,e),Array.from(n.values()))}async handleGraft(e,t){let r=[],n=this.score.score(e),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,ls.GraftBackoff),i=!1;let m=p+this.opts.graftFloodThreshold-this.opts.pruneBackoff;o<m&&this.score.addPenalty(e,1,ls.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,Ee.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,ls.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&&(je(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async r=>{if(r.peerID==null)return;let n=ns(Ye(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=Bt(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!==Pe.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(let t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==Pe.started)throw new Error("Pubsub is not started");let t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(let r of this.peers.keys())this.sendSubscriptions(r,[e],!1);this.leave(e)}join(e){if(this.status.code!==Pe.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);let t=new Set,r=this.backoff.get(e),n=this.fanout.get(e);if(n!=null&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),n.forEach(o=>{!this.direct.has(o)&&this.score.score(o)>=0&&r?.has(o)!==!0&&t.add(o)}),this.metrics?.onAddToMesh(e,Ee.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,Ee.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!==Pe.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);let t=this.mesh.get(e);t!=null&&(Promise.all(Array.from(t).map(async r=>{this.log("LEAVE: Remove mesh link to %s in %s",r,e),await this.sendPrune(r,e)})).catch(r=>{this.log("Error sending prunes to mesh peers",r)}),this.mesh.delete(e))}selectPeersToForward(e,t,r){let n=new Set,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 yc(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 b=r?.batchPublish??this.opts.batchPublish,g=ze([i]);if(b)this.sendRpcInBatch(m,g);else for(let I of m)this.sendRpc(I,g)||m.delete(I);let x=Date.now()-n;return this.metrics?.onPublishMsg(e,E,m.size,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(I=>this.peers.get(I)??Bt(I))}}sendRpcInBatch(e,t){let r=ot.encode(t),n=is.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===ge.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=Ko(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!==Nt&&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=ot.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=qo(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=qo(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||(je(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=je(Array.from(a)).slice(0,n),a.forEach(l=>{let u=r;r.length>5e3&&(u=je(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===Gr)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)??Bt(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===Pe.started){clearTimeout(this.status.heartbeatTimeout);let t=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;t<this.opts.heartbeatInterval*.25&&(t+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,t)}})};async heartbeat(){let{D:e,Dlo:t,Dhi:r,Dscore:n,Dout:o,fanoutTTL:i}=this.opts;this.heartbeatTicks++;let a=new Map,l=h=>{let b=a.get(h);return b===void 0&&(b=this.score.score(h),a.set(h,b)),b},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.applyIwantPenalties(),this.idontwantCounts.clear();for(let h of this.idontwants.values())for(let[b,g]of h)this.heartbeatTicks-g>=this.opts.mcacheLength&&h.delete(b);this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let E=new Map;this.mesh.forEach((h,b)=>{let g=this.topics.get(b),x=new Set,I=new Set;if(E.set(b,I),g!=null){let d=je(Array.from(g)),y=this.backoff.get(b);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 k=l(v);y?.has(v)!==!0&&k>=0&&x.add(v),k>=this.opts.scoreThresholds.gossipThreshold&&I.add(v)}}}let c=(d,y)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",d,b),this.addBackoff(d,b),h.delete(d),l(d)>=this.opts.scoreThresholds.gossipThreshold&&I.add(d),this.metrics?.onRemoveFromMesh(b,y,1);let v=p.get(d);v==null?p.set(d,[b]):v.push(b)},f=(d,y)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",d,b),this.score.graft(d,b),h.add(d),I.delete(d),this.metrics?.onAddToMesh(b,y,1);let v=u.get(d);v==null?u.set(d,[b]):v.push(b)};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,b),c(d,Ke.BadScore),m.set(d,!0))}),h.size<t){let d=e-h.size;ic(x,d).forEach(v=>{f(v,Ee.NotEnough)})}if(h.size>r){let d=Array.from(h);d.sort((v,S)=>l(S)-l(v)),d=d.slice(0,n).concat(je(d.slice(n)));let y=0;if(d.slice(0,e).forEach(v=>{(this.outbound.get(v)??!1)&&y++}),y<o){let v=k=>{let C=d[k];for(let N=k;N>0;N--)d[N]=d[N-1];d[0]=C};if(y>0){let k=y;for(let C=1;C<e&&k>0;C++)(this.outbound.get(d[C])??!1)&&(v(C),k--)}let S=e-y;for(let k=e;k<d.length&&S>0;k++)(this.outbound.get(d[k])??!1)&&(v(k),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;Cr(x,y,S=>this.outbound.get(S)===!0).forEach(S=>{f(S,Ee.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&h.size>1){let d=Array.from(h).sort((S,k)=>l(S)-l(k)),y=Math.floor(h.size/2),v=l(d[y]);if(v<this.opts.scoreThresholds.opportunisticGraftThreshold){let S=this.opts.opportunisticGraftPeers,k=Cr(x,S,C=>l(C)>v);for(let C of k)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",C,b),f(C,Ee.Opportunistic)}}});let w=Date.now();this.fanoutLastpub.forEach((h,b)=>{h+i<w&&(this.fanout.delete(b),this.fanoutLastpub.delete(b))}),this.fanout.forEach((h,b)=>{let g=this.topics.get(b);h.forEach(f=>{(!(g?.has(f)??!1)||l(f)<this.opts.scoreThresholds.publishThreshold)&&h.delete(f)});let x=this.topics.get(b),I=[],c=new Set;if(E.set(b,c),x!=null){let f=je(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&&I.push(d),v>=this.opts.scoreThresholds.gossipThreshold&&c.add(d)}}}if(h.size<e){let f=e-h.size;I.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=je(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=hc(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)??Bt(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)??Bt(t),{tags:{[r]:void 0}}).catch(n=>{this.log.error("Error untagging peer %s with topic %s",t,r,n)})}};var xt="StrictSign",Ct="StrictNoSign",ge;(function(s){s.Accept="accept",s.Ignore="ignore",s.Reject="reject"})(ge||(ge={}));var df=Nt;function pf(s={}){return e=>new zr(e,s)}return Rc(mf);})();
|
|
2
|
+
"use strict";var Libp2PGossipsub=(()=>{var Zl=Object.create;var ls=Object.defineProperty;var Yl=Object.getOwnPropertyDescriptor;var Xl=Object.getOwnPropertyNames;var Jl=Object.getPrototypeOf,Ql=Object.prototype.hasOwnProperty;var eu=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),V=(r,e)=>{for(var t in e)ls(r,t,{get:e[t],enumerable:!0})},Fi=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Xl(e))!Ql.call(r,n)&&n!==t&&ls(r,n,{get:()=>e[n],enumerable:!(s=Yl(e,n))||s.enumerable});return r};var tu=(r,e,t)=>(t=r!=null?Zl(Jl(r)):{},Fi(e||!r||!r.__esModule?ls(t,"default",{value:r,enumerable:!0}):t,r)),ru=r=>Fi(ls({},"__esModule",{value:!0}),r);var Bl=eu((gv,kl)=>{"use strict";function Y(r,t){var t=t||{};this._capacity=t.capacity,this._head=0,this._tail=0,Array.isArray(r)?this._fromArray(r):(this._capacityMask=3,this._list=new Array(4))}Y.prototype.peekAt=function(e){var t=e;if(t===(t|0)){var s=this.size();if(!(t>=s||t<-s))return t<0&&(t+=s),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 s=this._list[this._tail];return this._list[this._tail]=void 0,this._head<2&&e>1e4&&e<=t>>>2&&this._shrinkArray(),s}};Y.prototype.removeOne=function(e){var t=e;if(t===(t|0)&&this._head!==this._tail){var s=this.size(),n=this._list.length;if(!(t>=s||t<-s)){t<0&&(t+=s),t=this._head+t&this._capacityMask;var o=this._list[t],i;if(e<s/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=s-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 s=e,n,o=t;if(s===(s|0)&&this._head!==this._tail){var i=this.size(),a=this._list.length;if(!(s>=i||s<-i||t<1)){if(s<0&&(s+=i),t===1||!t)return n=new Array(1),n[0]=this.removeOne(s),n;if(s===0&&s+t>=i)return n=this.toArray(),this.clear(),n;s+t>i&&(t=i-s);var l;for(n=new Array(t),l=0;l<t;l++)n[l]=this._list[this._head+s+l&this._capacityMask];if(s=this._head+s&this._capacityMask,e+t===i){for(this._tail=this._tail-t+a&this._capacityMask,l=t;l>0;l--)this._list[s=s+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[s=s+1+a&this._capacityMask]=void 0;return n}if(s<i/2){for(this._head=this._head+e+t+a&this._capacityMask,l=e;l>0;l--)this.unshift(this._list[s=s-1+a&this._capacityMask]);for(s=this._head-1+a&this._capacityMask;o>0;)this._list[s=s-1+a&this._capacityMask]=void 0,o--;e<0&&(this._tail=s)}else{for(this._tail=s,s=s+t+a&this._capacityMask,l=i-(t+e);l>0;l--)this.push(this._list[s++]);for(s=this._tail;o>0;)this._list[s=s+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 s=e;if(s===(s|0)){var n=this.size();if(s<0&&(s+=n),!(s>n))if(arguments.length>2){var o,i,a,l=arguments.length,u=this._list.length,p=2;if(!n||s<n/2){for(i=new Array(s),o=0;o<s;o++)i[o]=this._list[this._head+o&this._capacityMask];for(t===0?(a=[],s>0&&(this._head=this._head+s+u&this._capacityMask)):(a=this.remove(s,t),this._head=this._head+s+u&this._capacityMask);l>p;)this.unshift(arguments[--l]);for(o=s;o>0;o--)this.unshift(i[o-1])}else{i=new Array(n-(s+t));var m=i.length;for(o=0;o<m;o++)i[o]=this._list[this._head+s+t+o&this._capacityMask];for(t===0?(a=[],s!=n&&(this._tail=this._head+s+u&this._capacityMask)):(a=this.remove(s,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(s,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,s=this._nextPowerOf2(t);this._list=new Array(s),this._capacityMask=s-1,this._tail=t;for(var n=0;n<t;n++)this._list[n]=e[n]};Y.prototype._copyArray=function(e,t){var s=this._list,n=s.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++]=s[l];for(l=0;l<this._tail;l++)i[a++]=s[l]}else for(l=this._head;l<this._tail;l++)i[a++]=s[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),s=1<<t+1;return Math.max(s,4)};kl.exports=Y});var sm={};V(sm,{StrictNoSign:()=>Ht,StrictSign:()=>Tt,TopicValidatorResult:()=>be,gossipsub:()=>rm,multicodec:()=>tm});var pn="/floodsub/1.0.0",mn="/meshsub/1.0.0",Ni="/meshsub/1.1.0",Vt="/meshsub/1.2.0";var Oi="ERR_TOPIC_VALIDATOR_REJECT",Ui="ERR_TOPIC_VALIDATOR_IGNORE";var X=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Wt=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var us=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},hs=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var $t=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var gn=Symbol.for("@libp2p/peer-id");function su(r){return typeof r?.handleEvent=="function"}function nu(r){return(r!==!0&&r!==!1&&r?.once)??!1}var fs=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,s){let n=nu(s);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))}su(t)?t.handleEvent(i):t(i)},s);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:n})}removeEventListener(e,t,s){super.removeEventListener(e.toString(),t??null,s);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 zi=Symbol.for("@libp2p/service-capabilities"),Gi=Symbol.for("@libp2p/service-dependencies");var vn={};V(vn,{base58btc:()=>Q,base58flickr:()=>fu});var Lm=new Uint8Array(0);function Hi(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Xe(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return Dt(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return Dt(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function qi(r){return new TextEncoder().encode(r)}function Vi(r){return new TextDecoder().decode(r)}function ou(r){return r?.buffer instanceof ArrayBuffer}function Dt(r){return ou(r)?r:r.slice()}function iu(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),s=0;s<t.length;s++)t[s]=255;for(var n=0;n<r.length;n++){var o=r.charAt(n),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=n}var a=r.length,l=r.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+=r.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 au=iu,cu=au,$i=cu;var bn=class{name;prefix;baseEncode;constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},yn=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,s){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=s}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 ji(this,e)}},wn=class{decoders;constructor(e){this.decoders=e}or(e){return ji(this,e)}decode(e){let t=e[0],s=this.decoders[t];if(s!=null)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ji(r,e){return new wn({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var xn=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,s,n){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=n,this.encoder=new bn(e,t,s),this.decoder=new yn(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function jt({name:r,prefix:e,encode:t,decode:s}){return new xn(r,e,t,s)}function lt({name:r,prefix:e,alphabet:t}){let{encode:s,decode:n}=$i(t,r);return jt({prefix:e,name:r,encode:s,decode:o=>Xe(n(o))})}function lu(r,e,t,s){let n=r.length;for(;r[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[r[u]];if(p===void 0)throw new SyntaxError(`Non-${s} 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 uu(r,e,t){let s=e[e.length-1]==="=",n=(1<<t)-1,o="",i=0,a=0;for(let l=0;l<r.length;++l)for(a=a<<8|r[l],i+=8;i>t;)i-=t,o+=e[n&a>>i];if(i!==0&&(o+=e[n&a<<t-i]),s)for(;(o.length*t&7)!==0;)o+="=";return o}function hu(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function J({name:r,prefix:e,bitsPerChar:t,alphabet:s}){let n=hu(s);return jt({prefix:e,name:r,encode(o){return uu(o,s,t)},decode(o){return lu(o,n,t,r)}})}var Q=lt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),fu=lt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var En={};V(En,{base32:()=>Zt,base32hex:()=>gu,base32hexpad:()=>yu,base32hexpadupper:()=>wu,base32hexupper:()=>bu,base32pad:()=>pu,base32padupper:()=>mu,base32upper:()=>du,base32z:()=>xu});var Zt=J({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),du=J({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),pu=J({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),mu=J({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),gu=J({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),bu=J({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),yu=J({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),wu=J({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),xu=J({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Sn={};V(Sn,{base36:()=>Ar,base36upper:()=>vu});var Ar=lt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),vu=lt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Eu=Xi,Zi=128,Su=127,_u=~Su,Iu=Math.pow(2,31);function Xi(r,e,t){e=e||[],t=t||0;for(var s=t;r>=Iu;)e[t++]=r&255|Zi,r/=128;for(;r&_u;)e[t++]=r&255|Zi,r>>>=7;return e[t]=r|0,Xi.bytes=t-s+1,e}var Tu=_n,Au=128,Yi=127;function _n(r,s){var t=0,s=s||0,n=0,o=s,i,a=r.length;do{if(o>=a)throw _n.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=n<28?(i&Yi)<<n:(i&Yi)*Math.pow(2,n),n+=7}while(i>=Au);return _n.bytes=o-s,t}var Du=Math.pow(2,7),Mu=Math.pow(2,14),Pu=Math.pow(2,21),ku=Math.pow(2,28),Bu=Math.pow(2,35),Lu=Math.pow(2,42),Ru=Math.pow(2,49),Cu=Math.pow(2,56),Fu=Math.pow(2,63),Nu=function(r){return r<Du?1:r<Mu?2:r<Pu?3:r<ku?4:r<Bu?5:r<Lu?6:r<Ru?7:r<Cu?8:r<Fu?9:10},Ou={encode:Eu,decode:Tu,encodingLength:Nu},Uu=Ou,Dr=Uu;function Mr(r,e=0){return[Dr.decode(r,e),Dr.decode.bytes]}function Yt(r,e,t=0){return Dr.encode(r,e,t),e}function Xt(r){return Dr.encodingLength(r)}function Ge(r,e){let t=e.byteLength,s=Xt(r),n=s+Xt(t),o=new Uint8Array(n+t);return Yt(r,o,0),Yt(t,o,s),o.set(e,n),new Jt(r,t,e,o)}function Je(r){let e=Xe(r),[t,s]=Mr(e),[n,o]=Mr(e.subarray(s)),i=e.subarray(s+o);if(i.byteLength!==n)throw new Error("Incorrect length");return new Jt(t,n,i,e)}function Ji(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Hi(r.bytes,t.bytes)}}var Jt=class{code;size;digest;bytes;constructor(e,t,s,n){this.code=e,this.size=t,this.digest=Dt(s),this.bytes=Dt(n)}};function Qi(r,e){let{bytes:t,version:s}=r;return s===0?zu(t,In(r),e??Q.encoder):Gu(t,In(r),e??Zt.encoder)}var ea=new WeakMap;function In(r){let e=ea.get(r);if(e==null){let t=new Map;return ea.set(r,t),t}return e}var ue=class r{code;version;multihash;bytes;"/";constructor(e,t,s,n){this.code=t,this.version=e,this.multihash=s,this.bytes=Dt(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!==Pr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Hu)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.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,s=Ge(e,t);return r.createV1(this.code,s)}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 r.equals(this,e)}static equals(e,t){let s=t;return s!=null&&e.code===s.code&&e.version===s.version&&Ji(e.multihash,s.multihash)}toString(e){return Qi(this,e)}toJSON(){return{"/":Qi(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 r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:s,code:n,multihash:o,bytes:i}=t;return new r(s,n,o,i??ta(s,n,o.bytes))}else if(t[qu]===!0){let{version:s,multihash:n,code:o}=t,i=Je(n);return r.create(s,o,i)}else return null}static create(e,t,s){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(s.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Pr)throw new Error(`Version 0 CID must use dag-pb (code: ${Pr}) block encoding`);return new r(e,t,s,s.bytes)}case 1:{let n=ta(e,t,s.bytes);return new r(e,t,s,n)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Pr,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,s]=r.decodeFirst(e);if(s.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),s=t.size-t.multihashSize,n=Xe(e.subarray(s,s+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=n.subarray(t.multihashSize-t.digestSize),i=new Jt(t.multihashCode,t.digestSize,o,n);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,s=()=>{let[m,E]=Mr(e.subarray(t));return t+=E,m},n=s(),o=Pr;if(n===18?(n=0,t=0):o=s(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let i=t,a=s(),l=s(),u=t+l,p=u-i;return{version:n,codec:o,multihashCode:a,digestSize:l,multihashSize:p,size:u}}static parse(e,t){let[s,n]=Ku(e,t),o=r.decode(n);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return In(o).set(s,e),o}};function Ku(r,e){switch(r[0]){case"Q":{let t=e??Q;return[Q.prefix,t.decode(`${Q.prefix}${r}`)]}case Q.prefix:{let t=e??Q;return[Q.prefix,t.decode(r)]}case Zt.prefix:{let t=e??Zt;return[Zt.prefix,t.decode(r)]}case Ar.prefix:{let t=e??Ar;return[Ar.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function zu(r,e,t){let{prefix:s}=t;if(s!==Q.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let n=e.get(s);if(n==null){let o=t.encode(r).slice(1);return e.set(s,o),o}else return n}function Gu(r,e,t){let{prefix:s}=t,n=e.get(s);if(n==null){let o=t.encode(r);return e.set(s,o),o}else return n}var Pr=112,Hu=18;function ta(r,e,t){let s=Xt(r),n=s+Xt(e),o=new Uint8Array(n+t.byteLength);return Yt(r,o,0),Yt(e,o,s),o.set(t,n),o}var qu=Symbol.for("@ipld/js-cid/CID");var Tn={};V(Tn,{identity:()=>Le});var ra=0,Vu="identity",sa=Xe;function Wu(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Ge(ra,sa(r))}var Le={code:ra,name:Vu,encode:sa,digest:Wu};function ke(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function $u(r){return r.buffer instanceof ArrayBuffer}function He(r){return $u(r)?r:r.slice()}async function na(r,e,t,s){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);s?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,He(e),He(t.subarray()));return s?.signal?.throwIfAborted(),o}function Qe(r=0){return new Uint8Array(r)}function kr(r=0){return new Uint8Array(r)}function An(r,e){e==null&&(e=r.reduce((n,o)=>n+o.length,0));let t=kr(e),s=0;for(let n of r)t.set(n,s),s+=n.length;return t}function oa(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var aa=Symbol.for("@achingbrain/uint8arraylist");function ia(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let s of r){let n=t+s.byteLength;if(e<n)return{buf:s,index:e-t};t=n}throw new RangeError("index is out of bounds")}function ps(r){return!!r?.[aa]}var ce=class r{bufs;length;[aa]=!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 s of e)if(s instanceof Uint8Array)t+=s.byteLength,this.bufs.push(s);else if(ps(s)){t+=s.byteLength;for(let n of s.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 s of e.reverse())if(s instanceof Uint8Array)t+=s.byteLength,this.bufs.unshift(s);else if(ps(s))t+=s.byteLength,this.bufs.unshift(...s.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=ia(this.bufs,e);return t.buf[t.index]}set(e,t){let s=ia(this.bufs,e);s.buf[s.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let s=0;s<e.length;s++)this.set(t+s,e[s]);else if(ps(e))for(let s=0;s<e.length;s++)this.set(t+s,e.get(s));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:s,length:n}=this._subList(e,t);return An(s,n)}subarray(e,t){let{bufs:s,length:n}=this._subList(e,t);return s.length===1?s[0]:An(s,n)}sublist(e,t){let{bufs:s,length:n}=this._subList(e,t),o=new r;return o.length=n,o.bufs=s,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 s=[],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){s.push(i);break}let m=e-a;s.push(i.subarray(m,m+(t-e)));break}if(u){if(e===0){s.push(i);continue}s.push(i.subarray(e-a));continue}if(p){if(t===l){s.push(i);break}s.push(i.subarray(0,t-a));break}s.push(i)}return{bufs:s,length:t-e}}indexOf(e,t=0){if(!ps(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let s=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=s.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[s[m]]=m;let a=i,l=this.byteLength-s.byteLength,u=s.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(s[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 s=kr(1);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt8(0,t),this.write(s,e)}getInt16(e,t){let s=this.subarray(e,e+2);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt16(0,t)}setInt16(e,t,s){let n=Qe(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,s),this.write(n,e)}getInt32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt32(0,t)}setInt32(e,t,s){let n=Qe(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,s),this.write(n,e)}getBigInt64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigInt64(0,t)}setBigInt64(e,t,s){let n=Qe(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,s),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 s=kr(1);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint8(0,t),this.write(s,e)}getUint16(e,t){let s=this.subarray(e,e+2);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint16(0,t)}setUint16(e,t,s){let n=Qe(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,s),this.write(n,e)}getUint32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint32(0,t)}setUint32(e,t,s){let n=Qe(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,s),this.write(n,e)}getBigUint64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigUint64(0,t)}setBigUint64(e,t,s){let n=Qe(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,s),this.write(n,e)}getFloat32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getFloat32(0,t)}setFloat32(e,t,s){let n=Qe(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,s),this.write(n,e)}getFloat64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getFloat64(0,t)}setFloat64(e,t,s){let n=Qe(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,s),this.write(n,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!oa(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let s=new r;return s.bufs=e,t==null&&(t=e.reduce((n,o)=>n+o.byteLength,0)),s.length=t,s}};var Dn={};V(Dn,{base10:()=>ju});var ju=lt({prefix:"9",name:"base10",alphabet:"0123456789"});var Mn={};V(Mn,{base16:()=>Zu,base16upper:()=>Yu});var Zu=J({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Yu=J({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Pn={};V(Pn,{base2:()=>Xu});var Xu=J({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var kn={};V(kn,{base256emoji:()=>rh});var ca=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=ca.reduce((r,e,t)=>(r[t]=e,r),[]),Qu=ca.reduce((r,e,t)=>{let s=e.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${e}`);return r[s]=t,r},[]);function eh(r){return r.reduce((e,t)=>(e+=Ju[t],e),"")}function th(r){let e=[];for(let t of r){let s=t.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${t}`);let n=Qu[s];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var rh=jt({prefix:"\u{1F680}",name:"base256emoji",encode:eh,decode:th});var Bn={};V(Bn,{base64:()=>sh,base64pad:()=>nh,base64url:()=>oh,base64urlpad:()=>ih});var sh=J({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),nh=J({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),oh=J({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ih=J({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ln={};V(Ln,{base8:()=>ah});var ah=J({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Rn={};V(Rn,{identity:()=>ch});var ch=jt({prefix:"\0",name:"identity",encode:r=>Vi(r),decode:r=>qi(r)});var xg=new TextEncoder,vg=new TextDecoder;var Nn={};V(Nn,{sha256:()=>Mt,sha512:()=>fh});var hh=20;function Fn({name:r,code:e,encode:t,minDigestLength:s,maxDigestLength:n}){return new Cn(r,e,t,s,n)}var Cn=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,s,n,o){this.name=e,this.code=t,this.encode=s,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 s=this.encode(e);return s instanceof Uint8Array?la(s,this.code,t?.truncate):s.then(n=>la(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function la(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Ge(e,r)}function ha(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Mt=Fn({name:"sha2-256",code:18,encode:ha("SHA-256")}),fh=Fn({name:"sha2-512",code:19,encode:ha("SHA-512")});var On={...Rn,...Pn,...Ln,...Dn,...Mn,...En,...Sn,...vn,...Bn,...kn},Lg={...Nn,...Tn};function ms(r=0){return new Uint8Array(r)}function da(r,e,t,s){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:s}}}var fa=da("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Un=da("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=ms(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),dh={utf8:fa,"utf-8":fa,hex:On.base16,latin1:Un,ascii:Un,binary:Un,...On},gs=dh;function j(r,e="utf8"){let t=gs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function q(r,e="utf8"){let t=gs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var ph=parseInt("11111",2),Kn=parseInt("10000000",2),mh=parseInt("01111111",2),pa={0:Br,1:Br,2:gh,3:wh,4:xh,5:yh,6:bh,16:Br,22:Br,48:Br};function et(r,e={offset:0}){let t=r[e.offset]&ph;if(e.offset++,pa[t]!=null)return pa[t](r,e);throw new Error("No decoder for tag "+t)}function Lr(r,e){let t=0;if((r[e.offset]&Kn)===Kn){let s=r[e.offset]&mh,n="0x";e.offset++;for(let o=0;o<s;o++,e.offset++)n+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(n,16)}else t=r[e.offset],e.offset++;return t}function Br(r,e){Lr(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let s=et(r,e);if(s===null)break;t.push(s)}return t}function gh(r,e){let t=Lr(r,e),s=e.offset,n=e.offset+t,o=[];for(let i=s;i<n;i++)i===s&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function bh(r,e){let t=Lr(r,e),s=e.offset+t,n=r[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<s;){let u=r[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 yh(r,e){return e.offset++,null}function wh(r,e){let t=Lr(r,e),s=r[e.offset];e.offset++;let n=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,s!==0)throw new Error("Unused bits in bit string is unimplemented");return n}function xh(r,e){let t=Lr(r,e),s=r.subarray(e.offset,e.offset+t);return e.offset+=t,s}function vh(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new ce;for(let s=0;s<e.length;s+=2)t.append(Uint8Array.from([parseInt(`${e[s]}${e[s+1]}`,16)]));return t}function zn(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=vh(r.byteLength);return new ce(Uint8Array.from([e.byteLength|Kn]),e)}function Ae(r){let e=new ce,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new ce(Uint8Array.from([2]),zn(e),e)}function bs(r){let e=Uint8Array.from([0]),t=new ce(e,r);return new ce(Uint8Array.from([3]),zn(t),t)}function ht(r,e=48){let t=new ce;for(let s of r)t.append(s);return new ce(Uint8Array.from([e]),zn(t),t)}var Eh=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Sh=Uint8Array.from([6,5,43,129,4,0,34]),_h=Uint8Array.from([6,5,43,129,4,0,35]),Ih={ext:!0,kty:"EC",crv:"P-256"},Th={ext:!0,kty:"EC",crv:"P-384"},Ah={ext:!0,kty:"EC",crv:"P-521"},Gn=32,Hn=48,qn=66;function Vn(r){let e=et(r);return ma(e)}function ma(r){let e=r[1][1][0],t=1,s,n;if(e.byteLength===Gn*2+1)return s=q(e.subarray(t,t+Gn),"base64url"),n=q(e.subarray(t+Gn),"base64url"),new Qt({...Ih,key_ops:["verify"],x:s,y:n});if(e.byteLength===Hn*2+1)return s=q(e.subarray(t,t+Hn),"base64url"),n=q(e.subarray(t+Hn),"base64url"),new Qt({...Th,key_ops:["verify"],x:s,y:n});if(e.byteLength===qn*2+1)return s=q(e.subarray(t,t+qn),"base64url"),n=q(e.subarray(t+qn),"base64url"),new Qt({...Ah,key_ops:["verify"],x:s,y:n});throw new X(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function ga(r){return ht([Ae(Uint8Array.from([1])),ht([Dh(r.crv)],160),ht([bs(new ce(Uint8Array.from([4]),j(r.x??"","base64url"),j(r.y??"","base64url")))],161)]).subarray()}function Dh(r){if(r==="P-256")return Eh;if(r==="P-384")return Sh;if(r==="P-521")return _h;throw new X(`Invalid curve ${r}`)}var Qt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=ga(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:ke(this.raw,e.raw)}async verify(e,t,s){return na(this.jwk,t,e,s)}};function Wn(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function ft(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function De(r,e,t=""){let s=Wn(r),n=r?.length,o=e!==void 0;if(!s||o&&n!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",l=s?`length=${n}`:`type=${typeof r}`,u=i+"expected Uint8Array"+a+", got "+l;throw s?new RangeError(u):new TypeError(u)}return r}function ys(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(ft(r.outputLen),ft(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function er(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function ws(r,e){De(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function rt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function xs(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Re(r,e){return r<<32-e|r>>>e}var ya=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Mh=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function vs(r){if(De(r),ya)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Mh[r[t]];return e}var tt={_0:48,_9:57,A:65,F:70,a:97,f:102};function ba(r){if(r>=tt._0&&r<=tt._9)return r-tt._0;if(r>=tt.A&&r<=tt.F)return r-(tt.A-10);if(r>=tt.a&&r<=tt.f)return r-(tt.a-10)}function Rr(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(ya)try{return Uint8Array.fromHex(r)}catch(n){throw n instanceof SyntaxError?new RangeError(n.message):n}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let s=new Uint8Array(t);for(let n=0,o=0;n<t;n++,o+=2){let i=ba(r.charCodeAt(o)),a=ba(r.charCodeAt(o+1));if(i===void 0||a===void 0){let l=r[o]+r[o+1];throw new RangeError('hex string expected, got non-hex character "'+l+'" at index '+o)}s[n]=i*16+a}return s}function $n(...r){let e=0;for(let s=0;s<r.length;s++){let n=r[s];De(n),e+=n.length}let t=new Uint8Array(e);for(let s=0,n=0;s<r.length;s++){let o=r[s];t.set(o,n),n+=o.length}return t}function jn(r,e={}){let t=(n,o)=>r(o).update(n).digest(),s=r(void 0);return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.canXOF=s.canXOF,t.create=n=>r(n),Object.assign(t,e),Object.freeze(t)}function wa(r=32){ft(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var Zn=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function xa(r,e,t){return r&e^~r&t}function va(r,e,t){return r&e^r&t^e&t}var Cr=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,s,n){this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=n,this.buffer=new Uint8Array(e),this.view=xs(this.buffer)}update(e){er(this),De(e);let{view:t,buffer:s,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=xs(e);for(;n<=o-i;i+=n)this.process(l,i);continue}s.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){er(this),ws(e,this),this.finished=!0;let{buffer:t,view:s,blockLen:n,isLE:o}=this,{pos:i}=this;t[i++]=128,rt(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(s,0),i=0);for(let m=i;m<n;m++)t[m]=0;s.setBigUint64(n-8,BigInt(this.length*8),o),this.process(s,0);let a=xs(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 s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:s,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(s),e}clone(){return this._cloneInto()}},st=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 Es=BigInt(4294967295),Ea=BigInt(32);function Ph(r,e=!1){return e?{h:Number(r&Es),l:Number(r>>Ea&Es)}:{h:Number(r>>Ea&Es)|0,l:Number(r&Es)|0}}function Sa(r,e=!1){let t=r.length,s=new Uint32Array(t),n=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=Ph(r[o],e);[s[o],n[o]]=[i,a]}return[s,n]}var Yn=(r,e,t)=>r>>>t,Xn=(r,e,t)=>r<<32-t|e>>>t,Pt=(r,e,t)=>r>>>t|e<<32-t,kt=(r,e,t)=>r<<32-t|e>>>t,Fr=(r,e,t)=>r<<64-t|e>>>t-32,Nr=(r,e,t)=>r>>>t-32|e<<64-t;function Ve(r,e,t,s){let n=(e>>>0)+(s>>>0);return{h:r+t+(n/2**32|0)|0,l:n|0}}var _a=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Ia=(r,e,t,s)=>e+t+s+(r/2**32|0)|0,Ta=(r,e,t,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(s>>>0),Aa=(r,e,t,s,n)=>e+t+s+n+(r/2**32|0)|0,Da=(r,e,t,s,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(s>>>0)+(n>>>0),Ma=(r,e,t,s,n,o)=>e+t+s+n+o+(r/2**32|0)|0;var Bh=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 Cr{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:s,D:n,E:o,F:i,G:a,H:l}=this;return[e,t,s,n,o,i,a,l]}set(e,t,s,n,o,i,a,l){this.A=e|0,this.B=t|0,this.C=s|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:s,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+xa(a,l,u)+Bh[m]+dt[m]|0,g=(Re(s,2)^Re(s,13)^Re(s,22))+va(s,n,o)|0;p=u,u=l,l=a,a=i+w|0,i=o,o=n,n=s,s=w+g|0}s=s+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(s,n,o,i,a,l,u,p)}roundClean(){rt(dt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),rt(this.buffer)}},Qn=class extends Jn{A=st[0]|0;B=st[1]|0;C=st[2]|0;D=st[3]|0;E=st[4]|0;F=st[5]|0;G=st[6]|0;H=st[7]|0;constructor(){super(32)}};var Pa=Sa(["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(r=>BigInt(r))),Lh=Pa[0],Rh=Pa[1],pt=new Uint32Array(80),mt=new Uint32Array(80),eo=class extends Cr{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:s,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,s,n,o,i,a,l,u,p,m,E,w,h,g,b]}set(e,t,s,n,o,i,a,l,u,p,m,E,w,h,g,b){this.Ah=e|0,this.Al=t|0,this.Bh=s|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=Pt(f,d,1)^Pt(f,d,8)^Yn(f,d,7),v=kt(f,d,1)^kt(f,d,8)^Xn(f,d,7),S=pt[c-2]|0,M=mt[c-2]|0,C=Pt(S,M,19)^Fr(S,M,61)^Yn(S,M,6),N=kt(S,M,19)^Nr(S,M,61)^Xn(S,M,6),I=Ta(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:s,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=Pt(m,E,14)^Pt(m,E,18)^Fr(m,E,41),d=kt(m,E,14)^kt(m,E,18)^Nr(m,E,41),y=m&w^~m&g,v=E&h^~E&b,S=Da(_,d,v,Rh[c],mt[c]),M=Ma(S,x,f,y,Lh[c],pt[c]),C=S|0,N=Pt(s,n,28)^Fr(s,n,34)^Fr(s,n,39),I=kt(s,n,28)^Nr(s,n,34)^Nr(s,n,39),T=s&o^s&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=s|0,i=n|0;let D=_a(C,I,P);s=Ia(D,M,N,T),n=D|0}({h:s,l:n}=Ve(this.Ah|0,this.Al|0,s|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(s,n,o,i,a,l,u,p,m,E,w,h,g,b,x,_)}roundClean(){rt(pt,mt)}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)}},to=class extends eo{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 tr=jn(()=>new Qn,Zn(1));var Ss=jn(()=>new to,Zn(3));var K=(r,e,t)=>De(r,e,t),so=ft,rr=vs,oe=(...r)=>$n(...r),sr=r=>Rr(r),Bt=Wn,Or=r=>wa(r),Is=BigInt(0),ro=BigInt(1);function Ce(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function Ts(r){if(typeof r=="bigint"){if(!_s(r))throw new RangeError("positive bigint expected, got "+r)}else so(r);return r}function Fe(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function Ur(r){let e=Ts(r).toString(16);return e.length&1?"0"+e:e}function ka(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Is:BigInt("0x"+r)}function Lt(r){return ka(vs(r))}function We(r){return ka(vs(Kr(De(r)).reverse()))}function As(r,e){if(ft(e),e===0)throw new RangeError("zero length");r=Ts(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Rr(t.padStart(e*2,"0"))}function no(r,e){return As(r,e).reverse()}function Ba(r,e){if(r=K(r),e=K(e),r.length!==e.length)return!1;let t=0;for(let s=0;s<r.length;s++)t|=r[s]^e[s];return t===0}function Kr(r){return Uint8Array.from(K(r))}function Ds(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let s=e.charCodeAt(0);if(e.length!==1||s>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${s} at position ${t}`);return s})}var _s=r=>typeof r=="bigint"&&Is<=r;function Ch(r,e,t){return _s(r)&&_s(e)&&_s(t)&&e<=r&&r<t}function nr(r,e,t,s){if(!Ch(e,t,s))throw new RangeError("expected valid "+r+": "+t+" <= n < "+s+", got "+e)}function or(r){if(r<Is)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>Is;r>>=ro,e+=1);return e}var zr=r=>(ro<<BigInt(r))-ro;function La(r,e,t){if(ft(r,"hashLen"),ft(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let s=b=>new Uint8Array(b),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,l=s(r),u=s(r),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(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function s(o,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,o))throw new TypeError(`param "${o}" is invalid: expected own property`);let l=r[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])=>s(a,l,i));n(e,!1),n(t,!0)}var oo=()=>{throw new Error("not implemented")};var fe=BigInt(0),ee=BigInt(1),Rt=BigInt(2),Na=BigInt(3),Oa=BigInt(4),Ua=BigInt(5),Fh=BigInt(7),Ka=BigInt(8),Nh=BigInt(9),za=BigInt(16);function se(r,e){if(e<=fe)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=fe?t:e+t}function $(r,e,t){if(e<fe)throw new Error("pow2: expected non-negative exponent, got "+e);let s=r;for(;e-- >fe;)s*=s,s%=t;return s}function Ra(r,e){if(r===fe)throw new Error("invert: expected non-zero number");if(e<=fe)throw new Error("invert: expected positive modulus, got "+e);let t=se(r,e),s=e,n=fe,o=ee,i=ee,a=fe;for(;t!==fe;){let u=s/t,p=s-t*u,m=n-i*u,E=o-a*u;s=t,t=p,n=i,o=a,i=m,a=E}if(s!==ee)throw new Error("invert: does not exist");return se(n,e)}function io(r,e,t){let s=r;if(!s.eql(s.sqr(e),t))throw new Error("Cannot find square root")}function Ga(r,e){let t=r,s=(t.ORDER+ee)/Oa,n=t.pow(e,s);return io(t,n,e),n}function Oh(r,e){let t=r,s=(t.ORDER-Ua)/Ka,n=t.mul(e,Rt),o=t.pow(n,s),i=t.mul(e,o),a=t.mul(t.mul(i,Rt),o),l=t.mul(i,t.sub(a,t.ONE));return io(t,l,e),l}function Uh(r){let e=ir(r),t=Ha(r),s=t(e,e.neg(e.ONE)),n=t(e,s),o=t(e,e.neg(s)),i=(r+Fh)/za;return((a,l)=>{let u=a,p=u.pow(l,i),m=u.mul(p,s),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 io(u,x,l),x})}function Ha(r){if(r<Na)throw new Error("sqrt is not defined for small field");let e=r-ee,t=0;for(;e%Rt===fe;)e/=Rt,t++;let s=Rt,n=ir(r);for(;Ca(n,s)===1;)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Ga;let o=n.pow(s,e),i=(e+ee)/Rt;return function(l,u){let p=l;if(p.is0(u))return u;if(Ca(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 Kh(r){return r%Oa===Na?Ga:r%Ka===Ua?Oh:r%za===Nh?Uh(r):Ha(r)}var nt=(r,e)=>(se(r,e)&ee)===ee,zh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ao(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=zh.reduce((s,n)=>(s[n]="function",s),e);if(Ne(r,t),Fe(r.BYTES,"BYTES"),Fe(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=ee)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Gh(r,e,t){let s=r;if(t<fe)throw new Error("invalid exponent, negatives unsupported");if(t===fe)return s.ONE;if(t===ee)return e;let n=s.ONE,o=e;for(;t>fe;)t&ee&&(n=s.mul(n,o)),o=s.sqr(o),t>>=ee;return n}function Gr(r,e,t=!1){let s=r,n=new Array(e.length).fill(t?s.ZERO:void 0),o=e.reduce((a,l,u)=>s.is0(l)?a:(n[u]=a,s.mul(a,l)),s.ONE),i=s.inv(o);return e.reduceRight((a,l,u)=>s.is0(l)?a:(n[u]=s.mul(a,n[u]),s.mul(a,l)),i),n}function Ca(r,e){let t=r,s=(t.ORDER-ee)/Rt,n=t.pow(e,s),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 Hh(r,e){if(e!==void 0&&so(e),r<=fe)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=or(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let s=e!==void 0?e:t,n=Math.ceil(s/8);return{nBitLength:s,nByteLength:n}}var Fa=new WeakMap,Ms=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 s;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(s=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}=Hh(e,s);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 se(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 se(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return se(e*e,this.ORDER)}add(e,t){return se(e+t,this.ORDER)}sub(e,t){return se(e-t,this.ORDER)}mul(e,t){return se(e*t,this.ORDER)}pow(e,t){return Gh(this,e,t)}div(e,t){return se(e*Ra(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 Ra(e,this.ORDER)}sqrt(e){let t=Fa.get(this);return t||Fa.set(this,t=Kh(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?no(e,this.BYTES):As(e,this.BYTES)}fromBytes(e,t=!1){K(e);let{_lengths:s,BYTES:n,isLE:o,ORDER:i,_mod:a}=this;if(s){if(e.length<1||!s.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+s+" 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):Lt(e);if(a&&(l=se(l,i)),!t&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return Gr(this,e)}cmov(e,t,s){return Ce(s,"condition"),s?t:e}};Object.freeze(Ms.prototype);function ir(r,e={}){return new Ms(r,e)}function qa(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=ee)throw new Error("field order must be greater than 1");let e=or(r-ee);return Math.ceil(e/8)}function co(r){let e=qa(r);return e+Math.ceil(e/2)}function lo(r,e,t=!1){K(r);let s=r.length,n=qa(e),o=Math.max(co(e),16);if(s<o||s>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+s);let i=t?We(r):Lt(r),a=se(i,e-ee)+ee;return t?no(a,n):As(a,n)}var ar=BigInt(0),Ct=BigInt(1);function Hr(r,e){let t=e.negate();return r?t:e}function Ft(r,e){let t=Gr(r.Fp,e.map(s=>s.Z));return e.map((s,n)=>r.fromAffine(s.toAffine(t[n])))}function ja(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function uo(r,e){ja(r,e);let t=Math.ceil(e/r)+1,s=2**(r-1),n=2**r,o=zr(r),i=BigInt(r);return{windows:t,windowSize:s,mask:o,maxNumber:n,shiftBy:i}}function Va(r,e,t){let{windowSize:s,mask:n,maxNumber:o,shiftBy:i}=t,a=Number(r&n),l=r>>i;a>s&&(a-=o,l+=Ct);let u=e*s,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 ho=new WeakMap,Za=new WeakMap;function fo(r){return Za.get(r)||1}function Wa(r){if(r!==ar)throw new Error("invalid wNAF")}var cr=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,s=this.ZERO){let n=e;for(;t>ar;)t&Ct&&(s=s.add(n)),n=n.double(),t>>=Ct;return s}precomputeWindow(e,t){let{windows:s,windowSize:n}=uo(t,this.bits),o=[],i=e,a=i;for(let l=0;l<s;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,s){if(!this.Fn.isValid(s))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE,i=uo(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:l,offset:u,isZero:p,isNeg:m,isNegF:E,offsetF:w}=Va(s,a,i);s=l,p?o=o.add(Hr(E,t[w])):n=n.add(Hr(m,t[u]))}return Wa(s),{p:n,f:o}}wNAFUnsafe(e,t,s,n=this.ZERO){let o=uo(e,this.bits);for(let i=0;i<o.windows&&s!==ar;i++){let{nextN:a,offset:l,isZero:u,isNeg:p}=Va(s,i,o);if(s=a,!u){let m=t[l];n=n.add(p?m.negate():m)}}return Wa(s),n}getPrecomputes(e,t,s){let n=ho.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof s=="function"&&(n=s(n)),ho.set(t,n))),n}cached(e,t,s){let n=fo(e);return this.wNAF(n,this.getPrecomputes(n,e,s),t)}unsafe(e,t,s,n){let o=fo(e);return o===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,s),t,n)}createCache(e,t){ja(t,this.bits),Za.set(e,t),ho.delete(e)}hasCache(e){return fo(e)!==1}};function Ya(r,e,t,s){let n=e,o=r.ZERO,i=r.ZERO;for(;t>ar||s>ar;)t&Ct&&(o=o.add(n)),s&Ct&&(i=i.add(n)),n=n.double(),t>>=Ct,s>>=Ct;return{p1:o,p2:i}}function $a(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ao(e),e}else return ir(r,{isLE:t})}function Ps(r,e,t={},s){if(s===void 0&&(s=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let l of["p","n","h"]){let u=e[l];if(!(typeof u=="bigint"&&u>ar))throw new Error(`CURVE.${l} must be positive bigint`)}let n=$a(e.p,t.Fp,s),o=$a(e.n,t.Fn,s),a=["Gx","Gy","a",r==="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 ks(r,e){return function(s){let n=r(s);return{secretKey:n,publicKey:e(n)}}}var gt=BigInt(0),le=BigInt(1),po=BigInt(2),qh=BigInt(8);function Vh(r,e,t,s){let n=r.sqr(t),o=r.sqr(s),i=r.add(r.mul(e.a,n),o),a=r.add(r.ONE,r.mul(e.d,r.mul(n,o)));return r.eql(i,a)}function Xa(r,e={}){let t=e,s=Ps("edwards",r,t,t.FpFnLE),{Fp:n,Fn:o}=s,i=s.CURVE,{h:a}=i;Ne(t,{},{uvRatio:"function"});let l=po<<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(!Vh(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 nr("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=Kr(K(b,_,"point")),Ce(x,"zip215");let d=Kr(b),y=b[_-1];d[_-1]=y&-129;let v=We(d),S=x?l:n.ORDER;nr("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,D=(y&128)!==0;if(!x&&T===gt&&D)throw new Error("bad point: x=0 and x_0=1");return D!==P&&(T=u(-T)),w.fromAffine({x:T,y:v})}static fromHex(b,x=!1){return w.fromBytes(sr(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(po),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),D=u(d*y);if(P!==D)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(po*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),D=u(M*I),A=u(N*C);return new w(T,P,A,D)}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),D=u((c+f)*(v+S)-N-I),A=P-T,k=P+T,L=u(I-x*N),B=u(D*A),R=u(k*L),F=u(D*L),U=u(A*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=>Ft(w,c));return Ft(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=>Ft(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?qh: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 rr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let h=new cr(w,o.BITS);return o.BITS>=8&&w.BASE.precompute(8),Object.freeze(w.prototype),Object.freeze(w),w}var Bs=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){oo()}static fromHex(e){oo()}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 rr(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 Ja(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let s=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}=r,u=s.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?Or: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(s(I),2*T,"hashedSecretKey"),D=E(P.slice(0,T)),A=P.slice(T,2*T),k=h(D);return{head:D,prefix:A,scalar:k}}function b(I){let{head:T,prefix:P,scalar:D}=g(I),A=i.multiply(D),k=A.toBytes();return{head:T,prefix:P,scalar:D,point:A,pointBytes:k}}function x(I){return b(I).pointBytes}function _(I=Uint8Array.of(),...T){let P=oe(...T);return h(s(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:D,scalar:A,pointBytes:k}=b(T),L=_(P.context,D,I),B=i.multiply(L).toBytes(),R=_(P.context,B,k,I),F=l.create(L+R*A);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,D=f){let{context:A}=D,k=D.zip215===void 0?!!f.zip215:D.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=r.fromBytes(P,k),z=r.fromBytes(R,k),O=i.multiplyUnsafe(F)}catch{return!1}if(!k&&U.isSmallOrder())return!1;let ne=_(A,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 Bt(I)&&I.length===v.secretKey}function C(I,T){try{return!!r.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}=r.fromBytes(I),P=v.publicKey,D=P===32;if(!D&&P!==57)throw new Error("only defined for 25519 and 448");let A=D?a.div(le+T,le-T):a.div(T-le,T+le);return a.toBytes(A)},toMontgomerySecret(I){let T=v.secretKey;K(I,T);let P=s(I.subarray(0,T));return E(P).subarray(0,T)}};return Object.freeze(v),Object.freeze(N),Object.freeze({keygen:ks(S,x),getPublicKey:x,sign:c,verify:d,utils:N,Point:r,lengths:v})}function qr(r,e){if(Fe(r),Fe(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let s=e-1;s>=0;s--)t[s]=r&255,r>>>=8;return new Uint8Array(t)}function Wh(r,e){let t=new Uint8Array(r.length);for(let s=0;s<r.length;s++)t[s]=r[s]^e[s];return t}function $h(r){if(!Bt(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?Ds(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function mo(r,e,t,s){K(r),Fe(t),e=$h(e),e.length>255&&(e=s(oe(Ds("H2C-OVERSIZE-DST-"),e)));let{outputLen:n,blockLen:o}=s,i=Math.ceil(t/n);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=oe(e,qr(e.length,1)),l=new Uint8Array(o),u=qr(t,2),p=new Array(i),m=s(oe(l,r,u,qr(0,1),a));p[0]=s(oe(m,qr(1,1),a));for(let w=1;w<i;w++){let h=[Wh(m,p[w-1]),qr(w+1,1),a];p[w]=s(oe(...h))}return oe(...p).slice(0,t)}var Qa="HashToScalar-";var jh=BigInt(0),ot=BigInt(1),ec=BigInt(2);var Zh=BigInt(5),Yh=BigInt(8),lr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),wo={p:lr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Yh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Xh(r){let e=BigInt(10),t=BigInt(20),s=BigInt(40),n=BigInt(80),o=lr,a=r*r%o*r%o,l=$(a,ec,o)*a%o,u=$(l,ot,o)*r%o,p=$(u,Zh,o)*u%o,m=$(p,e,o)*p%o,E=$(m,t,o)*m%o,w=$(E,s,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,ec,o)*r%o,b2:a}}function Jh(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var go=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function xo(r,e){let t=lr,s=se(e*e*e,t),n=se(s*s*e,t),o=Xh(r*n).pow_p_5_8,i=se(r*s*o,t),a=se(e*i*i,t),l=i,u=se(i*go,t),p=a===r,m=a===se(-r,t),E=a===se(-r*go,t);return p&&(i=l),(m||E)&&(i=u),nt(i,t)&&(i=se(-i,t)),{isValid:p||m,value:i}}var yt=Xa(wo,{uvRatio:xo}),bt=yt.Fp,sc=yt.Fn;function Qh(r){return Ja(yt,Ss,Object.assign({adjustScalarBytes:Jh,zip215:!0},r))}var nc=Qh({});var bo=go,ef=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),tf=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),rf=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),sf=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),tc=r=>xo(ot,r),nf=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),yo=r=>bt.create(We(r)&nf);function rc(r){let{d:e}=wo,t=lr,s=x=>bt.create(x),n=s(bo*r*r),o=s((n+ot)*rf),i=BigInt(-1),a=s((i-e*n)*s(n+e)),{isValid:l,value:u}=xo(o,a),p=s(u*r);nt(p,t)||(p=s(-p)),l||(u=p),l||(i=n);let m=s(i*(n-ot)*sf-a),E=u*u,w=s((u+u)*a),h=s(m*ef),g=s(ot-E),b=s(ot+E);return new yt(s(w*b),s(g*h),s(h*b),s(w*g))}var wt=class r extends Bs{static BASE=new r(yt.BASE);static ZERO=new r(yt.ZERO);static Fp=bt;static Fn=sc;constructor(e){super(e)}static fromAffine(e){return new r(yt.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){De(e,32);let{a:t,d:s}=wo,n=lr,o=f=>bt.create(f),i=yo(e);if(!Ba(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*s*p-m),{isValid:w,value:h}=tc(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)||_===jh)throw new Error("invalid ristretto255 encoding 2");return new r(new yt(x,_,ot,c))}static fromHex(e){return r.fromBytes(Rr(e))}toBytes(){let{X:e,Y:t,Z:s,T:n}=this.ep,o=lr,i=b=>bt.create(b),a=i(i(s+t)*i(s-t)),l=i(e*t),u=i(l*l),{value:p}=tc(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*bo),x=i(e*bo);e=b,t=x,h=i(m*tf)}else h=E;nt(e*w,o)&&(t=i(-t));let g=i((s-t)*h);return nt(g,o)&&(g=i(-g)),bt.toBytes(g)}equals(e){this.assertSame(e);let{X:t,Y:s}=this.ep,{X:n,Y:o}=e.ep,i=u=>bt.create(u),a=i(t*o)===i(s*n),l=i(s*o)===i(t*n);return a||l}is0(){return this.equals(r.ZERO)}};Object.freeze(wt.BASE);Object.freeze(wt.ZERO);Object.freeze(wt.prototype);Object.freeze(wt);var of=Object.freeze({Point:wt,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,s=mo(r,t,64,Ss);return of.deriveToCurve(s)},hashToScalar(r,e={DST:Qa}){let t=mo(r,e.DST,64,Ss);return sc.create(We(t))},deriveToCurve(r){De(r,64);let e=yo(r.subarray(0,32)),t=rc(e),s=yo(r.subarray(32,64)),n=rc(s);return new wt(t.add(n))}});var Vr=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Ls=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Be={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Ls("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 Rs=32;var vo,af=(async()=>{try{return await Be.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function cf(r,e,t){if(r.buffer instanceof ArrayBuffer){let s=await Be.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Be.get().subtle.verify({name:"Ed25519"},s,He(e),He(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function lf(r,e,t){return nc.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function oc(r,e,t){return vo==null&&(vo=await af),vo?cf(r,e,t):lf(r,e,t)}function uf(r){return r?.buffer instanceof ArrayBuffer}function ac(r){if(uf(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Cs(r,e){e==null&&(e=r.reduce((n,o)=>n+o.length,0));let t=ms(e),s=0;for(let n of r)t.set(n,s),s+=n.length;return ac(t)}function Fs(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ns=class{type="Ed25519";raw;constructor(e){this.raw=Eo(e,Rs)}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:ke(this.raw,e.raw)}verify(e,t,s){s?.signal?.throwIfAborted();let n=oc(this.raw,t,e);return Fs(n)?n.then(o=>(s?.signal?.throwIfAborted(),o)):n}};function So(r){return r=Eo(r,Rs),new Ns(r)}function Eo(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new X(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}function xt(r=0){return new Uint8Array(r)}var ff=Math.pow(2,7),df=Math.pow(2,14),pf=Math.pow(2,21),cc=Math.pow(2,28),lc=Math.pow(2,35),uc=Math.pow(2,42),hc=Math.pow(2,49),ye=128,vt=127;function Wr(r){if(r<ff)return 1;if(r<df)return 2;if(r<pf)return 3;if(r<cc)return 4;if(r<lc)return 5;if(r<uc)return 6;if(r<hc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function fc(r,e,t=0){switch(Wr(r)){case 8:e[t++]=r&255|ye,r/=128;case 7:e[t++]=r&255|ye,r/=128;case 6:e[t++]=r&255|ye,r/=128;case 5:e[t++]=r&255|ye,r/=128;case 4:e[t++]=r&255|ye,r>>>=7;case 3:e[t++]=r&255|ye,r>>>=7;case 2:e[t++]=r&255|ye,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function dc(r,e){let t=r[e],s=0;if(s+=t&vt,t<ye||(t=r[e+1],s+=(t&vt)<<7,t<ye)||(t=r[e+2],s+=(t&vt)<<14,t<ye)||(t=r[e+3],s+=(t&vt)<<21,t<ye)||(t=r[e+4],s+=(t&vt)*cc,t<ye)||(t=r[e+5],s+=(t&vt)*lc,t<ye)||(t=r[e+6],s+=(t&vt)*uc,t<ye)||(t=r[e+7],s+=(t&vt)*hc,t<ye))return s;throw new RangeError("Could not decode varint")}var _o=new Float32Array([-0]),Et=new Uint8Array(_o.buffer);function pc(r,e,t){_o[0]=r,e[t]=Et[0],e[t+1]=Et[1],e[t+2]=Et[2],e[t+3]=Et[3]}function mc(r,e){return Et[0]=r[e],Et[1]=r[e+1],Et[2]=r[e+2],Et[3]=r[e+3],_o[0]}var Io=new Float64Array([-0]),de=new Uint8Array(Io.buffer);function gc(r,e,t){Io[0]=r,e[t]=de[0],e[t+1]=de[1],e[t+2]=de[2],e[t+3]=de[3],e[t+4]=de[4],e[t+5]=de[5],e[t+6]=de[6],e[t+7]=de[7]}function bc(r,e){return de[0]=r[e],de[1]=r[e+1],de[2]=r[e+2],de[3]=r[e+3],de[4]=r[e+4],de[5]=r[e+5],de[6]=r[e+6],de[7]=r[e+7],Io[0]}var mf=BigInt(Number.MAX_SAFE_INTEGER),gf=BigInt(Number.MIN_SAFE_INTEGER),Me=class r{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,s=~this.hi>>>0;return t===0&&(s=s+1>>>0),-(t+s*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,s=~this.hi>>>0;return t===0&&(s=s+1>>>0),-(BigInt(t)+(BigInt(s)<<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,s=this.hi>>>24;return s===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:s<128?9:10}static fromBigInt(e){if(e===0n)return Nt;if(e<mf&&e>gf)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let s=e>>32n,n=e-(s<<32n);return t&&(s=~s|0n,n=~n|0n,++n>yc&&(n=0n,++s>yc&&(s=0n))),new r(Number(n),Number(s))}static fromNumber(e){if(e===0)return Nt;let t=e<0;t&&(e=-e);let s=e>>>0,n=(e-s)/4294967296>>>0;return t&&(n=~n>>>0,s=~s>>>0,++s>4294967295&&(s=0,++n>4294967295&&(n=0))),new r(s,n)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):Nt}},Nt=new Me(0,0);Nt.toBigInt=function(){return 0n};Nt.zzEncode=Nt.zzDecode=function(){return this};Nt.length=function(){return 1};var yc=4294967296n;function wc(r){let e=0,t=0;for(let s=0;s<r.length;++s)t=r.charCodeAt(s),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(s+1)&64512)===56320?(++s,e+=4):e+=3;return e}function xc(r,e,t){if(t-e<1)return"";let n,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[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 To(r,e,t){let s=t,n,o;for(let i=0;i<r.length;++i)n=r.charCodeAt(i),n<128?e[t++]=n:n<2048?(e[t++]=n>>6|192,e[t++]=n&63|128):(n&64512)===55296&&((o=r.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-s}function Oe(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Os(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Ao=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 Os(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Oe(this,4);return Os(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Oe(this,4);let e=mc(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Oe(this,4);let e=bc(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,s=this.pos+e;if(s>this.len)throw Oe(this,e);return this.pos+=e,t===s?new Uint8Array(0):this.buf.subarray(t,s)}string(){let e=this.bytes();return xc(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 Me(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw 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=Os(this.buf,this.pos+=4),t=Os(this.buf,this.pos+=4);return new Me(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=dc(this.buf,this.pos);return this.pos+=Wr(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 $r(r){return new Ao(r instanceof Uint8Array?r:r.subarray())}function we(r,e,t){let s=$r(r);return e.decode(s,void 0,t)}var Bo={};V(Bo,{base10:()=>Sf});var Ib=new Uint8Array(0);function Ec(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function it(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Sc(r){return new TextEncoder().encode(r)}function _c(r){return new TextDecoder().decode(r)}function bf(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),s=0;s<t.length;s++)t[s]=255;for(var n=0;n<r.length;n++){var o=r.charAt(n),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=n}var a=r.length,l=r.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+=r.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 yf=bf,wf=yf,Tc=wf;var Do=class{name;prefix;baseEncode;constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Mo=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,s){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=s}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 Ac(this,e)}},Po=class{decoders;constructor(e){this.decoders=e}or(e){return Ac(this,e)}decode(e){let t=e[0],s=this.decoders[t];if(s!=null)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Ac(r,e){return new Po({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ko=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,s,n){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=n,this.encoder=new Do(e,t,s),this.decoder=new Mo(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ur({name:r,prefix:e,encode:t,decode:s}){return new ko(r,e,t,s)}function St({name:r,prefix:e,alphabet:t}){let{encode:s,decode:n}=Tc(t,r);return ur({prefix:e,name:r,encode:s,decode:o=>it(n(o))})}function xf(r,e,t,s){let n=r.length;for(;r[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[r[u]];if(p===void 0)throw new SyntaxError(`Non-${s} 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 vf(r,e,t){let s=e[e.length-1]==="=",n=(1<<t)-1,o="",i=0,a=0;for(let l=0;l<r.length;++l)for(a=a<<8|r[l],i+=8;i>t;)i-=t,o+=e[n&a>>i];if(i!==0&&(o+=e[n&a<<t-i]),s)for(;(o.length*t&7)!==0;)o+="=";return o}function Ef(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function te({name:r,prefix:e,bitsPerChar:t,alphabet:s}){let n=Ef(s);return ur({prefix:e,name:r,encode(o){return vf(o,s,t)},decode(o){return xf(o,n,t,r)}})}var Sf=St({prefix:"9",name:"base10",alphabet:"0123456789"});var Lo={};V(Lo,{base16:()=>_f,base16upper:()=>If});var _f=te({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),If=te({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ro={};V(Ro,{base2:()=>Tf});var Tf=te({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Co={};V(Co,{base256emoji:()=>kf});var Dc=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}"),Af=Dc.reduce((r,e,t)=>(r[t]=e,r),[]),Df=Dc.reduce((r,e,t)=>{let s=e.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${e}`);return r[s]=t,r},[]);function Mf(r){return r.reduce((e,t)=>(e+=Af[t],e),"")}function Pf(r){let e=[];for(let t of r){let s=t.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${t}`);let n=Df[s];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var kf=ur({prefix:"\u{1F680}",name:"base256emoji",encode:Mf,decode:Pf});var Fo={};V(Fo,{base32:()=>hr,base32hex:()=>Cf,base32hexpad:()=>Nf,base32hexpadupper:()=>Of,base32hexupper:()=>Ff,base32pad:()=>Lf,base32padupper:()=>Rf,base32upper:()=>Bf,base32z:()=>Uf});var hr=te({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Bf=te({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Lf=te({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Rf=te({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Cf=te({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ff=te({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Nf=te({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Of=te({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Uf=te({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var No={};V(No,{base36:()=>jr,base36upper:()=>Kf});var jr=St({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Kf=St({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Oo={};V(Oo,{base58btc:()=>$e,base58flickr:()=>zf});var $e=St({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),zf=St({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Uo={};V(Uo,{base64:()=>Gf,base64pad:()=>Hf,base64url:()=>qf,base64urlpad:()=>Vf});var Gf=te({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Hf=te({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),qf=te({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Vf=te({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ko={};V(Ko,{base8:()=>Wf});var Wf=te({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var zo={};V(zo,{identity:()=>$f});var $f=ur({prefix:"\0",name:"identity",encode:r=>_c(r),decode:r=>Sc(r)});var zb=new TextEncoder,Gb=new TextDecoder;var Ho={};V(Ho,{identity:()=>gd});var Yf=kc,Mc=128,Xf=127,Jf=~Xf,Qf=Math.pow(2,31);function kc(r,e,t){e=e||[],t=t||0;for(var s=t;r>=Qf;)e[t++]=r&255|Mc,r/=128;for(;r&Jf;)e[t++]=r&255|Mc,r>>>=7;return e[t]=r|0,kc.bytes=t-s+1,e}var ed=Go,td=128,Pc=127;function Go(r,s){var t=0,s=s||0,n=0,o=s,i,a=r.length;do{if(o>=a)throw Go.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=n<28?(i&Pc)<<n:(i&Pc)*Math.pow(2,n),n+=7}while(i>=td);return Go.bytes=o-s,t}var rd=Math.pow(2,7),sd=Math.pow(2,14),nd=Math.pow(2,21),od=Math.pow(2,28),id=Math.pow(2,35),ad=Math.pow(2,42),cd=Math.pow(2,49),ld=Math.pow(2,56),ud=Math.pow(2,63),hd=function(r){return r<rd?1:r<sd?2:r<nd?3:r<od?4:r<id?5:r<ad?6:r<cd?7:r<ld?8:r<ud?9:10},fd={encode:Yf,decode:ed,encodingLength:hd},dd=fd,Zr=dd;function Yr(r,e=0){return[Zr.decode(r,e),Zr.decode.bytes]}function fr(r,e,t=0){return Zr.encode(r,e,t),e}function dr(r){return Zr.encodingLength(r)}function mr(r,e){let t=e.byteLength,s=dr(r),n=s+dr(t),o=new Uint8Array(n+t);return fr(r,o,0),fr(t,o,s),o.set(e,n),new pr(r,t,e,o)}function Bc(r){let e=it(r),[t,s]=Yr(e),[n,o]=Yr(e.subarray(s)),i=e.subarray(s+o);if(i.byteLength!==n)throw new Error("Incorrect length");return new pr(t,n,i,e)}function Lc(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Ec(r.bytes,t.bytes)}}var pr=class{code;size;digest;bytes;constructor(e,t,s,n){this.code=e,this.size=t,this.digest=s,this.bytes=n}};var Rc=0,pd="identity",Cc=it;function md(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return mr(Rc,Cc(r))}var gd={code:Rc,name:pd,encode:Cc,digest:md};var Wo={};V(Wo,{sha256:()=>yd,sha512:()=>wd});var bd=20;function Vo({name:r,code:e,encode:t,minDigestLength:s,maxDigestLength:n}){return new qo(r,e,t,s,n)}var qo=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,s,n,o){this.name=e,this.code=t,this.encode=s,this.minDigestLength=n??bd,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 s=this.encode(e);return s instanceof Uint8Array?Fc(s,this.code,t?.truncate):s.then(n=>Fc(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Fc(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return mr(e,r)}function Oc(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var yd=Vo({name:"sha2-256",code:18,encode:Oc("SHA-256")}),wd=Vo({name:"sha2-512",code:19,encode:Oc("SHA-512")});function Uc(r,e){let{bytes:t,version:s}=r;return s===0?vd(t,$o(r),e??$e.encoder):Ed(t,$o(r),e??hr.encoder)}var Kc=new WeakMap;function $o(r){let e=Kc.get(r);if(e==null){let t=new Map;return Kc.set(r,t),t}return e}var Ks=class r{code;version;multihash;bytes;"/";constructor(e,t,s,n){this.code=t,this.version=e,this.multihash=s,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!==Jr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Sd)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.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,s=mr(e,t);return r.createV1(this.code,s)}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 r.equals(this,e)}static equals(e,t){let s=t;return s!=null&&e.code===s.code&&e.version===s.version&&Lc(e.multihash,s.multihash)}toString(e){return Uc(this,e)}toJSON(){return{"/":Uc(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 r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:s,code:n,multihash:o,bytes:i}=t;return new r(s,n,o,i??zc(s,n,o.bytes))}else if(t[_d]===!0){let{version:s,multihash:n,code:o}=t,i=Bc(n);return r.create(s,o,i)}else return null}static create(e,t,s){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(s.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Jr)throw new Error(`Version 0 CID must use dag-pb (code: ${Jr}) block encoding`);return new r(e,t,s,s.bytes)}case 1:{let n=zc(e,t,s.bytes);return new r(e,t,s,n)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Jr,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,s]=r.decodeFirst(e);if(s.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),s=t.size-t.multihashSize,n=it(e.subarray(s,s+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=n.subarray(t.multihashSize-t.digestSize),i=new pr(t.multihashCode,t.digestSize,o,n);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,s=()=>{let[m,E]=Yr(e.subarray(t));return t+=E,m},n=s(),o=Jr;if(n===18?(n=0,t=0):o=s(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let i=t,a=s(),l=s(),u=t+l,p=u-i;return{version:n,codec:o,multihashCode:a,digestSize:l,multihashSize:p,size:u}}static parse(e,t){let[s,n]=xd(e,t),o=r.decode(n);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return $o(o).set(s,e),o}};function xd(r,e){switch(r[0]){case"Q":{let t=e??$e;return[$e.prefix,t.decode(`${$e.prefix}${r}`)]}case $e.prefix:{let t=e??$e;return[$e.prefix,t.decode(r)]}case hr.prefix:{let t=e??hr;return[hr.prefix,t.decode(r)]}case jr.prefix:{let t=e??jr;return[jr.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function vd(r,e,t){let{prefix:s}=t;if(s!==$e.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let n=e.get(s);if(n==null){let o=t.encode(r).slice(1);return e.set(s,o),o}else return n}function Ed(r,e,t){let{prefix:s}=t,n=e.get(s);if(n==null){let o=t.encode(r);return e.set(s,o),o}else return n}var Jr=112,Sd=18;function zc(r,e,t){let s=dr(r),n=s+dr(e),o=new Uint8Array(n+t.byteLength);return fr(r,o,0),fr(e,o,s),o.set(t,n),o}var _d=Symbol.for("@ipld/js-cid/CID");var jo={...zo,...Ro,...Ko,...Bo,...Lo,...Fo,...No,...Oo,...Uo,...Co},uy={...Wo,...Ho};function Hc(r,e,t,s){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:s}}}var Gc=Hc("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Zo=Hc("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=xt(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Id={utf8:Gc,"utf-8":Gc,hex:jo.base16,latin1:Zo,ascii:Zo,binary:Zo,...jo},qc=Id;function Vc(r,e="utf8"){let t=qc[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Yo(r){let e=r??8192,t=e>>>1,s,n=e;return function(i){if(i<1||i>t)return xt(i);n+i>e&&(s=xt(e),n=0);let a=s.subarray(n,n+=i);return(n&7)!==0&&(n=(n|7)+1),a}}var Ot=class{fn;len;next;val;constructor(e,t,s){this.fn=e,this.len=t,this.next=void 0,this.val=s}};function Xo(){}var Qo=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Td=Yo();function Ad(r){return globalThis.Buffer!=null?xt(r):Td(r)}var es=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ot(Xo,0,0),this.tail=this.head,this.states=null}_push(e,t,s){return this.tail=this.tail.next=new Ot(e,t,s),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new ei((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(zs,10,Me.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Me.fromBigInt(e);return this._push(zs,t.length(),t)}uint64Number(e){return this._push(fc,Wr(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Me.fromBigInt(e).zzEncode();return this._push(zs,t.length(),t)}sint64Number(e){let t=Me.fromNumber(e).zzEncode();return this._push(zs,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Jo,1,e?1:0)}fixed32(e){return this._push(Qr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Me.fromBigInt(e);return this._push(Qr,4,t.lo)._push(Qr,4,t.hi)}fixed64Number(e){let t=Me.fromNumber(e);return this._push(Qr,4,t.lo)._push(Qr,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(pc,4,e)}double(e){return this._push(gc,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Jo,1,0):this.uint32(t)._push(Md,t,e)}string(e){let t=wc(e);return t!==0?this.uint32(t)._push(To,t,e):this._push(Jo,1,0)}fork(){return this.states=new Qo(this),this.head=this.tail=new Ot(Xo,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 Ot(Xo,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,s=this.len;return this.reset().uint32(s),s!==0&&(this.tail.next=e.next,this.tail=t,this.len+=s),this}finish(){let e=this.head.next,t=Ad(this.len),s=0;for(;e!=null;)e.fn(e.val,t,s),s+=e.len,e=e.next;return t}};function Jo(r,e,t){e[t]=r&255}function Dd(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var ei=class extends Ot{next;constructor(e,t){super(Dd,e,t),this.next=void 0}};function zs(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Qr(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function Md(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(es.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Pd,e,r),this},es.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(kd,e,r),this});function Pd(r,e,t){e.set(r,t)}function kd(r,e,t){r.length<40?To(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Vc(r),t)}function ti(){return new es}function xe(r,e){let t=ti();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*ve(r,e,t){let s=$r(r);yield*e.stream(s,void 0,"$",t)}var Gs={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Hs(r,e,t,s,n){return{name:r,type:e,encode:t,decode:s,stream:n}}function ri(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(i,a){let l=e(i);a.int32(l)},s=function(i){let a=i.int32();return e(a)},n=function*(i){let a=i.int32();yield e(a)};return Hs("enum",Gs.VARINT,t,s,n)}function Ee(r,e,t){return Hs("message",Gs.LENGTH_DELIMITED,r,e,t)}var W=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var Z;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Z||(Z={}));var si;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(si||(si={}));(function(r){r.codec=()=>ri(si)})(Z||(Z={}));var je;(function(r){let e;r.codec=()=>(e==null&&(e=Ee((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 xe(o,r.codec())}r.encode=t;function s(o,i){return we(o,r.codec(),i)}r.decode=s;function n(o,i){return ve(o,r.codec(),i)}r.stream=n})(je||(je={}));var ni;(function(r){let e;r.codec=()=>(e==null&&(e=Ee((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 xe(o,r.codec())}r.encode=t;function s(o,i){return we(o,r.codec(),i)}r.decode=s;function n(o,i){return ve(o,r.codec(),i)}r.stream=n})(ni||(ni={}));var rs={};V(rs,{MAX_RSA_KEY_SIZE:()=>oi,generateRSAKeyPair:()=>Yc,jwkToJWKKeyPair:()=>Xc,jwkToPkcs1:()=>Cd,jwkToPkix:()=>li,jwkToRSAPrivateKey:()=>di,pkcs1MessageToJwk:()=>ai,pkcs1MessageToRSAPrivateKey:()=>ui,pkcs1ToJwk:()=>Rd,pkcs1ToRSAPrivateKey:()=>Zc,pkixMessageToJwk:()=>ci,pkixMessageToRSAPublicKey:()=>fi,pkixToJwk:()=>Fd,pkixToRSAPublicKey:()=>hi});var gr=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=rs.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:ke(this.raw,e.raw)}verify(e,t,s){return jc(this.jwk,t,e,s)}},ts=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=rs.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ke(this.raw,e.raw)}sign(e,t){return $c(this.jwk,e,t)}};var oi=8192,ii=18,Bd=1062,Ld=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Rd(r){let e=et(r);return ai(e)}function ai(r){return{n:q(r[1],"base64url"),e:q(r[2],"base64url"),d:q(r[3],"base64url"),p:q(r[4],"base64url"),q:q(r[5],"base64url"),dp:q(r[6],"base64url"),dq:q(r[7],"base64url"),qi:q(r[8],"base64url"),kty:"RSA"}}function Cd(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new X("JWK was missing components");return ht([Ae(Uint8Array.from([0])),Ae(j(r.n,"base64url")),Ae(j(r.e,"base64url")),Ae(j(r.d,"base64url")),Ae(j(r.p,"base64url")),Ae(j(r.q,"base64url")),Ae(j(r.dp,"base64url")),Ae(j(r.dq,"base64url")),Ae(j(r.qi,"base64url"))]).subarray()}function Fd(r){let e=et(r,{offset:0});return ci(e)}function ci(r){let e=et(r[1],{offset:0});return{kty:"RSA",n:q(e[0],"base64url"),e:q(e[1],"base64url")}}function li(r){if(r.n==null||r.e==null)throw new X("JWK was missing components");return ht([Ld,bs(ht([Ae(j(r.n,"base64url")),Ae(j(r.e,"base64url"))]))]).subarray()}function Zc(r){let e=et(r);return ui(e)}function ui(r){let e=ai(r);return di(e)}function hi(r,e){if(r.byteLength>=Bd)throw new Wt("Key size is too large");let t=et(r,{offset:0});return fi(t,r,e)}function fi(r,e,t){let s=ci(r);if(t==null){let n=tr(je.encode({Type:Z.RSA,Data:e}));t=Ge(ii,n)}return new gr(s,t)}function di(r){if(Qc(r)>oi)throw new X("Key size is too large");let e=Xc(r),t=tr(je.encode({Type:Z.RSA,Data:li(e.publicKey)})),s=Ge(ii,t);return new ts(e.privateKey,new gr(e.publicKey,s))}async function Yc(r){if(r>oi)throw new X("Key size is too large");let e=await Jc(r),t=tr(je.encode({Type:Z.RSA,Data:li(e.publicKey)})),s=Ge(ii,t);return new ts(e.privateKey,new gr(e.publicKey,s))}function Xc(r){if(r==null)throw new X("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Jc(r,e){let t=await Be.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let s=await Nd(t,e);return{privateKey:s[0],publicKey:s[1]}}async function $c(r,e,t){let s=await Be.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let n=await Be.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},s,He(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(n,0,n.byteLength)}async function jc(r,e,t,s){let n=await Be.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);s?.signal?.throwIfAborted();let o=await Be.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,He(e),He(t instanceof Uint8Array?t:t.subarray()));return s?.signal?.throwIfAborted(),o}async function Nd(r,e){if(r.privateKey==null||r.publicKey==null)throw new X("Private and public key are required");let t=await Promise.all([Be.get().subtle.exportKey("jwk",r.privateKey),Be.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Qc(r){if(r.kty!=="RSA")throw new X("invalid key type");if(r.n==null)throw new X("invalid key modulus");return j(r.n,"base64url").length*8}var qs=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(ys(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 s=this.blockLen,n=new Uint8Array(s);n.set(t.length>s?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 er(this),this.iHash.update(e),this}digestInto(e){er(this),ws(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:s,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=s._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},el=(()=>{let r=((e,t,s)=>new qs(e,t).update(s).digest());return r.create=(e,t)=>new qs(e,t),r})();var tl=(r,e)=>(r+(r>=0?e:-e)/rl)/e;function Od(r,e,t){nr("scalar",r,Ze,t);let[[s,n],[o,i]]=e,a=tl(i*r,t),l=tl(-n*r,t),u=r-a*s-l*o,p=-a*n-l*i,m=u<Ze,E=p<Ze;m&&(u=-u),E&&(p=-p);let w=zr(Math.ceil(or(t)/2))+_t;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 mi(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function pi(r,e){Ne(r);let t={};for(let s of Object.keys(e))t[s]=r[s]===void 0?e[s]:r[s];return Ce(t.lowS,"lowS"),Ce(t.prehash,"prehash"),t.format!==void 0&&mi(t.format),t}var gi=class extends Error{constructor(e=""){super(e)}},Ue={Err:gi,_tlv:{encode:(r,e)=>{let{Err:t}=Ue;if(Fe(r,"tag"),r<0||r>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 s=e.length/2,n=Ur(s);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let o=s>127?Ur(n.length/2|128):"";return Ur(r)+o+n+e},decode(r,e){let{Err:t}=Ue;e=K(e,void 0,"DER data");let s=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[s++]!==r)throw new t("tlv.decode: wrong tlv");let n=e[s++],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(s,s+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(s+=l,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(s,s+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(s+i)}}},_int:{encode(r){let{Err:e}=Ue;if(Ts(r),r<Ze)throw new e("integer: negative integers are not allowed");let t=Ur(r);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(r){let{Err:e}=Ue;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Lt(r)}},toSig(r){let{Err:e,_int:t,_tlv:s}=Ue,n=K(r,void 0,"signature"),{v:o,l:i}=s.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l}=s.decode(2,o),{v:u,l:p}=s.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(r){let{_tlv:e,_int:t}=Ue,s=e.encode(2,t.encode(r.r)),n=e.encode(2,t.encode(r.s)),o=s+n;return e.encode(48,o)}};Object.freeze(Ue._tlv);Object.freeze(Ue._int);Object.freeze(Ue);var Ze=BigInt(0),_t=BigInt(1),rl=BigInt(2),Vs=BigInt(3),Ud=BigInt(4);function sl(r,e={}){let t=Ps("weierstrass",r,e),s=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&&(!s.is0(o.a)||typeof l.beta!="bigint"||!Array.isArray(l.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let p=ol(s,n);function m(){if(!s.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:D}=I.toAffine(),A=s.toBytes(P);if(Ce(T,"isCompressed"),T){m();let k=!s.isOdd(D);return oe(nl(k),A)}else return oe(Uint8Array.of(4),A,s.toBytes(D))}function w(N){K(N,void 0,"Point");let{publicKey:I,publicKeyUncompressed:T}=p,P=N.length,D=N[0],A=N.subarray(1);if(u&&P===1&&D===0)return{x:s.ZERO,y:s.ZERO};if(P===I&&(D===2||D===3)){let k=s.fromBytes(A);if(!s.isValid(k))throw new Error("bad point: is not on curve, wrong x");let L=b(k),B;try{B=s.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=s.isOdd(B);return(D&1)===1!==R&&(B=s.neg(B)),{x:k,y:B}}else if(P===T&&D===4){let k=s.BYTES,L=s.fromBytes(A.subarray(0,k)),B=s.fromBytes(A.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=s.sqr(N),T=s.mul(I,N);return s.add(s.add(T,s.mul(N,o.a)),o.b)}function x(N,I){let T=s.sqr(I),P=b(N);return s.eql(T,P)}if(!x(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let _=s.mul(s.pow(o.a,Vs),Ud),c=s.mul(s.sqr(o.b),BigInt(27));if(s.is0(s.add(_,c)))throw new Error("bad curve params: a or b");function f(N,I,T=!1){if(!s.isValid(I)||T&&s.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 Od(N,l.basises,n.ORDER)}function v(N,I,T,P,D){return T=new S(s.mul(T.X,N),T.Y,T.Z),I=Hr(P,I),T=Hr(D,T),I.add(T)}class S{static BASE=new S(o.Gx,o.Gy,s.ONE);static ZERO=new S(s.ZERO,s.ONE,s.ZERO);static Fp=s;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||!s.isValid(T)||!s.isValid(P))throw new Error("invalid affine point");if(I instanceof S)throw new Error("projective point not allowed");return s.is0(T)&&s.is0(P)?S.ZERO:new S(T,P,s.ONE)}static fromBytes(I){let T=S.fromAffine(g(K(I,void 0,"point")));return T.assertValidity(),T}static fromHex(I){return S.fromBytes(sr(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(Vs),this}assertValidity(){let I=this;if(I.is0()){if(e.allowInfinityPoint&&s.is0(I.X)&&s.eql(I.Y,s.ONE)&&s.is0(I.Z))return;throw new Error("bad point: ZERO")}let{x:T,y:P}=I.toAffine();if(!s.isValid(T)||!s.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(!s.isOdd)throw new Error("Field doesn't support isOdd");return!s.isOdd(I)}equals(I){d(I);let{X:T,Y:P,Z:D}=this,{X:A,Y:k,Z:L}=I,B=s.eql(s.mul(T,L),s.mul(A,D)),R=s.eql(s.mul(P,L),s.mul(k,D));return B&&R}negate(){return new S(this.X,s.neg(this.Y),this.Z)}double(){let{a:I,b:T}=o,P=s.mul(T,Vs),{X:D,Y:A,Z:k}=this,L=s.ZERO,B=s.ZERO,R=s.ZERO,F=s.mul(D,D),U=s.mul(A,A),z=s.mul(k,k),O=s.mul(D,A);return O=s.add(O,O),R=s.mul(D,k),R=s.add(R,R),L=s.mul(I,R),B=s.mul(P,z),B=s.add(L,B),L=s.sub(U,B),B=s.add(U,B),B=s.mul(L,B),L=s.mul(O,L),R=s.mul(P,R),z=s.mul(I,z),O=s.sub(F,z),O=s.mul(I,O),O=s.add(O,R),R=s.add(F,F),F=s.add(R,F),F=s.add(F,z),F=s.mul(F,O),B=s.add(B,F),z=s.mul(A,k),z=s.add(z,z),F=s.mul(z,O),L=s.sub(L,F),R=s.mul(z,U),R=s.add(R,R),R=s.add(R,R),new S(L,B,R)}add(I){d(I);let{X:T,Y:P,Z:D}=this,{X:A,Y:k,Z:L}=I,B=s.ZERO,R=s.ZERO,F=s.ZERO,U=o.a,z=s.mul(o.b,Vs),O=s.mul(T,A),ne=s.mul(P,k),ie=s.mul(D,L),ae=s.add(T,P),re=s.add(A,k);ae=s.mul(ae,re),re=s.add(O,ne),ae=s.sub(ae,re),re=s.add(T,D);let Te=s.add(A,L);return re=s.mul(re,Te),Te=s.add(O,ie),re=s.sub(re,Te),Te=s.add(P,D),B=s.add(k,L),Te=s.mul(Te,B),B=s.add(ne,ie),Te=s.sub(Te,B),F=s.mul(U,re),B=s.mul(z,ie),F=s.add(B,F),B=s.sub(ne,F),F=s.add(ne,F),R=s.mul(B,F),ne=s.add(O,O),ne=s.add(ne,O),ie=s.mul(U,ie),re=s.mul(z,re),ne=s.add(ne,ie),ie=s.sub(O,ie),ie=s.mul(U,ie),re=s.add(re,ie),O=s.mul(ne,re),R=s.add(R,O),O=s.mul(Te,re),B=s.mul(ae,B),B=s.sub(B,O),O=s.mul(ae,ne),F=s.mul(Te,F),F=s.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,D,A=k=>C.cached(this,k,L=>Ft(S,L));if(T){let{k1neg:k,k1:L,k2neg:B,k2:R}=y(I),{p:F,f:U}=A(L),{p:z,f:O}=A(R);D=U.add(O),P=v(T.beta,F,z,k,B)}else{let{p:k,f:L}=A(I);P=k,D=L}return Ft(S,[P,D])[0]}multiplyUnsafe(I){let{endo:T}=e,P=this,D=I;if(!n.isValid(D))throw new RangeError("invalid scalar: out of range");if(D===Ze||P.is0())return S.ZERO;if(D===_t)return P;if(C.hasCache(this))return this.multiply(D);if(T){let{k1neg:A,k1:k,k2neg:L,k2:B}=y(D),{p1:R,p2:F}=Ya(S,P,k,B);return v(T.beta,R,F,A,L)}else return C.unsafe(P,D)}toAffine(I){let T=this,P=I,{X:D,Y:A,Z:k}=T;if(s.eql(k,s.ONE))return{x:D,y:A};let L=T.is0();P==null&&(P=L?s.ONE:s.inv(k));let B=s.mul(D,P),R=s.mul(A,P),F=s.mul(k,P);if(L)return{x:s.ZERO,y:s.ZERO};if(!s.eql(F,s.ONE))throw new Error("invZ was invalid");return{x:B,y:R}}isTorsionFree(){let{isTorsionFree:I}=e;return i===_t?!0:I?I(S,this):C.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:I}=e;return i===_t?this:I?I(S,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===_t?this.is0():this.clearCofactor().is0()}toBytes(I=!0){return Ce(I,"isCompressed"),this.assertValidity(),h(S,this,I)}toHex(I=!0){return rr(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let M=n.BITS,C=new cr(S,e.endo?Math.ceil(M/2):M);return M>=8&&S.BASE.precompute(8),Object.freeze(S.prototype),Object.freeze(S),S}function nl(r){return Uint8Array.of(r?2:3)}function ol(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Kd(r,e={}){let{Fn:t}=r,s=e.randomBytes===void 0?Or:e.randomBytes,n=Object.assign(ol(r.Fp,t),{seed:Math.max(co(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:!!r.fromBytes(w)}catch{return!1}}function a(w){return w=w===void 0?s(n.seed):w,lo(K(w,n.seed,"seed"),t.ORDER)}function l(w,h=!0){return r.BASE.multiply(t.fromBytes(w)).toBytes(h)}function u(w){let{secretKey:h,publicKey:g,publicKeyUncompressed:b}=n,x=t._lengths;if(!Bt(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 r.fromBytes(h).multiply(b).toBytes(g)}let m={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},E=ks(a,l);return Object.freeze(m),Object.freeze(n),Object.freeze({getPublicKey:l,getSharedSecret:p,keygen:E,Point:r,utils:m,lengths:n})}function il(r,e,t={}){let s=e;ys(s),Ne(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes===void 0?Or:t.randomBytes,o=t.hmac===void 0?(D,A)=>el(s,D,A):t.hmac,{Fp:i,Fn:a}=r,{ORDER:l,BITS:u}=a,{keygen:p,getPublicKey:m,getSharedSecret:E,utils:w,lengths:h}=Kd(r,t),g={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},b=l*rl+_t<i.ORDER;function x(D){let A=l>>_t;return D>A}function _(D,A){if(!a.isValidNot0(A))throw new Error(`invalid signature ${D}: out of range 1..Point.Fn.ORDER`);return A}function c(){if(b)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function f(D,A){mi(A);let k=h.signature,L=A==="compact"?k:A==="recovered"?k+1:void 0;return K(D,L)}class d{r;s;recovery;constructor(A,k,L){if(this.r=_("r",A),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(A,k=g.format){f(A,k);let L;if(k==="der"){let{r:U,s:z}=Ue.toSig(K(A));return new d(U,z)}k==="recovered"&&(L=A[0],k="compact",A=A.subarray(1));let B=h.signature/2,R=A.subarray(0,B),F=A.subarray(B,B*2);return new d(a.fromBytes(R),a.fromBytes(F),L)}static fromHex(A,k){return this.fromBytes(sr(A),k)}assertRecovery(){let{recovery:A}=this;if(A==null)throw new Error("invalid recovery id: must be present");return A}addRecoveryBit(A){return new d(this.r,this.s,A)}recoverPublicKey(A){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=r.fromBytes(oe(nl((B&1)===0),F)),z=a.inv(R),O=v(K(A,void 0,"msgHash")),ne=a.create(-O*z),ie=a.create(L*z),ae=r.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(A=g.format){if(mi(A),A==="der")return sr(Ue.hexFromSig(this));let{r:k,s:L}=this,B=a.toBytes(k),R=a.toBytes(L);return A==="recovered"?(c(),oe(Uint8Array.of(this.assertRecovery()),B,R)):oe(B,R)}toHex(A){return rr(this.toBytes(A))}}Object.freeze(d.prototype),Object.freeze(d);let y=t.bits2int===void 0?function(A){if(A.length>8192)throw new Error("input is too large");let k=Lt(A),L=A.length*8-u;return L>0?k>>BigInt(L):k}:t.bits2int,v=t.bits2int_modN===void 0?function(A){return a.create(y(A))}:t.bits2int_modN,S=zr(u);function M(D){return nr("num < 2^"+u,D,Ze,S),a.toBytes(D)}function C(D,A){return K(D,void 0,"message"),A?K(s(D),void 0,"prehashed message"):D}function N(D,A,k){let{lowS:L,prehash:B,extraEntropy:R}=pi(k,g);D=C(D,B);let F=v(D),U=a.fromBytes(A);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 re=y(ae);if(!a.isValidNot0(re))return;let Te=a.inv(re),qt=r.BASE.multiply(re).toAffine(),Tr=a.create(qt.x);if(Tr===Ze)return;let cs=a.create(Te*a.create(ne+Tr*U));if(cs===Ze)return;let Ri=(qt.x===Tr?0:2)|Number(qt.y&_t),Ci=cs;return L&&x(cs)&&(Ci=a.neg(cs),Ri^=1),new d(Tr,Ci,b?void 0:Ri)}return{seed:O,k2sig:ie}}function I(D,A,k={}){let{seed:L,k2sig:B}=N(D,A,k);return La(s.outputLen,a.BYTES,o)(L,B).toBytes(k.format)}function T(D,A,k,L={}){let{lowS:B,prehash:R,format:F}=pi(L,g);if(k=K(k,void 0,"publicKey"),A=C(A,R),!Bt(D)){let U=D instanceof d?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+U)}f(D,F);try{let U=d.fromBytes(D,F),z=r.fromBytes(k);if(B&&U.hasHighS())return!1;let{r:O,s:ne}=U,ie=v(A),ae=a.inv(ne),re=a.create(ie*ae),Te=a.create(O*ae),qt=r.BASE.multiplyUnsafe(re).add(z.multiplyUnsafe(Te));return qt.is0()?!1:a.create(qt.x)===O}catch{return!1}}function P(D,A,k={}){let{prehash:L}=pi(k,g);return A=C(A,L),d.fromBytes(D,"recovered").recoverPublicKey(A).toBytes()}return Object.freeze({keygen:p,getPublicKey:m,getSharedSecret:E,utils:w,lengths:h,Point:r,sign:I,verify:T,recoverPublicKey:P,Signature:d,hash:s})}var yi={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},zd={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var al=BigInt(2);function Gd(r){let e=yi.p,t=BigInt(3),s=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),l=BigInt(88),u=r*r*r%e,p=u*u*r%e,m=$(p,t,e)*p%e,E=$(m,t,e)*p%e,w=$(E,al,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,s,e)*u%e,y=$(d,al,e);if(!bi.eql(bi.sqr(y),r))throw new Error("Cannot find square root");return y}var bi=ir(yi.p,{sqrt:Gd}),Hd=sl(yi,{Fp:bi,endo:zd}),br=il(Hd,tr);function cl(r,e,t,s){let n=Mt.digest(t instanceof Uint8Array?t:t.subarray());if(Fs(n))return n.then(({digest:o})=>(s?.signal?.throwIfAborted(),br.verify(e,o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new Vr(String(o))});try{return s?.signal?.throwIfAborted(),br.verify(e,n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new Vr(String(o))}}var Ws=class{type="secp256k1";raw;_key;constructor(e){this._key=ul(e),this.raw=ll(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:ke(this.raw,e.raw)}verify(e,t,s){return cl(this._key,t,e,s)}};function wi(r){return new Ws(r)}function ll(r){return br.Point.fromBytes(r).toBytes()}function ul(r){try{return br.Point.fromBytes(r),r}catch(e){throw new Wt(String(e))}}function $s(r,e){let{Type:t,Data:s}=je.decode(r),n=s??new Uint8Array;switch(t){case Z.RSA:return hi(n,e);case Z.Ed25519:return So(n);case Z.secp256k1:return wi(n);case Z.ECDSA:return Vn(n);default:throw new $t}}function hl(r){let{Type:e,Data:t}=je.decode(r.digest),s=t??new Uint8Array;switch(e){case Z.Ed25519:return So(s);case Z.secp256k1:return wi(s);case Z.ECDSA:return Vn(s);default:throw new $t}}function qe(r){return je.encode({Type:Z[r.type],Data:r.raw})}var fl=Symbol.for("nodejs.util.inspect.custom"),qd=114,ss=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()})`}[gn]=!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(qd,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ke(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ke(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[fl](){return`PeerId(${this.toString()})`}},js=class extends ss{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Zs=class extends ss{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Ys=class extends ss{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Vd=2336,ns=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Le.digest(j(this.url))}[fl](){return`PeerId(${this.url})`}[gn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ue.createV1(Vd,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=q(e)),e.toString()===this.toString())}};var Wd=114,dl=2336;function Ut(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Je(Q.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return $d(ue.parse(r));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(r))}return yr(t)}function yr(r){if(Zd(r))return new js({multihash:r});if(jd(r))try{let e=hl(r);if(e.type==="Ed25519")return new Zs({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Ys({multihash:r,publicKey:e})}catch{let t=q(r.digest);return new ns(new URL(t))}throw new hs("Supplied PeerID Multihash is invalid")}function $d(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Wd&&r.code!==dl)throw new us("Supplied PeerID CID is invalid");if(r.code===dl){let e=q(r.multihash.digest);return new ns(new URL(e))}return yr(r.multihash)}function jd(r){return r.code===Le.code}function Zd(r){return r.code===Mt.code}function Xs(r=0){return new Uint8Array(r)}var Yd=Math.pow(2,7),Xd=Math.pow(2,14),Jd=Math.pow(2,21),xi=Math.pow(2,28),vi=Math.pow(2,35),Ei=Math.pow(2,42),Si=Math.pow(2,49),G=128,pe=127;function Kt(r){if(r<Yd)return 1;if(r<Xd)return 2;if(r<Jd)return 3;if(r<xi)return 4;if(r<vi)return 5;if(r<Ei)return 6;if(r<Si)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Qd(r,e,t=0){switch(Kt(r)){case 8:e[t++]=r&255|G,r/=128;case 7:e[t++]=r&255|G,r/=128;case 6:e[t++]=r&255|G,r/=128;case 5:e[t++]=r&255|G,r/=128;case 4:e[t++]=r&255|G,r>>>=7;case 3:e[t++]=r&255|G,r>>>=7;case 2:e[t++]=r&255|G,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function ep(r,e,t=0){switch(Kt(r)){case 8:e.set(t++,r&255|G),r/=128;case 7:e.set(t++,r&255|G),r/=128;case 6:e.set(t++,r&255|G),r/=128;case 5:e.set(t++,r&255|G),r/=128;case 4:e.set(t++,r&255|G),r>>>=7;case 3:e.set(t++,r&255|G),r>>>=7;case 2:e.set(t++,r&255|G),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function tp(r,e){let t=r[e],s=0;if(s+=t&pe,t<G||(t=r[e+1],s+=(t&pe)<<7,t<G)||(t=r[e+2],s+=(t&pe)<<14,t<G)||(t=r[e+3],s+=(t&pe)<<21,t<G)||(t=r[e+4],s+=(t&pe)*xi,t<G)||(t=r[e+5],s+=(t&pe)*vi,t<G)||(t=r[e+6],s+=(t&pe)*Ei,t<G)||(t=r[e+7],s+=(t&pe)*Si,t<G))return s;throw new RangeError("Could not decode varint")}function rp(r,e){let t=r.get(e),s=0;if(s+=t&pe,t<G||(t=r.get(e+1),s+=(t&pe)<<7,t<G)||(t=r.get(e+2),s+=(t&pe)<<14,t<G)||(t=r.get(e+3),s+=(t&pe)<<21,t<G)||(t=r.get(e+4),s+=(t&pe)*xi,t<G)||(t=r.get(e+5),s+=(t&pe)*vi,t<G)||(t=r.get(e+6),s+=(t&pe)*Ei,t<G)||(t=r.get(e+7),s+=(t&pe)*Si,t<G))return s;throw new RangeError("Could not decode varint")}function pl(r,e,t=0){return e==null&&(e=Xs(Kt(r))),e instanceof Uint8Array?Qd(r,e,t):ep(r,e,t)}function ml(r,e=0){return r instanceof Uint8Array?tp(r,e):rp(r,e)}var Js=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},wr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Qs=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},os=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function en(r){return r[Symbol.asyncIterator]!=null}function bl(r,e){if(r.byteLength>e)throw new wr("Message length too long")}var rn=r=>{let e=Kt(r),t=Xs(e);return pl(r,t),rn.bytes=e,t};rn.bytes=0;function xr(r,e){e=e??{};let t=e.lengthEncoder??rn,s=e?.maxDataLength??4194304;function*n(o){bl(o,s);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return en(r)?(async function*(){for await(let o of r)yield*n(o)})():(function*(){for(let o of r)yield*n(o)})()}xr.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??rn,s=e?.maxDataLength??4194304;return bl(r,s),new ce(t(r.byteLength),r)};var zt;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(zt||(zt={}));var _i=r=>{let e=ml(r);return _i.bytes=Kt(e),e};_i.bytes=0;function is(r,e){let t=new ce,s=zt.LENGTH,n=-1,o=e?.lengthDecoder??_i,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*l(){for(;t.byteLength>0;){if(s===zt.LENGTH)try{if(n=o(t),n<0)throw new Js("Invalid message length");if(n>a)throw new wr("Message length too long");let u=o.bytes;t.consume(u),e?.onLength!=null&&e.onLength(n),s=zt.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new Qs("Message length length too long");break}throw u}if(s===zt.DATA){if(t.byteLength<n)break;let u=t.sublist(0,n);t.consume(n),e?.onData!=null&&e.onData(u),yield u,s=zt.LENGTH}}}return en(r)?(async function*(){for await(let u of r)t.append(u),yield*l();if(t.byteLength>0)throw new os("Unexpected end of input")})():(function*(){for(let u of r)t.append(u),yield*l();if(t.byteLength>0)throw new os("Unexpected end of input")})()}is.fromReader=(r,e)=>{let t=1,s=(async function*(){for(;;)try{let{done:o,value:i}=await r.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 is(s,{...e??{},onLength:o=>{t=o}})};function at(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var sn=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}},vr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new sn(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 sn(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 Ii=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Gt(r={}){return np(t=>{let s=t.shift();if(s==null)return{done:!0};if(s.error!=null)throw s.error;return{done:s.done===!0,value:s.value}},r)}function np(r,e){e=e??{};let t=e.onEnd,s=new vr,n,o,i,a=at(),l=async()=>{try{return s.isEmpty()?i?{done:!0}:await new Promise((b,x)=>{o=_=>{o=null,s.push(_);try{b(r(s))}catch(c){x(c)}return n}}):r(s)}finally{s.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=at()})}},u=b=>o!=null?o(b):(s.push(b),n),p=b=>(s=new vr,o!=null?o({error:b}):(s.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=()=>(s=new vr,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 s.size},onEmpty:async b=>{let x=b?.signal;if(x?.throwIfAborted(),s.isEmpty())return;let _,c;x!=null&&(_=new Promise((f,d)=>{c=()=>{d(new Ii)},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 op(r){return r.reason}async function Ti(r,e,t){if(e==null)return r;let s=t?.translateError??op;if(e.aborted)return r.catch(()=>{}),Promise.reject(s(e));let n;try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s(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 Ti(this.readNext.promise,t?.signal,t)}};function yl(){return new Ai}function ip(r){return r[Symbol.asyncIterator]!=null}async function ap(r,e,t){try{await Promise.all(r.map(async s=>{for await(let n of s)await e.push(n,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(s){await e.end(s,{signal:t}).catch(()=>{})}}async function*cp(r){let e=new AbortController,t=yl();ap(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*lp(r){for(let e of r)yield*e}function up(...r){let e=[];for(let t of r)ip(t)||e.push(t);return e.length===r.length?lp(e):cp(r)}var wl=up;function as(r,...e){if(r==null)throw new Error("Empty pipeline");if(Di(r)){let s=r;r=()=>s.source}else if(vl(r)||xl(r)){let s=r;r=()=>s}let t=[r,...e];if(t.length>1&&Di(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let s=1;s<t.length-1;s++)Di(t[s])&&(t[s]=fp(t[s]));return hp(...t)}var hp=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},xl=r=>r?.[Symbol.asyncIterator]!=null,vl=r=>r?.[Symbol.iterator]!=null,Di=r=>r==null?!1:r.sink!=null&&r.source!=null,fp=r=>e=>{let t=r.sink(e);if(t?.then!=null){let s=Gt({objectMode:!0});t.then(()=>{s.end()},i=>{s.end(i)});let n,o=r.source;if(xl(o))n=async function*(){yield*o,s.end()};else if(vl(o))n=function*(){yield*o,s.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return wl(s,n())}return r.source};var El={maxSubscriptions:5e3,maxMessages:5e3,maxIhaveMessageIDs:5e3,maxIwantMessageIDs:5e3,maxControlMessages:5e3,maxIdontwantMessageIDs:512,maxPeerInfos:16};var ct;(function(r){let e;(function(h){let g;h.codec=()=>(g==null&&(g=Ee((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 xe(c,h.codec())}h.encode=b;function x(c,f){return we(c,h.codec(),f)}h.decode=x;function _(c,f){return ve(c,h.codec(),f)}h.stream=_})(e=r.SubOpts||(r.SubOpts={}));let t;(function(h){let g;h.codec=()=>(g==null&&(g=Ee((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 xe(c,h.codec())}h.encode=b;function x(c,f){return we(c,h.codec(),f)}h.decode=x;function _(c,f){return ve(c,h.codec(),f)}h.stream=_})(t=r.Message||(r.Message={}));let s;(function(h){let g;h.codec=()=>(g==null&&(g=Ee((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),r.ControlIHave.codec().encode(y,f);if(c.iwant!=null&&c.iwant.length>0)for(let y of c.iwant)f.uint32(18),r.ControlIWant.codec().encode(y,f);if(c.graft!=null&&c.graft.length>0)for(let y of c.graft)f.uint32(26),r.ControlGraft.codec().encode(y,f);if(c.prune!=null&&c.prune.length>0)for(let y of c.prune)f.uint32(34),r.ControlPrune.codec().encode(y,f);if(c.idontwant!=null&&c.idontwant.length>0)for(let y of c.idontwant)f.uint32(42),r.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(r.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(r.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(r.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(r.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(r.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 r.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 r.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 r.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 r.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 r.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 xe(c,h.codec())}h.encode=b;function x(c,f){return we(c,h.codec(),f)}h.decode=x;function _(c,f){return ve(c,h.codec(),f)}h.stream=_})(s=r.ControlMessage||(r.ControlMessage={}));let n;(function(h){let g;h.codec=()=>(g==null&&(g=Ee((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 xe(c,h.codec())}h.encode=b;function x(c,f){return we(c,h.codec(),f)}h.decode=x;function _(c,f){return ve(c,h.codec(),f)}h.stream=_})(n=r.ControlIHave||(r.ControlIHave={}));let o;(function(h){let g;h.codec=()=>(g==null&&(g=Ee((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 xe(c,h.codec())}h.encode=b;function x(c,f){return we(c,h.codec(),f)}h.decode=x;function _(c,f){return ve(c,h.codec(),f)}h.stream=_})(o=r.ControlIWant||(r.ControlIWant={}));let i;(function(h){let g;h.codec=()=>(g==null&&(g=Ee((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 xe(c,h.codec())}h.encode=b;function x(c,f){return we(c,h.codec(),f)}h.decode=x;function _(c,f){return ve(c,h.codec(),f)}h.stream=_})(i=r.ControlGraft||(r.ControlGraft={}));let a;(function(h){let g;h.codec=()=>(g==null&&(g=Ee((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),r.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(r.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 r.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 xe(c,h.codec())}h.encode=b;function x(c,f){return we(c,h.codec(),f)}h.decode=x;function _(c,f){return ve(c,h.codec(),f)}h.stream=_})(a=r.ControlPrune||(r.ControlPrune={}));let l;(function(h){let g;h.codec=()=>(g==null&&(g=Ee((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 xe(c,h.codec())}h.encode=b;function x(c,f){return we(c,h.codec(),f)}h.decode=x;function _(c,f){return ve(c,h.codec(),f)}h.stream=_})(l=r.PeerInfo||(r.PeerInfo={}));let u;(function(h){let g;h.codec=()=>(g==null&&(g=Ee((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 xe(c,h.codec())}h.encode=b;function x(c,f){return we(c,h.codec(),f)}h.decode=x;function _(c,f){return ve(c,h.codec(),f)}h.stream=_})(u=r.ControlIDontWant||(r.ControlIDontWant={}));let p;r.codec=()=>(p==null&&(p=Ee((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),r.SubOpts.codec().encode(x,g);if(h.messages!=null&&h.messages.length>0)for(let x of h.messages)g.uint32(18),r.Message.codec().encode(x,g);h.control!=null&&(g.uint32(26),r.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(r.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(r.Message.codec().decode(h,h.uint32(),{limits:b.limits?.messages$}));break}case 3:{x.control=r.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 r.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 r.Message.codec().stream(h,h.uint32(),`${b}.messages[]`,{limits:x.limits?.messages$}))yield{...d,index:_.messages};_.messages++;break}case 3:{yield*r.ControlMessage.codec().stream(h,h.uint32(),`${b}.control`,{limits:x.limits?.control});break}default:{h.skipType(f&7);break}}}})),p);function m(h){return xe(h,r.codec())}r.encode=m;function E(h,g){return we(h,r.codec(),g)}r.decode=E;function w(h,g){return ve(h,r.codec(),g)}r.stream=w})(ct||(ct={}));var nn=class{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,s){this.gossip=e,this.msgIdToStrFn=s;for(let n=0;n<t;n++)this.history[n]=[]}get size(){return this.msgs.size}put(e,t,s=!1){let{msgIdStr:n}=e;return this.msgs.has(n)?!1:(this.msgs.set(n,{message:t,validated:s,originatingPeers:new Set,iwantCounts:new Map}),this.history[0].push({...e,topic:t.topic}),s||this.notValidatedCount++,!0)}observeDuplicate(e,t){let s=this.msgs.get(e);s!=null&&!s.validated&&s.originatingPeers.add(t)}get(e){return this.msgs.get(this.msgIdToStrFn(e))?.message}getWithIWantCount(e,t){let s=this.msgs.get(e);if(s==null)return null;let n=(s.iwantCounts.get(t)??0)+1;return s.iwantCounts.set(t,n),{msg:s.message,count:n}}getGossipIDs(e){let t=new Map;for(let s=0;s<this.gossip;s++)this.history[s].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:s,originatingPeers:n}=t;return t.validated=!0,t.originatingPeers=new Set,{message:s,originatingPeers:n}}shift(){this.history[this.history.length-1].forEach(t=>{let s=this.msgs.get(t.msgIdStr);s!=null&&(this.msgs.delete(t.msgIdStr),s.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 Sl;(function(r){r.StrictSign="StrictSign",r.StrictNoSign="StrictNoSign"})(Sl||(Sl={}));var It;(function(r){r[r.Signing=0]="Signing",r[r.Anonymous=1]="Anonymous"})(It||(It={}));var Se;(function(r){r.Error="error",r.Ignore="ignore",r.Reject="reject",r.Blacklisted="blacklisted"})(Se||(Se={}));var me;(function(r){r.InvalidSignature="invalid_signature",r.InvalidSeqno="invalid_seqno",r.InvalidPeerId="invalid_peerid",r.SignaturePresent="signature_present",r.SeqnoPresent="seqno_present",r.FromPresent="from_present",r.TransformFailed="transform_failed"})(me||(me={}));var ge;(function(r){r.duplicate="duplicate",r.invalid="invalid",r.valid="valid"})(ge||(ge={}));function Mi(r){switch(r){case be.Ignore:return Se.Ignore;case be.Reject:return Se.Reject;default:throw new Error("Unreachable")}}var _l;(function(r){r.forward="forward",r.publish="publish"})(_l||(_l={}));var _e;(function(r){r.Fanout="fanout",r.Random="random",r.Subscribed="subscribed",r.Outbound="outbound",r.NotEnough="not_enough",r.Opportunistic="opportunistic"})(_e||(_e={}));var Ke;(function(r){r.Dc="disconnected",r.BadScore="bad_score",r.Prune="prune",r.Excess="excess"})(Ke||(Ke={}));var Sr;(function(r){r.GraftBackoff="graft_backoff",r.BrokenPromise="broken_promise",r.MessageDeficit="message_deficit",r.IPColocation="IP_colocation"})(Sr||(Sr={}));var _r;(function(r){r.LowScore="low_score",r.MaxIhave="max_ihave",r.MaxIasked="max_iasked"})(_r||(_r={}));var Er;(function(r){r.graylist="graylist",r.publish="publish",r.gossip="gossip",r.mesh="mesh"})(Er||(Er={}));function Il(r,e,t){return{protocolsEnabled:r.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:r.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:r.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:r.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEventsFanout:r.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:r.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:r.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:r.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:r.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:r.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:r.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:r.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:r.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:r.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:r.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:r.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:r.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:r.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:r.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),acceptedMessagesTotal:r.gauge({name:"gossipsub_accepted_messages_total",help:"Total accepted messages for each topic",labelNames:["topic"]}),ignoredMessagesTotal:r.gauge({name:"gossipsub_ignored_messages_total",help:"Total ignored messages for each topic",labelNames:["topic"]}),rejectedMessagesTotal:r.gauge({name:"gossipsub_rejected_messages_total",help:"Total rejected messages for each topic",labelNames:["topic"]}),unknownValidationResultsTotal:r.gauge({name:"gossipsub_unknown_validation_results_total",help:"Total unknown validation results for each topic",labelNames:["topic"]}),asyncValidationMcacheHit:r.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),asyncValidationDelayFromFirstSeenSec:r.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:r.gauge({name:"gossipsub_async_validation_unknown_first_seen_count_total",help:"Async validation report unknown first seen value for message"}),peerReadStreamError:r.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:r.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:r.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:r.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:r.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:r.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:r.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:r.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:r.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:r.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:r.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:r.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:r.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:r.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:r.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:r.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:r.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:r.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:r.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:r.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:r.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:r.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),rpcSentIDontWant:r.gauge({name:"gossipsub_rpc_sent_idontwant_total",help:"RPC sent"}),msgPublishCount:r.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeersByTopic:r.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),directPeersPublishedTotal:r.gauge({name:"gossipsub_direct_peers_published_total",help:"Total direct peers that we publish a msg to",labelNames:["topic"]}),floodsubPeersPublishedTotal:r.gauge({name:"gossipsub_floodsub_peers_published_total",help:"Total floodsub peers that we publish a msg to",labelNames:["topic"]}),meshPeersPublishedTotal:r.gauge({name:"gossipsub_mesh_peers_published_total",help:"Total mesh peers that we publish a msg to",labelNames:["topic"]}),fanoutPeersPublishedTotal:r.gauge({name:"gossipsub_fanout_peers_published_total",help:"Total fanout peers that we publish a msg to",labelNames:["topic"]}),msgPublishBytes:r.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgPublishTime:r.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:r.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:r.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:r.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:r.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),prevalidationInvalidTotal:r.gauge({name:"gossipsub_pre_validation_invalid_total",help:"Total count of invalid messages received",labelNames:["topic"]}),prevalidationValidTotal:r.gauge({name:"gossipsub_pre_validation_valid_total",help:"Total count of valid messages received",labelNames:["topic"]}),prevalidationDuplicateTotal:r.gauge({name:"gossipsub_pre_validation_duplicate_total",help:"Total count of duplicate messages received",labelNames:["topic"]}),prevalidationUnknownTotal:r.gauge({name:"gossipsub_pre_validation_unknown_status_total",help:"Total count of unknown_status messages received",labelNames:["topic"]}),msgReceivedInvalid:r.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["error"]}),msgReceivedInvalidByTopic:r.gauge({name:"gossipsub_msg_received_invalid_by_topic_total",help:"Tracks specific invalid message by topic",labelNames:["topic"]}),duplicateMsgDeliveryDelay:r.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:r.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:r.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:r.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:r.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:r.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:r.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:r.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores"}),scoreWeights:r.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:r.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:r.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:r.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:r.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:r.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:r.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:r.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:r.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),idontwantRcvMsgids:r.gauge({name:"gossipsub_idontwant_rcv_msgids_total",help:"Total received IDONTWANT messages"}),idontwantRcvDonthaveMsgids:r.gauge({name:"gossipsub_idontwant_rcv_dont_have_msgids_total",help:"Total received IDONTWANT messageIDs that we do not have in mcache"}),iwantPromiseStarted:r.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:r.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:r.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:r.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:r.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:r.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:r.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:r.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),connectedPeersBackoffSec:r.histogram({name:"gossipsub_connected_peers_backoff_seconds",help:"Backoff time in seconds",buckets:[1,2,4,10,20,60,120]}),cacheSize:r.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:r.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:r.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:r.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:r.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:e,toTopic(s){return this.topicStrToLabel.get(s)??s},onJoin(s){this.topicSubscriptionStatus.set({topicStr:s},1),this.meshPeerCounts.set({topicStr:s},0)},onLeave(s){this.topicSubscriptionStatus.set({topicStr:s},0),this.meshPeerCounts.set({topicStr:s},0)},onAddToMesh(s,n,o){let i=this.toTopic(s);switch(n){case _e.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:i},o);break;case _e.Random:this.meshPeerInclusionEventsRandom.inc({topic:i},o);break;case _e.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:i},o);break;case _e.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:i},o);break;case _e.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:i},o);break;case _e.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:i},o);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:i},o);break}},onRemoveFromMesh(s,n,o){let i=this.toTopic(s);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(s,n,o){if(this.asyncValidationMcacheHit.inc({hit:s!=null?"hit":"miss"}),s!=null){let i=this.toTopic(s.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(s){this.scoringPenalties.inc({penalty:s},1)},onIhaveRcv(s,n,o){let i=this.toTopic(s);this.ihaveRcvMsgids.inc({topic:i},n),this.ihaveRcvNotSeenMsgids.inc({topic:i},o)},onIwantRcv(s,n){for(let[o,i]of s){let a=this.toTopic(o);this.iwantRcvMsgids.inc({topic:a},i)}this.iwantRcvDonthaveMsgids.inc(n)},onIdontwantRcv(s,n){this.idontwantRcvMsgids.inc(s),this.idontwantRcvDonthaveMsgids.inc(n)},onForwardMsg(s,n){let o=this.toTopic(s);this.msgForwardCount.inc({topic:o},1),this.msgForwardPeers.inc({topic:o},n)},onPublishMsg(s,n,o,i,a){let l=this.toTopic(s);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(s){let n=this.toTopic(s);this.msgReceivedPreValidation.inc({topic:n},1)},onMsgRecvError(s){let n=this.toTopic(s);this.msgReceivedError.inc({topic:n},1)},onPrevalidationResult(s,n){let o=this.toTopic(s);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(s,n){let o=this.toTopic(s),i=n.reason===Se.Error?n.error:n.reason;this.msgReceivedInvalid.inc({error:i},1),this.msgReceivedInvalidByTopic.inc({topic:o},1)},onDuplicateMsgDelivery(s,n,o){let i=this.toTopic(s);this.duplicateMsgDeliveryDelay.observe({topic:i},n/1e3),o&&this.duplicateMsgLateDelivery.inc({topic:i},1)},onPublishDuplicateMsg(s){let n=this.toTopic(s);this.duplicateMsgIgnored.inc({topic:n},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(s,n){this.rpcRecvBytes.inc(n),this.rpcRecvCount.inc(1),s.subscriptions!=null&&this.rpcRecvSubscription.inc(s.subscriptions.length),s.messages!=null&&this.rpcRecvMessage.inc(s.messages.length),s.control!=null&&(this.rpcRecvControl.inc(1),s.control.ihave!=null&&this.rpcRecvIHave.inc(s.control.ihave.length),s.control.iwant!=null&&this.rpcRecvIWant.inc(s.control.iwant.length),s.control.graft!=null&&this.rpcRecvGraft.inc(s.control.graft.length),s.control.prune!=null&&this.rpcRecvPrune.inc(s.control.prune.length))},onRpcSent(s,n){if(this.rpcSentBytes.inc(n),this.rpcSentCount.inc(1),s.subscriptions!=null&&this.rpcSentSubscription.inc(s.subscriptions.length),s.messages!=null&&this.rpcSentMessage.inc(s.messages.length),s.control!=null){let o=s.control.ihave?.length??0,i=s.control.iwant?.length??0,a=s.control.graft?.length??0,l=s.control.prune?.length??0,u=s.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(s,n){let o=0,i=0,a=0,l=0;for(let u of s)u>=n.graylistThreshold&&o++,u>=n.publishThreshold&&i++,u>=n.gossipThreshold&&a++,u>=0&&l++;this.peersByScoreThreshold.set({threshold:Er.graylist},o),this.peersByScoreThreshold.set({threshold:Er.publish},i),this.peersByScoreThreshold.set({threshold:Er.gossip},a),this.peersByScoreThreshold.set({threshold:Er.mesh},l),this.score.set(s)},registerScoreWeights(s){for(let[n,o]of s.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"},s.p5w),this.scoreWeights.set({p:"p6"},s.p6w),this.scoreWeights.set({p:"p7"},s.p7w)},registerScorePerMesh(s,n){let o=new Map;s.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 H=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var dp={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},pp={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 Tl(r={}){return{...dp,...r,topics:r.topics!=null?Object.entries(r.topics).reduce((e,[t,s])=>(e[t]=mp(s),e),{}):{}}}function mp(r={}){return{...pp,...r}}function Al(r){for(let[e,t]of Object.entries(r.topics))try{gp(t)}catch(s){throw new H(`invalid score parameters for topic ${e}: ${s.message}`)}if(r.topicScoreCap<0)throw new H("invalid topic score cap; must be positive (or 0 for no cap)");if(r.appSpecificScore===null||r.appSpecificScore===void 0)throw new H("missing application specific score function");if(r.IPColocationFactorWeight>0)throw new H("invalid IPColocationFactorWeight; must be negative (or 0 to disable)");if(r.IPColocationFactorWeight!==0&&r.IPColocationFactorThreshold<1)throw new H("invalid IPColocationFactorThreshold; must be at least 1");if(r.behaviourPenaltyWeight>0)throw new H("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)");if(r.behaviourPenaltyWeight!==0&&(r.behaviourPenaltyDecay<=0||r.behaviourPenaltyDecay>=1))throw new H("invalid BehaviourPenaltyDecay; must be between 0 and 1");if(r.decayInterval<1e3)throw new H("invalid DecayInterval; must be at least 1s");if(r.decayToZero<=0||r.decayToZero>=1)throw new H("invalid DecayToZero; must be between 0 and 1")}function gp(r){if(r.topicWeight<0)throw new H("invalid topic weight; must be >= 0");if(r.timeInMeshQuantum===0)throw new H("invalid TimeInMeshQuantum; must be non zero");if(r.timeInMeshWeight<0)throw new H("invalid TimeInMeshWeight; must be positive (or 0 to disable)");if(r.timeInMeshWeight!==0&&r.timeInMeshQuantum<=0)throw new H("invalid TimeInMeshQuantum; must be positive");if(r.timeInMeshWeight!==0&&r.timeInMeshCap<=0)throw new H("invalid TimeInMeshCap; must be positive");if(r.firstMessageDeliveriesWeight<0)throw new H("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)");if(r.firstMessageDeliveriesWeight!==0&&(r.firstMessageDeliveriesDecay<=0||r.firstMessageDeliveriesDecay>=1))throw new H("invalid FirstMessageDeliveriesDecay; must be between 0 and 1");if(r.firstMessageDeliveriesWeight!==0&&r.firstMessageDeliveriesCap<=0)throw new H("invalid FirstMessageDeliveriesCap; must be positive");if(r.meshMessageDeliveriesWeight>0)throw new H("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)");if(r.meshMessageDeliveriesWeight!==0&&(r.meshMessageDeliveriesDecay<=0||r.meshMessageDeliveriesDecay>=1))throw new H("invalid MeshMessageDeliveriesDecay; must be between 0 and 1");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesCap<=0)throw new H("invalid MeshMessageDeliveriesCap; must be positive");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesThreshold<=0)throw new H("invalid MeshMessageDeliveriesThreshold; must be positive");if(r.meshMessageDeliveriesWindow<0)throw new H("invalid MeshMessageDeliveriesWindow; must be non-negative");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesActivation<1e3)throw new H("invalid MeshMessageDeliveriesActivation; must be at least 1s");if(r.meshFailurePenaltyWeight>0)throw new H("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)");if(r.meshFailurePenaltyWeight!==0&&(r.meshFailurePenaltyDecay<=0||r.meshFailurePenaltyDecay>=1))throw new H("invalid MeshFailurePenaltyDecay; must be between 0 and 1");if(r.invalidMessageDeliveriesWeight>0)throw new H("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)");if(r.invalidMessageDeliveriesDecay<=0||r.invalidMessageDeliveriesDecay>=1)throw new H("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1")}var bp={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function Dl(r={}){return{...bp,...r}}function an(r,e,t=()=>!0){let s=new Set;if(e<=0)return s;for(let n of r){if(s.size>=e)break;t(n)&&(s.add(n),r.delete(n))}return s}function Ml(r,e){return an(r,e,()=>!0)}var on=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 Pl(r,e,t,s){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(r);if(n+=o*t.appSpecificWeight,e.knownIPs.forEach(i=>{if(t.IPColocationFactorWhitelist.has(i))return;let a=s.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 Ll=tu(Bl(),1);var Ie;(function(r){r[r.unknown=0]="unknown",r[r.valid=1]="valid",r[r.invalid=2]="invalid",r[r.ignored=3]="ignored"})(Ie||(Ie={}));var cn=class{records;queue;constructor(){this.records=new Map,this.queue=new Ll.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:Ie.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let s={msgId:e,expire:Date.now()+12e4};return this.queue.push(s),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 ln=class{params;metrics;peerStats=new Map;peerIPs=new on(()=>new Set);scoreCache=new Map;deliveryRecords=new cn;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,s,n){this.params=e,this.metrics=t,Al(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??Pl,this.log=s.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((s,n)=>{if(!s.connected){e>s.expire&&(this.removeIPsForPeer(n,s.knownIPs),this.peerStats.delete(n),this.scoreCache.delete(n));return}Object.entries(s.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)))}),s.behaviourPenalty*=this.params.behaviourPenaltyDecay,s.behaviourPenalty<t&&(s.behaviourPenalty=0)})}score(e){this.metrics?.scoreFnCalls.inc();let t=this.peerStats.get(e);if(t==null)return 0;let s=Date.now(),n=this.scoreCache.get(e);if(n!=null&&n.cacheUntil>s)return n.score;this.metrics?.scoreFnRuns.inc();let o=this.computeScore(e,t,this.params,this.peerIPs),i=s+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,s){let n=this.peerStats.get(e);n!=null&&(n.behaviourPenalty+=t,this.metrics?.onScorePenalty(s))}addPeer(e){let t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){let s=this.peerStats.get(e);s?.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){let s=this.peerStats.get(e);s?.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(([s,n])=>{n.firstMessageDeliveries=0;let o=this.params.topics[s].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 s=this.peerStats.get(e);if(s!=null){let n=this.getPtopicStats(s,t);n!=null&&(n.inMesh=!0,n.graftTime=Date.now(),n.meshTime=0,n.meshMessageDeliveriesActive=!1)}}prune(e,t){let s=this.peerStats.get(e);if(s!=null){let n=this.getPtopicStats(s,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,s){this.markFirstMessageDelivery(e,s);let n=this.deliveryRecords.ensureRecord(t),o=Date.now();if(n.status!==Ie.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,o-n.firstSeenTsMs,Ie[n.status]);return}n.status=Ie.valid,n.validated=o,n.peers.forEach(i=>{i!==e.toString()&&this.markDuplicateMessageDelivery(i,s)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,s,n){switch(n){case Se.Error:this.markInvalidMessageDelivery(e,s);return;case Se.Blacklisted:return}let o=this.deliveryRecords.ensureRecord(t);if(o.status!==Ie.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-o.firstSeenTsMs,Ie[o.status]);return}if(n===Se.Ignore){o.status=Ie.ignored,o.peers.clear();return}o.status=Ie.invalid,this.markInvalidMessageDelivery(e,s),o.peers.forEach(i=>{this.markInvalidMessageDelivery(i,s)}),o.peers.clear()}duplicateMessage(e,t,s){let n=this.deliveryRecords.ensureRecord(t);if(!n.peers.has(e))switch(n.status){case Ie.unknown:n.peers.add(e);break;case Ie.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,s,n.validated);break;case Ie.invalid:this.markInvalidMessageDelivery(e,s);break;case Ie.ignored:break}}markInvalidMessageDelivery(e,t){let s=this.peerStats.get(e);if(s!=null){let n=this.getPtopicStats(s,t);n!=null&&(n.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){let s=this.peerStats.get(e);if(s!=null){let n=this.getPtopicStats(s,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,s){let n=this.peerStats.get(e);if(n!=null){let o=s!==void 0?Date.now():0,i=this.getPtopicStats(n,t);if(i!=null&&i.inMesh){let a=this.params.topics[t];if(s!==void 0){let u=o-s,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 s of t){let n=this.peerIPs.get(s);n!=null&&(n.delete(e),n.size===0&&this.peerIPs.delete(s))}}getPtopicStats(e,t){let s=e.topics[t];return s!==void 0?s:this.params.topics[t]!==void 0?(s={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=s,s):null}};function yp(r,e,t,s,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(r);a+=p*t.appSpecificWeight,e.knownIPs.forEach(E=>{if(t.IPColocationFactorWhitelist.has(E))return;let w=s.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 Rl(r,e,t,s,n){let o={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let i of r){let a=e.get(i);if(a!=null){let l=yp(i,a,t,s,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 Pi(r){let e=r.getComponents(),t={},s=0;return e[s]?.name==="ip6zone"&&(t.zone=`${e[s].value}`,s++),e[s]?.name==="ip4"||e[s]?.name==="ip6"||e[s]?.name==="dns"||e[s]?.name==="dns4"||e[s]?.name==="dns6"?(t.type=e[s].name,t.host=e[s].value,s++):e[s]?.name==="dnsaddr"&&(t.type=e[s].name,t.host=`_dnsaddr.${e[s].value}`,s++),(e[s]?.name==="tcp"||e[s]?.name==="udp")&&(t.protocol=e[s].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[s].value}`),s++),e[s]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[s].value}`):t.type==="ip6"&&(t.cidr=`${e[s].value}`),s++),t.type==null||t.host==null?null:(e[s]?.name==="tls"&&e[s+1]?.name==="sni"&&(t.sni=e[s+1].value,s+=2),t)}function Cl(r){let e=Pi(r);if(e==null)throw new X(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function Fl(r){return Pi(r)!==null}var ki=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Nl=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Bi(r,e){let{milliseconds:t,fallback:s,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(Nl(i));return}if(i&&(l=()=>{E(Nl(i))},i.addEventListener("abort",l,{once:!0})),r.then(m,E),t===Number.POSITIVE_INFINITY)return;let w=new ki;a=o.setTimeout.call(void 0,()=>{if(s){try{m(s())}catch(h){E(h)}return}typeof r.cancel=="function"&&r.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 wp=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function xp(r,e,t){let s,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}=wp(r),m=async(...w)=>{let h=t.multiArgs?w:w[0];if(t.filter)try{if(!await t.filter(h))return}catch(g){s(),i(g);return}l.push(h),t.count===l.length&&(s(),o(l))},E=(...w)=>{s(),i(t.rejectionMultiArgs?w:w[0])};s=()=>{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=s,typeof t.timeout=="number"){let o=Bi(n,{milliseconds:t.timeout});return o.cancel=()=>{s(),o.clear()},o}return n}function Ol(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let s=xp(r,e,t),n=s.then(o=>o[0]);return n.cancel=s.cancel,n}var Fv=Math.pow(2,7),Nv=Math.pow(2,14),Ov=Math.pow(2,21),Uv=Math.pow(2,28),Kv=Math.pow(2,35),zv=Math.pow(2,42),Gv=Math.pow(2,49);function Ep(r){return r?.addEventListener!=null}function Sp(r){let e=Gt(),t,s=i=>{e.push(i.data)},n=()=>{e.end(),r.removeEventListener("message",s),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",n)},o=i=>{e.end(i.error),i.error!=null&&t?.reject(i.error),r.removeEventListener("message",s),r.removeEventListener("close",o),r.removeEventListener("remoteCloseWrite",n)};return r.addEventListener("message",s),r.addEventListener("close",o,{once:!0}),r.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(r.writeStatus==="closing"||r.writeStatus==="closed"||(p!=null&&(r.send(p)||await Promise.race([Ol(r,"drain",{rejectionEvents:["close"]})])),u===!0))break}await r.close()}}}function Ul(...r){let e=r.map(t=>Ep(t)?Sp(t):t);return as(...e)}var un=class{rawStream;constructor(e,t,s){this.rawStream=e,s.maxBufferSize!=null&&(e.maxWriteBufferLength=s.maxBufferSize),e.addEventListener("close",n=>{n.error!=null&&t(n.error)})}get protocol(){return this.rawStream.protocol}push(e){this.pushPrefixed(xr.single(e))}pushPrefixed(e){this.rawStream.send(e)}async close(e){await this.rawStream.close(e).catch(t=>{this.rawStream.abort(t)})}},hn=class{source;rawStream;closeController;constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(s=>{e.abort(s)})}),this.source=Ul(this.rawStream,s=>is(s,t))}async close(){this.closeController.abort()}};var fn=class{gossipsubIWantFollowupMs;msgIdToStrFn;metrics;promises=new Map;requestMsByMsg=new Map;requestMsByMsgExpire;constructor(e,t,s){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=s,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){let s=Math.floor(Math.random()*t.length),n=t[s],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,s=0;return this.promises.forEach((n,o)=>{n.forEach((i,a)=>{i<e&&(t.set(a,(t.get(a)??0)+1),n.delete(a),s++)}),n.size===0&&this.promises.delete(o)}),this.metrics?.iwantPromiseBroken.inc(s),t}deliverMessage(e,t=!1){this.trackMessage(e);let s=this.promises.get(e);s!=null&&(this.promises.delete(e),this.metrics!=null&&(this.metrics.iwantPromiseResolved.inc(1),t&&this.metrics.iwantPromiseResolvedFromDuplicate.inc(1),this.metrics.iwantPromiseResolvedPeers.inc(s.size)))}rejectMessage(e,t){this.trackMessage(e),t!==Se.Error&&this.promises.delete(e)}clear(){this.promises.clear()}prune(){let e=Date.now()-this.requestMsByMsgExpire,t=0;for(let[s,n]of this.requestMsByMsg.entries())if(n<e)this.requestMsByMsg.delete(s),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 Kl=j("libp2p-pubsub:"),_p=BigInt(Date.now())*1000000n;function Ip(){let r=++_p,e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,r,!1),e}async function zl(r,e,t,s){switch(r.type){case It.Signing:{let n={from:r.author.toMultihash().bytes,data:s,seqno:Ip(),topic:e,signature:void 0,key:void 0},o=Cs([Kl,ct.Message.encode(n)]);n.signature=await r.privateKey.sign(o),n.key=r.key;let i={type:"signed",from:r.author,data:t,sequenceNumber:BigInt(`0x${q(n.seqno??new Uint8Array(0),"base16")}`),topic:e,signature:n.signature,key:$s(n.key)};return{raw:n,msg:i}}case It.Anonymous:return{raw:{from:void 0,data:s,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 Gl(r,e){switch(r){case Ht: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 Tt:{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=yr(Je(e.from))}catch{return{valid:!1,error:me.InvalidPeerId}}let s;if(e.key!=null){if(s=$s(e.key),t.publicKey!==void 0&&!s.equals(t.publicKey))return{valid:!1,error:me.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:me.InvalidPeerId};s=t.publicKey}let n={from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0},o=Cs([Kl,ct.Message.encode(n)]);return await s.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?$s(e.key):s}}:{valid:!1,error:me.InvalidSignature}}default:throw new Error("Unreachable")}}function ze(r=[],e){return{subscriptions:[],messages:r,control:e!==void 0?{graft:e.graft??[],prune:e.prune??[],ihave:e.ihave??[],iwant:e.iwant??[],idontwant:e.idontwant??[]}:void 0}}function Li(r){return r.control===void 0&&(r.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),r}function Ye(r){if(r.length<=1)return r;let e=()=>Math.floor(Math.random()*Math.floor(r.length));for(let t=0;t<r.length;t++){let s=e(),n=r[t];r[t]=r[s],r[s]=n}return r}function Hl(r){return q(r,"base64")}function ql(r,e,t){switch(r){case Tt:return{type:It.Signing,author:e,key:qe(t.publicKey),privateKey:t};case Ht:return{type:It.Anonymous};default:throw new Error(`Unknown signature policy "${r}"`)}}var Tp=(r,e)=>{let t=j(e.toString(16).padStart(16,"0"),"base16"),s=qe(r),n=new Uint8Array(s.byteLength+t.length);return n.set(s,0),n.set(t,s.byteLength),n};function Vl(r){if(r.type!=="signed")throw new Error("expected signed message type");if(r.sequenceNumber==null)throw Error("missing seqno field");return Tp(r.from.publicKey??r.key,r.sequenceNumber)}async function Wl(r){return Mt.encode(r.data)}function $l(r){if(Fl(r)){let e=Cl(r);switch(e.type){case"ip4":case"ip6":return e.host;default:break}}return null}var Ir=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,s]of this.entries.entries())if(s.validUntilMs<e)this.entries.delete(t);else break}has(e){return this.entries.has(e)}get(e){let t=this.entries.get(e);return t!=null&&t.validUntilMs>=Date.now()?t.value:void 0}clear(){this.entries.clear()}};var Pe;(function(r){r[r.started=0]="started",r[r.stopped=1]="stopped"})(Pe||(Pe={}));var dn=class extends fs{globalSignaturePolicy;protocols=[Vt,Ni,mn];publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=Gt({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=Vt;opts;decodeRpcLimits;metrics;status={code:Pe.stopped};maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;allowedTopics;heartbeatTimer=null;constructor(e,t={}){super();let s={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:Tl(t.scoreParams),scoreThresholds:Dl(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=s.decodeRpcLimits??El,this.globalSignaturePolicy=s.globalSignaturePolicy??Tt,s.fallbackToFloodsub&&this.protocols.push(pn),this.log=e.logger.forComponent(s.debugName??"libp2p:gossipsub"),this.opts=s,this.direct=new Set(s.directPeers.map(n=>n.id.toString())),this.seenCache=new Ir({validityMs:s.seenTTL}),this.publishedMessageIds=new Ir({validityMs:s.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case Tt:this.msgIdFn=Vl;break;case Ht:this.msgIdFn=Wl;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new Ir({validityMs:s.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??Hl,this.mcache=t.messageCache??new nn(s.mcacheGossip,s.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(s.scoreParams.topics).map(i=>i.meshMessageDeliveriesWindow),1e3),o=Il(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:s.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 fn(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new ln(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:s.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnLimitedConnection=t.runOnLimitedConnection,this.allowedTopics=s.allowedTopics!=null?new Set(s.allowedTopics):null}[Symbol.toStringTag]="@libp2p/gossipsub";[zi]=["@libp2p/pubsub"];[Gi]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===Pe.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=ql(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=Gt({objectMode:!0}),as(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},s=await Promise.all(this.protocols.map(async o=>e.register(o,t))),n=setTimeout(this.runHeartbeat,100);this.status={code:Pe.started,registrarTopologyIds:s,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!==Pe.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:Pe.stopped},this.opts.tagMeshPeers&&(this.removeEventListener("gossipsub:graft",this.tagMeshPeer),this.removeEventListener("gossipsub:prune",this.untagMeshPeer));let t=this.components.registrar;await Promise.all(this.protocols.map(async n=>t.unhandle(n))),e.forEach(n=>{t.unregister(n)}),this.outboundInflightQueue.end();let s=[];for(let n of this.streamsOutbound.values())s.push(n.close());this.streamsOutbound.clear();for(let n of this.streamsInbound.values())s.push(n.close());this.streamsInbound.clear(),await Promise.all(s),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 s=t.remotePeer;this.addPeer(s,t.direction,t.remoteAddr),this.createInboundStream(s,e),this.outboundInflightQueue.push({peerId:s,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 s=e.toString();if(this.peers.has(s)&&!this.streamsOutbound.has(s))try{let n=new un(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(s,n);let o=n.protocol;o===pn&&this.floodsubPeers.add(s),this.metrics?.peersPerProtocol.inc({protocol:o},1),this.subscriptions.size>0&&(this.log("send subscriptions to",s),this.sendSubscriptions(s,Array.from(this.subscriptions),!0))}catch(n){this.log.error("createOutboundStream error",n)}}createInboundStream(e,t){if(!this.isStarted())return;let s=e.toString();if(!this.peers.has(s))return;let n=this.streamsInbound.get(s);n!==void 0&&(this.log("replacing existing inbound steam %s",s),n.close().catch(i=>{this.log.error(i)})),this.log("create inbound stream %s",s);let o=new hn(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(s,o),this.pipePeerReadStream(e,o.source).catch(i=>{this.log(i)})}addPeer(e,t,s){let n=e.toString();if(!this.peers.has(n)){this.peers.set(n,e),this.score.addPeer(n);let o=$l(s);o!==null?this.score.addIP(n,o):this.log("Added peer has no IP in current address %s %s",n,s.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 s=this.streamsOutbound.get(t),n=this.streamsInbound.get(t);s!=null&&this.metrics?.peersPerProtocol.inc({protocol:s.protocol},-1),s?.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===Pe.started}getMeshPeers(e){let t=this.mesh.get(e);return t!=null?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(t!=null?Array.from(t):[]).map(s=>this.peers.get(s)??Ut(s))}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 as(t,async s=>{for await(let n of s)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(s){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(s,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 s=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 ${s} 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,s){this.log("subscription update from %p topic %s",e,t);let n=this.topics.get(t);s?(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 s=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,s.code);let n=s.code;switch(n){case ge.duplicate:this.score.duplicateMessage(e.toString(),s.msgIdStr,t.topic),this.gossipTracer.deliverMessage(s.msgIdStr,!0),this.mcache.observeDuplicate(s.msgIdStr,e.toString());return;case ge.invalid:if(s.msgIdStr!=null){let o=s.msgIdStr;this.score.rejectMessage(e.toString(),o,t.topic,s.reason),this.gossipTracer.rejectMessage(o,s.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);this.metrics?.onMsgRecvInvalid(t.topic,s);return;case ge.valid:this.score.validateMessage(s.messageId.msgIdStr),this.gossipTracer.deliverMessage(s.messageId.msgIdStr),this.mcache.put(s.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:s.messageId.msgIdStr,msg:s.msg}})),super.dispatchEvent(new CustomEvent("message",{detail:s.msg}))),this.opts.asyncValidation||this.forwardMessage(s.messageId.msgIdStr,t,e.toString());break;default:throw new Error(`Invalid validation result: ${n}`)}}async validateReceivedMessage(e,t){let s=this.fastMsgIdFn?.(t),n=s!==void 0?this.fastMsgIdCache?.get(s):void 0;if(n!=null)return{code:ge.duplicate,msgIdStr:n};let o=await Gl(this.globalSignaturePolicy,t);if(!o.valid)return{code:ge.invalid,reason:Se.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:Se.Error,error:me.TransformFailed}}let a=await this.msgIdFn(i),l=this.msgIdToStrFn(a),u={msgId:a,msgIdStr:l};if(s!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(s,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===Ui&&(m=be.Ignore),w===Oi?m=be.Reject:m=be.Ignore}if(m!==be.Accept)return{code:ge.invalid,reason:Mi(m),msgIdStr:l}}return{code:ge.valid,messageId:u,msg:i}}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,s){this.sendRpc(e,{subscriptions:t.map(n=>({topic:n,subscribe:s})),messages:[]})}async handleControlMessage(e,t){if(t===void 0)return;let s=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),s.length===0&&n.length===0&&o.length===0)return;let i=this.sendRpc(e,ze(n,{iwant:s,prune:o})),a=s[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(),s=this.acceptFromWhitelist.get(e);if(s!=null&&s.messagesAccepted<128&&s.acceptUntil>=t)return s.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 s=this.score.score(e);if(s<this.opts.scoreThresholds.gossipThreshold)return this.log("IHAVE: ignoring peer %s with score below threshold [ score = %d ]",e,s),this.metrics?.ihaveRcvIgnored.inc({reason:_r.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:_r.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:_r.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 s=this.score.score(e);if(s<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,s),[];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 s=[],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),s.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,Sr.GraftBackoff),i=!1;let m=p+this.opts.graftFloodThreshold-this.opts.pruneBackoff;o<m&&this.score.addPenalty(e,1,Sr.GraftBackoff),this.addBackoff(e,l),s.push(l)}else n<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,n,l),s.push(l),i=!1,this.addBackoff(e,l)):u.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(s.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,_e.Subscribed,1));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:l,direction:"inbound"}})}),s.length===0)return[];let a=!1;return Promise.all(s.map(async l=>this.makePrune(e,l,i,a)))}async handlePrune(e,t){let s=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&&(s<this.opts.scoreThresholds.acceptPXThreshold?this.log("PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]",e,s,n):await this.pxConnect(i)),this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:n,direction:"inbound"}})}}handleIdontwant(e,t){let s=this.idontwantCounts.get(e)??0;if(s>=this.opts.idontwantMaxMessages)return;let n=s,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(s>=this.opts.idontwantMaxMessages)break e;s++;let p=this.msgIdToStrFn(u);o.set(p,this.heartbeatTicks),this.mcache.msgs.has(p)||i++}this.idontwantCounts.set(e,s);let a=s-n;this.metrics?.onIdontwantRcv(a,i)}addBackoff(e,t){this.doAddBackoff(e,t,this.opts.pruneBackoff)}doAddBackoff(e,t,s){let n=this.backoff.get(t);n==null&&(n=new Map,this.backoff.set(t,n));let o=Date.now()+s;(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,Sr.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!==0)return;let e=Date.now();this.backoff.forEach((t,s)=>{t.forEach((n,o)=>{n+1*this.opts.heartbeatInterval<e&&t.delete(o)}),t.size===0&&this.backoff.delete(s)})}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 s=>{if(s.peerID==null)return;let n=yr(Je(s.peerID)),o=n.toString();if(!this.peers.has(o)){if(s.signedPeerRecord==null){t.push(o);return}try{if(!await this.components.peerStore.consumePeerRecord(s.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 s=>this.connect(s)))}async connect(e){this.log("Initiating connection with %s",e);let t=Ut(e),s=await this.components.connectionManager.openConnection(t);for(let n of this.protocols)for(let o of this.components.registrar.getTopologies(n))o.onConnect?.(t,s)}subscribe(e){if(this.status.code!==Pe.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(let t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==Pe.started)throw new Error("Pubsub is not started");let t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(let s of this.peers.keys())this.sendSubscriptions(s,[e],!1);this.leave(e)}join(e){if(this.status.code!==Pe.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);let t=new Set,s=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&&s?.has(o)!==!0&&t.add(o)}),this.metrics?.onAddToMesh(e,_e.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&&s?.has(a)!==!0).forEach(a=>{t.add(a)}),this.metrics?.onAddToMesh(e,_e.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!==Pe.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);let t=this.mesh.get(e);t!=null&&(Promise.all(Array.from(t).map(async s=>{this.log("LEAVE: Remove mesh link to %s in %s",s,e),await this.sendPrune(s,e)})).catch(s=>{this.log("Error sending prunes to mesh peers",s)}),this.mesh.delete(e))}selectPeersToForward(e,t,s){let n=new Set,o=this.topics.get(e);o!=null&&(this.direct.forEach(a=>{o.has(a)&&t!==a&&!(s?.has(a)??!1)&&n.add(a)}),this.floodsubPeers.forEach(a=>{o.has(a)&&t!==a&&!(s?.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&&!(s?.has(a)??!1)&&n.add(a)}),n}selectPeersToPublish(e){let t=new Set,s={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),s.direct++):this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),s.floodsub++)});else{this.direct.forEach(i=>{n.has(i)&&(t.add(i),s.direct++)}),this.floodsubPeers.forEach(i=>{n.has(i)&&this.score.score(i)>=this.opts.scoreThresholds.publishThreshold&&(t.add(i),s.floodsub++)});let o=this.mesh.get(e);if(o!=null&&o.size>0)o.forEach(i=>{t.add(i),s.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),s.mesh++});else{let i=this.fanout.get(e);if(i!=null&&i.size>0)i.forEach(a=>{t.add(a),s.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),s.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:s}}forwardMessage(e,t,s,n){s!=null&&this.score.deliverMessage(s,e,t.topic);let o=this.selectPeersToForward(t.topic,s,n);o.forEach(i=>{this.sendRpc(i,ze([t]))}),this.metrics?.onForwardMsg(t.topic,o.size)}async publish(e,t,s){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 zl(this.publishConfig,e,t,o),l=await this.msgIdFn(a),u=this.msgIdToStrFn(l),p=s?.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=s?.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=s?.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(_)??Ut(_))}}sendRpcInBatch(e,t){let s=ct.encode(t),n=xr.single(s);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,s.length)}}reportMessageValidationResult(e,t,s){let n;if(s===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=Mi(s),{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,s,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,s){let n=this.mesh.get(t);if(n==null)return;let o=new Set(n);o.delete(s);for(let a of o)this.streamsOutbound.get(a)?.protocol!==Vt&&o.delete(a);let i=ze([],{idontwant:[{messageIDs:[e]}]});this.sendRpcInBatch(o,i)}sendRpc(e,t){let s=this.streamsOutbound.get(e);if(s==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{s.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,s){let n=Li(t);for(let o of s.graft)o.topicID!=null&&(this.mesh.get(o.topicID)?.has(e)??!1)&&n.control.graft.push(o);for(let o of s.prune)o.topicID!=null&&!(this.mesh.get(o.topicID)?.has(e)??!1)&&n.control.prune.push(o)}piggybackGossip(e,t,s){let n=Li(t);n.control.ihave=s}async sendGraftPrune(e,t,s){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&&!(s.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&&!(s.get(i)??!1),o)));this.sendRpc(i,ze([],{prune:l}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[s,n]of e)this.doEmitGossip(s,n,t.get(s)??[])}doEmitGossip(e,t,s){if(s.length===0||(Ye(s),s.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",s.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=s;s.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 s=ze([],{graft:t.graft,prune:t.prune});this.sendRpc(e,s)}}pushGossip(e,t){this.log("Add gossip to %s",e);let s=this.gossip.get(e)??[];this.gossip.set(e,s.concat(t))}async makePrune(e,t,s,n){if(this.score.prune(e,t),this.streamsOutbound.get(e)?.protocol===mn)return{topicID:t,peers:[]};let o=n?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,i=o/1e3;if(this.doAddBackoff(e,t,o),!s)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)??Ut(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===Pe.started){clearTimeout(this.status.heartbeatTimeout);let t=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;t<this.opts.heartbeatInterval*.25&&(t+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,t)}})};async heartbeat(){let{D:e,Dlo:t,Dhi:s,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;Ml(x,d).forEach(v=>{f(v,_e.NotEnough)})}if(h.size>s){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;an(x,y,S=>this.outbound.get(S)===!0).forEach(S=>{f(S,_e.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=an(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,_e.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,s=()=>!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)&&s(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,s=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-s)/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=Rl(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(a)}tagMeshPeer=e=>{let{peerId:t,topic:s}=e.detail;this.components.peerStore.merge(this.peers.get(t)??Ut(t),{tags:{[s]:{value:100}}}).catch(n=>{this.log.error("Error tagging peer %s with topic %s",t,s,n)})};untagMeshPeer=e=>{let{peerId:t,topic:s}=e.detail;this.components.peerStore.merge(this.peers.get(t)??Ut(t),{tags:{[s]:void 0}}).catch(n=>{this.log.error("Error untagging peer %s with topic %s",t,s,n)})}};var Tt="StrictSign",Ht="StrictNoSign",be;(function(r){r.Accept="accept",r.Ignore="ignore",r.Reject="reject"})(be||(be={}));var tm=Vt;function rm(r={}){return e=>new dn(e,r)}return ru(sm);})();
|
|
3
3
|
/*! Bundled license information:
|
|
4
4
|
|
|
5
5
|
@noble/curves/utils.js:
|