@libp2p/gossipsub 14.1.1-6059227cb

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.
Files changed (160) hide show
  1. package/README.md +85 -0
  2. package/dist/index.min.js +19 -0
  3. package/dist/index.min.js.map +7 -0
  4. package/dist/src/config.d.ts +32 -0
  5. package/dist/src/config.d.ts.map +1 -0
  6. package/dist/src/config.js +2 -0
  7. package/dist/src/config.js.map +1 -0
  8. package/dist/src/constants.d.ts +213 -0
  9. package/dist/src/constants.d.ts.map +1 -0
  10. package/dist/src/constants.js +217 -0
  11. package/dist/src/constants.js.map +1 -0
  12. package/dist/src/errors.d.ts +9 -0
  13. package/dist/src/errors.d.ts.map +1 -0
  14. package/dist/src/errors.js +15 -0
  15. package/dist/src/errors.js.map +1 -0
  16. package/dist/src/gossipsub.d.ts +419 -0
  17. package/dist/src/gossipsub.d.ts.map +1 -0
  18. package/dist/src/gossipsub.js +2520 -0
  19. package/dist/src/gossipsub.js.map +1 -0
  20. package/dist/src/index.d.ts +344 -0
  21. package/dist/src/index.d.ts.map +1 -0
  22. package/dist/src/index.js +43 -0
  23. package/dist/src/index.js.map +1 -0
  24. package/dist/src/message/decodeRpc.d.ts +11 -0
  25. package/dist/src/message/decodeRpc.d.ts.map +1 -0
  26. package/dist/src/message/decodeRpc.js +10 -0
  27. package/dist/src/message/decodeRpc.js.map +1 -0
  28. package/dist/src/message/index.d.ts +2 -0
  29. package/dist/src/message/index.d.ts.map +1 -0
  30. package/dist/src/message/index.js +2 -0
  31. package/dist/src/message/index.js.map +1 -0
  32. package/dist/src/message/rpc.d.ts +99 -0
  33. package/dist/src/message/rpc.d.ts.map +1 -0
  34. package/dist/src/message/rpc.js +663 -0
  35. package/dist/src/message/rpc.js.map +1 -0
  36. package/dist/src/message-cache.d.ts +80 -0
  37. package/dist/src/message-cache.d.ts.map +1 -0
  38. package/dist/src/message-cache.js +144 -0
  39. package/dist/src/message-cache.js.map +1 -0
  40. package/dist/src/metrics.d.ts +467 -0
  41. package/dist/src/metrics.d.ts.map +1 -0
  42. package/dist/src/metrics.js +896 -0
  43. package/dist/src/metrics.js.map +1 -0
  44. package/dist/src/score/compute-score.d.ts +4 -0
  45. package/dist/src/score/compute-score.d.ts.map +1 -0
  46. package/dist/src/score/compute-score.js +75 -0
  47. package/dist/src/score/compute-score.js.map +1 -0
  48. package/dist/src/score/index.d.ts +4 -0
  49. package/dist/src/score/index.d.ts.map +1 -0
  50. package/dist/src/score/index.js +4 -0
  51. package/dist/src/score/index.js.map +1 -0
  52. package/dist/src/score/message-deliveries.d.ts +45 -0
  53. package/dist/src/score/message-deliveries.d.ts.map +1 -0
  54. package/dist/src/score/message-deliveries.js +75 -0
  55. package/dist/src/score/message-deliveries.js.map +1 -0
  56. package/dist/src/score/peer-score-params.d.ts +125 -0
  57. package/dist/src/score/peer-score-params.d.ts.map +1 -0
  58. package/dist/src/score/peer-score-params.js +159 -0
  59. package/dist/src/score/peer-score-params.js.map +1 -0
  60. package/dist/src/score/peer-score-thresholds.d.ts +31 -0
  61. package/dist/src/score/peer-score-thresholds.d.ts.map +1 -0
  62. package/dist/src/score/peer-score-thresholds.js +32 -0
  63. package/dist/src/score/peer-score-thresholds.js.map +1 -0
  64. package/dist/src/score/peer-score.d.ts +119 -0
  65. package/dist/src/score/peer-score.d.ts.map +1 -0
  66. package/dist/src/score/peer-score.js +459 -0
  67. package/dist/src/score/peer-score.js.map +1 -0
  68. package/dist/src/score/peer-stats.d.ts +32 -0
  69. package/dist/src/score/peer-stats.d.ts.map +1 -0
  70. package/dist/src/score/peer-stats.js +2 -0
  71. package/dist/src/score/peer-stats.js.map +1 -0
  72. package/dist/src/score/scoreMetrics.d.ts +23 -0
  73. package/dist/src/score/scoreMetrics.d.ts.map +1 -0
  74. package/dist/src/score/scoreMetrics.js +155 -0
  75. package/dist/src/score/scoreMetrics.js.map +1 -0
  76. package/dist/src/stream.d.ts +30 -0
  77. package/dist/src/stream.d.ts.map +1 -0
  78. package/dist/src/stream.js +55 -0
  79. package/dist/src/stream.js.map +1 -0
  80. package/dist/src/tracer.d.ts +53 -0
  81. package/dist/src/tracer.d.ts.map +1 -0
  82. package/dist/src/tracer.js +155 -0
  83. package/dist/src/tracer.js.map +1 -0
  84. package/dist/src/types.d.ts +148 -0
  85. package/dist/src/types.d.ts.map +1 -0
  86. package/dist/src/types.js +90 -0
  87. package/dist/src/types.js.map +1 -0
  88. package/dist/src/utils/buildRawMessage.d.ts +20 -0
  89. package/dist/src/utils/buildRawMessage.d.ts.map +1 -0
  90. package/dist/src/utils/buildRawMessage.js +151 -0
  91. package/dist/src/utils/buildRawMessage.js.map +1 -0
  92. package/dist/src/utils/create-gossip-rpc.d.ts +7 -0
  93. package/dist/src/utils/create-gossip-rpc.d.ts.map +1 -0
  94. package/dist/src/utils/create-gossip-rpc.js +31 -0
  95. package/dist/src/utils/create-gossip-rpc.js.map +1 -0
  96. package/dist/src/utils/index.d.ts +4 -0
  97. package/dist/src/utils/index.d.ts.map +1 -0
  98. package/dist/src/utils/index.js +4 -0
  99. package/dist/src/utils/index.js.map +1 -0
  100. package/dist/src/utils/messageIdToString.d.ts +5 -0
  101. package/dist/src/utils/messageIdToString.d.ts.map +1 -0
  102. package/dist/src/utils/messageIdToString.js +8 -0
  103. package/dist/src/utils/messageIdToString.js.map +1 -0
  104. package/dist/src/utils/msgIdFn.d.ts +10 -0
  105. package/dist/src/utils/msgIdFn.d.ts.map +1 -0
  106. package/dist/src/utils/msgIdFn.js +23 -0
  107. package/dist/src/utils/msgIdFn.js.map +1 -0
  108. package/dist/src/utils/multiaddr.d.ts +3 -0
  109. package/dist/src/utils/multiaddr.d.ts.map +1 -0
  110. package/dist/src/utils/multiaddr.js +15 -0
  111. package/dist/src/utils/multiaddr.js.map +1 -0
  112. package/dist/src/utils/publishConfig.d.ts +8 -0
  113. package/dist/src/utils/publishConfig.d.ts.map +1 -0
  114. package/dist/src/utils/publishConfig.js +25 -0
  115. package/dist/src/utils/publishConfig.js.map +1 -0
  116. package/dist/src/utils/set.d.ts +14 -0
  117. package/dist/src/utils/set.d.ts.map +1 -0
  118. package/dist/src/utils/set.js +41 -0
  119. package/dist/src/utils/set.js.map +1 -0
  120. package/dist/src/utils/shuffle.d.ts +7 -0
  121. package/dist/src/utils/shuffle.d.ts.map +1 -0
  122. package/dist/src/utils/shuffle.js +21 -0
  123. package/dist/src/utils/shuffle.js.map +1 -0
  124. package/dist/src/utils/time-cache.d.ts +22 -0
  125. package/dist/src/utils/time-cache.d.ts.map +1 -0
  126. package/dist/src/utils/time-cache.js +54 -0
  127. package/dist/src/utils/time-cache.js.map +1 -0
  128. package/package.json +142 -0
  129. package/src/config.ts +31 -0
  130. package/src/constants.ts +261 -0
  131. package/src/errors.ts +17 -0
  132. package/src/gossipsub.ts +3061 -0
  133. package/src/index.ts +404 -0
  134. package/src/message/decodeRpc.ts +19 -0
  135. package/src/message/index.ts +1 -0
  136. package/src/message/rpc.proto +58 -0
  137. package/src/message/rpc.ts +848 -0
  138. package/src/message-cache.ts +196 -0
  139. package/src/metrics.ts +1014 -0
  140. package/src/score/compute-score.ts +98 -0
  141. package/src/score/index.ts +3 -0
  142. package/src/score/message-deliveries.ts +95 -0
  143. package/src/score/peer-score-params.ts +316 -0
  144. package/src/score/peer-score-thresholds.ts +70 -0
  145. package/src/score/peer-score.ts +565 -0
  146. package/src/score/peer-stats.ts +33 -0
  147. package/src/score/scoreMetrics.ts +215 -0
  148. package/src/stream.ts +79 -0
  149. package/src/tracer.ts +177 -0
  150. package/src/types.ts +178 -0
  151. package/src/utils/buildRawMessage.ts +174 -0
  152. package/src/utils/create-gossip-rpc.ts +34 -0
  153. package/src/utils/index.ts +3 -0
  154. package/src/utils/messageIdToString.ts +8 -0
  155. package/src/utils/msgIdFn.ts +24 -0
  156. package/src/utils/multiaddr.ts +19 -0
  157. package/src/utils/publishConfig.ts +33 -0
  158. package/src/utils/set.ts +43 -0
  159. package/src/utils/shuffle.ts +21 -0
  160. package/src/utils/time-cache.ts +71 -0
@@ -0,0 +1,19 @@
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 yc=Object.create;var zs=Object.defineProperty;var wc=Object.getOwnPropertyDescriptor;var xc=Object.getOwnPropertyNames;var vc=Object.getPrototypeOf,Ec=Object.prototype.hasOwnProperty;var Sc=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),_e=(s,e)=>{for(var t in e)zs(s,t,{get:e[t],enumerable:!0})},Ho=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of xc(e))!Ec.call(s,n)&&n!==t&&zs(s,n,{get:()=>e[n],enumerable:!(r=wc(e,n))||r.enumerable});return s};var _c=(s,e,t)=>(t=s!=null?yc(vc(s)):{},Ho(e||!s||!s.__esModule?zs(t,"default",{value:s,enumerable:!0}):t,s)),Ic=s=>Ho(zs({},"__esModule",{value:!0}),s);var ec=Sc((T0,Qa)=>{"use strict";function $(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))}$.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]}};$.prototype.get=function(e){return this.peekAt(e)};$.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};$.prototype.peekFront=function(){return this.peek()};$.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty($.prototype,"length",{get:function(){return this.size()}});$.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};$.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)};$.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}};$.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)};$.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}};$.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}}};$.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 c;for(n=new Array(t),c=0;c<t;c++)n[c]=this._list[this._head+r+c&this._capacityMask];if(r=this._head+r&this._capacityMask,e+t===i){for(this._tail=this._tail-t+a&this._capacityMask,c=t;c>0;c--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(e===0){for(this._head=this._head+t+a&this._capacityMask,c=t-1;c>0;c--)this._list[r=r+1+a&this._capacityMask]=void 0;return n}if(r<i/2){for(this._head=this._head+e+t+a&this._capacityMask,c=e;c>0;c--)this.unshift(this._list[r=r-1+a&this._capacityMask]);for(r=this._head-1+a&this._capacityMask;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,c=i-(t+e);c>0;c--)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}}};$.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,c=arguments.length,f=this._list.length,m=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+f&this._capacityMask)):(a=this.remove(r,t),this._head=this._head+r+f&this._capacityMask);c>m;)this.unshift(arguments[--c]);for(o=r;o>0;o--)this.unshift(i[o-1])}else{i=new Array(n-(r+t));var h=i.length;for(o=0;o<h;o++)i[o]=this._list[this._head+r+t+o&this._capacityMask];for(t===0?(a=[],r!=n&&(this._tail=this._head+r+f&this._capacityMask)):(a=this.remove(r,t),this._tail=this._tail-h+f&this._capacityMask);m<c;)this.push(arguments[m++]);for(o=0;o<h;o++)this.push(i[o])}return a}else return this.remove(r,t)}};$.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0};$.prototype.isEmpty=function(){return this._head===this._tail};$.prototype.toArray=function(){return this._copyArray(!1)};$.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]};$.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,c;if(e||this._head>this._tail){for(c=this._head;c<n;c++)i[a++]=r[c];for(c=0;c<this._tail;c++)i[a++]=r[c]}else for(c=this._head;c<this._tail;c++)i[a++]=r[c];return i};$.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};$.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1};$.prototype._nextPowerOf2=function(e){var t=Math.log(e)/Math.log(2),r=1<<t+1;return Math.max(r,4)};Qa.exports=$});var lf={};_e(lf,{StrictNoSign:()=>Ot,StrictSign:()=>It,TopicValidatorResult:()=>pe,gossipsub:()=>cf,multicodec:()=>af});var Fr="/floodsub/1.0.0",Hr="/meshsub/1.0.0",Go="/meshsub/1.1.0",Kt="/meshsub/1.2.0";var qo="ERR_TOPIC_VALIDATOR_REJECT",zo="ERR_TOPIC_VALIDATOR_IGNORE";var W=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Ft=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Vs=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Ws=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Ht=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Gr=Symbol.for("@libp2p/peer-id");var js=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,r){super.addEventListener(e,t,r);let n=this.#e.get(e);n==null&&(n=[],this.#e.set(e,n)),n.push({callback:t,once:(r!==!0&&r!==!1&&r?.once)??!1})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),t??null,r);let n=this.#e.get(e);n!=null&&(n=n.filter(({callback:o})=>o!==t),this.#e.set(e,n))}dispatchEvent(e){let t=super.dispatchEvent(e),r=this.#e.get(e.type);return r==null||(r=r.filter(({once:n})=>!n),this.#e.set(e.type,r)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Wo=Symbol.for("@libp2p/service-capabilities"),jo=Symbol.for("@libp2p/service-dependencies");var jr={};_e(jr,{base58btc:()=>Q,base58flickr:()=>kc});var Kf=new Uint8Array(0);function $o(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 je(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 Zo(s){return new TextEncoder().encode(s)}function Xo(s){return new TextDecoder().decode(s)}function Tc(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,c=s.charAt(0),f=Math.log(a)/Math.log(256),m=Math.log(256)/Math.log(a);function h(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";for(var p=0,g=0,b=0,E=u.length;b!==E&&u[b]===0;)b++,p++;for(var w=(E-b)*m+1>>>0,T=new Uint8Array(w);b!==E;){for(var _=u[b],D=0,A=w-1;(_!==0||D<g)&&A!==-1;A--,D++)_+=256*T[A]>>>0,T[A]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");g=D,b++}for(var M=w-g;M!==w&&T[M]===0;)M++;for(var y=c.repeat(p);M<w;++M)y+=s.charAt(T[M]);return y}function d(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;var p=0;if(u[p]!==" "){for(var g=0,b=0;u[p]===c;)g++,p++;for(var E=(u.length-p)*f+1>>>0,w=new Uint8Array(E);u[p];){var T=t[u.charCodeAt(p)];if(T===255)return;for(var _=0,D=E-1;(T!==0||_<b)&&D!==-1;D--,_++)T+=a*w[D]>>>0,w[D]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");b=_,p++}if(u[p]!==" "){for(var A=E-b;A!==E&&w[A]===0;)A++;for(var M=new Uint8Array(g+(E-A)),y=g;A!==E;)M[y++]=w[A++];return M}}}function l(u){var p=d(u);if(p)return p;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:l}}var Ac=Tc,Pc=Ac,Jo=Pc;var qr=class{name;prefix;baseEncode;constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},zr=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,r){this.name=e,this.prefix=t;let n=t.codePointAt(0);if(n===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Qo(this,e)}},Vr=class{decoders;constructor(e){this.decoders=e}or(e){return Qo(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 Qo(s,e){return new Vr({...s.decoders??{[s.prefix]:s},...e.decoders??{[e.prefix]:e}})}var Wr=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,r,n){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new qr(e,t,r),this.decoder=new zr(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Gt({name:s,prefix:e,encode:t,decode:r}){return new Wr(s,e,t,r)}function ft({name:s,prefix:e,alphabet:t}){let{encode:r,decode:n}=Jo(t,s);return Gt({prefix:e,name:s,encode:r,decode:o=>je(n(o))})}function Dc(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,c=0;for(let f=0;f<n;++f){let m=e[s[f]];if(m===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<t|m,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Mc(s,e,t){let r=e[e.length-1]==="=",n=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<s.length;++c)for(a=a<<8|s[c],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 Bc(s){let e={};for(let t=0;t<s.length;++t)e[s[t]]=t;return e}function J({name:s,prefix:e,bitsPerChar:t,alphabet:r}){let n=Bc(r);return Gt({prefix:e,name:s,encode(o){return Mc(o,r,t)},decode(o){return Dc(o,n,t,s)}})}var Q=ft({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),kc=ft({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var $r={};_e($r,{base32:()=>qt,base32hex:()=>Nc,base32hexpad:()=>Oc,base32hexpadupper:()=>Kc,base32hexupper:()=>Uc,base32pad:()=>Rc,base32padupper:()=>Cc,base32upper:()=>Lc,base32z:()=>Fc});var qt=J({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Lc=J({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Rc=J({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Cc=J({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Nc=J({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Uc=J({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Oc=J({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Kc=J({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Fc=J({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Zr={};_e(Zr,{base36:()=>gs,base36upper:()=>Hc});var gs=ft({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Hc=ft({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Gc=si,ei=128,qc=127,zc=~qc,Vc=Math.pow(2,31);function si(s,e,t){e=e||[],t=t||0;for(var r=t;s>=Vc;)e[t++]=s&255|ei,s/=128;for(;s&zc;)e[t++]=s&255|ei,s>>>=7;return e[t]=s|0,si.bytes=t-r+1,e}var Wc=Xr,jc=128,ti=127;function Xr(s,r){var t=0,r=r||0,n=0,o=r,i,a=s.length;do{if(o>=a)throw Xr.bytes=0,new RangeError("Could not decode varint");i=s[o++],t+=n<28?(i&ti)<<n:(i&ti)*Math.pow(2,n),n+=7}while(i>=jc);return Xr.bytes=o-r,t}var $c=Math.pow(2,7),Zc=Math.pow(2,14),Xc=Math.pow(2,21),Yc=Math.pow(2,28),Jc=Math.pow(2,35),Qc=Math.pow(2,42),el=Math.pow(2,49),tl=Math.pow(2,56),sl=Math.pow(2,63),rl=function(s){return s<$c?1:s<Zc?2:s<Xc?3:s<Yc?4:s<Jc?5:s<Qc?6:s<el?7:s<tl?8:s<sl?9:10},nl={encode:Gc,decode:Wc,encodingLength:rl},ol=nl,bs=ol;function ys(s,e=0){return[bs.decode(s,e),bs.decode.bytes]}function zt(s,e,t=0){return bs.encode(s,e,t),e}function Vt(s){return bs.encodingLength(s)}function He(s,e){let t=e.byteLength,r=Vt(s),n=r+Vt(t),o=new Uint8Array(n+t);return zt(s,o,0),zt(t,o,r),o.set(e,n),new Wt(s,t,e,o)}function Ge(s){let e=je(s),[t,r]=ys(e),[n,o]=ys(e.subarray(r)),i=e.subarray(r+o);if(i.byteLength!==n)throw new Error("Incorrect length");return new Wt(t,n,i,e)}function ri(s,e){if(s===e)return!0;{let t=e;return s.code===t.code&&s.size===t.size&&t.bytes instanceof Uint8Array&&$o(s.bytes,t.bytes)}}var Wt=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}};function ni(s,e){let{bytes:t,version:r}=s;switch(r){case 0:return al(t,Yr(s),e??Q.encoder);default:return cl(t,Yr(s),e??qt.encoder)}}var oi=new WeakMap;function Yr(s){let e=oi.get(s);if(e==null){let t=new Map;return oi.set(s,t),t}return e}var ie=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!==ws)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==ll)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&&ri(e.multihash,r.multihash)}toString(e){return ni(this,e)}toJSON(){return{"/":ni(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??ii(r,n,o.bytes))}else if(t[ul]===!0){let{version:r,multihash:n,code:o}=t,i=Ge(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!==ws)throw new Error(`Version 0 CID must use dag-pb (code: ${ws}) block encoding`);return new s(e,t,r,r.bytes)}case 1:{let n=ii(e,t,r.bytes);return new s(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return s.create(0,ws,e)}static createV1(e,t){return s.create(1,e,t)}static decode(e){let[t,r]=s.decodeFirst(e);if(r.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=s.inspectBytes(e),r=t.size-t.multihashSize,n=je(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 Wt(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[h,d]=ys(e.subarray(t));return t+=d,h},n=r(),o=ws;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(),c=r(),f=t+c,m=f-i;return{version:n,codec:o,multihashCode:a,digestSize:c,multihashSize:m,size:f}}static parse(e,t){let[r,n]=il(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 Yr(o).set(r,e),o}};function il(s,e){switch(s[0]){case"Q":{let t=e??Q;return[Q.prefix,t.decode(`${Q.prefix}${s}`)]}case Q.prefix:{let t=e??Q;return[Q.prefix,t.decode(s)]}case qt.prefix:{let t=e??qt;return[qt.prefix,t.decode(s)]}case gs.prefix:{let t=e??gs;return[gs.prefix,t.decode(s)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[s[0],e.decode(s)]}}}function al(s,e,t){let{prefix:r}=t;if(r!==Q.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let n=e.get(r);if(n==null){let o=t.encode(s).slice(1);return e.set(r,o),o}else return n}function cl(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 ws=112,ll=18;function ii(s,e,t){let r=Vt(s),n=r+Vt(e),o=new Uint8Array(n+t.byteLength);return zt(s,o,0),zt(e,o,r),o.set(t,n),o}var ul=Symbol.for("@ipld/js-cid/CID");var Jr={};_e(Jr,{identity:()=>Ne});var ai=0,hl="identity",ci=je;function fl(s,e){if(e?.truncate!=null&&e.truncate!==s.byteLength){if(e.truncate<0||e.truncate>s.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${s.byteLength}`);s=s.subarray(0,e.truncate)}return He(ai,ci(s))}var Ne={code:ai,name:hl,encode:ci,digest:fl};function Ie(s,e){if(s===e)return!0;if(s.byteLength!==e.byteLength)return!1;for(let t=0;t<s.byteLength;t++)if(s[t]!==e[t])return!1;return!0}function Ze(s=0){return new Uint8Array(s)}function le(s=0){return new Uint8Array(s)}function Tt(s,e){e==null&&(e=s.reduce((n,o)=>n+o.length,0));let t=le(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var ui=Symbol.for("@achingbrain/uint8arraylist");function li(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 Zs(s){return!!s?.[ui]}var re=class s{bufs;length;[ui]=!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(Zs(r))t+=r.byteLength,this.bufs.push(...r.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else if(Zs(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=li(this.bufs,e);return t.buf[t.index]}set(e,t){let r=li(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(Zs(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 Tt(r,n)}subarray(e,t){let{bufs:r,length:n}=this._subList(e,t);return r.length===1?r[0]:Tt(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,c=a+i.byteLength;if(n=c,e>=c)continue;let f=e>=a&&e<c,m=t>a&&t<=c;if(f&&m){if(e===a&&t===c){r.push(i);break}let h=e-a;r.push(i.subarray(h,h+(t-e)));break}if(f){if(e===0){r.push(i);continue}r.push(i.subarray(e-a));continue}if(m){if(t===c){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(!Zs(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 h=0;h<o;h++)i[h]=-1;for(let h=0;h<n;h++)i[r[h]]=h;let a=i,c=this.byteLength-r.byteLength,f=r.byteLength-1,m;for(let h=t;h<=c;h+=m){m=0;for(let d=f;d>=0;d--){let l=this.get(h+d);if(r[d]!==l){m=Math.max(1,d-a[l]);break}}if(m===0)return h}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let r=le(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){let n=Ze(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=Ze(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=Ze(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let r=le(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){let n=Ze(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=Ze(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=Ze(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=Ze(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=Ze(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(e==null||!(e instanceof s)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Ie(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let r=new s;return r.bufs=e,t==null&&(t=e.reduce((n,o)=>n+o.byteLength,0)),r.length=t,r}};var Qr={};_e(Qr,{base10:()=>dl});var dl=ft({prefix:"9",name:"base10",alphabet:"0123456789"});var en={};_e(en,{base16:()=>pl,base16upper:()=>ml});var pl=J({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ml=J({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var tn={};_e(tn,{base2:()=>gl});var gl=J({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var sn={};_e(sn,{base256emoji:()=>vl});var hi=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}"),bl=hi.reduce((s,e,t)=>(s[t]=e,s),[]),yl=hi.reduce((s,e,t)=>{let r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return s[r]=t,s},[]);function wl(s){return s.reduce((e,t)=>(e+=bl[t],e),"")}function xl(s){let e=[];for(let t of s){let r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);let n=yl[r];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var vl=Gt({prefix:"\u{1F680}",name:"base256emoji",encode:wl,decode:xl});var rn={};_e(rn,{base64:()=>El,base64pad:()=>Sl,base64url:()=>_l,base64urlpad:()=>Il});var El=J({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Sl=J({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),_l=J({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Il=J({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var nn={};_e(nn,{base8:()=>Tl});var Tl=J({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var on={};_e(on,{identity:()=>Al});var Al=Gt({prefix:"\0",name:"identity",encode:s=>Xo(s),decode:s=>Zo(s)});var Ed=new TextEncoder,Sd=new TextDecoder;var ln={};_e(ln,{sha256:()=>dt,sha512:()=>Bl});var Ml=20;function cn({name:s,code:e,encode:t,minDigestLength:r,maxDigestLength:n}){return new an(s,e,t,r,n)}var an=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,r,n,o){this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??Ml,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?fi(r,this.code,t?.truncate):r.then(n=>fi(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function fi(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 pi(s){return async e=>new Uint8Array(await crypto.subtle.digest(s,e))}var dt=cn({name:"sha2-256",code:18,encode:pi("SHA-256")}),Bl=cn({name:"sha2-512",code:19,encode:pi("SHA-512")});var un={...on,...tn,...nn,...Qr,...en,...$r,...Zr,...jr,...rn,...sn},Cd={...ln,...Jr};function gi(s,e,t,r){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:r}}}var mi=gi("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),hn=gi("ascii","a",s=>{let e="a";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return e},s=>{s=s.substring(1);let e=le(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),kl={utf8:mi,"utf-8":mi,hex:un.base16,latin1:hn,ascii:hn,binary:hn,...un},Xs=kl;function V(s,e="utf8"){let t=Xs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${s}`)}function F(s,e="utf8"){let t=Xs[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(s).substring(1)}var Ll=parseInt("11111",2),fn=parseInt("10000000",2),Rl=parseInt("01111111",2),bi={0:xs,1:xs,2:Cl,3:Ol,4:Kl,5:Ul,6:Nl,16:xs,22:xs,48:xs};function Xe(s,e={offset:0}){let t=s[e.offset]&Ll;if(e.offset++,bi[t]!=null)return bi[t](s,e);throw new Error("No decoder for tag "+t)}function vs(s,e){let t=0;if((s[e.offset]&fn)===fn){let r=s[e.offset]&Rl,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 xs(s,e){vs(s,e);let t=[];for(;!(e.offset>=s.byteLength);){let r=Xe(s,e);if(r===null)break;t.push(r)}return t}function Cl(s,e){let t=vs(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 Nl(s,e){let t=vs(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}`,c=[];for(;e.offset<r;){let f=s[e.offset];if(e.offset++,c.push(f&127),f<128){c.reverse();let m=0;for(let h=0;h<c.length;h++)m+=c[h]<<h*7;a+=`.${m}`,c=[]}}return a}function Ul(s,e){return e.offset++,null}function Ol(s,e){let t=vs(s,e),r=s[e.offset];e.offset++;let n=s.subarray(e.offset,e.offset+t-1);if(e.offset+=t,r!==0)throw new Error("Unused bits in bit string is unimplemented");return n}function Kl(s,e){let t=vs(s,e),r=s.subarray(e.offset,e.offset+t);return e.offset+=t,r}function Fl(s){let e=s.toString(16);e.length%2===1&&(e="0"+e);let t=new re;for(let r=0;r<e.length;r+=2)t.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return t}function dn(s){if(s.byteLength<128)return Uint8Array.from([s.byteLength]);let e=Fl(s.byteLength);return new re(Uint8Array.from([e.byteLength|fn]),e)}function Te(s){let e=new re,t=128;return(s.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(s),new re(Uint8Array.from([2]),dn(e),e)}function Ys(s){let e=Uint8Array.from([0]),t=new re(e,s);return new re(Uint8Array.from([3]),dn(t),t)}function pt(s,e=48){let t=new re;for(let r of s)t.append(r);return new re(Uint8Array.from([e]),dn(t),t)}async function yi(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}var Hl=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Gl=Uint8Array.from([6,5,43,129,4,0,34]),ql=Uint8Array.from([6,5,43,129,4,0,35]),zl={ext:!0,kty:"EC",crv:"P-256"},Vl={ext:!0,kty:"EC",crv:"P-384"},Wl={ext:!0,kty:"EC",crv:"P-521"},pn=32,mn=48,gn=66;function bn(s){let e=Xe(s);return wi(e)}function wi(s){let e=s[1][1][0],t=1,r,n;if(e.byteLength===pn*2+1)return r=F(e.subarray(t,t+pn),"base64url"),n=F(e.subarray(t+pn),"base64url"),new jt({...zl,key_ops:["verify"],x:r,y:n});if(e.byteLength===mn*2+1)return r=F(e.subarray(t,t+mn),"base64url"),n=F(e.subarray(t+mn),"base64url"),new jt({...Vl,key_ops:["verify"],x:r,y:n});if(e.byteLength===gn*2+1)return r=F(e.subarray(t,t+gn),"base64url"),n=F(e.subarray(t+gn),"base64url"),new jt({...Wl,key_ops:["verify"],x:r,y:n});throw new W(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function xi(s){return pt([Te(Uint8Array.from([1])),pt([jl(s.crv)],160),pt([Ys(new re(Uint8Array.from([4]),V(s.x??"","base64url"),V(s.y??"","base64url")))],161)]).subarray()}function jl(s){if(s==="P-256")return Hl;if(s==="P-384")return Gl;if(s==="P-521")return ql;throw new W(`Invalid curve ${s}`)}var jt=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=xi(this.jwk)),this._raw}toMultihash(){return Ne.digest(qe(this))}toCID(){return ie.createV1(114,this.toMultihash())}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}async verify(e,t,r){return yi(this.jwk,t,e,r)}};var At=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Je(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Es(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function Ae(s,...e){if(!Je(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function Js(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Es(s.outputLen),Es(s.blockLen)}function Zt(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Ei(s,e){Ae(s);let t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Qe(...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 Ue(s,e){return s<<32-e|s>>>e}var Si=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",$l=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Le(s){if(Ae(s),Si)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=$l[s[t]];return e}var Ye={_0:48,_9:57,A:65,F:70,a:97,f:102};function vi(s){if(s>=Ye._0&&s<=Ye._9)return s-Ye._0;if(s>=Ye.A&&s<=Ye.F)return s-(Ye.A-10);if(s>=Ye.a&&s<=Ye.f)return s-(Ye.a-10)}function Pt(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Si)return Uint8Array.fromHex(s);let e=s.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let n=0,o=0;n<t;n++,o+=2){let i=vi(s.charCodeAt(o)),a=vi(s.charCodeAt(o+1));if(i===void 0||a===void 0){let c=s[o]+s[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}r[n]=i*16+a}return r}function yn(s){if(typeof s!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(s))}function Ss(s){return typeof s=="string"&&(s=yn(s)),Ae(s),s}function me(...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}var $t=class{};function wn(s){let e=r=>s().update(Ss(r)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function mt(s=32){if(At&&typeof At.getRandomValues=="function")return At.getRandomValues(new Uint8Array(s));if(At&&typeof At.randomBytes=="function")return Uint8Array.from(At.randomBytes(s));throw new Error("crypto.getRandomValues must be defined")}function Zl(s,e,t,r){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,r);let n=BigInt(32),o=BigInt(4294967295),i=Number(t>>n&o),a=Number(t&o),c=r?4:0,f=r?0:4;s.setUint32(e+c,i,r),s.setUint32(e+f,a,r)}function _i(s,e,t){return s&e^~s&t}function Ii(s,e,t){return s&e^s&t^e&t}var _s=class extends $t{constructor(e,t,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Qs(this.buffer)}update(e){Zt(this),e=Ss(e),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 c=Qs(e);for(;n<=o-i;i+=n)this.process(c,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){Zt(this),Ei(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;t[i++]=128,Qe(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(r,0),i=0);for(let h=i;h<n;h++)t[h]=0;Zl(r,n-8,BigInt(this.length*8),o),this.process(r,0);let a=Qs(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let f=c/4,m=this.get();if(f>m.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<f;h++)a.setUint32(4*h,m[h],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){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()}},et=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ae=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var er=BigInt(4294967295),Ti=BigInt(32);function Xl(s,e=!1){return e?{h:Number(s&er),l:Number(s>>Ti&er)}:{h:Number(s>>Ti&er)|0,l:Number(s&er)|0}}function Ai(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}=Xl(s[o],e);[r[o],n[o]]=[i,a]}return[r,n]}var xn=(s,e,t)=>s>>>t,vn=(s,e,t)=>s<<32-t|e>>>t,Dt=(s,e,t)=>s>>>t|e<<32-t,Mt=(s,e,t)=>s<<32-t|e>>>t,Is=(s,e,t)=>s<<64-t|e>>>t-32,Ts=(s,e,t)=>s>>>t-32|e<<64-t;function ze(s,e,t,r){let n=(e>>>0)+(r>>>0);return{h:s+t+(n/2**32|0)|0,l:n|0}}var Pi=(s,e,t)=>(s>>>0)+(e>>>0)+(t>>>0),Di=(s,e,t,r)=>e+t+r+(s/2**32|0)|0,Mi=(s,e,t,r)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0),Bi=(s,e,t,r,n)=>e+t+r+n+(s/2**32|0)|0,ki=(s,e,t,r,n)=>(s>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Li=(s,e,t,r,n,o)=>e+t+r+n+o+(s/2**32|0)|0;var Jl=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]),gt=new Uint32Array(64),tr=class extends _s{constructor(e=32){super(64,e,8,!1),this.A=et[0]|0,this.B=et[1]|0,this.C=et[2]|0,this.D=et[3]|0,this.E=et[4]|0,this.F=et[5]|0,this.G=et[6]|0,this.H=et[7]|0}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:a,H:c}=this;return[e,t,r,n,o,i,a,c]}set(e,t,r,n,o,i,a,c){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=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)gt[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let d=gt[h-15],l=gt[h-2],u=Ue(d,7)^Ue(d,18)^d>>>3,p=Ue(l,17)^Ue(l,19)^l>>>10;gt[h]=p+gt[h-7]+u+gt[h-16]|0}let{A:r,B:n,C:o,D:i,E:a,F:c,G:f,H:m}=this;for(let h=0;h<64;h++){let d=Ue(a,6)^Ue(a,11)^Ue(a,25),l=m+d+_i(a,c,f)+Jl[h]+gt[h]|0,p=(Ue(r,2)^Ue(r,13)^Ue(r,22))+Ii(r,n,o)|0;m=f,f=c,c=a,a=i+l|0,i=o,o=n,n=r,r=l+p|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,c=c+this.F|0,f=f+this.G|0,m=m+this.H|0,this.set(r,n,o,i,a,c,f,m)}roundClean(){Qe(gt)}destroy(){this.set(0,0,0,0,0,0,0,0),Qe(this.buffer)}};var Ri=Ai(["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))),Ql=Ri[0],eu=Ri[1],bt=new Uint32Array(80),yt=new Uint32Array(80),En=class extends _s{constructor(e=64){super(128,e,16,!1),this.Ah=ae[0]|0,this.Al=ae[1]|0,this.Bh=ae[2]|0,this.Bl=ae[3]|0,this.Ch=ae[4]|0,this.Cl=ae[5]|0,this.Dh=ae[6]|0,this.Dl=ae[7]|0,this.Eh=ae[8]|0,this.El=ae[9]|0,this.Fh=ae[10]|0,this.Fl=ae[11]|0,this.Gh=ae[12]|0,this.Gl=ae[13]|0,this.Hh=ae[14]|0,this.Hl=ae[15]|0}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:o,Cl:i,Dh:a,Dl:c,Eh:f,El:m,Fh:h,Fl:d,Gh:l,Gl:u,Hh:p,Hl:g}=this;return[e,t,r,n,o,i,a,c,f,m,h,d,l,u,p,g]}set(e,t,r,n,o,i,a,c,f,m,h,d,l,u,p,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=c|0,this.Eh=f|0,this.El=m|0,this.Fh=h|0,this.Fl=d|0,this.Gh=l|0,this.Gl=u|0,this.Hh=p|0,this.Hl=g|0}process(e,t){for(let w=0;w<16;w++,t+=4)bt[w]=e.getUint32(t),yt[w]=e.getUint32(t+=4);for(let w=16;w<80;w++){let T=bt[w-15]|0,_=yt[w-15]|0,D=Dt(T,_,1)^Dt(T,_,8)^xn(T,_,7),A=Mt(T,_,1)^Mt(T,_,8)^vn(T,_,7),M=bt[w-2]|0,y=yt[w-2]|0,P=Dt(M,y,19)^Is(M,y,61)^xn(M,y,6),N=Mt(M,y,19)^Ts(M,y,61)^vn(M,y,6),R=Mi(A,N,yt[w-7],yt[w-16]),S=Bi(R,D,P,bt[w-7],bt[w-16]);bt[w]=S|0,yt[w]=R|0}let{Ah:r,Al:n,Bh:o,Bl:i,Ch:a,Cl:c,Dh:f,Dl:m,Eh:h,El:d,Fh:l,Fl:u,Gh:p,Gl:g,Hh:b,Hl:E}=this;for(let w=0;w<80;w++){let T=Dt(h,d,14)^Dt(h,d,18)^Is(h,d,41),_=Mt(h,d,14)^Mt(h,d,18)^Ts(h,d,41),D=h&l^~h&p,A=d&u^~d&g,M=ki(E,_,A,eu[w],yt[w]),y=Li(M,b,T,D,Ql[w],bt[w]),P=M|0,N=Dt(r,n,28)^Is(r,n,34)^Is(r,n,39),R=Mt(r,n,28)^Ts(r,n,34)^Ts(r,n,39),S=r&o^r&a^o&a,x=n&i^n&c^i&c;b=p|0,E=g|0,p=l|0,g=u|0,l=h|0,u=d|0,{h,l:d}=ze(f|0,m|0,y|0,P|0),f=a|0,m=c|0,a=o|0,c=i|0,o=r|0,i=n|0;let v=Pi(P,R,x);r=Di(v,y,N,S),n=v|0}({h:r,l:n}=ze(this.Ah|0,this.Al|0,r|0,n|0)),{h:o,l:i}=ze(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=ze(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:m}=ze(this.Dh|0,this.Dl|0,f|0,m|0),{h,l:d}=ze(this.Eh|0,this.El|0,h|0,d|0),{h:l,l:u}=ze(this.Fh|0,this.Fl|0,l|0,u|0),{h:p,l:g}=ze(this.Gh|0,this.Gl|0,p|0,g|0),{h:b,l:E}=ze(this.Hh|0,this.Hl|0,b|0,E|0),this.set(r,n,o,i,a,c,f,m,h,d,l,u,p,g,b,E)}roundClean(){Qe(bt,yt)}destroy(){Qe(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var sr=wn(()=>new tr);var Ci=wn(()=>new En);var In=BigInt(0),_n=BigInt(1);function tt(s,e=""){if(typeof s!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof s)}return s}function De(s,e,t=""){let r=Je(s),n=s?.length,o=e!==void 0;if(!r||o&&n!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=r?`length=${n}`:`type=${typeof s}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return s}function As(s){let e=s.toString(16);return e.length&1?"0"+e:e}function Ni(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?In:BigInt("0x"+s)}function Xt(s){return Ni(Le(s))}function st(s){return Ae(s),Ni(Le(Uint8Array.from(s).reverse()))}function rr(s,e){return Pt(s.toString(16).padStart(e*2,"0"))}function Tn(s,e){return rr(s,e).reverse()}function q(s,e,t){let r;if(typeof e=="string")try{r=Pt(e)}catch(o){throw new Error(s+" must be hex string or Uint8Array, cause: "+o)}else if(Je(e))r=Uint8Array.from(e);else throw new Error(s+" must be hex string or Uint8Array");let n=r.length;if(typeof t=="number"&&n!==t)throw new Error(s+" of length "+t+" expected, got "+n);return r}function Ui(s,e){if(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 An(s){return Uint8Array.from(s)}var Sn=s=>typeof s=="bigint"&&In<=s;function Oi(s,e,t){return Sn(s)&&Sn(e)&&Sn(t)&&e<=s&&s<t}function Ps(s,e,t,r){if(!Oi(e,t,r))throw new Error("expected valid "+s+": "+t+" <= n < "+r+", got "+e)}function nr(s){let e;for(e=0;s>In;s>>=_n,e+=1);return e}var wt=s=>(_n<<BigInt(s))-_n;function Ki(s,e,t){if(typeof s!="number"||s<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let r=l=>new Uint8Array(l),n=l=>Uint8Array.of(l),o=r(s),i=r(s),a=0,c=()=>{o.fill(1),i.fill(0),a=0},f=(...l)=>t(i,o,...l),m=(l=r(0))=>{i=f(n(0),l),o=f(),l.length!==0&&(i=f(n(1),l),o=f())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let l=0,u=[];for(;l<e;){o=f();let p=o.slice();u.push(p),l+=o.length}return me(...u)};return(l,u)=>{c(),m(l);let p;for(;!(p=u(h()));)m();return c(),p}}function xt(s,e,t={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function r(n,o,i){let a=s[n];if(i&&a===void 0)return;let c=typeof a;if(c!==o||a===null)throw new Error(`param "${n}" is invalid: expected ${o}, got ${c}`)}Object.entries(e).forEach(([n,o])=>r(n,o,!1)),Object.entries(t).forEach(([n,o])=>r(n,o,!0))}var Pn=()=>{throw new Error("not implemented")};function Yt(s){let e=new WeakMap;return(t,...r)=>{let n=e.get(t);if(n!==void 0)return n;let o=s(t,...r);return e.set(t,o),o}}var ge=BigInt(0),ne=BigInt(1),Bt=BigInt(2),Gi=BigInt(3),qi=BigInt(4),zi=BigInt(5),tu=BigInt(7),Vi=BigInt(8),su=BigInt(9),Wi=BigInt(16);function ee(s,e){let t=s%e;return t>=ge?t:e+t}function j(s,e,t){let r=s;for(;e-- >ge;)r*=r,r%=t;return r}function Fi(s,e){if(s===ge)throw new Error("invert: expected non-zero number");if(e<=ge)throw new Error("invert: expected positive modulus, got "+e);let t=ee(s,e),r=e,n=ge,o=ne,i=ne,a=ge;for(;t!==ge;){let f=r/t,m=r%t,h=n-i*f,d=o-a*f;r=t,t=m,n=i,o=a,i=h,a=d}if(r!==ne)throw new Error("invert: does not exist");return ee(n,e)}function Dn(s,e,t){if(!s.eql(s.sqr(e),t))throw new Error("Cannot find square root")}function ji(s,e){let t=(s.ORDER+ne)/qi,r=s.pow(e,t);return Dn(s,r,e),r}function ru(s,e){let t=(s.ORDER-zi)/Vi,r=s.mul(e,Bt),n=s.pow(r,t),o=s.mul(e,n),i=s.mul(s.mul(o,Bt),n),a=s.mul(o,s.sub(i,s.ONE));return Dn(s,a,e),a}function nu(s){let e=Me(s),t=$i(s),r=t(e,e.neg(e.ONE)),n=t(e,r),o=t(e,e.neg(r)),i=(s+tu)/Wi;return(a,c)=>{let f=a.pow(c,i),m=a.mul(f,r),h=a.mul(f,n),d=a.mul(f,o),l=a.eql(a.sqr(m),c),u=a.eql(a.sqr(h),c);f=a.cmov(f,m,l),m=a.cmov(d,h,u);let p=a.eql(a.sqr(m),c),g=a.cmov(f,m,p);return Dn(a,g,c),g}}function $i(s){if(s<Gi)throw new Error("sqrt is not defined for small field");let e=s-ne,t=0;for(;e%Bt===ge;)e/=Bt,t++;let r=Bt,n=Me(s);for(;Hi(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+ne)/Bt;return function(c,f){if(c.is0(f))return f;if(Hi(c,f)!==1)throw new Error("Cannot find square root");let m=t,h=c.mul(c.ONE,o),d=c.pow(f,e),l=c.pow(f,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let u=1,p=c.sqr(d);for(;!c.eql(p,c.ONE);)if(u++,p=c.sqr(p),u===m)throw new Error("Cannot find square root");let g=ne<<BigInt(m-u-1),b=c.pow(h,g);m=u,h=c.sqr(b),d=c.mul(d,h),l=c.mul(l,b)}return l}}function ou(s){return s%qi===Gi?ji:s%Vi===zi?ru:s%Wi===su?nu(s):$i(s)}var rt=(s,e)=>(ee(s,e)&ne)===ne,iu=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Mn(s){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=iu.reduce((r,n)=>(r[n]="function",r),e);return xt(s,t),s}function au(s,e,t){if(t<ge)throw new Error("invalid exponent, negatives unsupported");if(t===ge)return s.ONE;if(t===ne)return e;let r=s.ONE,n=e;for(;t>ge;)t&ne&&(r=s.mul(r,n)),n=s.sqr(n),t>>=ne;return r}function Ds(s,e,t=!1){let r=new Array(e.length).fill(t?s.ZERO:void 0),n=e.reduce((i,a,c)=>s.is0(a)?i:(r[c]=i,s.mul(i,a)),s.ONE),o=s.inv(n);return e.reduceRight((i,a,c)=>s.is0(a)?i:(r[c]=s.mul(i,r[c]),s.mul(i,a)),o),r}function Hi(s,e){let t=(s.ORDER-ne)/Bt,r=s.pow(e,t),n=s.eql(r,s.ONE),o=s.eql(r,s.ZERO),i=s.eql(r,s.neg(s.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function or(s,e){e!==void 0&&Es(e);let t=e!==void 0?e:s.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function Me(s,e,t=!1,r={}){if(s<=ge)throw new Error("invalid field: expected ORDER > 0, got "+s);let n,o,i=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||t)throw new Error("cannot specify opts in two arguments");let d=e;d.BITS&&(n=d.BITS),d.sqrt&&(o=d.sqrt),typeof d.isLE=="boolean"&&(t=d.isLE),typeof d.modFromBytes=="boolean"&&(i=d.modFromBytes),a=d.allowedLengths}else typeof e=="number"&&(n=e),r.sqrt&&(o=r.sqrt);let{nBitLength:c,nByteLength:f}=or(s,n);if(f>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let m,h=Object.freeze({ORDER:s,isLE:t,BITS:c,BYTES:f,MASK:wt(c),ZERO:ge,ONE:ne,allowedLengths:a,create:d=>ee(d,s),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return ge<=d&&d<s},is0:d=>d===ge,isValidNot0:d=>!h.is0(d)&&h.isValid(d),isOdd:d=>(d&ne)===ne,neg:d=>ee(-d,s),eql:(d,l)=>d===l,sqr:d=>ee(d*d,s),add:(d,l)=>ee(d+l,s),sub:(d,l)=>ee(d-l,s),mul:(d,l)=>ee(d*l,s),pow:(d,l)=>au(h,d,l),div:(d,l)=>ee(d*Fi(l,s),s),sqrN:d=>d*d,addN:(d,l)=>d+l,subN:(d,l)=>d-l,mulN:(d,l)=>d*l,inv:d=>Fi(d,s),sqrt:o||(d=>(m||(m=ou(s)),m(h,d))),toBytes:d=>t?Tn(d,f):rr(d,f),fromBytes:(d,l=!0)=>{if(a){if(!a.includes(d.length)||d.length>f)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);let p=new Uint8Array(f);p.set(d,t?0:p.length-d.length),d=p}if(d.length!==f)throw new Error("Field.fromBytes: expected "+f+" bytes, got "+d.length);let u=t?st(d):Xt(d);if(i&&(u=ee(u,s)),!l&&!h.isValid(u))throw new Error("invalid field element: outside of range 0..ORDER");return u},invertBatch:d=>Ds(h,d),cmov:(d,l,u)=>u?l:d});return Object.freeze(h)}function Zi(s){if(typeof s!="bigint")throw new Error("field order must be bigint");let e=s.toString(2).length;return Math.ceil(e/8)}function Bn(s){let e=Zi(s);return e+Math.ceil(e/2)}function kn(s,e,t=!1){let r=s.length,n=Zi(e),o=Bn(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);let i=t?st(s):Xt(s),a=ee(i,e-ne)+ne;return t?Tn(a,n):rr(a,n)}var Jt=BigInt(0),kt=BigInt(1);function Ms(s,e){let t=e.negate();return s?t:e}function nt(s,e){let t=Ds(s.Fp,e.map(r=>r.Z));return e.map((r,n)=>s.fromAffine(r.toAffine(t[n])))}function Qi(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function Ln(s,e){Qi(s,e);let t=Math.ceil(e/s)+1,r=2**(s-1),n=2**s,o=wt(s),i=BigInt(s);return{windows:t,windowSize:r,mask:o,maxNumber:n,shiftBy:i}}function Xi(s,e,t){let{windowSize:r,mask:n,maxNumber:o,shiftBy:i}=t,a=Number(s&n),c=s>>i;a>r&&(a-=o,c+=kt);let f=e*r,m=f+Math.abs(a)-1,h=a===0,d=a<0,l=e%2!==0;return{nextN:c,offset:m,isZero:h,isNeg:d,isNegF:l,offsetF:f}}function cu(s,e){if(!Array.isArray(s))throw new Error("array expected");s.forEach((t,r)=>{if(!(t instanceof e))throw new Error("invalid point at index "+r)})}function lu(s,e){if(!Array.isArray(s))throw new Error("array of scalars expected");s.forEach((t,r)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+r)})}var Rn=new WeakMap,ea=new WeakMap;function Cn(s){return ea.get(s)||1}function Yi(s){if(s!==Jt)throw new Error("invalid wNAF")}var Qt=class{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>Jt;)t&kt&&(r=r.add(n)),n=n.double(),t>>=kt;return r}precomputeWindow(e,t){let{windows:r,windowSize:n}=Ln(t,this.bits),o=[],i=e,a=i;for(let c=0;c<r;c++){a=i,o.push(a);for(let f=1;f<n;f++)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=Ln(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:m,isNeg:h,isNegF:d,offsetF:l}=Xi(r,a,i);r=c,m?o=o.add(Ms(d,t[l])):n=n.add(Ms(h,t[f]))}return Yi(r),{p:n,f:o}}wNAFUnsafe(e,t,r,n=this.ZERO){let o=Ln(e,this.bits);for(let i=0;i<o.windows&&r!==Jt;i++){let{nextN:a,offset:c,isZero:f,isNeg:m}=Xi(r,i,o);if(r=a,!f){let h=t[c];n=n.add(m?h.negate():h)}}return Yi(r),n}getPrecomputes(e,t,r){let n=Rn.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(n=r(n)),Rn.set(t,n))),n}cached(e,t,r){let n=Cn(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){let o=Cn(e);return o===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,n)}createCache(e,t){Qi(t,this.bits),ea.set(e,t),Rn.delete(e)}hasCache(e){return Cn(e)!==1}};function ta(s,e,t,r){let n=e,o=s.ZERO,i=s.ZERO;for(;t>Jt||r>Jt;)t&kt&&(o=o.add(n)),r&kt&&(i=i.add(n)),n=n.double(),t>>=kt,r>>=kt;return{p1:o,p2:i}}function es(s,e,t,r){cu(t,s),lu(r,e);let n=t.length,o=r.length;if(n!==o)throw new Error("arrays of points and scalars must have equal length");let i=s.ZERO,a=nr(BigInt(n)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let f=wt(c),m=new Array(Number(f)+1).fill(i),h=Math.floor((e.BITS-1)/c)*c,d=i;for(let l=h;l>=0;l-=c){m.fill(i);for(let p=0;p<o;p++){let g=r[p],b=Number(g>>BigInt(l)&f);m[b]=m[b].add(t[p])}let u=i;for(let p=m.length-1,g=i;p>0;p--)g=g.add(m[p]),u=u.add(g);if(d=d.add(u),l!==0)for(let p=0;p<c;p++)d=d.double()}return d}function Ji(s,e,t){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Mn(e),e}else return Me(s,{isLE:t})}function ir(s,e,t={},r){if(r===void 0&&(r=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(let c of["p","n","h"]){let f=e[c];if(!(typeof f=="bigint"&&f>Jt))throw new Error(`CURVE.${c} must be positive bigint`)}let n=Ji(e.p,t.Fp,r),o=Ji(e.n,t.Fn,r),a=["Gx","Gy","a",s==="weierstrass"?"b":"d"];for(let c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:o}}var vt=BigInt(0),oe=BigInt(1),Nn=BigInt(2),uu=BigInt(8);function hu(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 fu(s,e={}){let t=ir("edwards",s,e,e.FpFnLE),{Fp:r,Fn:n}=t,o=t.CURVE,{h:i}=o;xt(e,{},{uvRatio:"function"});let a=Nn<<BigInt(n.BYTES*8)-oe,c=g=>r.create(g),f=e.uvRatio||((g,b)=>{try{return{isValid:!0,value:r.sqrt(r.div(g,b))}}catch{return{isValid:!1,value:vt}}});if(!hu(r,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function m(g,b,E=!1){let w=E?oe:vt;return Ps("coordinate "+g,b,w,a),b}function h(g){if(!(g instanceof u))throw new Error("ExtendedPoint expected")}let d=Yt((g,b)=>{let{X:E,Y:w,Z:T}=g,_=g.is0();b==null&&(b=_?uu:r.inv(T));let D=c(E*b),A=c(w*b),M=r.mul(T,b);if(_)return{x:vt,y:oe};if(M!==oe)throw new Error("invZ was invalid");return{x:D,y:A}}),l=Yt(g=>{let{a:b,d:E}=o;if(g.is0())throw new Error("bad point: ZERO");let{X:w,Y:T,Z:_,T:D}=g,A=c(w*w),M=c(T*T),y=c(_*_),P=c(y*y),N=c(A*b),R=c(y*c(N+M)),S=c(P+c(E*c(A*M)));if(R!==S)throw new Error("bad point: equation left != right (1)");let x=c(w*T),v=c(_*D);if(x!==v)throw new Error("bad point: equation left != right (2)");return!0});class u{constructor(b,E,w,T){this.X=m("x",b),this.Y=m("y",E),this.Z=m("z",w,!0),this.T=m("t",T),Object.freeze(this)}static CURVE(){return o}static fromAffine(b){if(b instanceof u)throw new Error("extended point not allowed");let{x:E,y:w}=b||{};return m("x",E),m("y",w),new u(E,w,oe,c(E*w))}static fromBytes(b,E=!1){let w=r.BYTES,{a:T,d:_}=o;b=An(De(b,w,"point")),tt(E,"zip215");let D=An(b),A=b[w-1];D[w-1]=A&-129;let M=st(D),y=E?a:r.ORDER;Ps("point.y",M,vt,y);let P=c(M*M),N=c(P-oe),R=c(_*P-T),{isValid:S,value:x}=f(N,R);if(!S)throw new Error("bad point: invalid y coordinate");let v=(x&oe)===oe,I=(A&128)!==0;if(!E&&x===vt&&I)throw new Error("bad point: x=0 and x_0=1");return I!==v&&(x=c(-x)),u.fromAffine({x,y:M})}static fromHex(b,E=!1){return u.fromBytes(q("point",b),E)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,E=!0){return p.createCache(this,b),E||this.multiply(Nn),this}assertValidity(){l(this)}equals(b){h(b);let{X:E,Y:w,Z:T}=this,{X:_,Y:D,Z:A}=b,M=c(E*A),y=c(_*T),P=c(w*A),N=c(D*T);return M===y&&P===N}is0(){return this.equals(u.ZERO)}negate(){return new u(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:b}=o,{X:E,Y:w,Z:T}=this,_=c(E*E),D=c(w*w),A=c(Nn*c(T*T)),M=c(b*_),y=E+w,P=c(c(y*y)-_-D),N=M+D,R=N-A,S=M-D,x=c(P*R),v=c(N*S),I=c(P*S),B=c(R*N);return new u(x,v,B,I)}add(b){h(b);let{a:E,d:w}=o,{X:T,Y:_,Z:D,T:A}=this,{X:M,Y:y,Z:P,T:N}=b,R=c(T*M),S=c(_*y),x=c(A*w*N),v=c(D*P),I=c((T+_)*(M+y)-R-S),B=v-x,C=v+x,k=c(S-E*R),L=c(I*B),U=c(C*k),O=c(I*k),Z=c(B*C);return new u(L,U,Z,O)}subtract(b){return this.add(b.negate())}multiply(b){if(!n.isValidNot0(b))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:E,f:w}=p.cached(this,b,T=>nt(u,T));return nt(u,[E,w])[0]}multiplyUnsafe(b,E=u.ZERO){if(!n.isValid(b))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return b===vt?u.ZERO:this.is0()||b===oe?this:p.unsafe(this,b,w=>nt(u,w),E)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return p.unsafe(this,o.n).is0()}toAffine(b){return d(this,b)}clearCofactor(){return i===oe?this:this.multiplyUnsafe(i)}toBytes(){let{x:b,y:E}=this.toAffine(),w=r.toBytes(E);return w[w.length-1]|=b&oe?128:0,w}toHex(){return Le(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(b){return nt(u,b)}static msm(b,E){return es(u,n,b,E)}_setWindowSize(b){this.precompute(b)}toRawBytes(){return this.toBytes()}}u.BASE=new u(o.Gx,o.Gy,oe,c(o.Gx*o.Gy)),u.ZERO=new u(vt,oe,oe,vt),u.Fp=r,u.Fn=n;let p=new Qt(u,n.BITS);return u.BASE.precompute(8),u}var ar=class{constructor(e){this.ep=e}static fromBytes(e){Pn()}static fromHex(e){Pn()}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 Le(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.init(this.ep.precompute(e,t))}toRawBytes(){return this.toBytes()}};function du(s,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');xt(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:r}=t,{BASE:n,Fp:o,Fn:i}=s,a=t.randomBytes||mt,c=t.adjustScalarBytes||(y=>y),f=t.domain||((y,P,N)=>{if(tt(N,"phflag"),P.length||N)throw new Error("Contexts/pre-hash are not supported");return y});function m(y){return i.create(st(y))}function h(y){let P=w.secretKey;y=q("private key",y,P);let N=q("hashed private key",e(y),2*P),R=c(N.slice(0,P)),S=N.slice(P,2*P),x=m(R);return{head:R,prefix:S,scalar:x}}function d(y){let{head:P,prefix:N,scalar:R}=h(y),S=n.multiply(R),x=S.toBytes();return{head:P,prefix:N,scalar:R,point:S,pointBytes:x}}function l(y){return d(y).pointBytes}function u(y=Uint8Array.of(),...P){let N=me(...P);return m(e(f(N,q("context",y),!!r)))}function p(y,P,N={}){y=q("message",y),r&&(y=r(y));let{prefix:R,scalar:S,pointBytes:x}=d(P),v=u(N.context,R,y),I=n.multiply(v).toBytes(),B=u(N.context,I,x,y),C=i.create(v+B*S);if(!i.isValid(C))throw new Error("sign failed: invalid s");let k=me(I,i.toBytes(C));return De(k,w.signature,"result")}let g={zip215:!0};function b(y,P,N,R=g){let{context:S,zip215:x}=R,v=w.signature;y=q("signature",y,v),P=q("message",P),N=q("publicKey",N,w.publicKey),x!==void 0&&tt(x,"zip215"),r&&(P=r(P));let I=v/2,B=y.subarray(0,I),C=st(y.subarray(I,v)),k,L,U;try{k=s.fromBytes(N,x),L=s.fromBytes(B,x),U=n.multiplyUnsafe(C)}catch{return!1}if(!x&&k.isSmallOrder())return!1;let O=u(S,L.toBytes(),k.toBytes(),P);return L.add(k.multiplyUnsafe(O)).subtract(U).clearCofactor().is0()}let E=o.BYTES,w={secretKey:E,publicKey:E,signature:2*E,seed:E};function T(y=a(w.seed)){return De(y,w.seed,"seed")}function _(y){let P=M.randomSecretKey(y);return{secretKey:P,publicKey:l(P)}}function D(y){return Je(y)&&y.length===i.BYTES}function A(y,P){try{return!!s.fromBytes(y,P)}catch{return!1}}let M={getExtendedPublicKey:d,randomSecretKey:T,isValidSecretKey:D,isValidPublicKey:A,toMontgomery(y){let{y:P}=s.fromBytes(y),N=w.publicKey,R=N===32;if(!R&&N!==57)throw new Error("only defined for 25519 and 448");let S=R?o.div(oe+P,oe-P):o.div(P-oe,P+oe);return o.toBytes(S)},toMontgomerySecret(y){let P=w.secretKey;De(y,P);let N=e(y.subarray(0,P));return c(N).subarray(0,P)},randomPrivateKey:T,precompute(y=8,P=s.BASE){return P.precompute(y,!1)}};return Object.freeze({keygen:_,getPublicKey:l,sign:p,verify:b,utils:M,Point:s,lengths:w})}function pu(s){let e={a:s.a,d:s.d,p:s.Fp.ORDER,n:s.n,h:s.h,Gx:s.Gx,Gy:s.Gy},t=s.Fp,r=Me(e.n,s.nBitLength,!0),n={Fp:t,Fn:r,uvRatio:s.uvRatio},o={randomBytes:s.randomBytes,adjustScalarBytes:s.adjustScalarBytes,domain:s.domain,prehash:s.prehash,mapToCurve:s.mapToCurve};return{CURVE:e,curveOpts:n,hash:s.hash,eddsaOpts:o}}function mu(s,e){let t=e.Point;return Object.assign({},e,{ExtendedPoint:t,CURVE:s,nBitLength:t.Fn.BITS,nByteLength:t.Fn.BYTES})}function sa(s){let{CURVE:e,curveOpts:t,hash:r,eddsaOpts:n}=pu(s),o=fu(e,t),i=du(o,r,n);return mu(s,i)}var gu=BigInt(0),ot=BigInt(1),ra=BigInt(2),qp=BigInt(3),bu=BigInt(5),yu=BigInt(8),ts=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Bs={p:ts,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:yu,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function wu(s){let e=BigInt(10),t=BigInt(20),r=BigInt(40),n=BigInt(80),o=ts,a=s*s%o*s%o,c=j(a,ra,o)*a%o,f=j(c,ot,o)*s%o,m=j(f,bu,o)*f%o,h=j(m,e,o)*m%o,d=j(h,t,o)*h%o,l=j(d,r,o)*d%o,u=j(l,n,o)*l%o,p=j(u,n,o)*l%o,g=j(p,e,o)*m%o;return{pow_p_5_8:j(g,ra,o)*s%o,b2:a}}function xu(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}var Un=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Fn(s,e){let t=ts,r=ee(e*e*e,t),n=ee(r*r*e,t),o=wu(s*n).pow_p_5_8,i=ee(s*r*o,t),a=ee(e*i*i,t),c=i,f=ee(i*Un,t),m=a===s,h=a===ee(-s,t),d=a===ee(-s*Un,t);return m&&(i=c),(h||d)&&(i=f),rt(i,t)&&(i=ee(-i,t)),{isValid:m||h,value:i}}var Et=Me(Bs.p,{isLE:!0}),vu=Me(Bs.n,{isLE:!0}),Eu={...Bs,Fp:Et,hash:Ci,adjustScalarBytes:xu,uvRatio:Fn},it=sa(Eu);var On=Un,Su=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),_u=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Iu=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Tu=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),na=s=>Fn(ot,s),Au=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Kn=s=>it.Point.Fp.create(st(s)&Au);function oa(s){let{d:e}=Bs,t=ts,r=b=>Et.create(b),n=r(On*s*s),o=r((n+ot)*Iu),i=BigInt(-1),a=r((i-e*n)*r(n+e)),{isValid:c,value:f}=Fn(o,a),m=r(f*s);rt(m,t)||(m=r(-m)),c||(f=m),c||(i=n);let h=r(i*(n-ot)*Tu-a),d=f*f,l=r((f+f)*a),u=r(h*Su),p=r(ot-d),g=r(ot+d);return new it.Point(r(l*g),r(p*u),r(u*g),r(l*p))}function Pu(s){Ae(s,64);let e=Kn(s.subarray(0,32)),t=oa(e),r=Kn(s.subarray(32,64)),n=oa(r);return new at(t.add(n))}var at=class s extends ar{constructor(e){super(e)}static fromAffine(e){return new s(it.Point.fromAffine(e))}assertSame(e){if(!(e instanceof s))throw new Error("RistrettoPoint expected")}init(e){return new s(e)}static hashToCurve(e){return Pu(q("ristrettoHash",e,64))}static fromBytes(e){Ae(e,32);let{a:t,d:r}=Bs,n=ts,o=T=>Et.create(T),i=Kn(e);if(!Ui(Et.toBytes(i),e)||rt(i,n))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),c=o(ot+t*a),f=o(ot-t*a),m=o(c*c),h=o(f*f),d=o(t*r*m-h),{isValid:l,value:u}=na(o(d*h)),p=o(u*f),g=o(u*p*d),b=o((i+i)*p);rt(b,n)&&(b=o(-b));let E=o(c*g),w=o(b*E);if(!l||rt(w,n)||E===gu)throw new Error("invalid ristretto255 encoding 2");return new s(new it.Point(b,E,ot,w))}static fromHex(e){return s.fromBytes(q("ristrettoHex",e,32))}static msm(e,t){return es(s,it.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:r,T:n}=this.ep,o=ts,i=g=>Et.create(g),a=i(i(r+t)*i(r-t)),c=i(e*t),f=i(c*c),{value:m}=na(i(a*f)),h=i(m*a),d=i(m*c),l=i(h*d*n),u;if(rt(n*l,o)){let g=i(t*On),b=i(e*On);e=g,t=b,u=i(h*_u)}else u=d;rt(e*l,o)&&(t=i(-t));let p=i((r-t)*u);return rt(p,o)&&(p=i(-p)),Et.toBytes(p)}equals(e){this.assertSame(e);let{X:t,Y:r}=this.ep,{X:n,Y:o}=e.ep,i=f=>Et.create(f),a=i(t*o)===i(r*n),c=i(r*o)===i(t*n);return a||c}is0(){return this.equals(s.ZERO)}};at.BASE=new at(it.Point.BASE);at.ZERO=new at(it.Point.ZERO);at.Fp=Et;at.Fn=vu;var ks=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},cr=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var ia={get(s=globalThis){let e=s.crypto;if(e?.subtle==null)throw new cr("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 Re=ia;var lr=32;var Hn,Du=(async()=>{try{return await Re.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Mu(s,e,t){if(s.buffer instanceof ArrayBuffer){let r=await Re.get().subtle.importKey("raw",s.buffer,{name:"Ed25519"},!1,["verify"]);return await Re.get().subtle.verify({name:"Ed25519"},r,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Bu(s,e,t){return it.verify(e,t instanceof Uint8Array?t:t.subarray(),s)}async function aa(s,e,t){return Hn==null&&(Hn=await Du),Hn?Mu(s,e,t):Bu(s,e,t)}function ur(s){return s==null?!1:typeof s.then=="function"&&typeof s.catch=="function"&&typeof s.finally=="function"}var hr=class{type="Ed25519";raw;constructor(e){this.raw=Gn(e,lr)}toMultihash(){return Ne.digest(qe(this))}toCID(){return ie.createV1(114,this.toMultihash())}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();let n=aa(this.raw,t,e);return ur(n)?n.then(o=>(r?.signal?.throwIfAborted(),o)):n}};function qn(s){return s=Gn(s,lr),new hr(s)}function Gn(s,e){if(s=Uint8Array.from(s??[]),s.length!==e)throw new W(`Key must be a Uint8Array of length ${e}, got ${s.length}`);return s}var Lu=Math.pow(2,7),Ru=Math.pow(2,14),Cu=Math.pow(2,21),zn=Math.pow(2,28),Vn=Math.pow(2,35),Wn=Math.pow(2,42),jn=Math.pow(2,49),H=128,ue=127;function Ce(s){if(s<Lu)return 1;if(s<Ru)return 2;if(s<Cu)return 3;if(s<zn)return 4;if(s<Vn)return 5;if(s<Wn)return 6;if(s<jn)return 7;if(Number.MAX_SAFE_INTEGER!=null&&s>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function $n(s,e,t=0){switch(Ce(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 Nu(s,e,t=0){switch(Ce(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 Zn(s,e){let t=s[e],r=0;if(r+=t&ue,t<H||(t=s[e+1],r+=(t&ue)<<7,t<H)||(t=s[e+2],r+=(t&ue)<<14,t<H)||(t=s[e+3],r+=(t&ue)<<21,t<H)||(t=s[e+4],r+=(t&ue)*zn,t<H)||(t=s[e+5],r+=(t&ue)*Vn,t<H)||(t=s[e+6],r+=(t&ue)*Wn,t<H)||(t=s[e+7],r+=(t&ue)*jn,t<H))return r;throw new RangeError("Could not decode varint")}function Uu(s,e){let t=s.get(e),r=0;if(r+=t&ue,t<H||(t=s.get(e+1),r+=(t&ue)<<7,t<H)||(t=s.get(e+2),r+=(t&ue)<<14,t<H)||(t=s.get(e+3),r+=(t&ue)<<21,t<H)||(t=s.get(e+4),r+=(t&ue)*zn,t<H)||(t=s.get(e+5),r+=(t&ue)*Vn,t<H)||(t=s.get(e+6),r+=(t&ue)*Wn,t<H)||(t=s.get(e+7),r+=(t&ue)*jn,t<H))return r;throw new RangeError("Could not decode varint")}function Xn(s,e,t=0){return e==null&&(e=le(Ce(s))),e instanceof Uint8Array?$n(s,e,t):Nu(s,e,t)}function Yn(s,e=0){return s instanceof Uint8Array?Zn(s,e):Uu(s,e)}var Qn=new Float32Array([-0]),St=new Uint8Array(Qn.buffer);function la(s,e,t){Qn[0]=s,e[t]=St[0],e[t+1]=St[1],e[t+2]=St[2],e[t+3]=St[3]}function ua(s,e){return St[0]=s[e],St[1]=s[e+1],St[2]=s[e+2],St[3]=s[e+3],Qn[0]}var eo=new Float64Array([-0]),he=new Uint8Array(eo.buffer);function ha(s,e,t){eo[0]=s,e[t]=he[0],e[t+1]=he[1],e[t+2]=he[2],e[t+3]=he[3],e[t+4]=he[4],e[t+5]=he[5],e[t+6]=he[6],e[t+7]=he[7]}function fa(s,e){return he[0]=s[e],he[1]=s[e+1],he[2]=s[e+2],he[3]=s[e+3],he[4]=s[e+4],he[5]=s[e+5],he[6]=s[e+6],he[7]=s[e+7],eo[0]}var Ou=BigInt(Number.MAX_SAFE_INTEGER),Ku=BigInt(Number.MIN_SAFE_INTEGER),Be=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 Lt;if(e<Ou&&e>Ku)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>da&&(n=0n,++r>da&&(r=0n))),new s(Number(n),Number(r))}static fromNumber(e){if(e===0)return Lt;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):Lt}},Lt=new Be(0,0);Lt.toBigInt=function(){return 0n};Lt.zzEncode=Lt.zzDecode=function(){return this};Lt.length=function(){return 1};var da=4294967296n;function pa(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 ma(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 to(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 fr(s,e){return(s[e-4]|s[e-3]<<8|s[e-2]<<16|s[e-1]<<24)>>>0}var so=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 fr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Oe(this,4);return fr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Oe(this,4);let e=ua(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Oe(this,4);let e=fa(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 ma(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 Be(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=fr(this.buf,this.pos+=4),t=fr(this.buf,this.pos+=4);return new Be(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=Zn(this.buf,this.pos);return this.pos+=Ce(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 ro(s){return new so(s instanceof Uint8Array?s:s.subarray())}function be(s,e,t){let r=ro(s);return e.decode(r,void 0,t)}function no(s){let e=s??8192,t=e>>>1,r,n=e;return function(i){if(i<1||i>t)return le(i);n+i>e&&(r=le(e),n=0);let a=r.subarray(n,n+=i);return(n&7)!==0&&(n=(n|7)+1),a}}var Rt=class{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}};function oo(){}var ao=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Fu=no();function Hu(s){return globalThis.Buffer!=null?le(s):Fu(s)}var Rs=class{len;head;tail;states;constructor(){this.len=0,this.head=new Rt(oo,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new Rt(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new co((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(dr,10,Be.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Be.fromBigInt(e);return this._push(dr,t.length(),t)}uint64Number(e){return this._push($n,Ce(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=Be.fromBigInt(e).zzEncode();return this._push(dr,t.length(),t)}sint64Number(e){let t=Be.fromNumber(e).zzEncode();return this._push(dr,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(io,1,e?1:0)}fixed32(e){return this._push(Ls,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Be.fromBigInt(e);return this._push(Ls,4,t.lo)._push(Ls,4,t.hi)}fixed64Number(e){let t=Be.fromNumber(e);return this._push(Ls,4,t.lo)._push(Ls,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(la,4,e)}double(e){return this._push(ha,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(io,1,0):this.uint32(t)._push(qu,t,e)}string(e){let t=pa(e);return t!==0?this.uint32(t)._push(to,t,e):this._push(io,1,0)}fork(){return this.states=new ao(this),this.head=this.tail=new Rt(oo,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 Rt(oo,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=Hu(this.len),r=0;for(;e!=null;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}};function io(s,e,t){e[t]=s&255}function Gu(s,e,t){for(;s>127;)e[t++]=s&127|128,s>>>=7;e[t]=s}var co=class extends Rt{next;constructor(e,t){super(Gu,e,t),this.next=void 0}};function dr(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 Ls(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 qu(s,e,t){e.set(s,t)}globalThis.Buffer!=null&&(Rs.prototype.bytes=function(s){let e=s.length>>>0;return this.uint32(e),e>0&&this._push(zu,e,s),this},Rs.prototype.string=function(s){let e=globalThis.Buffer.byteLength(s);return this.uint32(e),e>0&&this._push(Vu,e,s),this});function zu(s,e,t){e.set(s,t)}function Vu(s,e,t){s.length<40?to(s,e,t):e.utf8Write!=null?e.utf8Write(s,t):e.set(V(s),t)}function lo(){return new Rs}function ye(s,e){let t=lo();return e.encode(s,t,{lengthDelimited:!1}),t.finish()}var ss;(function(s){s[s.VARINT=0]="VARINT",s[s.BIT64=1]="BIT64",s[s.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",s[s.START_GROUP=3]="START_GROUP",s[s.END_GROUP=4]="END_GROUP",s[s.BIT32=5]="BIT32"})(ss||(ss={}));function pr(s,e,t,r){return{name:s,type:e,encode:t,decode:r}}function uo(s){function e(n){if(s[n.toString()]==null)throw new Error("Invalid enum value");return s[n]}let t=function(o,i){let a=e(o);i.int32(a)},r=function(o){let i=o.int32();return e(i)};return pr("enum",ss.VARINT,t,r)}function we(s,e){return pr("message",ss.LENGTH_DELIMITED,s,e)}var Pe=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var te;(function(s){s.RSA="RSA",s.Ed25519="Ed25519",s.secp256k1="secp256k1",s.ECDSA="ECDSA"})(te||(te={}));var ho;(function(s){s[s.RSA=0]="RSA",s[s.Ed25519=1]="Ed25519",s[s.secp256k1=2]="secp256k1",s[s.ECDSA=3]="ECDSA"})(ho||(ho={}));(function(s){s.codec=()=>uo(ho)})(te||(te={}));var Ve;(function(s){let e;s.codec=()=>(e==null&&(e=we((t,r,n={})=>{n.lengthDelimited!==!1&&r.fork(),t.Type!=null&&(r.uint32(8),te.codec().encode(t.Type,r)),t.Data!=null&&(r.uint32(18),r.bytes(t.Data)),n.lengthDelimited!==!1&&r.ldelim()},(t,r,n={})=>{let o={},i=r==null?t.len:t.pos+r;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=te.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),s.encode=t=>ye(t,s.codec()),s.decode=(t,r)=>be(t,s.codec(),r)})(Ve||(Ve={}));var fo;(function(s){let e;s.codec=()=>(e==null&&(e=we((t,r,n={})=>{n.lengthDelimited!==!1&&r.fork(),t.Type!=null&&(r.uint32(8),te.codec().encode(t.Type,r)),t.Data!=null&&(r.uint32(18),r.bytes(t.Data)),n.lengthDelimited!==!1&&r.ldelim()},(t,r,n={})=>{let o={},i=r==null?t.len:t.pos+r;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=te.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),s.encode=t=>ye(t,s.codec()),s.decode=(t,r)=>be(t,s.codec(),r)})(fo||(fo={}));function mr(s){if(isNaN(s)||s<=0)throw new W("random bytes length must be a Number bigger than 0");return mt(s)}var Ns={};_e(Ns,{MAX_RSA_KEY_SIZE:()=>po,generateRSAKeyPair:()=>va,jwkToJWKKeyPair:()=>Ea,jwkToPkcs1:()=>Zu,jwkToPkix:()=>yo,jwkToRSAPrivateKey:()=>Eo,pkcs1MessageToJwk:()=>go,pkcs1MessageToRSAPrivateKey:()=>wo,pkcs1ToJwk:()=>$u,pkcs1ToRSAPrivateKey:()=>xa,pkixMessageToJwk:()=>bo,pkixMessageToRSAPublicKey:()=>vo,pkixToJwk:()=>Xu,pkixToRSAPublicKey:()=>xo});var gr=sr;var rs=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Ns.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ie.createV1(114,this._multihash)}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}verify(e,t,r){return wa(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=Ns.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}sign(e,t){return ya(this.jwk,e,t)}};var po=8192,mo=18,Wu=1062,ju=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function $u(s){let e=Xe(s);return go(e)}function go(s){return{n:F(s[1],"base64url"),e:F(s[2],"base64url"),d:F(s[3],"base64url"),p:F(s[4],"base64url"),q:F(s[5],"base64url"),dp:F(s[6],"base64url"),dq:F(s[7],"base64url"),qi:F(s[8],"base64url"),kty:"RSA"}}function Zu(s){if(s.n==null||s.e==null||s.d==null||s.p==null||s.q==null||s.dp==null||s.dq==null||s.qi==null)throw new W("JWK was missing components");return pt([Te(Uint8Array.from([0])),Te(V(s.n,"base64url")),Te(V(s.e,"base64url")),Te(V(s.d,"base64url")),Te(V(s.p,"base64url")),Te(V(s.q,"base64url")),Te(V(s.dp,"base64url")),Te(V(s.dq,"base64url")),Te(V(s.qi,"base64url"))]).subarray()}function Xu(s){let e=Xe(s,{offset:0});return bo(e)}function bo(s){let e=Xe(s[1],{offset:0});return{kty:"RSA",n:F(e[0],"base64url"),e:F(e[1],"base64url")}}function yo(s){if(s.n==null||s.e==null)throw new W("JWK was missing components");return pt([ju,Ys(pt([Te(V(s.n,"base64url")),Te(V(s.e,"base64url"))]))]).subarray()}function xa(s){let e=Xe(s);return wo(e)}function wo(s){let e=go(s);return Eo(e)}function xo(s,e){if(s.byteLength>=Wu)throw new Ft("Key size is too large");let t=Xe(s,{offset:0});return vo(t,s,e)}function vo(s,e,t){let r=bo(s);if(t==null){let n=gr(Ve.encode({Type:te.RSA,Data:e}));t=He(mo,n)}return new rs(r,t)}function Eo(s){if(_a(s)>po)throw new W("Key size is too large");let e=Ea(s),t=gr(Ve.encode({Type:te.RSA,Data:yo(e.publicKey)})),r=He(mo,t);return new Cs(e.privateKey,new rs(e.publicKey,r))}async function va(s){if(s>po)throw new W("Key size is too large");let e=await Sa(s),t=gr(Ve.encode({Type:te.RSA,Data:yo(e.publicKey)})),r=He(mo,t);return new Cs(e.privateKey,new rs(e.publicKey,r))}function Ea(s){if(s==null)throw new W("Missing key parameter");return{privateKey:s,publicKey:{kty:s.kty,n:s.n,e:s.e}}}async function Sa(s,e){let t=await Re.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:s,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let r=await Yu(t,e);return{privateKey:r[0],publicKey:r[1]}}async function ya(s,e,t){let r=await Re.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let n=await Re.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(n,0,n.byteLength)}async function wa(s,e,t,r){let n=await Re.get().subtle.importKey("jwk",s,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();let o=await Re.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray());return r?.signal?.throwIfAborted(),o}async function Yu(s,e){if(s.privateKey==null||s.publicKey==null)throw new W("Private and public key are required");let t=await Promise.all([Re.get().subtle.exportKey("jwk",s.privateKey),Re.get().subtle.exportKey("jwk",s.publicKey)]);return e?.signal?.throwIfAborted(),t}function _a(s){if(s.kty!=="RSA")throw new W("invalid key type");if(s.n==null)throw new W("invalid key modulus");return V(s.n,"base64url").length*8}var br=class extends $t{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Js(e);let r=Ss(t);if(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 n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Qe(o)}update(e){return Zt(this),this.iHash.update(e),this}digestInto(e){Zt(this),Ae(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(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()}},So=(s,e,t)=>new br(s,e).update(t).digest();So.create=(s,e)=>new br(s,e);var Ia=(s,e)=>(s+(s>=0?e:-e)/Ta)/e;function Ju(s,e,t){let[[r,n],[o,i]]=e,a=Ia(i*s,t),c=Ia(-n*s,t),f=s-a*r-c*o,m=-a*n-c*i,h=f<lt,d=m<lt;h&&(f=-f),d&&(m=-m);let l=wt(Math.ceil(nr(t)/2))+os;if(f<lt||f>=l||m<lt||m>=l)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:h,k1:f,k2neg:d,k2:m}}function Io(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function _o(s,e){let t={};for(let r of Object.keys(e))t[r]=s[r]===void 0?e[r]:s[r];return tt(t.lowS,"lowS"),tt(t.prehash,"prehash"),t.format!==void 0&&Io(t.format),t}var To=class extends Error{constructor(e=""){super(e)}},ct={Err:To,_tlv:{encode:(s,e)=>{let{Err:t}=ct;if(s<0||s>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let r=e.length/2,n=As(r);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let o=r>127?As(n.length/2|128):"";return As(s)+o+n+e},decode(s,e){let{Err:t}=ct,r=0;if(s<0||s>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[r++]!==s)throw new t("tlv.decode: wrong tlv");let n=e[r++],o=!!(n&128),i=0;if(!o)i=n;else{let c=n&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let f=e.subarray(r,r+c);if(f.length!==c)throw new t("tlv.decode: length bytes not complete");if(f[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let m of f)i=i<<8|m;if(r+=c,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}=ct;if(s<lt)throw new e("integer: negative integers are not allowed");let t=As(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}=ct;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Xt(s)}},toSig(s){let{Err:e,_int:t,_tlv:r}=ct,n=q("signature",s),{v:o,l:i}=r.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=r.decode(2,o),{v:f,l:m}=r.decode(2,c);if(m.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(f)}},hexFromSig(s){let{_tlv:e,_int:t}=ct,r=e.encode(2,t.encode(s.r)),n=e.encode(2,t.encode(s.s)),o=r+n;return e.encode(48,o)}},lt=BigInt(0),os=BigInt(1),Ta=BigInt(2),yr=BigInt(3),Qu=BigInt(4);function ns(s,e){let{BYTES:t}=s,r;if(typeof e=="bigint")r=e;else{let n=q("private key",e);try{r=s.fromBytes(n)}catch{throw new Error(`invalid private key: expected ui8a of size ${t}, got ${typeof e}`)}}if(!s.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function eh(s,e={}){let t=ir("weierstrass",s,e),{Fp:r,Fn:n}=t,o=t.CURVE,{h:i,n:a}=o;xt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!r.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let f=Pa(r,n);function m(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(R,S,x){let{x:v,y:I}=S.toAffine(),B=r.toBytes(v);if(tt(x,"isCompressed"),x){m();let C=!r.isOdd(I);return me(Aa(C),B)}else return me(Uint8Array.of(4),B,r.toBytes(I))}function d(R){De(R,void 0,"Point");let{publicKey:S,publicKeyUncompressed:x}=f,v=R.length,I=R[0],B=R.subarray(1);if(v===S&&(I===2||I===3)){let C=r.fromBytes(B);if(!r.isValid(C))throw new Error("bad point: is not on curve, wrong x");let k=p(C),L;try{L=r.sqrt(k)}catch(Z){let z=Z instanceof Error?": "+Z.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}m();let U=r.isOdd(L);return(I&1)===1!==U&&(L=r.neg(L)),{x:C,y:L}}else if(v===x&&I===4){let C=r.BYTES,k=r.fromBytes(B.subarray(0,C)),L=r.fromBytes(B.subarray(C,C*2));if(!g(k,L))throw new Error("bad point: is not on curve");return{x:k,y:L}}else throw new Error(`bad point: got length ${v}, expected compressed=${S} or uncompressed=${x}`)}let l=e.toBytes||h,u=e.fromBytes||d;function p(R){let S=r.sqr(R),x=r.mul(S,R);return r.add(r.add(x,r.mul(R,o.a)),o.b)}function g(R,S){let x=r.sqr(S),v=p(R);return r.eql(x,v)}if(!g(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let b=r.mul(r.pow(o.a,yr),Qu),E=r.mul(r.sqr(o.b),BigInt(27));if(r.is0(r.add(b,E)))throw new Error("bad curve params: a or b");function w(R,S,x=!1){if(!r.isValid(S)||x&&r.is0(S))throw new Error(`bad point coordinate ${R}`);return S}function T(R){if(!(R instanceof y))throw new Error("ProjectivePoint expected")}function _(R){if(!c||!c.basises)throw new Error("no endo");return Ju(R,c.basises,n.ORDER)}let D=Yt((R,S)=>{let{X:x,Y:v,Z:I}=R;if(r.eql(I,r.ONE))return{x,y:v};let B=R.is0();S==null&&(S=B?r.ONE:r.inv(I));let C=r.mul(x,S),k=r.mul(v,S),L=r.mul(I,S);if(B)return{x:r.ZERO,y:r.ZERO};if(!r.eql(L,r.ONE))throw new Error("invZ was invalid");return{x:C,y:k}}),A=Yt(R=>{if(R.is0()){if(e.allowInfinityPoint&&!r.is0(R.Y))return;throw new Error("bad point: ZERO")}let{x:S,y:x}=R.toAffine();if(!r.isValid(S)||!r.isValid(x))throw new Error("bad point: x or y not field elements");if(!g(S,x))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function M(R,S,x,v,I){return x=new y(r.mul(x.X,R),x.Y,x.Z),S=Ms(v,S),x=Ms(I,x),S.add(x)}class y{constructor(S,x,v){this.X=w("x",S),this.Y=w("y",x,!0),this.Z=w("z",v),Object.freeze(this)}static CURVE(){return o}static fromAffine(S){let{x,y:v}=S||{};if(!S||!r.isValid(x)||!r.isValid(v))throw new Error("invalid affine point");if(S instanceof y)throw new Error("projective point not allowed");return r.is0(x)&&r.is0(v)?y.ZERO:new y(x,v,r.ONE)}static fromBytes(S){let x=y.fromAffine(u(De(S,void 0,"point")));return x.assertValidity(),x}static fromHex(S){return y.fromBytes(q("pointHex",S))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(S=8,x=!0){return N.createCache(this,S),x||this.multiply(yr),this}assertValidity(){A(this)}hasEvenY(){let{y:S}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(S)}equals(S){T(S);let{X:x,Y:v,Z:I}=this,{X:B,Y:C,Z:k}=S,L=r.eql(r.mul(x,k),r.mul(B,I)),U=r.eql(r.mul(v,k),r.mul(C,I));return L&&U}negate(){return new y(this.X,r.neg(this.Y),this.Z)}double(){let{a:S,b:x}=o,v=r.mul(x,yr),{X:I,Y:B,Z:C}=this,k=r.ZERO,L=r.ZERO,U=r.ZERO,O=r.mul(I,I),Z=r.mul(B,B),z=r.mul(C,C),K=r.mul(I,B);return K=r.add(K,K),U=r.mul(I,C),U=r.add(U,U),k=r.mul(S,U),L=r.mul(v,z),L=r.add(k,L),k=r.sub(Z,L),L=r.add(Z,L),L=r.mul(k,L),k=r.mul(K,k),U=r.mul(v,U),z=r.mul(S,z),K=r.sub(O,z),K=r.mul(S,K),K=r.add(K,U),U=r.add(O,O),O=r.add(U,O),O=r.add(O,z),O=r.mul(O,K),L=r.add(L,O),z=r.mul(B,C),z=r.add(z,z),O=r.mul(z,K),k=r.sub(k,O),U=r.mul(z,Z),U=r.add(U,U),U=r.add(U,U),new y(k,L,U)}add(S){T(S);let{X:x,Y:v,Z:I}=this,{X:B,Y:C,Z:k}=S,L=r.ZERO,U=r.ZERO,O=r.ZERO,Z=o.a,z=r.mul(o.b,yr),K=r.mul(x,B),X=r.mul(v,C),se=r.mul(I,k),Se=r.add(x,v),Y=r.add(B,C);Se=r.mul(Se,Y),Y=r.add(K,X),Se=r.sub(Se,Y),Y=r.add(x,I);let ce=r.add(B,k);return Y=r.mul(Y,ce),ce=r.add(K,se),Y=r.sub(Y,ce),ce=r.add(v,I),L=r.add(C,k),ce=r.mul(ce,L),L=r.add(X,se),ce=r.sub(ce,L),O=r.mul(Z,Y),L=r.mul(z,se),O=r.add(L,O),L=r.sub(X,O),O=r.add(X,O),U=r.mul(L,O),X=r.add(K,K),X=r.add(X,K),se=r.mul(Z,se),Y=r.mul(z,Y),X=r.add(X,se),se=r.sub(K,se),se=r.mul(Z,se),Y=r.add(Y,se),K=r.mul(X,Y),U=r.add(U,K),K=r.mul(ce,Y),L=r.mul(Se,L),L=r.sub(L,K),K=r.mul(Se,X),O=r.mul(ce,O),O=r.add(O,K),new y(L,U,O)}subtract(S){return this.add(S.negate())}is0(){return this.equals(y.ZERO)}multiply(S){let{endo:x}=e;if(!n.isValidNot0(S))throw new Error("invalid scalar: out of range");let v,I,B=C=>N.cached(this,C,k=>nt(y,k));if(x){let{k1neg:C,k1:k,k2neg:L,k2:U}=_(S),{p:O,f:Z}=B(k),{p:z,f:K}=B(U);I=Z.add(K),v=M(x.beta,O,z,C,L)}else{let{p:C,f:k}=B(S);v=C,I=k}return nt(y,[v,I])[0]}multiplyUnsafe(S){let{endo:x}=e,v=this;if(!n.isValid(S))throw new Error("invalid scalar: out of range");if(S===lt||v.is0())return y.ZERO;if(S===os)return v;if(N.hasCache(this))return this.multiply(S);if(x){let{k1neg:I,k1:B,k2neg:C,k2:k}=_(S),{p1:L,p2:U}=ta(y,v,B,k);return M(x.beta,L,U,I,C)}else return N.unsafe(v,S)}multiplyAndAddUnsafe(S,x,v){let I=this.multiplyUnsafe(x).add(S.multiplyUnsafe(v));return I.is0()?void 0:I}toAffine(S){return D(this,S)}isTorsionFree(){let{isTorsionFree:S}=e;return i===os?!0:S?S(y,this):N.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:S}=e;return i===os?this:S?S(y,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(S=!0){return tt(S,"isCompressed"),this.assertValidity(),l(y,this,S)}toHex(S=!0){return Le(this.toBytes(S))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(S=!0){return this.toBytes(S)}_setWindowSize(S){this.precompute(S)}static normalizeZ(S){return nt(y,S)}static msm(S,x){return es(y,n,S,x)}static fromPrivateKey(S){return y.BASE.multiply(ns(n,S))}}y.BASE=new y(o.Gx,o.Gy,r.ONE),y.ZERO=new y(r.ZERO,r.ONE,r.ZERO),y.Fp=r,y.Fn=n;let P=n.BITS,N=new Qt(y,e.endo?Math.ceil(P/2):P);return y.BASE.precompute(8),y}function Aa(s){return Uint8Array.of(s?2:3)}function Pa(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function th(s,e={}){let{Fn:t}=s,r=e.randomBytes||mt,n=Object.assign(Pa(s.Fp,t),{seed:Bn(t.ORDER)});function o(l){try{return!!ns(t,l)}catch{return!1}}function i(l,u){let{publicKey:p,publicKeyUncompressed:g}=n;try{let b=l.length;return u===!0&&b!==p||u===!1&&b!==g?!1:!!s.fromBytes(l)}catch{return!1}}function a(l=r(n.seed)){return kn(De(l,n.seed,"seed"),t.ORDER)}function c(l,u=!0){return s.BASE.multiply(ns(t,l)).toBytes(u)}function f(l){let u=a(l);return{secretKey:u,publicKey:c(u)}}function m(l){if(typeof l=="bigint")return!1;if(l instanceof s)return!0;let{secretKey:u,publicKey:p,publicKeyUncompressed:g}=n;if(t.allowedLengths||u===p)return;let b=q("key",l).length;return b===p||b===g}function h(l,u,p=!0){if(m(l)===!0)throw new Error("first arg must be private key");if(m(u)===!1)throw new Error("second arg must be public key");let g=ns(t,l);return s.fromHex(u).multiply(g).toBytes(p)}return Object.freeze({getPublicKey:c,getSharedSecret:h,keygen:f,Point:s,utils:{isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:o,randomPrivateKey:a,normPrivateKeyToScalar:l=>ns(t,l),precompute(l=8,u=s.BASE){return u.precompute(l,!1)}},lengths:n})}function sh(s,e,t={}){Js(e),xt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=t.randomBytes||mt,n=t.hmac||((x,...v)=>So(e,x,me(...v))),{Fp:o,Fn:i}=s,{ORDER:a,BITS:c}=i,{keygen:f,getPublicKey:m,getSharedSecret:h,utils:d,lengths:l}=th(s,t),u={prehash:!1,lowS:typeof t.lowS=="boolean"?t.lowS:!1,format:void 0,extraEntropy:!1},p="compact";function g(x){let v=a>>os;return x>v}function b(x,v){if(!i.isValidNot0(v))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return v}function E(x,v){Io(v);let I=l.signature,B=v==="compact"?I:v==="recovered"?I+1:void 0;return De(x,B,`${v} signature`)}class w{constructor(v,I,B){this.r=b("r",v),this.s=b("s",I),B!=null&&(this.recovery=B),Object.freeze(this)}static fromBytes(v,I=p){E(v,I);let B;if(I==="der"){let{r:U,s:O}=ct.toSig(De(v));return new w(U,O)}I==="recovered"&&(B=v[0],I="compact",v=v.subarray(1));let C=i.BYTES,k=v.subarray(0,C),L=v.subarray(C,C*2);return new w(i.fromBytes(k),i.fromBytes(L),B)}static fromHex(v,I){return this.fromBytes(Pt(v),I)}addRecoveryBit(v){return new w(this.r,this.s,v)}recoverPublicKey(v){let I=o.ORDER,{r:B,s:C,recovery:k}=this;if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");if(a*Ta<I&&k>1)throw new Error("recovery id is ambiguous for h>1 curve");let U=k===2||k===3?B+a:B;if(!o.isValid(U))throw new Error("recovery id 2 or 3 invalid");let O=o.toBytes(U),Z=s.fromBytes(me(Aa((k&1)===0),O)),z=i.inv(U),K=_(q("msgHash",v)),X=i.create(-K*z),se=i.create(C*z),Se=s.BASE.multiplyUnsafe(X).add(Z.multiplyUnsafe(se));if(Se.is0())throw new Error("point at infinify");return Se.assertValidity(),Se}hasHighS(){return g(this.s)}toBytes(v=p){if(Io(v),v==="der")return Pt(ct.hexFromSig(this));let I=i.toBytes(this.r),B=i.toBytes(this.s);if(v==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return me(Uint8Array.of(this.recovery),I,B)}return me(I,B)}toHex(v){return Le(this.toBytes(v))}assertValidity(){}static fromCompact(v){return w.fromBytes(q("sig",v),"compact")}static fromDER(v){return w.fromBytes(q("sig",v),"der")}normalizeS(){return this.hasHighS()?new w(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Le(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Le(this.toBytes("compact"))}}let T=t.bits2int||function(v){if(v.length>8192)throw new Error("input is too large");let I=Xt(v),B=v.length*8-c;return B>0?I>>BigInt(B):I},_=t.bits2int_modN||function(v){return i.create(T(v))},D=wt(c);function A(x){return Ps("num < 2^"+c,x,lt,D),i.toBytes(x)}function M(x,v){return De(x,void 0,"message"),v?De(e(x),void 0,"prehashed message"):x}function y(x,v,I){if(["recovered","canonical"].some(X=>X in I))throw new Error("sign() legacy options not supported");let{lowS:B,prehash:C,extraEntropy:k}=_o(I,u);x=M(x,C);let L=_(x),U=ns(i,v),O=[A(U),A(L)];if(k!=null&&k!==!1){let X=k===!0?r(l.secretKey):k;O.push(q("extraEntropy",X))}let Z=me(...O),z=L;function K(X){let se=T(X);if(!i.isValidNot0(se))return;let Se=i.inv(se),Y=s.BASE.multiply(se).toAffine(),ce=i.create(Y.x);if(ce===lt)return;let qs=i.create(Se*i.create(z+ce*U));if(qs===lt)return;let Ko=(Y.x===ce?0:2)|Number(Y.y&os),Fo=qs;return B&&g(qs)&&(Fo=i.neg(qs),Ko^=1),new w(ce,Fo,Ko)}return{seed:Z,k2sig:K}}function P(x,v,I={}){x=q("message",x);let{seed:B,k2sig:C}=y(x,v,I);return Ki(e.outputLen,i.BYTES,n)(B,C)}function N(x){let v,I=typeof x=="string"||Je(x),B=!I&&x!==null&&typeof x=="object"&&typeof x.r=="bigint"&&typeof x.s=="bigint";if(!I&&!B)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(B)v=new w(x.r,x.s);else if(I){try{v=w.fromBytes(q("sig",x),"der")}catch(C){if(!(C instanceof ct.Err))throw C}if(!v)try{v=w.fromBytes(q("sig",x),"compact")}catch{return!1}}return v||!1}function R(x,v,I,B={}){let{lowS:C,prehash:k,format:L}=_o(B,u);if(I=q("publicKey",I),v=M(q("message",v),k),"strict"in B)throw new Error("options.strict was renamed to lowS");let U=L===void 0?N(x):w.fromBytes(q("sig",x),L);if(U===!1)return!1;try{let O=s.fromBytes(I);if(C&&U.hasHighS())return!1;let{r:Z,s:z}=U,K=_(v),X=i.inv(z),se=i.create(K*X),Se=i.create(Z*X),Y=s.BASE.multiplyUnsafe(se).add(O.multiplyUnsafe(Se));return Y.is0()?!1:i.create(Y.x)===Z}catch{return!1}}function S(x,v,I={}){let{prehash:B}=_o(I,u);return v=M(v,B),w.fromBytes(x,"recovered").recoverPublicKey(v).toBytes()}return Object.freeze({keygen:f,getPublicKey:m,getSharedSecret:h,utils:d,lengths:l,Point:s,sign:P,verify:R,recoverPublicKey:S,Signature:w,hash:e})}function rh(s){let e={a:s.a,b:s.b,p:s.Fp.ORDER,n:s.n,h:s.h,Gx:s.Gx,Gy:s.Gy},t=s.Fp,r=s.allowedPrivateKeyLengths?Array.from(new Set(s.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,n=Me(e.n,{BITS:s.nBitLength,allowedLengths:r,modFromBytes:s.wrapPrivateKey}),o={Fp:t,Fn:n,allowInfinityPoint:s.allowInfinityPoint,endo:s.endo,isTorsionFree:s.isTorsionFree,clearCofactor:s.clearCofactor,fromBytes:s.fromBytes,toBytes:s.toBytes};return{CURVE:e,curveOpts:o}}function nh(s){let{CURVE:e,curveOpts:t}=rh(s),r={hmac:s.hmac,randomBytes:s.randomBytes,lowS:s.lowS,bits2int:s.bits2int,bits2int_modN:s.bits2int_modN};return{CURVE:e,curveOpts:t,hash:s.hash,ecdsaOpts:r}}function oh(s,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},s,or(t.Fn.ORDER,t.Fn.BITS))})}function Da(s){let{CURVE:e,curveOpts:t,hash:r,ecdsaOpts:n}=nh(s),o=eh(e,t),i=sh(o,r,n);return oh(s,i)}function Ma(s,e){let t=r=>Da({...s,hash:r});return{...t(e),create:t}}var Po={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},ih={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Ba=BigInt(2);function ah(s){let e=Po.p,t=BigInt(3),r=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=s*s*s%e,m=f*f*s%e,h=j(m,t,e)*m%e,d=j(h,t,e)*m%e,l=j(d,Ba,e)*f%e,u=j(l,n,e)*l%e,p=j(u,o,e)*u%e,g=j(p,a,e)*p%e,b=j(g,c,e)*g%e,E=j(b,a,e)*p%e,w=j(E,t,e)*m%e,T=j(w,i,e)*u%e,_=j(T,r,e)*f%e,D=j(_,Ba,e);if(!Ao.eql(Ao.sqr(D),s))throw new Error("Cannot find square root");return D}var Ao=Me(Po.p,{sqrt:ah}),is=Ma({...Po,Fp:Ao,lowS:!0,endo:ih},sr);function ka(s,e,t,r){let n=dt.digest(t instanceof Uint8Array?t:t.subarray());if(ur(n))return n.then(({digest:o})=>(r?.signal?.throwIfAborted(),is.verify(e,o,s))).catch(o=>{throw o.name==="AbortError"?o:new ks(String(o))});try{return r?.signal?.throwIfAborted(),is.verify(e,n.digest,s)}catch(o){throw new ks(String(o))}}var wr=class{type="secp256k1";raw;_key;constructor(e){this._key=Ra(e),this.raw=La(this._key)}toMultihash(){return Ne.digest(qe(this))}toCID(){return ie.createV1(114,this.toMultihash())}toString(){return Q.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ie(this.raw,e.raw)}verify(e,t,r){return ka(this._key,t,e,r)}};function Do(s){return new wr(s)}function La(s){return is.ProjectivePoint.fromHex(s).toRawBytes(!0)}function Ra(s){try{return is.ProjectivePoint.fromHex(s),s}catch(e){throw new Ft(String(e))}}function Us(s,e){let{Type:t,Data:r}=Ve.decode(s),n=r??new Uint8Array;switch(t){case te.RSA:return xo(n,e);case te.Ed25519:return qn(n);case te.secp256k1:return Do(n);case te.ECDSA:return bn(n);default:throw new Ht}}function Ca(s){let{Type:e,Data:t}=Ve.decode(s.digest),r=t??new Uint8Array;switch(e){case te.Ed25519:return qn(r);case te.secp256k1:return Do(r);case te.ECDSA:return bn(r);default:throw new Ht}}function qe(s){return Ve.encode({Type:te[s.type],Data:s.raw})}var Na=Symbol.for("nodejs.util.inspect.custom"),ch=114,Os=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()})`}[Gr]=!0;toString(){return this.string==null&&(this.string=Q.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ie.createV1(ch,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Ie(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Ie(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Na](){return`PeerId(${this.toString()})`}},xr=class extends Os{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},vr=class extends Os{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Er=class extends Os{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},lh=2336,Ks=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ne.digest(V(this.url))}[Na](){return`PeerId(${this.url})`}[Gr]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ie.createV1(lh,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=F(e)),e.toString()===this.toString())}};var uh=114,Ua=2336;function Ct(s,e){let t;if(s.charAt(0)==="1"||s.charAt(0)==="Q")t=Ge(Q.decode(`z${s}`));else{if(s.startsWith("k51qzi5uqu5")||s.startsWith("kzwfwjn5ji4")||s.startsWith("k2k4r8")||s.startsWith("bafz"))return hh(ie.parse(s));if(e==null)throw new W('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ge(e.decode(s))}return as(t)}function as(s){if(dh(s))return new xr({multihash:s});if(fh(s))try{let e=Ca(s);if(e.type==="Ed25519")return new vr({multihash:s,publicKey:e});if(e.type==="secp256k1")return new Er({multihash:s,publicKey:e})}catch{let t=F(s.digest);return new Ks(new URL(t))}throw new Ws("Supplied PeerID Multihash is invalid")}function hh(s){if(s?.multihash==null||s.version==null||s.version===1&&s.code!==uh&&s.code!==Ua)throw new Vs("Supplied PeerID CID is invalid");if(s.code===Ua){let e=F(s.multihash.digest);return new Ks(new URL(e))}return as(s.multihash)}function fh(s){return s.code===Ne.code}function dh(s){return s.code===dt.code}var Sr=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},cs=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},_r=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Fs=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Ir(s){return s[Symbol.asyncIterator]!=null}function Oa(s,e){if(s.byteLength>e)throw new cs("Message length too long")}var Ar=s=>{let e=Ce(s),t=le(e);return Xn(s,t),Ar.bytes=e,t};Ar.bytes=0;function ls(s,e){e=e??{};let t=e.lengthEncoder??Ar,r=e?.maxDataLength??4194304;function*n(o){Oa(o,r);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return Ir(s)?(async function*(){for await(let o of s)yield*n(o)})():(function*(){for(let o of s)yield*n(o)})()}ls.single=(s,e)=>{e=e??{};let t=e.lengthEncoder??Ar,r=e?.maxDataLength??4194304;return Oa(s,r),new re(t(s.byteLength),s)};var Nt;(function(s){s[s.LENGTH=0]="LENGTH",s[s.DATA=1]="DATA"})(Nt||(Nt={}));var Mo=s=>{let e=Yn(s);return Mo.bytes=Ce(e),e};Mo.bytes=0;function Hs(s,e){let t=new re,r=Nt.LENGTH,n=-1,o=e?.lengthDecoder??Mo,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(r===Nt.LENGTH)try{if(n=o(t),n<0)throw new Sr("Invalid message length");if(n>a)throw new cs("Message length too long");let f=o.bytes;t.consume(f),e?.onLength!=null&&e.onLength(n),r=Nt.DATA}catch(f){if(f instanceof RangeError){if(t.byteLength>i)throw new _r("Message length length too long");break}throw f}if(r===Nt.DATA){if(t.byteLength<n)break;let f=t.sublist(0,n);t.consume(n),e?.onData!=null&&e.onData(f),yield f,r=Nt.LENGTH}}}return Ir(s)?(async function*(){for await(let f of s)t.append(f),yield*c();if(t.byteLength>0)throw new Fs("Unexpected end of input")})():(function*(){for(let f of s)t.append(f),yield*c();if(t.byteLength>0)throw new Fs("Unexpected end of input")})()}Hs.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 Hs(r,{...e??{},onLength:o=>{t=o}})};function ut(){let s={};return s.promise=new Promise((e,t)=>{s.resolve=e,s.reject=t}),s}var Pr=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},us=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Pr(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 Pr(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 Bo=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ut(s={}){return mh(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 mh(s,e){e=e??{};let t=e.onEnd,r=new us,n,o,i,a=ut(),c=async()=>{try{return r.isEmpty()?i?{done:!0}:await new Promise((g,b)=>{o=E=>{o=null,r.push(E);try{g(s(r))}catch(w){b(w)}return n}}):s(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ut()})}},f=g=>o!=null?o(g):(r.push(g),n),m=g=>(r=new us,o!=null?o({error:g}):(r.push({error:g}),n)),h=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 f({done:!1,value:g})},d=g=>i?n:(i=!0,g!=null?m(g):f({done:!0})),l=()=>(r=new us,d(),{done:!0}),u=g=>(d(g),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:c,return:l,throw:u,push:h,end:d,get readableLength(){return r.size},onEmpty:async g=>{let b=g?.signal;if(b?.throwIfAborted(),r.isEmpty())return;let E,w;b!=null&&(E=new Promise((T,_)=>{w=()=>{_(new Bo)},b.addEventListener("abort",w)}));try{await Promise.race([a.promise,E])}finally{w!=null&&b!=null&&b?.removeEventListener("abort",w)}}},t==null)return n;let p=n;return n={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(g){return p.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return p.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(g){return p.end(g),t!=null&&(t(g),t=void 0),n},get readableLength(){return p.readableLength},onEmpty:g=>p.onEmpty(g)},n}var Dr=class extends Error{type;code;constructor(e,t,r){super(e??"The operation was aborted"),this.type="aborted",this.name=r??"AbortError",this.code=t??"ABORT_ERR"}};async function Ka(s,e,t){if(e==null)return s;if(e.aborted)return s.catch(()=>{}),Promise.reject(new Dr(t?.errorMessage,t?.errorCode,t?.errorName));let r,n=new Dr(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([s,new Promise((o,i)=>{r=()=>{i(n)},e.addEventListener("abort",r)})])}finally{r!=null&&e.removeEventListener("abort",r)}}var ko=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ut(),this.haveNext=ut()}[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=ut(),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=ut(),await Ka(this.readNext.promise,t?.signal,t)}};function Fa(){return new ko}function gh(s){return s[Symbol.asyncIterator]!=null}async function bh(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*yh(s){let e=new AbortController,t=Fa();bh(s,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*wh(s){for(let e of s)yield*e}function xh(...s){let e=[];for(let t of s)gh(t)||e.push(t);return e.length===s.length?wh(e):yh(s)}var Ha=xh;function Gs(s,...e){if(s==null)throw new Error("Empty pipeline");if(Lo(s)){let r=s;s=()=>r.source}else if(qa(s)||Ga(s)){let r=s;s=()=>r}let t=[s,...e];if(t.length>1&&Lo(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++)Lo(t[r])&&(t[r]=Eh(t[r]));return vh(...t)}var vh=(...s)=>{let e;for(;s.length>0;)e=s.shift()(e);return e},Ga=s=>s?.[Symbol.asyncIterator]!=null,qa=s=>s?.[Symbol.iterator]!=null,Lo=s=>s==null?!1:s.sink!=null&&s.source!=null,Eh=s=>e=>{let t=s.sink(e);if(t?.then!=null){let r=Ut({objectMode:!0});t.then(()=>{r.end()},i=>{r.end(i)});let n,o=s.source;if(Ga(o))n=async function*(){yield*o,r.end()};else if(qa(o))n=function*(){yield*o,r.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Ha(r,n())}return s.source};var za={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxIdontwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};var ht;(function(s){let e;(function(h){let d;h.codec=()=>(d==null&&(d=we((l,u,p={})=>{p.lengthDelimited!==!1&&u.fork(),l.subscribe!=null&&(u.uint32(8),u.bool(l.subscribe)),l.topic!=null&&(u.uint32(18),u.string(l.topic)),p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let g={},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let E=l.uint32();switch(E>>>3){case 1:{g.subscribe=l.bool();break}case 2:{g.topic=l.string();break}default:{l.skipType(E&7);break}}}return g})),d),h.encode=l=>ye(l,h.codec()),h.decode=(l,u)=>be(l,h.codec(),u)})(e=s.SubOpts||(s.SubOpts={}));let t;(function(h){let d;h.codec=()=>(d==null&&(d=we((l,u,p={})=>{p.lengthDelimited!==!1&&u.fork(),l.from!=null&&(u.uint32(10),u.bytes(l.from)),l.data!=null&&(u.uint32(18),u.bytes(l.data)),l.seqno!=null&&(u.uint32(26),u.bytes(l.seqno)),l.topic!=null&&l.topic!==""&&(u.uint32(34),u.string(l.topic)),l.signature!=null&&(u.uint32(42),u.bytes(l.signature)),l.key!=null&&(u.uint32(50),u.bytes(l.key)),p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let g={topic:""},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let E=l.uint32();switch(E>>>3){case 1:{g.from=l.bytes();break}case 2:{g.data=l.bytes();break}case 3:{g.seqno=l.bytes();break}case 4:{g.topic=l.string();break}case 5:{g.signature=l.bytes();break}case 6:{g.key=l.bytes();break}default:{l.skipType(E&7);break}}}return g})),d),h.encode=l=>ye(l,h.codec()),h.decode=(l,u)=>be(l,h.codec(),u)})(t=s.Message||(s.Message={}));let r;(function(h){let d;h.codec=()=>(d==null&&(d=we((l,u,p={})=>{if(p.lengthDelimited!==!1&&u.fork(),l.ihave!=null)for(let g of l.ihave)u.uint32(10),s.ControlIHave.codec().encode(g,u);if(l.iwant!=null)for(let g of l.iwant)u.uint32(18),s.ControlIWant.codec().encode(g,u);if(l.graft!=null)for(let g of l.graft)u.uint32(26),s.ControlGraft.codec().encode(g,u);if(l.prune!=null)for(let g of l.prune)u.uint32(34),s.ControlPrune.codec().encode(g,u);if(l.idontwant!=null)for(let g of l.idontwant)u.uint32(42),s.ControlIDontWant.codec().encode(g,u);p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let g={ihave:[],iwant:[],graft:[],prune:[],idontwant:[]},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let E=l.uint32();switch(E>>>3){case 1:{if(p.limits?.ihave!=null&&g.ihave.length===p.limits.ihave)throw new Pe('Decode error - map field "ihave" had too many elements');g.ihave.push(s.ControlIHave.codec().decode(l,l.uint32(),{limits:p.limits?.ihave$}));break}case 2:{if(p.limits?.iwant!=null&&g.iwant.length===p.limits.iwant)throw new Pe('Decode error - map field "iwant" had too many elements');g.iwant.push(s.ControlIWant.codec().decode(l,l.uint32(),{limits:p.limits?.iwant$}));break}case 3:{if(p.limits?.graft!=null&&g.graft.length===p.limits.graft)throw new Pe('Decode error - map field "graft" had too many elements');g.graft.push(s.ControlGraft.codec().decode(l,l.uint32(),{limits:p.limits?.graft$}));break}case 4:{if(p.limits?.prune!=null&&g.prune.length===p.limits.prune)throw new Pe('Decode error - map field "prune" had too many elements');g.prune.push(s.ControlPrune.codec().decode(l,l.uint32(),{limits:p.limits?.prune$}));break}case 5:{if(p.limits?.idontwant!=null&&g.idontwant.length===p.limits.idontwant)throw new Pe('Decode error - map field "idontwant" had too many elements');g.idontwant.push(s.ControlIDontWant.codec().decode(l,l.uint32(),{limits:p.limits?.idontwant$}));break}default:{l.skipType(E&7);break}}}return g})),d),h.encode=l=>ye(l,h.codec()),h.decode=(l,u)=>be(l,h.codec(),u)})(r=s.ControlMessage||(s.ControlMessage={}));let n;(function(h){let d;h.codec=()=>(d==null&&(d=we((l,u,p={})=>{if(p.lengthDelimited!==!1&&u.fork(),l.topicID!=null&&(u.uint32(10),u.string(l.topicID)),l.messageIDs!=null)for(let g of l.messageIDs)u.uint32(18),u.bytes(g);p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let g={messageIDs:[]},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let E=l.uint32();switch(E>>>3){case 1:{g.topicID=l.string();break}case 2:{if(p.limits?.messageIDs!=null&&g.messageIDs.length===p.limits.messageIDs)throw new Pe('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(l.bytes());break}default:{l.skipType(E&7);break}}}return g})),d),h.encode=l=>ye(l,h.codec()),h.decode=(l,u)=>be(l,h.codec(),u)})(n=s.ControlIHave||(s.ControlIHave={}));let o;(function(h){let d;h.codec=()=>(d==null&&(d=we((l,u,p={})=>{if(p.lengthDelimited!==!1&&u.fork(),l.messageIDs!=null)for(let g of l.messageIDs)u.uint32(10),u.bytes(g);p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let g={messageIDs:[]},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let E=l.uint32();switch(E>>>3){case 1:{if(p.limits?.messageIDs!=null&&g.messageIDs.length===p.limits.messageIDs)throw new Pe('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(l.bytes());break}default:{l.skipType(E&7);break}}}return g})),d),h.encode=l=>ye(l,h.codec()),h.decode=(l,u)=>be(l,h.codec(),u)})(o=s.ControlIWant||(s.ControlIWant={}));let i;(function(h){let d;h.codec=()=>(d==null&&(d=we((l,u,p={})=>{p.lengthDelimited!==!1&&u.fork(),l.topicID!=null&&(u.uint32(10),u.string(l.topicID)),p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let g={},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let E=l.uint32();switch(E>>>3){case 1:{g.topicID=l.string();break}default:{l.skipType(E&7);break}}}return g})),d),h.encode=l=>ye(l,h.codec()),h.decode=(l,u)=>be(l,h.codec(),u)})(i=s.ControlGraft||(s.ControlGraft={}));let a;(function(h){let d;h.codec=()=>(d==null&&(d=we((l,u,p={})=>{if(p.lengthDelimited!==!1&&u.fork(),l.topicID!=null&&(u.uint32(10),u.string(l.topicID)),l.peers!=null)for(let g of l.peers)u.uint32(18),s.PeerInfo.codec().encode(g,u);l.backoff!=null&&(u.uint32(24),u.uint64Number(l.backoff)),p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let g={peers:[]},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let E=l.uint32();switch(E>>>3){case 1:{g.topicID=l.string();break}case 2:{if(p.limits?.peers!=null&&g.peers.length===p.limits.peers)throw new Pe('Decode error - map field "peers" had too many elements');g.peers.push(s.PeerInfo.codec().decode(l,l.uint32(),{limits:p.limits?.peers$}));break}case 3:{g.backoff=l.uint64Number();break}default:{l.skipType(E&7);break}}}return g})),d),h.encode=l=>ye(l,h.codec()),h.decode=(l,u)=>be(l,h.codec(),u)})(a=s.ControlPrune||(s.ControlPrune={}));let c;(function(h){let d;h.codec=()=>(d==null&&(d=we((l,u,p={})=>{p.lengthDelimited!==!1&&u.fork(),l.peerID!=null&&(u.uint32(10),u.bytes(l.peerID)),l.signedPeerRecord!=null&&(u.uint32(18),u.bytes(l.signedPeerRecord)),p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let g={},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let E=l.uint32();switch(E>>>3){case 1:{g.peerID=l.bytes();break}case 2:{g.signedPeerRecord=l.bytes();break}default:{l.skipType(E&7);break}}}return g})),d),h.encode=l=>ye(l,h.codec()),h.decode=(l,u)=>be(l,h.codec(),u)})(c=s.PeerInfo||(s.PeerInfo={}));let f;(function(h){let d;h.codec=()=>(d==null&&(d=we((l,u,p={})=>{if(p.lengthDelimited!==!1&&u.fork(),l.messageIDs!=null)for(let g of l.messageIDs)u.uint32(10),u.bytes(g);p.lengthDelimited!==!1&&u.ldelim()},(l,u,p={})=>{let g={messageIDs:[]},b=u==null?l.len:l.pos+u;for(;l.pos<b;){let E=l.uint32();switch(E>>>3){case 1:{if(p.limits?.messageIDs!=null&&g.messageIDs.length===p.limits.messageIDs)throw new Pe('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(l.bytes());break}default:{l.skipType(E&7);break}}}return g})),d),h.encode=l=>ye(l,h.codec()),h.decode=(l,u)=>be(l,h.codec(),u)})(f=s.ControlIDontWant||(s.ControlIDontWant={}));let m;s.codec=()=>(m==null&&(m=we((h,d,l={})=>{if(l.lengthDelimited!==!1&&d.fork(),h.subscriptions!=null)for(let u of h.subscriptions)d.uint32(10),s.SubOpts.codec().encode(u,d);if(h.messages!=null)for(let u of h.messages)d.uint32(18),s.Message.codec().encode(u,d);h.control!=null&&(d.uint32(26),s.ControlMessage.codec().encode(h.control,d)),l.lengthDelimited!==!1&&d.ldelim()},(h,d,l={})=>{let u={subscriptions:[],messages:[]},p=d==null?h.len:h.pos+d;for(;h.pos<p;){let g=h.uint32();switch(g>>>3){case 1:{if(l.limits?.subscriptions!=null&&u.subscriptions.length===l.limits.subscriptions)throw new Pe('Decode error - map field "subscriptions" had too many elements');u.subscriptions.push(s.SubOpts.codec().decode(h,h.uint32(),{limits:l.limits?.subscriptions$}));break}case 2:{if(l.limits?.messages!=null&&u.messages.length===l.limits.messages)throw new Pe('Decode error - map field "messages" had too many elements');u.messages.push(s.Message.codec().decode(h,h.uint32(),{limits:l.limits?.messages$}));break}case 3:{u.control=s.ControlMessage.codec().decode(h,h.uint32(),{limits:l.limits?.control});break}default:{h.skipType(g&7);break}}}return u})),m),s.encode=h=>ye(h,s.codec()),s.decode=(h,d)=>be(h,s.codec(),d)})(ht||(ht={}));var Mr=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 Va;(function(s){s.StrictSign="StrictSign",s.StrictNoSign="StrictNoSign"})(Va||(Va={}));var _t;(function(s){s[s.Signing=0]="Signing",s[s.Anonymous=1]="Anonymous"})(_t||(_t={}));var xe;(function(s){s.Error="error",s.Ignore="ignore",s.Reject="reject",s.Blacklisted="blacklisted"})(xe||(xe={}));var fe;(function(s){s.InvalidSignature="invalid_signature",s.InvalidSeqno="invalid_seqno",s.InvalidPeerId="invalid_peerid",s.SignaturePresent="signature_present",s.SeqnoPresent="seqno_present",s.FromPresent="from_present",s.TransformFailed="transform_failed"})(fe||(fe={}));var de;(function(s){s.duplicate="duplicate",s.invalid="invalid",s.valid="valid"})(de||(de={}));function Ro(s){switch(s){case pe.Ignore:return xe.Ignore;case pe.Reject:return xe.Reject;default:throw new Error("Unreachable")}}var Wa;(function(s){s.forward="forward",s.publish="publish"})(Wa||(Wa={}));var ve;(function(s){s.Fanout="fanout",s.Random="random",s.Subscribed="subscribed",s.Outbound="outbound",s.NotEnough="not_enough",s.Opportunistic="opportunistic"})(ve||(ve={}));var Ke;(function(s){s.Dc="disconnected",s.BadScore="bad_score",s.Prune="prune",s.Excess="excess"})(Ke||(Ke={}));var fs;(function(s){s.GraftBackoff="graft_backoff",s.BrokenPromise="broken_promise",s.MessageDeficit="message_deficit",s.IPColocation="IP_colocation"})(fs||(fs={}));var ds;(function(s){s.LowScore="low_score",s.MaxIhave="max_ihave",s.MaxIasked="max_iasked"})(ds||(ds={}));var hs;(function(s){s.graylist="graylist",s.publish="publish",s.gossip="gossip",s.mesh="mesh"})(hs||(hs={}));function ja(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 ve.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:i},o);break;case ve.Random:this.meshPeerInclusionEventsRandom.inc({topic:i},o);break;case ve.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:i},o);break;case ve.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:i},o);break;case ve.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:i},o);break;case ve.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 pe.Accept:this.acceptedMessagesTotal.inc({topic:i});break;case pe.Ignore:this.ignoredMessagesTotal.inc({topic:i});break;case pe.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 c=this.toTopic(r);this.msgPublishCount.inc({topic:c},1),this.msgPublishBytes.inc({topic:c},o*i),this.msgPublishPeersByTopic.inc({topic:c},o),this.directPeersPublishedTotal.inc({topic:c},n.direct),this.floodsubPeersPublishedTotal.inc({topic:c},n.floodsub),this.meshPeersPublishedTotal.inc({topic:c},n.mesh),this.fanoutPeersPublishedTotal.inc({topic:c},n.fanout),this.msgPublishTime.observe({topic:c},a/1e3)},onMsgRecvPreValidation(r){let n=this.toTopic(r);this.msgReceivedPreValidation.inc({topic:n},1)},onMsgRecvError(r){let n=this.toTopic(r);this.msgReceivedError.inc({topic:n},1)},onPrevalidationResult(r,n){let o=this.toTopic(r);switch(n){case de.duplicate:this.prevalidationDuplicateTotal.inc({topic:o});break;case de.invalid:this.prevalidationInvalidTotal.inc({topic:o});break;case de.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===xe.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,c=r.control.prune?.length??0,f=r.control.idontwant?.length??0;o>0&&this.rpcSentIHave.inc(o),i>0&&this.rpcSentIWant.inc(i),a>0&&this.rpcSentGraft.inc(a),c>0&&this.rpcSentPrune.inc(c),f>0&&this.rpcSentIDontWant.inc(f),(o>0||i>0||a>0||c>0||f>0)&&this.rpcSentControl.inc(1)}},registerScores(r,n){let o=0,i=0,a=0,c=0;for(let f of r)f>=n.graylistThreshold&&o++,f>=n.publishThreshold&&i++,f>=n.gossipThreshold&&a++,f>=0&&c++;this.peersByScoreThreshold.set({threshold:hs.graylist},o),this.peersByScoreThreshold.set({threshold:hs.publish},i),this.peersByScoreThreshold.set({threshold:hs.gossip},a),this.peersByScoreThreshold.set({threshold:hs.mesh},c),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 c=this.topicStrToLabel.get(a)??"unknown",f=o.get(c);f==null&&(f=new Set,o.set(c,f)),i.forEach(m=>f?.add(m))});for(let[i,a]of o){let c=[];a.forEach(f=>{c.push(n.get(f)??0)}),this.scorePerMesh.set({topic:i},c)}}}}var G=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var Sh={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},_h={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 $a(s={}){return{...Sh,...s,topics:s.topics!=null?Object.entries(s.topics).reduce((e,[t,r])=>(e[t]=Ih(r),e),{}):{}}}function Ih(s={}){return{..._h,...s}}function Za(s){for(let[e,t]of Object.entries(s.topics))try{Th(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 Th(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 Ah={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function Xa(s={}){return{...Ah,...s}}function kr(s,e,t=()=>!0){let r=new Set;if(e<=0)return r;for(let n of s){if(r.size>=e)break;t(n)&&(r.add(n),s.delete(n))}return r}function Ya(s,e){return kr(s,e,()=>!0)}var Br=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 Ja(s,e,t,r){let n=0;Object.entries(e.topics).forEach(([i,a])=>{let c=t.topics[i];if(c===void 0)return;let f=0;if(a.inMesh){let l=a.meshTime/c.timeInMeshQuantum;l>c.timeInMeshCap&&(l=c.timeInMeshCap),f+=l*c.timeInMeshWeight}let m=a.firstMessageDeliveries;if(m>c.firstMessageDeliveriesCap&&(m=c.firstMessageDeliveriesCap),f+=m*c.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries<c.meshMessageDeliveriesThreshold){let l=c.meshMessageDeliveriesThreshold-a.meshMessageDeliveries,u=l*l;f+=u*c.meshMessageDeliveriesWeight}let h=a.meshFailurePenalty;f+=h*c.meshFailurePenaltyWeight;let d=a.invalidMessageDeliveries*a.invalidMessageDeliveries;f+=d*c.invalidMessageDeliveriesWeight,n+=f*c.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),c=a!=null?a.size:0;if(c>t.IPColocationFactorThreshold){let f=c-t.IPColocationFactorThreshold,m=f*f;n+=m*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let i=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=i*i;n+=a*t.behaviourPenaltyWeight}return n}var tc=_c(ec(),1);var Ee;(function(s){s[s.unknown=0]="unknown",s[s.valid=1]="valid",s[s.invalid=2]="invalid",s[s.ignored=3]="ignored"})(Ee||(Ee={}));var Lr=class{records;queue;constructor(){this.records=new Map,this.queue=new tc.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:Ee.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 Rr=class{params;metrics;peerStats=new Map;peerIPs=new Br(()=>new Set);scoreCache=new Map;deliveryRecords=new Lr;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,r,n){this.params=e,this.metrics=t,Za(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??Ja,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!==Ee.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,o-n.firstSeenTsMs,Ee[n.status]);return}n.status=Ee.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 xe.Error:this.markInvalidMessageDelivery(e,r);return;case xe.Blacklisted:return}let o=this.deliveryRecords.ensureRecord(t);if(o.status!==Ee.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-o.firstSeenTsMs,Ee[o.status]);return}if(n===xe.Ignore){o.status=Ee.ignored,o.peers.clear();return}o.status=Ee.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 Ee.unknown:n.peers.add(e);break;case Ee.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,r,n.validated);break;case Ee.invalid:this.markInvalidMessageDelivery(e,r);break;case Ee.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 f=o-r,m=f>a.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,f,m),m)return}let c=a.meshMessageDeliveriesCap;i.meshMessageDeliveries=Math.min(c,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 Ph(s,e,t,r,n){let o=0,i=new Map;if(Object.entries(e.topics).forEach(([d,l])=>{let u=n.get(d)??"unknown",p=t.topics[d];if(p===void 0)return;let g=i.get(u);g==null&&(g={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},i.set(u,g));let b=0,E=0,w=0,T=0,_=0;if(l.inMesh){let y=Math.max(l.meshTime/p.timeInMeshQuantum,p.timeInMeshCap);b+=y*p.timeInMeshWeight}let D=l.firstMessageDeliveries;if(D>p.firstMessageDeliveriesCap&&(D=p.firstMessageDeliveriesCap),E+=D*p.firstMessageDeliveriesWeight,l.meshMessageDeliveriesActive&&l.meshMessageDeliveries<p.meshMessageDeliveriesThreshold){let y=p.meshMessageDeliveriesThreshold-l.meshMessageDeliveries,P=y*y;w+=P*p.meshMessageDeliveriesWeight}let A=l.meshFailurePenalty;T+=A*p.meshFailurePenaltyWeight;let M=l.invalidMessageDeliveries*l.invalidMessageDeliveries;_+=M*p.invalidMessageDeliveriesWeight,o+=(b+E+w+T+_)*p.topicWeight,g.p1w+=b,g.p2w+=E,g.p3w+=w,g.p3bw+=T,g.p4w+=_}),t.topicScoreCap>0&&o>t.topicScoreCap){o=t.topicScoreCap;let d=t.topicScoreCap/o;for(let l of i.values())l.p1w*=d,l.p2w*=d,l.p3w*=d,l.p3bw*=d,l.p4w*=d}let a=0,c=0,f=0,m=t.appSpecificScore(s);a+=m*t.appSpecificWeight,e.knownIPs.forEach(d=>{if(t.IPColocationFactorWhitelist.has(d))return;let l=r.get(d),u=l!=null?l.size:0;if(u>t.IPColocationFactorThreshold){let p=u-t.IPColocationFactorThreshold,g=p*p;c+=g*t.IPColocationFactorWeight}});let h=e.behaviourPenalty*e.behaviourPenalty;return f+=h*t.behaviourPenaltyWeight,o+=a+c+f,{byTopic:i,p5w:a,p6w:c,p7w:f,score:o}}function sc(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 c=Ph(i,a,t,r,n);for(let[f,m]of c.byTopic){let h=o.byTopic.get(f);h==null&&(h={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},o.byTopic.set(f,h)),h.p1w.push(m.p1w),h.p2w.push(m.p2w),h.p3w.push(m.p3w),h.p3bw.push(m.p3bw),h.p4w.push(m.p4w)}o.p5w.push(c.p5w),o.p6w.push(c.p6w),o.p7w.push(c.p7w),o.score.push(c.score)}else o.p5w.push(0),o.p6w.push(0),o.p7w.push(0),o.score.push(0)}return o}function Cr(s){let e=s.getComponents(),t={},r=0;if(e[r]?.name==="ip6zone"&&(t.zone=`${e[r].value}`,r++),e[r].name==="ip4"||e[r].name==="ip6"||e[r].name==="dns"||e[r].name==="dns4"||e[r].name==="dns6"?(t.type=e[r].name,t.host=e[r].value,r++):e[r].name==="dnsaddr"&&(t.type=e[r].name,t.host=`_dnsaddr.${e[r].value}`,r++),(e[r]?.name==="tcp"||e[r]?.name==="udp")&&(t.protocol=e[r].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[r].value}`),r++),e[r]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[r].value}`):t.type==="ip6"&&(t.cidr=`${e[r].value}`),r++),t.type==null||t.host==null)throw new W(`Multiaddr ${s} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[r]?.name==="tls"&&e[r+1]?.name==="sni"&&(t.sni=e[r+1].value,r+=2),t}function rc(s){try{return Cr(s),!0}catch{return!1}}var Co=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},No=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},nc=s=>globalThis.DOMException===void 0?new No(s):new DOMException(s),oc=s=>{let e=s.reason===void 0?nc("This operation was aborted."):s.reason;return e instanceof Error?e:nc(e)};function Uo(s,e){let{milliseconds:t,fallback:r,message:n,customTimers:o={setTimeout,clearTimeout}}=e,i,a,f=new Promise((m,h)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:l}=e;l.aborted&&h(oc(l)),a=()=>{h(oc(l))},l.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){s.then(m,h);return}let d=new Co;i=o.setTimeout.call(void 0,()=>{if(r){try{m(r())}catch(l){h(l)}return}typeof s.cancel=="function"&&s.cancel(),n===!1?m():n instanceof Error?h(n):(d.message=n??`Promise timed out after ${t} milliseconds`,h(d))},t),(async()=>{try{m(await s)}catch(l){h(l)}})()}).finally(()=>{f.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return f.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},f}var Dh=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 Mh(s,e,t){let r,n=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:f,removeListener:m}=Dh(s),h=(...l)=>{let u=t.multiArgs?l:l[0];t.filter&&!t.filter(u)||(c.push(u),t.count===c.length&&(r(),o(c)))},d=l=>{r(),i(l)};r=()=>{for(let l of a)m(l,h);for(let l of t.rejectionEvents)m(l,d)};for(let l of a)f(l,h);for(let l of t.rejectionEvents)f(l,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(n.cancel=r,typeof t.timeout=="number"){let o=Uo(n,{milliseconds:t.timeout});return o.cancel=r,o}return n}function ic(s,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let r=Mh(s,e,t),n=r.then(o=>o[0]);return n.cancel=r.cancel,n}function Bh(s){return s?.addEventListener!=null}function kh(s){let e=Ut(),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 c=a();for(;;){t=Promise.withResolvers();let{done:f,value:m}=await Promise.race([c.next(),t.promise]);if(s.writeStatus==="closing"||s.writeStatus==="closed"||(m!=null&&(s.send(m)||await Promise.race([ic(s,"drain",{rejectionEvents:["close"]})])),f===!0))break}await s.close()}}}function ac(...s){let e=s.map(t=>Bh(t)?kh(t):t);return Gs(...e)}var Nr=class{rawStream;constructor(e,t,r){this.rawStream=e,r.maxBufferSize!=null&&(e.maxWriteBufferLength=r.maxBufferSize),e.addEventListener("close",n=>{n.error!=null&&t(n.error)})}get protocol(){return this.rawStream.protocol}async push(e){return this.pushPrefixed(ls.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=ac(this.rawStream,r=>Hs(r,t))}async close(){this.closeController.abort()}};var Or=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){switch(this.trackMessage(e),t){case xe.Error:return;default:break}this.promises.delete(e)}clear(){this.promises.clear()}prune(){let e=Date.now()-this.requestMsByMsgExpire,t=0;for(let[r,n]of this.requestMsByMsg.entries())if(n<e)this.requestMsByMsg.delete(r),t++;else break;this.metrics?.iwantMessagePruned.inc(t)}trackMessage(e){if(this.metrics!=null){let t=this.requestMsByMsg.get(e);t!==void 0&&(this.metrics.iwantPromiseDeliveryTime.observe((Date.now()-t)/1e3),this.requestMsByMsg.delete(e))}}};var cc=V("libp2p-pubsub:");async function lc(s,e,t,r){switch(s.type){case _t.Signing:{let n={from:s.author.toMultihash().bytes,data:r,seqno:mr(8),topic:e,signature:void 0,key:void 0},o=Tt([cc,ht.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${F(n.seqno??new Uint8Array(0),"base16")}`),topic:e,signature:n.signature,key:Us(n.key)};return{raw:n,msg:i}}case _t.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 uc(s,e){switch(s){case Ot:return e.signature!=null?{valid:!1,error:fe.SignaturePresent}:e.seqno!=null?{valid:!1,error:fe.SeqnoPresent}:e.key!=null?{valid:!1,error:fe.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case It:{if(e.seqno==null)return{valid:!1,error:fe.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:fe.InvalidSeqno};if(e.signature==null)return{valid:!1,error:fe.InvalidSignature};if(e.from==null)return{valid:!1,error:fe.InvalidPeerId};let t;try{t=as(Ge(e.from))}catch{return{valid:!1,error:fe.InvalidPeerId}}let r;if(e.key!=null){if(r=Us(e.key),t.publicKey!==void 0&&!r.equals(t.publicKey))return{valid:!1,error:fe.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:fe.InvalidPeerId};r=t.publicKey}let n={from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0},o=Tt([cc,ht.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${F(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:e.key!=null?Us(e.key):r}}:{valid:!1,error:fe.InvalidSignature}}default:throw new Error("Unreachable")}}function Fe(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 Oo(s){return s.control===void 0&&(s.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),s}function We(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 hc(s){return F(s,"base64")}function fc(s,e,t){switch(s){case It:return{type:_t.Signing,author:e,key:qe(t.publicKey),privateKey:t};case Ot:return{type:_t.Anonymous};default:throw new Error(`Unknown signature policy "${s}"`)}}var dc=(s,e)=>{let t=V(e.toString(16).padStart(16,"0"),"base16"),r=qe(s),n=new Uint8Array(r.byteLength+t.length);return n.set(r,0),n.set(t,r.byteLength),n};function pc(s){if(s.type!=="signed")throw new Error("expected signed message type");if(s.sequenceNumber==null)throw Error("missing seqno field");return dc(s.from.publicKey??s.key,s.sequenceNumber)}async function mc(s){return dt.encode(s.data)}function gc(s){if(rc(s)){let e=Cr(s);switch(e.type){case"ip4":case"ip6":return e.host;default:break}}return null}var ps=class{entries=new Map;validityMs;constructor(e){this.validityMs=e.validityMs}get size(){return this.entries.size}put(e,t){return this.entries.has(e)?!0:(this.entries.set(e,{value:t,validUntilMs:Date.now()+this.validityMs}),!1)}prune(){let e=Date.now();for(let[t,r]of this.entries.entries())if(r.validUntilMs<e)this.entries.delete(t);else break}has(e){return this.entries.has(e)}get(e){let t=this.entries.get(e);return t!=null&&t.validUntilMs>=Date.now()?t.value:void 0}clear(){this.entries.clear()}};var ke;(function(s){s[s.started=0]="started",s[s.stopped=1]="stopped"})(ke||(ke={}));var Kr=class extends js{globalSignaturePolicy;protocols=[Kt,Go,Hr];publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=Ut({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=Kt;opts;decodeRpcLimits;metrics;status={code:ke.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:$a(t.scoreParams),scoreThresholds:Xa(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=r.decodeRpcLimits??za,this.globalSignaturePolicy=r.globalSignaturePolicy??It,r.fallbackToFloodsub&&this.protocols.push(Fr),this.log=e.logger.forComponent(r.debugName??"libp2p:gossipsub"),this.opts=r,this.direct=new Set(r.directPeers.map(n=>n.id.toString())),this.seenCache=new ps({validityMs:r.seenTTL}),this.publishedMessageIds=new ps({validityMs:r.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case It:this.msgIdFn=pc;break;case Ot:this.msgIdFn=mc;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new ps({validityMs:r.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??hc,this.mcache=t.messageCache??new Mr(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=ja(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 Or(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new Rr(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";[Wo]=["@libp2p/pubsub"];[jo]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===ke.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=fc(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=Ut({objectMode:!0}),Gs(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:ke.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!==ke.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:ke.stopped},this.opts.tagMeshPeers&&(this.removeEventListener("gossipsub:graft",this.tagMeshPeer),this.removeEventListener("gossipsub:prune",this.untagMeshPeer));let t=this.components.registrar;await Promise.all(this.protocols.map(async n=>t.unhandle(n))),e.forEach(n=>{t.unregister(n)}),this.outboundInflightQueue.end();let r=[];for(let n of this.streamsOutbound.values())r.push(n.close());this.streamsOutbound.clear();for(let n of this.streamsInbound.values())r.push(n.close());this.streamsInbound.clear(),await Promise.all(r),this.peers.clear(),this.subscriptions.clear(),this.heartbeatTimer!=null&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.backoff.clear(),this.outbound.clear(),this.gossipTracer.clear(),this.seenCache.clear(),this.fastMsgIdCache!=null&&this.fastMsgIdCache.clear(),this.directPeerInitial!=null&&clearTimeout(this.directPeerInitial),this.idontwantCounts.clear(),this.idontwants.clear(),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream(e,t){if(!this.isStarted())return;let r=t.remotePeer;this.addPeer(r,t.direction,t.remoteAddr),this.createInboundStream(r,e),this.outboundInflightQueue.push({peerId:r,connection:t})}onPeerConnected(e,t){this.metrics?.newConnectionCount.inc({status:t.status}),!(!this.isStarted()||t.status!=="open")&&(this.addPeer(e,t.direction,t.remoteAddr),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}async createOutboundStream(e,t){if(!this.isStarted())return;let r=e.toString();if(this.peers.has(r)&&!this.streamsOutbound.has(r))try{let n=new Nr(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===Fr&&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=gc(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 of this.topics.values())o.delete(t);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===ke.started}getMeshPeers(e){let t=this.mesh.get(e);return t!=null?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(t!=null?Array.from(t):[]).map(r=>this.peers.get(r)??Ct(r))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await Gs(t,async r=>{for await(let n of r)try{let o=n.subarray(),i=ht.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,c=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&&(c=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${r} messages ${n} ihave ${o} iwant ${i} graft ${a} prune ${c}`),t.subscriptions!=null&&t.subscriptions.length>0){let f=[];t.subscriptions.forEach(m=>{let h=m.topic,d=m.subscribe===!0;if(h!=null){if(this.allowedTopics!=null&&!this.allowedTopics.has(h))return;this.handleReceivedSubscription(e,h,d),f.push({topic:h,subscribe:d})}}),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:f}})}for(let f of t.messages){if(this.allowedTopics!=null&&!this.allowedTopics.has(f.topic))continue;let m=this.handleReceivedMessage(e,f).catch(h=>{this.metrics?.onMsgRecvError(f.topic),this.log(h)});this.opts.awaitRpcMessageHandler&&await m}t.control!=null&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,r){this.log("subscription update from %p topic %s",e,t);let n=this.topics.get(t);n==null&&(n=new Set,this.topics.set(t,n)),r?n.add(e.toString()):n.delete(e.toString())}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);let r=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,r.code);let n=r.code;switch(n){case de.duplicate:this.score.duplicateMessage(e.toString(),r.msgIdStr,t.topic),this.gossipTracer.deliverMessage(r.msgIdStr,!0),this.mcache.observeDuplicate(r.msgIdStr,e.toString());return;case de.invalid:if(r.msgIdStr!=null){let 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 de.valid:this.score.validateMessage(r.messageId.msgIdStr),this.gossipTracer.deliverMessage(r.messageId.msgIdStr),this.mcache.put(r.messageId,t,!this.opts.asyncValidation),this.subscriptions.has(t.topic)&&(!this.components.peerId.equals(e)||this.opts.emitSelf)&&(super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:e,msgId:r.messageId.msgIdStr,msg:r.msg}})),super.dispatchEvent(new CustomEvent("message",{detail:r.msg}))),this.opts.asyncValidation||this.forwardMessage(r.messageId.msgIdStr,t,e.toString());break;default:throw new Error(`Invalid validation result: ${n}`)}}async validateReceivedMessage(e,t){let r=this.fastMsgIdFn?.(t),n=r!==void 0?this.fastMsgIdCache?.get(r):void 0;if(n!=null)return{code:de.duplicate,msgIdStr:n};let o=await uc(this.globalSignaturePolicy,t);if(!o.valid)return{code:de.invalid,reason:xe.Error,error:o.error};let i=o.message;try{this.dataTransform!=null&&(i.data=this.dataTransform.inboundTransform(t.topic,i.data))}catch(h){return this.log("Invalid message, transform failed",h),{code:de.invalid,reason:xe.Error,error:fe.TransformFailed}}let a=await this.msgIdFn(i),c=this.msgIdToStrFn(a),f={msgId:a,msgIdStr:c};if(r!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(r,c)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(c))return{code:de.duplicate,msgIdStr:c};this.seenCache.put(c),(t.data?.length??0)>=this.opts.idontwantMinDataSize&&this.sendIDontWants(a,t.topic,e.toString());let m=this.topicValidators.get(t.topic);if(m!=null){let h;try{h=await m(e,i)}catch(d){let l=d.code;l===zo&&(h=pe.Ignore),l===qo?h=pe.Reject:h=pe.Ignore}if(h!==pe.Accept)return{code:de.invalid,reason:Ro(h),msgIdStr:c}}return{code:de.valid,messageId:f,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,Fe(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:ds.LowScore}),[];let n=(this.peerhave.get(e)??0)+1;if(this.peerhave.set(e,n),n>10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:ds.MaxIhave}),[];let 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:ds.MaxIasked}),[];let i=new Map;if(t.forEach(({topicID:f,messageIDs:m})=>{if(f==null||m==null||!this.mesh.has(f))return;let h=0;m.forEach(d=>{let l=this.msgIdToStrFn(d);this.seenCache.has(l)||(i.set(l,d),h++)}),this.metrics?.onIhaveRcv(f,m.length,h)}),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 c=Array.from(i.values());return We(c),c=c.slice(0,a),this.iasked.set(e,o+a),[{messageIDs:c}]}handleIWant(e,t){if(t.length===0)return[];let r=this.score.score(e);if(r<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,r),[];let n=new Map,o=new Map,i=0;return t.forEach(({messageIDs:a})=>{a?.forEach(c=>{let f=this.msgIdToStrFn(c),m=this.mcache.getWithIWantCount(f,e);if(m==null){i++;return}if(o.set(m.msg.topic,1+(o.get(m.msg.topic)??0)),m.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,c);return}n.set(f,m.msg)})}),this.metrics?.onIwantRcv(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:c})=>{if(c==null)return;let f=this.mesh.get(c);if(f==null){i=!1;return}if(f.has(e))return;let m=this.backoff.get(c)?.get(e);if(this.direct.has(e))this.log("GRAFT: ignoring request from direct peer %s",e),r.push(c),i=!1;else if(typeof m=="number"&&o<m){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,fs.GraftBackoff),i=!1;let h=m+this.opts.graftFloodThreshold-this.opts.pruneBackoff;o<h&&this.score.addPenalty(e,1,fs.GraftBackoff),this.addBackoff(e,c),r.push(c)}else n<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,n,c),r.push(c),i=!1,this.addBackoff(e,c)):f.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(r.push(c),this.addBackoff(e,c)):(this.log("GRAFT: Add mesh link from %s in %s",e,c),this.score.graft(e,c),f.add(e),this.metrics?.onAddToMesh(c,ve.Subscribed,1));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:c,direction:"inbound"}})}),r.length===0)return[];let a=!1;return Promise.all(r.map(async c=>this.makePrune(e,c,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:c}of t)for(let f of c){if(r>=this.opts.idontwantMaxMessages)break e;r++;let m=this.msgIdToStrFn(f);o.set(m,this.heartbeatTicks),this.mcache.msgs.has(m)||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,fs.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&&(We(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async r=>{if(r.peerID==null)return;let n=as(Ge(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=Ct(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!==ke.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!==ke.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!==ke.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,ve.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,ve.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!==ke.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,c=>this.score.score(c)>=this.opts.scoreThresholds.publishThreshold);a.size>0&&(this.fanout.set(e,a),a.forEach(c=>{t.add(c),r.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:r}}forwardMessage(e,t,r,n){r!=null&&this.score.deliverMessage(r,e,t.topic);let o=this.selectPeersToForward(t.topic,r,n);o.forEach(i=>{this.sendRpc(i,Fe([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 lc(this.publishConfig,e,t,o),c=await this.msgIdFn(a),f=this.msgIdToStrFn(c),m=r?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(f)){if(m)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:h,tosendCount:d}=this.selectPeersToPublish(e),l=this.opts.emitSelf&&this.subscriptions.has(e),u=r?.allowPublishToZeroTopicPeers??this.opts.allowPublishToZeroTopicPeers;if(h.size===0&&!u&&!l)throw Error("PublishError.NoPeersSubscribedToTopic");this.seenCache.put(f),this.mcache.put({msgId:c,msgIdStr:f},i,!0),this.gossipTracer.deliverMessage(f),this.publishedMessageIds.put(f);let p=r?.batchPublish??this.opts.batchPublish,g=Fe([i]);if(p)this.sendRpcInBatch(h,g);else for(let E of h)this.sendRpc(E,g)||h.delete(E);let b=Date.now()-n;return this.metrics?.onPublishMsg(e,d,h.size,i.data!=null?i.data.length:0,b),l&&(h.add(this.components.peerId.toString()),super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:f,msg:a}})),super.dispatchEvent(new CustomEvent("message",{detail:a}))),{recipients:Array.from(h.values()).map(E=>this.peers.get(E)??Ct(E))}}sendRpcInBatch(e,t){let r=ht.encode(t),n=ls.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===pe.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=Ro(r),{message:a,originatingPeers:c}=n;this.score.rejectMessage(t,e,a.topic,i);for(let f of c)this.score.rejectMessage(f,e,a.topic,i)}let o=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(n,r,o)}sendGraft(e,t){let n=Fe([],{graft:[{topicID:t}]});this.sendRpc(e,n)}async sendPrune(e,t){let n=[await this.makePrune(e,t,this.opts.doPX,!0)],o=Fe([],{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!==Kt&&o.delete(a);let i=Fe([],{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=ht.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=Oo(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=Oo(t);n.control.ihave=r}async sendGraftPrune(e,t,r){let n=this.opts.doPX,o=!1;for(let[i,a]of e){let c=a.map(h=>({topicID:h})),f=[],m=t.get(i);m!=null&&(f=await Promise.all(m.map(async h=>this.makePrune(i,h,n&&!(r.get(i)??!1),o))),t.delete(i)),this.sendRpc(i,Fe([],{graft:c,prune:f}))}for(let[i,a]of t){let c=await Promise.all(a.map(async f=>this.makePrune(i,f,n&&!(r.get(i)??!1),o)));this.sendRpc(i,Fe([],{prune:c}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[r,n]of e)this.doEmitGossip(r,n,t.get(r)??[])}doEmitGossip(e,t,r){if(r.length===0||(We(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=We(Array.from(a)).slice(0,n),a.forEach(c=>{let f=r;r.length>5e3&&(f=We(f.slice()).slice(0,5e3)),this.pushGossip(c,{topicID:e,messageIDs:f})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,Fe([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let r=Fe([],{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===Hr)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,f=>f!==e&&this.score.score(f)>=0),c=await Promise.all(Array.from(a).map(async f=>{let m=this.peers.get(f)??Ct(f),h;try{h=await this.components.peerStore.get(m)}catch(d){if(d.name!=="NotFoundError")throw d}return{peerID:m.toMultihash().bytes,signedPeerRecord:h?.peerRecordEnvelope}}));return{topicID:t,peers:c,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===ke.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,c=u=>{let p=a.get(u);return p===void 0&&(p=this.score.score(u),a.set(u,p)),p},f=new Map,m=new Map,h=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.applyIwantPenalties(),this.idontwantCounts.clear();for(let u of this.idontwants.values())for(let[p,g]of u)this.heartbeatTicks-g>=this.opts.mcacheLength&&u.delete(p);this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let d=new Map;this.mesh.forEach((u,p)=>{let g=this.topics.get(p),b=new Set,E=new Set;if(d.set(p,E),g!=null){let _=We(Array.from(g)),D=this.backoff.get(p);for(let A of _){let M=this.streamsOutbound.get(A);if(M!=null&&this.protocols.includes(M.protocol)&&!u.has(A)&&!this.direct.has(A)){let y=c(A);D?.has(A)!==!0&&y>=0&&b.add(A),y>=this.opts.scoreThresholds.gossipThreshold&&E.add(A)}}}let w=(_,D)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",_,p),this.addBackoff(_,p),u.delete(_),c(_)>=this.opts.scoreThresholds.gossipThreshold&&E.add(_),this.metrics?.onRemoveFromMesh(p,D,1);let A=m.get(_);A==null?m.set(_,[p]):A.push(p)},T=(_,D)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",_,p),this.score.graft(_,p),u.add(_),E.delete(_),this.metrics?.onAddToMesh(p,D,1);let A=f.get(_);A==null?f.set(_,[p]):A.push(p)};if(u.forEach(_=>{let D=c(_);D<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",_,D,p),w(_,Ke.BadScore),h.set(_,!0))}),u.size<t){let _=e-u.size;Ya(b,_).forEach(A=>{T(A,ve.NotEnough)})}if(u.size>r){let _=Array.from(u);_.sort((A,M)=>c(M)-c(A)),_=_.slice(0,n).concat(We(_.slice(n)));let D=0;if(_.slice(0,e).forEach(A=>{(this.outbound.get(A)??!1)&&D++}),D<o){let A=y=>{let P=_[y];for(let N=y;N>0;N--)_[N]=_[N-1];_[0]=P};if(D>0){let y=D;for(let P=1;P<e&&y>0;P++)(this.outbound.get(_[P])??!1)&&(A(P),y--)}let M=e-D;for(let y=e;y<_.length&&M>0;y++)(this.outbound.get(_[y])??!1)&&(A(y),M--)}_.slice(e).forEach(A=>{w(A,Ke.Excess)})}if(u.size>=t){let _=0;if(u.forEach(D=>{(this.outbound.get(D)??!1)&&_++}),_<o){let D=o-_;kr(b,D,M=>this.outbound.get(M)===!0).forEach(M=>{T(M,ve.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&u.size>1){let _=Array.from(u).sort((M,y)=>c(M)-c(y)),D=Math.floor(u.size/2),A=c(_[D]);if(A<this.opts.scoreThresholds.opportunisticGraftThreshold){let M=this.opts.opportunisticGraftPeers,y=kr(b,M,P=>c(P)>A);for(let P of y)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",P,p),T(P,ve.Opportunistic)}}});let l=Date.now();this.fanoutLastpub.forEach((u,p)=>{u+i<l&&(this.fanout.delete(p),this.fanoutLastpub.delete(p))}),this.fanout.forEach((u,p)=>{let g=this.topics.get(p);u.forEach(T=>{(!(g?.has(T)??!1)||c(T)<this.opts.scoreThresholds.publishThreshold)&&u.delete(T)});let b=this.topics.get(p),E=[],w=new Set;if(d.set(p,w),b!=null){let T=We(Array.from(b));for(let _ of T){let D=this.streamsOutbound.get(_);if(D!=null&&this.protocols.includes(D.protocol)&&!u.has(_)&&!this.direct.has(_)){let A=c(_);A>=this.opts.scoreThresholds.publishThreshold&&E.push(_),A>=this.opts.scoreThresholds.gossipThreshold&&w.add(_)}}}if(u.size<e){let T=e-u.size;E.slice(0,T).forEach(_=>{u.add(_),w?.delete(_)})}}),this.emitGossip(d),await this.sendGraftPrune(f,m,h),this.flush(),this.mcache.shift(),this.dispatchEvent(new CustomEvent("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,r=()=>!0){let n=this.topics.get(e);if(n==null)return new Set;let o=[];return n.forEach(i=>{let a=this.streamsOutbound.get(i);a!=null&&this.protocols.includes(a.protocol)&&r(i)&&o.push(i)}),o=We(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 c of this.backoff.values()){t+=c.size;for(let[f,m]of c.entries())this.peers.has(f)&&e.connectedPeersBackoffSec.observe(Math.max(0,m-r)/1e3)}e.cacheSize.set({cache:"backoff"},t);let n=0;for(let c of this.idontwants.values())n+=c.size;e.cacheSize.set({cache:"idontwants"},n);for(let[c,f]of this.topics)e.topicPeersCount.set({topicStr:c},f.size);for(let[c,f]of this.mesh)e.meshPeerCounts.set({topicStr:c},f.size);let o=[],i=new Map;e.behaviourPenalty.reset();for(let c of this.peers.keys()){let f=this.score.score(c);o.push(f),i.set(c,f),e.behaviourPenalty.observe(this.score.peerStats.get(c)?.behaviourPenalty??0)}e.registerScores(o,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,i);let a=sc(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(a)}tagMeshPeer=e=>{let{peerId:t,topic:r}=e.detail;this.components.peerStore.merge(this.peers.get(t)??Ct(t),{tags:{[r]:{value:100}}}).catch(n=>{this.log.error("Error tagging peer %s with topic %s",t,r,n)})};untagMeshPeer=e=>{let{peerId:t,topic:r}=e.detail;this.components.peerStore.merge(this.peers.get(t)??Ct(t),{tags:{[r]:void 0}}).catch(n=>{this.log.error("Error untagging peer %s with topic %s",t,r,n)})}};var It="StrictSign",Ot="StrictNoSign",pe;(function(s){s.Accept="accept",s.Ignore="ignore",s.Reject="reject"})(pe||(pe={}));var af=Kt;function cf(s={}){return e=>new Kr(e,s)}return Ic(lf);})();
3
+ /*! Bundled license information:
4
+
5
+ @noble/hashes/esm/utils.js:
6
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
7
+
8
+ @noble/curves/esm/utils.js:
9
+ @noble/curves/esm/abstract/modular.js:
10
+ @noble/curves/esm/abstract/curve.js:
11
+ @noble/curves/esm/abstract/edwards.js:
12
+ @noble/curves/esm/ed25519.js:
13
+ @noble/curves/esm/abstract/weierstrass.js:
14
+ @noble/curves/esm/_shortw_utils.js:
15
+ @noble/curves/esm/secp256k1.js:
16
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
17
+ */
18
+ return Libp2PGossipsub}));
19
+ //# sourceMappingURL=index.min.js.map