webpeerjs 0.1.8 → 0.1.9

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.
@@ -81,6 +81,6 @@ const Tl=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff
81
81
  //! TODO unclear how to add backpressure here?
82
82
  for(;;){const{done:e,value:c}=await t.read();if(e)break;if(a.length>=r.maxInboundStreams)i(`too many inbound streams open - ${a.length}/${r.maxInboundStreams}, closing new incoming stream`),c.writable.close().catch((e=>{i.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${e.message}`)})),c.readable.cancel().catch((e=>{i.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${e.message}`)}));else{const e=await Um(c,String(s++),"inbound",a,o?.onStreamEnd,n);a.push(e),o?.onIncomingStream?.(e)}}}));const c={protocol:"webtransport",streams:a,newStream:async t=>{i("new outgoing stream",t);const r=await e.createBidirectionalStream(),c=await Um(r,String(s++),o?.direction??"outbound",a,o?.onStreamEnd,n);return a.push(c),c},close:async()=>{i("closing webtransport muxer gracefully"),e.close()},abort:t=>{i("closing webtransport muxer with err:",t),e.close()},...Fm()};return c}}}const Km=Object.values(_t).map((e=>e.decoder)).reduce(((e,t)=>e.or(t)));function $m(e){if(!kp.matches(e))throw new pn("Invalid multiaddr, was not a WebTransport address","ERR_INVALID_MULTIADDR");const t=e.stringTuples(),n=t.filter((([e,t])=>e===Un("certhash").code)).map((([e,t])=>{return n=t??"",lt(Km.decode(n));var n})),r=t.filter((([e,t])=>e===Un("p2p").code)).map((([e,t])=>Is(t??"")))[0],s=e.toOptions();let i=s.host;return 6===s.family&&i?.includes(":")&&(i=`[${i}]`),{url:`https://${i}:${s.port}`,certhashes:n,remotePeer:r}}var qm=WebTransport;class Hm{log;components;config;metrics;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webtransport"),this.components=e,this.config={...t,maxInboundStreams:t.maxInboundStreams??1e3,certificates:t.certificates??[]},null!=e.metrics&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webtransport_dialer_events_total",{label:"event",help:"Total count of WebTransport dialer events by type"})})}[Symbol.toStringTag]="@libp2p/webtransport";[un]=!0;async dial(e,t){if(!0===t?.signal?.aborted)throw new dn;this.log("dialing %s",e);const n=this.components.peerId;if(void 0===n)throw new pn("Need a local peerid","ERR_INVALID_PARAMETERS");t=t??{};const{url:r,certhashes:s,remotePeer:i}=$m(e);let o,a,c=()=>{},l=!1,u=!1,h=!1;try{this.metrics?.dialerEvents.increment({pending:!0});const d=new qm(`${r}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:s.map((e=>({algorithm:"sha-256",value:e.digest})))});if(c=e=>{if(!l)try{this.metrics?.dialerEvents.increment({[e]:!0}),d.close()}catch(e){this.log.error("error closing wt session",e)}finally{null!=a&&(a.timeline.close=Date.now()),l=!0}},o=()=>{c(u?"noise_timeout":"ready_timeout")},t.signal?.addEventListener("abort",o,{once:!0}),this.log("wait for session to be ready"),await Promise.race([d.closed,d.ready]),this.log("session became ready"),u=!0,this.metrics?.dialerEvents.increment({ready:!0}),d.closed.catch((e=>{this.log.error("error on remote wt session close",e)})).finally((()=>{c("remote_close")})),h=await Rr(this.authenticateWebTransport(d,n,i,s),t.signal),!h)throw new pn("Failed to authenticate webtransport","ERR_AUTHENTICATION_FAILED");return this.metrics?.dialerEvents.increment({open:!0}),a={close:async()=>{this.log("closing webtransport"),c("close")},abort:e=>{this.log("aborting webtransport due to passed err",e),c("abort")},remoteAddr:e,timeline:{open:Date.now()},log:this.components.logger.forComponent("libp2p:webtransport:maconn"),...Fm()},await t.upgrader.upgradeOutbound(a,{skipEncryption:!0,muxerFactory:Vm(d,d.incomingBidirectionalStreams.getReader(),this.components.logger,this.config),skipProtection:!0})}catch(e){throw this.log.error("caught wt session err",e),c(h?"upgrade_error":u?"noise_error":"ready_error"),e}finally{null!=o&&t.signal?.removeEventListener("abort",o)}}async authenticateWebTransport(e,t,n,r=[],s){if(!0===s?.aborted)throw new dn;const i=await e.createBidirectionalStream(),o=i.writable.getWriter(),a=i.readable.getReader(),c={source:async function*(){for(;;){const e=await a.read();if(null!=e.value&&(yield e.value),e.done)break}}(),sink:async e=>{for await(const t of e){await Rr(o.ready,s);const e=t instanceof Uint8Array?t:t.subarray();o.write(e).catch((e=>{this.log.error("could not write chunk during authentication of WebTransport stream",e)}))}}},l=Nm()(this.components),{remoteExtensions:u}=await l.secureOutbound(t,c,n);if(o.close().catch((e=>{this.log.error(`Failed to close authentication stream writer: ${e.message}`)})),a.cancel().catch((e=>{this.log.error(`Failed to close authentication stream reader: ${e.message}`)})),h=u?.webtransportCerthashes??[],(d=r.map((e=>e.bytes))).filter((e=>Boolean(h.find((t=>_n(e,t)))))).length!==d.length)throw new Error("Our certhashes are not a subset of the remote's reported certhashes");var h,d;return!0}createListener(e){return function(e){throw new Error("Not implemented")}(this.components,(this.config.certificates,this.config.maxInboundStreams))}listenFilter(){return[]}dialFilter(e){return e.filter((e=>{if(!kp.exactMatch(e))return!1;const{url:t,certhashes:n}=$m(e);return null!=t&&n.length>0}))}}function zm(e={}){return t=>new Hm(t,e)}const Wm=[Un("tcp").code,Un("dns").code,Un("dnsaddr").code,Un("dns4").code,Un("dns6").code];function jm(e){let t;try{t=Un("sni").code}catch(e){return null}for(const[n,r]of e)if(n===t&&void 0!==r)return r;return null}function Gm(e){return e.some((([e,t])=>e===Un("tls").code))}function Ym(e,t,n){const r=Qm[Un(e).name];if(void 0===r)throw new Error(`Can't interpret protocol ${Un(e).name}`);const s=r(t,n);return e===Un("ip6").code?`[${s}]`:s}const Qm={ip4:(e,t)=>e,ip6:(e,t)=>0===t.length?e:`[${e}]`,tcp:(e,t)=>{const n=t.pop();if(void 0===n)throw new Error("Unexpected end of multiaddr");return`tcp://${Ym(n[0],n[1]??"",t)}:${e}`},udp:(e,t)=>{const n=t.pop();if(void 0===n)throw new Error("Unexpected end of multiaddr");return`udp://${Ym(n[0],n[1]??"",t)}:${e}`},dnsaddr:(e,t)=>e,dns4:(e,t)=>e,dns6:(e,t)=>e,dns:(e,t)=>e,ipfs:(e,t)=>{const n=t.pop();if(void 0===n)throw new Error("Unexpected end of multiaddr");return`${Ym(n[0],n[1]??"",t)}/ipfs/${e}`},p2p:(e,t)=>{const n=t.pop();if(void 0===n)throw new Error("Unexpected end of multiaddr");return`${Ym(n[0],n[1]??"",t)}/p2p/${e}`},http:(e,t)=>{const n=Gm(t),r=jm(t);if(n&&null!==r)return`https://${r}`;const s=n?"https://":"http://",i=t.pop();if(void 0===i)throw new Error("Unexpected end of multiaddr");let o=Ym(i[0],i[1]??"",t);return o=o.replace("tcp://",""),`${s}${o}`},"http-path":(e,t)=>{const n=t.pop();if(void 0===n)throw new Error("Unexpected end of multiaddr");return`${Ym(n[0],n[1]??"",t)}/${decodeURIComponent(e)}`},tls:(e,t)=>{const n=t.pop();if(void 0===n)throw new Error("Unexpected end of multiaddr");return Ym(n[0],n[1]??"",t)},sni:(e,t)=>{const n=t.pop();if(void 0===n)throw new Error("Unexpected end of multiaddr");return Ym(n[0],n[1]??"",t)},https:(e,t)=>{const n=t.pop();if(void 0===n)throw new Error("Unexpected end of multiaddr");let r=Ym(n[0],n[1]??"",t);return r=r.replace("tcp://",""),`https://${r}`},ws:(e,t)=>{const n=Gm(t),r=jm(t);if(n&&null!==r)return`wss://${r}`;const s=n?"wss://":"ws://",i=t.pop();if(void 0===i)throw new Error("Unexpected end of multiaddr");let o=Ym(i[0],i[1]??"",t);return o=o.replace("tcp://",""),`${s}${o}`},wss:(e,t)=>{const n=t.pop();if(void 0===n)throw new Error("Unexpected end of multiaddr");let r=Ym(n[0],n[1]??"",t);return r=r.replace("tcp://",""),`wss://${r}`},"p2p-websocket-star":(e,t)=>{const n=t.pop();if(void 0===n)throw new Error("Unexpected end of multiaddr");return`${Ym(n[0],n[1]??"",t)}/p2p-websocket-star`},"p2p-webrtc-star":(e,t)=>{const n=t.pop();if(void 0===n)throw new Error("Unexpected end of multiaddr");return`${Ym(n[0],n[1]??"",t)}/p2p-webrtc-star`},"p2p-webrtc-direct":(e,t)=>{const n=t.pop();if(void 0===n)throw new Error("Unexpected end of multiaddr");return`${Ym(n[0],n[1]??"",t)}/p2p-webrtc-direct`}};var Jm=async e=>{if(e.readyState>=2)throw new Error("socket closed");1!==e.readyState&&await new Promise(((t,n)=>{function r(){e.removeEventListener("open",s),e.removeEventListener("error",i)}function s(){r(),t()}function i(t){r(),n(t.error??new Error(`connect ECONNREFUSED ${e.url}`))}e.addEventListener("open",s),e.addEventListener("error",i)}))},Zm=(e,t)=>{(t=t??{}).closeOnEnd=!1!==t.closeOnEnd;return async n=>{for await(const t of n){try{await Jm(e)}catch(e){if("socket closed"===e.message)break;throw e}if(e.readyState===e.CLOSING||e.readyState===e.CLOSED)break;e.send(t)}null!=t.closeOnEnd&&e.readyState<=1&&await new Promise(((t,n)=>{e.addEventListener("close",(e=>{if(e.wasClean||1006===e.code)t();else{const t=Object.assign(new Error("ws error"),{event:e});n(t)}})),setTimeout((()=>{e.close()}))}))}},Xm={},ey={};Object.defineProperty(ey,"__esModule",{value:!0});class ty{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;const t={value:e,done:!1};if(this.pullQueue.length){const e=this.pullQueue.shift();e&&e.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),void 0!==this.highWaterMark&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{const t=Promise.reject(e);t.catch((()=>{})),this.pushQueue.push(t)}}remove(){Promise.resolve().then((()=>{this.removeCallback&&this.removeCallback()}))}[Symbol.asyncIterator](){return{next:e=>{const t=this.pushQueue.shift();return t?(void 0!==this.lowWaterMark&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise(((e,t)=>{this.pullQueue.push({resolve:e,reject:t})}))},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}let ny=class{constructor(e,{highWaterMark:t=100,lowWaterMark:n=1}={}){const r=new ty;r.highWaterMark=t,r.lowWaterMark=n,r.removeCallback=e({push:e=>r.push(e),stop:()=>r.stop(),fail:e=>r.fail(e),on:(e,t)=>{r.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>r[Symbol.asyncIterator](),Object.freeze(this)}};ey.EventIterator=ny,ey.default=ny,Object.defineProperty(Xm,"__esModule",{value:!0});const ry=ey;var sy=Xm.EventIterator=ry.EventIterator;function iy(e){return e instanceof ArrayBuffer||"ArrayBuffer"===e?.constructor?.name&&"number"==typeof e?.byteLength}Xm.subscribe=function(e,t,n){return new ry.EventIterator((({push:n})=>(this.addEventListener(e,n,t),()=>this.removeEventListener(e,n,t))),n)},Xm.default=ry.EventIterator;var oy=(e,t)=>{t=t??{};const n=(e=>{e.binaryType="arraybuffer";const t=async()=>{await new Promise(((t,n)=>{if(s)return void t();if(null!=r)return void n(r);const i=t=>{e.removeEventListener("open",o),e.removeEventListener("error",a),t()},o=()=>{i(t)},a=t=>{i((()=>{n(t.error??new Error(`connect ECONNREFUSED ${e.url}`))}))};e.addEventListener("open",o),e.addEventListener("error",a)}))},n=async function*(){const n=new sy((({push:t,stop:n,fail:r})=>{const s=e=>{let n=null;"string"==typeof e.data&&(n=kt(e.data)),iy(e.data)&&(n=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(n=e.data),null!=n&&t(n)},i=e=>{r(e.error??new Error("Socket error"))};return e.addEventListener("message",s),e.addEventListener("error",i),e.addEventListener("close",n),()=>{e.removeEventListener("message",s),e.removeEventListener("error",i),e.removeEventListener("close",n)}}),{highWaterMark:1/0});await t();for await(const e of n)yield iy(e)?new Uint8Array(e):e}();let r,s=1===e.readyState;return e.addEventListener("open",(()=>{s=!0,r=null})),e.addEventListener("close",(()=>{s=!1,r=null})),e.addEventListener("error",(t=>{s||(r=t.error??new Error(`connect ECONNREFUSED ${e.url}`))})),Object.assign(n,{connected:t})})(e);let r=t.remoteAddress,s=t.remotePort;if(null!=e.url)try{const t=new URL(e.url);r=t.hostname,s=parseInt(t.port,10)}catch{}if(null==r||null==s)throw new Error("Remote connection did not have address and/or port");return{sink:Zm(e,t),source:n,connected:async()=>{await n.connected()},close:async()=>{e.readyState!==e.CONNECTING&&e.readyState!==e.OPEN||await new Promise((t=>{e.addEventListener("close",(()=>{t()})),e.close()}))},destroy:()=>{null!=e.terminate?e.terminate():e.close()},remoteAddress:r,remotePort:s,socket:e}},ay=WebSocket;const cy={"http:":"ws:","https:":"wss:"};function ly(e,t){t=t??{};const n=((e,t)=>{if(e.startsWith("//")&&(e=`${t?.protocol??"ws:"}${e}`),e.startsWith("/")&&null!=t){const n=t.protocol??"ws:",r=t.host,s=null!=t.port&&!0!==r?.endsWith(`:${t.port}`)?`:${t.port}`:"";e=`${n}//${r}${s}${e}`}const n=new URL(e);for(const[e,t]of Object.entries(cy))n.protocol===e&&(n.protocol=t);return n})(e,"undefined"==typeof window?void 0:window.location),r=new ay(n.toString(),t.websocket);return oy(r,t)}var uy=Lr((function(){return"undefined"!=typeof window&&"object"==typeof window.process&&"renderer"===window.process.type||(!("undefined"==typeof process||"object"!=typeof process.versions||!process.versions.electron)||"object"==typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0)}));const hy="object"==typeof window&&"object"==typeof document&&9===document.nodeType,dy=uy(),py=hy&&!dy,fy=dy&&!hy,gy=dy&&hy,my=void 0!==globalThis.process&&void 0!==globalThis.process.release&&"node"===globalThis.process.release.name&&!dy,yy="function"==typeof importScripts&&"undefined"!=typeof self&&"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope;void 0!==globalThis.process&&void 0!==globalThis.process.env&&globalThis.process.env.NODE_ENV;const wy="undefined"!=typeof navigator&&"ReactNative"===navigator.product,by=Yy("dns4"),vy=Yy("dns6"),Ey=Yy("dnsaddr"),Sy=Gy(Yy("dns"),Ey,by,vy),_y=Gy(Yy("ip4"),Yy("ip6")),Iy=Gy(jy(_y,Yy("tcp")),jy(Sy,Yy("tcp"))),Ry=jy(_y,Yy("udp")),Ay=jy(Ry,Yy("utp")),Ty=jy(Ry,Yy("quic")),ky=jy(Ry,Yy("quic-v1")),Dy=Gy(jy(Iy,Yy("ws")),jy(Sy,Yy("ws"))),Py=Gy(jy(Dy,Yy("p2p")),Dy),Cy=Gy(jy(Iy,Yy("wss")),jy(Sy,Yy("wss")),jy(Iy,Yy("tls"),Yy("ws")),jy(Sy,Yy("tls"),Yy("ws"))),xy=Gy(jy(Cy,Yy("p2p")),Cy),Ny=Gy(jy(Iy,Yy("http")),jy(_y,Yy("http")),jy(Sy,Yy("http"))),My=Gy(jy(Iy,Yy("https")),jy(_y,Yy("https")),jy(Sy,Yy("https"))),Oy=jy(Ry,Yy("webrtc-direct"),Yy("certhash")),Ly=Gy(jy(Oy,Yy("p2p")),Oy),By=jy(ky,Yy("webtransport"),Yy("certhash"),Yy("certhash")),Uy=Gy(jy(By,Yy("p2p")),By),Fy=Gy(jy(Py,Yy("p2p-webrtc-star"),Yy("p2p")),jy(xy,Yy("p2p-webrtc-star"),Yy("p2p")),jy(Py,Yy("p2p-webrtc-star")),jy(xy,Yy("p2p-webrtc-star"))),Vy=Gy(jy(Ny,Yy("p2p-webrtc-direct"),Yy("p2p")),jy(My,Yy("p2p-webrtc-direct"),Yy("p2p")),jy(Ny,Yy("p2p-webrtc-direct")),jy(My,Yy("p2p-webrtc-direct"))),Ky=Gy(Dy,Cy,Ny,My,Fy,Vy,Iy,Ay,Ty,Sy,Ly,Uy),$y=Gy(jy(Ky,Yy("p2p")),Fy,Vy,Ly,Uy,Yy("p2p")),qy=Gy(jy($y,Yy("p2p-circuit"),$y),jy($y,Yy("p2p-circuit")),jy(Yy("p2p-circuit"),$y),jy(Ky,Yy("p2p-circuit")),jy(Yy("p2p-circuit"),Ky),Yy("p2p-circuit")),Hy=()=>Gy(jy(qy,Hy),qy),zy=Hy();function Wy(e){return function(t){let n;try{n=ar(t)}catch(e){return!1}const r=e(n.protoNames());return null!==r&&(!0===r||!1===r?r:0===r.length)}}function jy(...e){function t(t){if(t.length<e.length)return null;let n=t;return e.some((e=>(n="function"==typeof e?e().partialMatch(t):e.partialMatch(t),Array.isArray(n)&&(t=n),null===n))),n}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:Wy(t),partialMatch:t}}function Gy(...e){function t(t){let n=null;return e.some((e=>{const r="function"==typeof e?e().partialMatch(t):e.partialMatch(t);return null!=r&&(n=r,!0)})),n}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:Wy(t),partialMatch:t}}function Yy(e){const t=e;return{toString:function(){return t},matches:function(e){let n;try{n=ar(e)}catch(e){return!1}const r=n.protoNames();return 1===r.length&&r[0]===t},partialMatch:function(e){return 0===e.length?null:e[0]===t?e.slice(1):null}}}class Qy{log;init;logger;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.init=t}[un]=!0;[Symbol.toStringTag]="@libp2p/websockets";[En]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};const n=function(e,t,n){const r=n.logger.forComponent("libp2p:websockets:maconn"),s={log:r,async sink(t){try{await e.sink(async function*(){for await(const e of t)e instanceof Uint8Array?yield e:yield e.subarray()}())}catch(e){"aborted"!==e.type&&r.error(e)}},source:e.source,remoteAddr:t,timeline:{open:Date.now()},async close(t={}){const n=Date.now();if(null==t.signal){const e=AbortSignal.timeout(500);t={...t,signal:e}}const i=()=>{const{host:e,port:t}=s.remoteAddr.toOptions();r("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-n),this.abort(new pn("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};t.signal?.addEventListener("abort",i);try{await e.close()}catch(e){r.error("error closing WebSocket gracefully",e),this.abort(e)}finally{t.signal?.removeEventListener("abort",i),s.timeline.close=Date.now()}},abort(t){const{host:n,port:i}=s.remoteAddr.toOptions();r("timeout closing stream to %s:%s due to error",n,i,t),e.destroy(),s.timeline.close=Date.now()}};return e.socket.addEventListener("close",(()=>{null==s.timeline.close&&(s.timeline.close=Date.now())}),{once:!0}),s}(await this._connect(e,t),e,{logger:this.logger});this.log("new outbound connection %s",n.remoteAddr);const r=await t.upgrader.upgradeOutbound(n);return this.log("outbound connection %s upgraded",n.remoteAddr),r}async _connect(e,t){if(!0===t?.signal?.aborted)throw new dn;const n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);const r=cr(),s=ly(function(e,t){const n=ar(e).stringTuples(),r=n.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");const s=Un(r[0]),i=Qm[s.name];if(null==i)throw new Error(`No interpreter found for ${s.name}`);let o=i(r[1]??"",n);return Wm.includes(r[0])&&(o=o.replace(/^.*:\/\//,""),o="443"===r[1]?`https://${o}`:`http://${o}`),(o.startsWith("http://")||o.startsWith("https://"))&&(o=new URL(o).toString(),o.endsWith("/")&&(o=o.substring(0,o.length-1))),o}(e),this.init);if(s.socket.addEventListener("error",(()=>{const t=new pn(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");this.log.error("connection error:",t),r.reject(t)})),null==t.signal)return await Promise.race([s.connected(),r.promise]),this.log("connected %s",e),s;let i;const o=new Promise(((e,n)=>{i=()=>{n(new dn),s.close().catch((e=>{this.log.error("error closing raw socket",e)}))},!0!==t?.signal?.aborted?t?.signal?.addEventListener("abort",i):i()}));try{await Promise.race([o,r.promise,s.connected()])}finally{null!=i&&t?.signal?.removeEventListener("abort",i)}return this.log("connected %s",e),s}createListener(e){return function(){throw new Error("WebSocket Servers can not be created in the browser!")}(this.logger,this.init)}listenFilter(e){return e=Array.isArray(e)?e:[e],null!=this.init?.filter?this.init?.filter(e):py||yy?function(e){return e.filter((e=>{if(e.protoCodes().includes(290))return!1;const t=e.decapsulateCode(421);return xy.matches(t)}))}(e):function(e){return e.filter((e=>{if(e.protoCodes().includes(290))return!1;const t=e.decapsulateCode(421);return Py.matches(t)||xy.matches(t)}))}(e)}dialFilter(e){return this.listenFilter(e)}}function Jy(e={}){return t=>new Qy(t,e)}var Zy;!function(e){e.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",e.ERR_DATA_CHANNEL="ERR_DATA_CHANNEL",e.ERR_CONNECTION_CLOSED="ERR_CONNECTION_CLOSED",e.ERR_HASH_NOT_SUPPORTED="ERR_HASH_NOT_SUPPORTED",e.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",e.ERR_INVALID_FINGERPRINT="ERR_INVALID_FINGERPRINT",e.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",e.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",e.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",e.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS"}(Zy||(Zy={}));var Xy=function(e,t,n){if(n||2===arguments.length)for(var r,s=0,i=t.length;s<i;s++)!r&&s in t||(r||(r=Array.prototype.slice.call(t,0,s)),r[s]=t[s]);return e.concat(r||Array.prototype.slice.call(t))},ew=function(e,t,n){this.name=e,this.version=t,this.os=n,this.type="browser"},tw=function(e){this.version=e,this.type="node",this.name="node",this.os=process.platform},nw=function(e,t,n,r){this.name=e,this.version=t,this.os=n,this.bot=r,this.type="bot-device"},rw=function(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null},sw=function(){this.type="react-native",this.name="react-native",this.version=null,this.os=null},iw=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,ow=3,aw=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/]],cw=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];const lw="undefined"==typeof document&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product?new sw:"undefined"!=typeof navigator?function(e){var t=function(e){return""!==e&&aw.reduce((function(t,n){var r=n[0],s=n[1];if(t)return t;var i=s.exec(e);return!!i&&[r,i]}),!1)}(e);if(!t)return null;var n=t[0],r=t[1];if("searchbot"===n)return new rw;var s=r[1]&&r[1].split(".").join("_").split("_").slice(0,3);s?s.length<ow&&(s=Xy(Xy([],s,!0),function(e){for(var t=[],n=0;n<e;n++)t.push("0");return t}(ow-s.length),!0)):s=[];var i=s.join("."),o=function(e){for(var t=0,n=cw.length;t<n;t++){var r=cw[t],s=r[0];if(r[1].exec(e))return s}return null}(e),a=iw.exec(e);return a&&a[1]?new nw(n,i,o,a[1]):new ew(n,i,o)}(navigator.userAgent):function(){var e="undefined"!=typeof process&&process.version;return e?new tw(process.version.slice(1)):null}(),uw=null!=lw&&"firefox"===lw.name,hw=async function*(){},dw=async e=>{};class pw{log;peerConnection;remoteAddr;timeline;metrics;source=hw();sink=dw;constructor(e,t){this.log=e.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=t.remoteAddr,this.timeline=t.timeline,this.peerConnection=t.peerConnection;const n=this.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",this.peerConnection.connectionState,"initial state",n),"disconnected"!==this.peerConnection.connectionState&&"failed"!==this.peerConnection.connectionState&&"closed"!==this.peerConnection.connectionState||(this.timeline.close=Date.now())}}async close(e){this.log.trace("closing connection"),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({close:!0})}abort(e){this.log.error("closing connection due to error",e),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({abort:!0})}}const fw=e=>{const t=e.addEventListener||e.on||e.addListener,n=e.removeEventListener||e.off||e.removeListener;if(!t||!n)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:n.bind(e)}};function gw(e,t,n){"function"==typeof n&&(n={filter:n});const r=function(e,t,n){let r;const s=new Promise(((s,i)=>{if(!((n={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...n}).count>=0)||n.count!==Number.POSITIVE_INFINITY&&!Number.isInteger(n.count))throw new TypeError("The `count` option should be at least 0 or more");n.signal?.throwIfAborted();const o=[t].flat(),a=[],{addListener:c,removeListener:l}=fw(e),u=(...e)=>{const t=n.multiArgs?e:e[0];n.filter&&!n.filter(t)||(a.push(t),n.count===a.length&&(r(),s(a)))},h=e=>{r(),i(e)};r=()=>{for(const e of o)l(e,u);for(const e of n.rejectionEvents)l(e,h)};for(const e of o)c(e,u);for(const e of n.rejectionEvents)c(e,h);n.signal&&n.signal.addEventListener("abort",(()=>{h(n.signal.reason)}),{once:!0}),n.resolveImmediately&&s(a)}));if(s.cancel=r,"number"==typeof n.timeout){const e=Ph(s,{milliseconds:n.timeout});return e.cancel=r,e}return s}(e,t,n={...n,count:1,resolveImmediately:!1}),s=r.then((e=>e[0]));return s.cancel=r.cancel,s}var mw;!function(e){let t,n;!function(e){e.FIN="FIN",e.STOP_SENDING="STOP_SENDING",e.RESET="RESET",e.FIN_ACK="FIN_ACK"}(e.Flag||(e.Flag={})),function(e){e[e.FIN=0]="FIN",e[e.STOP_SENDING=1]="STOP_SENDING",e[e.RESET=2]="RESET",e[e.FIN_ACK=3]="FIN_ACK"}(t||(t={})),function(e){e.codec=()=>zt(t)}(e.Flag||(e.Flag={})),e.codec=()=>(null==n&&(n=Wt(((t,n,r={})=>{!1!==r.lengthDelimited&&n.fork(),null!=t.flag&&(n.uint32(8),e.Flag.codec().encode(t.flag,n)),null!=t.message&&(n.uint32(18),n.bytes(t.message)),!1!==r.lengthDelimited&&n.ldelim()}),((t,n)=>{const r={},s=null==n?t.len:t.pos+n;for(;t.pos<s;){const n=t.uint32();switch(n>>>3){case 1:r.flag=e.Flag.codec().decode(t);break;case 2:r.message=t.bytes();break;default:t.skipType(7&n)}}return r}))),n),e.encode=t=>$t(t,e.codec()),e.decode=t=>j(t,e.codec())}(mw||(mw={}));class yw extends Lm{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;constructor(e){const t=e.onEnd;switch(e.onEnd=e=>{this.log.trace("readable and writeable ends closed",this.status),Promise.resolve((async()=>{if(null==this.timeline.abort&&null===this.timeline.reset)try{await Ph(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(e){this.log.error("error receiving FIN_ACK",e)}})).then((()=>{this.incomingData.end(),t?.(e)})).catch((e=>{this.log.error("error ending stream",e)}))},super(e),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=dr(),this.bufferedAmountLowEventTimeout=e.bufferedAmountLowEventTimeout??3e4,this.maxBufferedAmount=e.maxBufferedAmount??16777216,this.maxMessageSize=(e.maxMessageSize??16384)-5-2,this.receiveFinAck=cr(),this.finAckTimeout=e.closeTimeout??5e3,this.openTimeout=e.openTimeout??5e3,this.channel.readyState){case"open":this.timeline.open=(new Date).getTime();break;case"closed":case"closing":void 0!==this.timeline.close&&0!==this.timeline.close||(this.timeline.close=Date.now());break;case"connecting":break;default:throw this.log.error("unknown datachannel state %s",this.channel.readyState),new pn("Unknown datachannel state","ERR_INVALID_STATE")}this.channel.onopen=e=>{this.timeline.open=(new Date).getTime()},this.channel.onclose=e=>{this.receiveFinAck.resolve(),this.close().catch((e=>{this.log.error("error closing stream after channel closed",e)}))},this.channel.onerror=e=>{const t=e.error;this.abort(t)},this.channel.onmessage=async e=>{const{data:t}=e;null!==t&&0!==t.byteLength&&this.incomingData.push(new Uint8Array(t,0,t.byteLength))};const n=this;Promise.resolve().then((async()=>{for await(const e of $r(this.incomingData)){const t=n.processIncomingProtobuf(e);null!=t&&n.sourcePush(new _r(t))}})).catch((e=>{this.log.error("error processing incoming data channel messages",e)}))}sendNewStream(){}async _sendMessage(e,t=!0){if(t&&this.channel.bufferedAmount>this.maxBufferedAmount)try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await gw(this.channel,"bufferedamountlow",{timeout:this.bufferedAmountLowEventTimeout})}catch(e){if(e instanceof Ah)throw new pn(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`,"ERR_BUFFER_CLEAR_TIMEOUT");throw e}if("closed"===this.channel.readyState||"closing"===this.channel.readyState)throw new pn(`Invalid datachannel state - ${this.channel.readyState}`,"ERR_INVALID_STATE");"open"!==this.channel.readyState&&(this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await gw(this.channel,"open",{timeout:this.openTimeout}),this.log('channel state is now "%s", sending data',this.channel.readyState)),this.channel.send(e.subarray())}async sendData(e){for(e=e.sublist();e.byteLength>0;){const t=Math.min(e.byteLength,this.maxMessageSize),n=e.subarray(0,t),r=mw.encode({message:n}),s=Mr.single(r);await this._sendMessage(s),e.consume(t)}}async sendReset(){await this._sendFlag(mw.Flag.RESET)}async sendCloseWrite(e){if(await this._sendFlag(mw.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await Rr(this.receiveFinAck.promise,e?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorCode:"ERR_FIN_ACK_NOT_RECEIVED"})}catch(e){this.log.error("failed to await FIN_ACK",e)}}else this.log.trace("sending FIN failed, not awaiting FIN_ACK");this.receiveFinAck.resolve()}async sendCloseRead(){await this._sendFlag(mw.Flag.STOP_SENDING)}processIncomingProtobuf(e){const t=mw.decode(e);if(void 0!==t.flag&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',t.flag,this.writeStatus,this.readStatus),t.flag===mw.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(mw.Flag.FIN_ACK).catch((e=>{this.log.error("error sending FIN_ACK immediately",e)}))),t.flag===mw.Flag.RESET&&this.reset(),t.flag===mw.Flag.STOP_SENDING&&this.remoteCloseRead(),t.flag===mw.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),"ready"===this.readStatus)return t.message}async _sendFlag(e){if("open"!==this.channel.readyState)return this.log.trace('not sending flag %s because channel is "%s" and not "open"',this.channel.readyState,e.toString()),!1;this.log.trace("sending flag %s",e.toString());const t=mw.encode({flag:e}),n=Mr.single(t);try{return await this._sendMessage(n,!1),!0}catch(t){this.log.error("could not send flag %s",e.toString(),t)}return!1}}function ww(e){const{channel:t,direction:n}=e;return new yw({id:"inbound"===n?`i${t.id}`:`r${t.id}`,log:e.logger.forComponent(`libp2p:webrtc:stream:${n}:${t.id}`),...e})}const bw="/webrtc";class vw{protocol;peerConnection;bufferedStreams=[];metrics;dataChannelOptions;components;log;constructor(e,t){this.components=e,this.peerConnection=t.peerConnection,this.metrics=t.metrics,this.protocol=t.protocol??bw,this.dataChannelOptions=t.dataChannelOptions??{},this.log=e.logger.forComponent("libp2p:webrtc:datachannelmuxerfactory"),this.peerConnection.ondatachannel=({channel:t})=>{if(this.log.trace('incoming early datachannel with channel id %d and label "%s"',t.id),"init"===t.label)return this.log.trace("closing early init channel"),void t.close();const n={},r=ww({channel:t,direction:"inbound",onEnd:e=>{n.onEnd(e)},logger:e.logger,...this.dataChannelOptions});n.stream=r,n.channel=t,n.onEnd=()=>{this.bufferedStreams=this.bufferedStreams.filter((e=>e.stream.id!==r.id))},this.bufferedStreams.push(n)}}createStreamMuxer(e){return new Ew(this.components,{...e,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}}class Ew{init;streams;protocol;log;peerConnection;dataChannelOptions;metrics;logger;constructor(e,t){this.init=t,this.log=e.logger.forComponent("libp2p:webrtc:muxer"),this.logger=e.logger,this.streams=t.streams.map((e=>e.stream)),this.peerConnection=t.peerConnection,this.protocol=t.protocol??bw,this.metrics=t.metrics,this.dataChannelOptions=t.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:e})=>{if(this.log.trace("incoming datachannel with channel id %d",e.id),"init"===e.label)return this.log.trace("closing init channel"),void e.close();const n=ww({channel:e,direction:"inbound",onEnd:()=>{this.log("incoming channel %s ended with state %s",e.id,e.readyState),this.#L(n,e)},logger:this.logger,...this.dataChannelOptions});this.streams.push(n),this.metrics?.increment({incoming_stream:!0}),t?.onIncomingStream?.(n)},this.init.streams.length>0&&queueMicrotask((()=>{this.init.streams.forEach((e=>{e.onEnd=()=>{this.log("incoming early channel %s ended with state %s",e.channel.id,e.channel.readyState),this.#L(e.stream,e.channel)},this.metrics?.increment({incoming_stream:!0}),this.init?.onIncomingStream?.(e.stream)}))}))}#L(e,t){this.log.trace("stream %s %s %s onEnd",e.direction,e.id,e.protocol),function(e,t,n=3e4,r){"open"===e.readyState&&Promise.resolve().then((async()=>{if(e.bufferedAmount>0){r.log("%s drain channel with %d buffered bytes",t,e.bufferedAmount);const s=cr();let i=!1;e.bufferedAmountLowThreshold=0;const o=()=>{i||(r.log("%s drain channel closed before drain",t),s.resolve())};e.addEventListener("close",o,{once:!0}),e.addEventListener("bufferedamountlow",(()=>{i=!0,e.removeEventListener("close",o),s.resolve()})),await Ph(s.promise,{milliseconds:n})}})).then((async()=>{"open"===e.readyState&&e.close()})).catch((e=>{r.log.error("error closing outbound stream",e)}))}(t,`${e.direction} ${e.id} ${e.protocol}`,this.dataChannelOptions.drainTimeout,{log:this.log}),this.streams=this.streams.filter((t=>t.id!==e.id)),this.metrics?.increment({stream_end:!0}),this.init?.onStreamEnd?.(e)}async close(e){try{await Promise.all(this.streams.map((async t=>t.close(e))))}catch(e){this.abort(e)}}abort(e){for(const t of this.streams)t.abort(e)}source=hw();sink=dw;newStream(){const e=this.peerConnection.createDataChannel("");this.log.trace("opened outgoing datachannel with channel id %s",e.id);const t=ww({channel:e,direction:"outbound",onEnd:()=>{this.log("outgoing channel %s ended with state %s",e.id,e.readyState),this.#L(t,e)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(t),this.metrics?.increment({outgoing_stream:!0}),t}}const Sw=globalThis.RTCPeerConnection,_w=globalThis.RTCSessionDescription,Iw=globalThis.RTCIceCandidate;function Rw(e,t){const n=Cr(e,t),r={read:async(e,t)=>{const r=await n.read(t);return e.decode(r)},write:async(e,t,r)=>{await n.write(t.encode(e),r)},writeV:async(e,t,r)=>{await n.writeV(e.map((e=>t.encode(e))),r)},pb:e=>({read:async t=>r.read(e,t),write:async(t,n)=>r.write(t,e,n),writeV:async(t,n)=>r.writeV(t,e,n),unwrap:()=>r}),unwrap:()=>n.unwrap()};return r}var Aw;!function(e){let t,n;!function(e){e.SDP_OFFER="SDP_OFFER",e.SDP_ANSWER="SDP_ANSWER",e.ICE_CANDIDATE="ICE_CANDIDATE"}(e.Type||(e.Type={})),function(e){e[e.SDP_OFFER=0]="SDP_OFFER",e[e.SDP_ANSWER=1]="SDP_ANSWER",e[e.ICE_CANDIDATE=2]="ICE_CANDIDATE"}(t||(t={})),function(e){e.codec=()=>zt(t)}(e.Type||(e.Type={})),e.codec=()=>(null==n&&(n=Wt(((t,n,r={})=>{!1!==r.lengthDelimited&&n.fork(),null!=t.type&&(n.uint32(8),e.Type.codec().encode(t.type,n)),null!=t.data&&(n.uint32(18),n.string(t.data)),!1!==r.lengthDelimited&&n.ldelim()}),((t,n)=>{const r={},s=null==n?t.len:t.pos+n;for(;t.pos<s;){const n=t.uint32();switch(n>>>3){case 1:r.type=e.Type.codec().decode(t);break;case 2:r.data=t.string();break;default:t.skipType(7&n)}}return r}))),n),e.encode=t=>$t(t,e.codec()),e.decode=t=>j(t,e.codec())}(Aw||(Aw={}));const Tw=async(e,t,n)=>{try{const r=cr();for(!function(e,t){e[uw?"oniceconnectionstatechange":"onconnectionstatechange"]=n=>{switch(function(e){return uw?e.iceConnectionState:e.connectionState}(e)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new pn("RTCPeerConnection was closed","ERR_CONNECTION_CLOSED_BEFORE_CONNECTED"))}}}(e,r);;){const s=await Promise.race([r.promise,t.read({signal:n.signal}).catch((()=>{}))]);if(null==s){n.signal?.throwIfAborted();break}if(s.type!==Aw.Type.ICE_CANDIDATE)throw new pn("ICE candidate message expected","ERR_NOT_ICE_CANDIDATE");const i=JSON.parse(s.data??"null");if(""===i||null===i){n.log.trace("end-of-candidates received");continue}const o=new Iw(i);n.log.trace("%s received new ICE candidate %o",n.direction,i);try{await e.addIceCandidate(o)}catch(e){n.log.error("%s bad candidate received",n.direction,i,e)}}}catch(e){if(n.log.error("%s error parsing ICE candidate",n.direction,e),!0===n.signal?.aborted)throw e}};async function kw({rtcConfiguration:e,dataChannel:t,signal:n,metrics:r,multiaddr:s,connectionManager:i,transportManager:o,log:a,logger:c}){const{baseAddr:l}=function(e){const t=e.toString().split(Pw+"/");if(2!==t.length)throw new pn("webrtc protocol was not present in multiaddr",Zy.ERR_INVALID_MULTIADDR);if(!t[0].includes(Cw))throw new pn("p2p-circuit protocol was not present in multiaddr",Zy.ERR_INVALID_MULTIADDR);let n=ar(t[0]);const r=ar("/"+t[1]).getPeerId();if(null==r)throw new pn("destination peer id was missing",Zy.ERR_INVALID_MULTIADDR);const s=n.protos().pop();if(void 0===s)throw new pn("invalid multiaddr",Zy.ERR_INVALID_MULTIADDR);"p2p"!==s.name&&(n=n.encapsulate(`/p2p/${r}`));return{baseAddr:n,peerId:Is(r)}}(s);r?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",l);const u=l.getPeerId();if(null==u)throw new pn("Relay peer was missing","ERR_INVALID_ADDRESS");const h=i.getConnections(Is(u));let d,p=!1;0===h.length?(d=await o.dial(l,{signal:n}),p=!0):d=h[0];try{const r=await d.newStream(xw,{signal:n,runOnTransientConnection:!0}),i=Rw(r).pb(Aw),o=new Sw(e),l=new vw({logger:c},{peerConnection:o,dataChannelOptions:t});try{const e=o.createDataChannel("init");o.onicecandidate=({candidate:e})=>{const t=JSON.stringify(e?.toJSON()??null);a.trace("initiator sending ICE candidate %o",e),i.write({type:Aw.Type.ICE_CANDIDATE,data:t},{signal:n}).catch((e=>{a.error("error sending ICE candidate",e)}))},o.onicecandidateerror=e=>{a.error("initiator ICE candidate error",e)};const t=await o.createOffer().catch((e=>{throw a.error("could not execute createOffer",e),new pn("Failed to set createOffer","ERR_SDP_HANDSHAKE_FAILED")}));a.trace("initiator send SDP offer %s",t.sdp),await i.write({type:Aw.Type.SDP_OFFER,data:t.sdp},{signal:n}),await o.setLocalDescription(t).catch((e=>{throw a.error("could not execute setLocalDescription",e),new pn("Failed to set localDescription","ERR_SDP_HANDSHAKE_FAILED")}));const c=await i.read({signal:n});if(c.type!==Aw.Type.SDP_ANSWER)throw new pn("Remote should send an SDP answer","ERR_SDP_HANDSHAKE_FAILED");a.trace("initiator receive SDP answer %s",c.data);const u=new _w({type:"answer",sdp:c.data});return await o.setRemoteDescription(u).catch((e=>{throw a.error("could not execute setRemoteDescription",e),new pn("Failed to set remoteDescription","ERR_SDP_HANDSHAKE_FAILED")})),a.trace("initiator read candidates until connected"),await Tw(o,i,{direction:"initiator",signal:n,log:a}),a.trace("initiator connected, closing init channel"),e.close(),a.trace("closing signalling channel"),await r.close({signal:n}),a.trace("initiator connected to remote address %s",s),{remoteAddress:s,peerConnection:o,muxerFactory:l}}catch(e){throw a.error("outgoing signalling error",e),o.close(),r.abort(e),e}finally{o.onicecandidate=null,o.onicecandidateerror=null}}finally{if(p)try{await d.close({signal:n})}catch(e){d.abort(e)}}}class Dw extends yn{peerId;transportManager;shutdownController;constructor(e,t){super(),this.peerId=e.peerId,this.transportManager=e.transportManager,this.shutdownController=t.shutdownController}async listen(){this.safeDispatchEvent("listening",{})}getAddrs(){return this.transportManager.getListeners().filter((e=>e!==this)).map((e=>e.getAddrs().filter((e=>zy.matches(e))).map((e=>e.encapsulate(`/webrtc/p2p/${this.peerId}`))))).flat()}async close(){this.shutdownController.abort(),this.safeDispatchEvent("close",{})}}const Pw="/webrtc",Cw="/p2p-circuit",xw="/webrtc-signaling/0.0.1";class Nw{components;init;log;_started=!1;metrics;shutdownController;constructor(e,t={}){this.components=e,this.init=t,this.log=e.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,null!=e.metrics&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[un]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[En]=["@libp2p/transport"];[Sn]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(xw,(e=>{this._onProtocol(e).catch((t=>{this.log.error("failed to handle incoming connect from %p",e.connection.remotePeer,t)}))}),{runOnTransientConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(xw),this._started=!1}createListener(e){return new Dw(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(Cp.exactMatch)}dialFilter(e){return this.listenFilter(e)}async dial(e,t){this.log.trace("dialing address: %a",e);const{remoteAddress:n,peerConnection:r,muxerFactory:s}=await kw({rtcConfiguration:"function"==typeof this.init.rtcConfiguration?await this.init.rtcConfiguration():this.init.rtcConfiguration,dataChannel:this.init.dataChannel,multiaddr:e,dataChannelOptions:this.init.dataChannel,signal:t.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger}),i=new pw(this.components,{peerConnection:r,timeline:{open:Date.now()},remoteAddr:n,metrics:this.metrics?.dialerEvents}),o=await t.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,muxerFactory:s});return this._closeOnShutdown(r,i),o}async _onProtocol({connection:e,stream:t}){const n=AbortSignal.timeout(this.init.inboundConnectionTimeout??3e4),r=new Sw("function"==typeof this.init.rtcConfiguration?await this.init.rtcConfiguration():this.init.rtcConfiguration),s=new vw(this.components,{peerConnection:r,dataChannelOptions:this.init.dataChannel});try{const{remoteAddress:i}=await async function({peerConnection:e,stream:t,signal:n,connection:r,log:s}){s.trace("new inbound signaling stream");const i=Rw(t).pb(Aw);try{e.onicecandidate=({candidate:e})=>{const t=JSON.stringify(e?.toJSON()??null);s.trace("recipient sending ICE candidate %s",t),i.write({type:Aw.Type.ICE_CANDIDATE,data:t},{signal:n}).catch((e=>{s.error("error sending ICE candidate",e)}))};const t=await i.read({signal:n});if(t.type!==Aw.Type.SDP_OFFER)throw new pn(`expected message type SDP_OFFER, received: ${t.type??"undefined"} `,"ERR_SDP_HANDSHAKE_FAILED");s.trace("recipient receive SDP offer %s",t.data);const r=new _w({type:"offer",sdp:t.data});await e.setRemoteDescription(r).catch((e=>{throw s.error("could not execute setRemoteDescription",e),new pn("Failed to set remoteDescription","ERR_SDP_HANDSHAKE_FAILED")}));const o=await e.createAnswer().catch((e=>{throw s.error("could not execute createAnswer",e),new pn("Failed to create answer","ERR_SDP_HANDSHAKE_FAILED")}));s.trace("recipient send SDP answer %s",o.sdp),await i.write({type:Aw.Type.SDP_ANSWER,data:o.sdp},{signal:n}),await e.setLocalDescription(o).catch((e=>{throw s.error("could not execute setLocalDescription",e),new pn("Failed to set localDescription","ERR_SDP_HANDSHAKE_FAILED")})),s.trace("recipient read candidates until connected"),await Tw(e,i,{direction:"recipient",signal:n,log:s})}catch(t){if("connected"!==e.connectionState)throw s.error("error while handling signaling stream from peer %a",r.remoteAddr,t),e.close(),t;s("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",r.remoteAddr,t)}const o=ar(`/webrtc/p2p/${r.remoteAddr.getPeerId()}`);return s.trace("recipient connected to remote address %s",o),{remoteAddress:o}}({peerConnection:r,connection:e,stream:t,signal:n,log:this.log});await t.close({signal:n});const o=new pw(this.components,{peerConnection:r,timeline:{open:(new Date).getTime()},remoteAddr:i,metrics:this.metrics?.listenerEvents});await this.components.upgrader.upgradeInbound(o,{skipEncryption:!0,skipProtection:!0,muxerFactory:s}),this._closeOnShutdown(r,o)}catch(e){throw this.log.error("incoming signalling error",e),r.close(),t.abort(e),e}}_closeOnShutdown(e,t){const n=()=>{t.close().catch((e=>{this.log.error("could not close WebRTCMultiaddrConnection",e)}))};this.shutdownController.signal.addEventListener("abort",n),e.addEventListener("close",(()=>{this.shutdownController.signal.removeEventListener("abort",n)}))}}var Mw;function Ow(e,t){if(Pp.matches(e))return!1;return null!=t.dialTransportForMultiaddr(e)&&(!!dp.matches(e)||!!mp.matches(e)&&!1===Qd(e.toOptions().host))}!function(e){let t,n;!function(e){e.UNUSED="UNUSED",e.CONNECT="CONNECT",e.SYNC="SYNC"}(e.Type||(e.Type={})),function(e){e[e.UNUSED=0]="UNUSED",e[e.CONNECT=100]="CONNECT",e[e.SYNC=300]="SYNC"}(t||(t={})),function(e){e.codec=()=>zt(t)}(e.Type||(e.Type={})),e.codec=()=>(null==n&&(n=Wt(((t,n,r={})=>{if(!1!==r.lengthDelimited&&n.fork(),null!=t.type&&(n.uint32(8),e.Type.codec().encode(t.type,n)),null!=t.observedAddresses)for(const e of t.observedAddresses)n.uint32(18),n.bytes(e);!1!==r.lengthDelimited&&n.ldelim()}),((t,n)=>{const r={observedAddresses:[]},s=null==n?t.len:t.pos+n;for(;t.pos<s;){const n=t.uint32();switch(n>>>3){case 1:r.type=e.Type.codec().decode(t);break;case 2:r.observedAddresses.push(t.bytes());break;default:t.skipType(7&n)}}return r}))),n),e.encode=t=>$t(t,e.codec()),e.decode=t=>j(t,e.codec())}(Mw||(Mw={}));const Lw=5e3,Bw=3,Uw=1,Fw=1;class Vw{started;timeout;retries;maxInboundStreams;maxOutboundStreams;peerStore;registrar;connectionManager;addressManager;transportManager;topologyId;log;constructor(e,t){this.log=e.logger.forComponent("libp2p:dcutr"),this.started=!1,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.timeout=t.timeout??Lw,this.retries=t.retries??Bw,this.maxInboundStreams=t.maxInboundStreams??Uw,this.maxOutboundStreams=t.maxOutboundStreams??Fw}[Symbol.toStringTag]="@libp2p/dcutr";[Sn]=["@libp2p/identify"];isStarted(){return this.started}async start(){this.started||(this.topologyId=await this.registrar.register(Kw,{notifyOnTransient:!0,onConnect:(e,t)=>{t.transient&&"inbound"===t.direction&&this.upgradeInbound(t).catch((e=>{this.log.error("error during outgoing DCUtR attempt",e)}))}}),await this.registrar.handle(Kw,(e=>{this.handleIncomingUpgrade(e.stream,e.connection).catch((t=>{this.log.error("error during incoming DCUtR attempt",t),e.stream.abort(t)}))}),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:!0}),this.started=!0)}async stop(){await this.registrar.unhandle(Kw),null!=this.topologyId&&this.registrar.unregister(this.topologyId),this.started=!1}async upgradeInbound(e){if(await this.attemptUnilateralConnectionUpgrade(e))return;let t;for(let n=0;n<this.retries;n++){const r={signal:AbortSignal.timeout(this.timeout)};try{t=await e.newStream([Kw],{signal:r.signal,runOnTransientConnection:!0});const n=Rw(t,{maxDataLength:4096}).pb(Mw);this.log("B sending connect to %p",e.remotePeer);const s=Date.now();await n.write({type:Mw.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map((e=>e.bytes))},r),this.log("B receiving connect from %p",e.remotePeer);const i=await n.read(r);if(i.type!==Mw.Type.CONNECT)throw this.log("A sent wrong message type"),new pn("DCUtR message type was incorrect",mn);const o=this.getDialableMultiaddrs(i.observedAddresses);if(0===o.length)throw this.log("A did not have any dialable multiaddrs"),new pn("DCUtR connect message had no multiaddrs",mn);const a=Date.now()-s;this.log("A sending sync, rtt %dms",a),await n.write({type:Mw.Type.SYNC,observedAddresses:[]},r),this.log("A waiting for half RTT"),await hf(a/2),this.log("B dialing",o);const c=await this.connectionManager.openConnection(o,{signal:r.signal,priority:100});this.log("DCUtR to %p succeeded to address %a, closing relayed connection",e.remotePeer,c.remoteAddr),await e.close(r);break}catch(e){if(this.log.error("error while attempting DCUtR on attempt %d of %d",n+1,this.retries,e),t?.abort(e),n===this.retries)throw e}finally{null!=t&&await t.close(r)}}}async attemptUnilateralConnectionUpgrade(e){const t=(await this.peerStore.get(e.remotePeer)).addresses.map((t=>{const n=t.multiaddr;return null==n.getPeerId()?n.encapsulate(`/p2p/${e.remotePeer}`):n})).filter((e=>Ow(e,this.transportManager)));if(t.length>0){const n=AbortSignal.timeout(this.timeout);try{this.log("attempting unilateral connection upgrade to %a",t);const r=await this.connectionManager.openConnection(t,{signal:n,force:!0});if(r.transient)throw new Error("Could not open a new, non-transient, connection");return this.log("unilateral connection upgrade to %p succeeded via %a, closing relayed connection",e.remotePeer,r.remoteAddr),await e.close({signal:n}),!0}catch(n){this.log.error("unilateral connection upgrade to %p on addresses %a failed",e.remotePeer,t,n)}}else this.log("peer %p has no public addresses, not attempting unilateral connection upgrade",e.remotePeer);return!1}async handleIncomingUpgrade(e,t){const n={signal:AbortSignal.timeout(this.timeout)};try{const r=Rw(e,{maxDataLength:4096}).pb(Mw);this.log("A receiving connect");const s=await r.read(n);if(s.type!==Mw.Type.CONNECT)throw this.log("B sent wrong message type"),new pn("DCUtR message type was incorrect",mn);if(0===s.observedAddresses.length)throw this.log("B sent no multiaddrs"),new pn("DCUtR connect message had no multiaddrs",mn);const i=this.getDialableMultiaddrs(s.observedAddresses);if(0===i.length)throw this.log("B had no dialable multiaddrs"),new pn("DCUtR connect message had no dialable multiaddrs",mn);this.log("A sending connect"),await r.write({type:Mw.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map((e=>e.bytes))}),this.log("A receiving sync");if((await r.read(n)).type!==Mw.Type.SYNC)throw new pn("DCUtR message type was incorrect",mn);this.log("A dialing",i);const o=await this.connectionManager.openConnection(i,{signal:n.signal,priority:100,force:!0});this.log("DCUtR to %p succeeded via %a, closing relayed connection",t.remotePeer,o.remoteAddr),await t.close(n)}catch(n){this.log.error("incoming DCUtR from %p failed",t.remotePeer,n),e.abort(n)}finally{await e.close(n)}}getDialableMultiaddrs(e){const t=[];for(const n of e)if(null!=n&&0!==n.length)try{const e=ar(n);if(!Ow(e,this.transportManager))continue;t.push(e)}catch{}return t}}const Kw="/libp2p/dcutr";function $w(e={}){return t=>new Vw(t,e)}const qw="ERR_INVALID_FRAME",Hw="ERR_UNREQUESTED_PING",zw="ERR_NOT_MATCHING_PING",Ww="ERR_STREAM_ALREADY_EXISTS",jw="ERR_DECODE_INVALID_VERSION",Gw="ERR_BOTH_CLIENTS",Yw="ERR_RECV_WINDOW_EXCEEDED",Qw=new Set([qw,Hw,zw,Ww,jw,Gw,Yw]),Jw="ERR_INVALID_CONFIG",Zw="ERR_MUXER_LOCAL_CLOSED",Xw="ERR_MUXER_REMOTE_CLOSED",eb=262144,tb={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,initialStreamWindowSize:eb,maxStreamWindowSize:16777216,maxMessageSize:65536};var nb,rb;!function(e){e[e.Data=0]="Data",e[e.WindowUpdate=1]="WindowUpdate",e[e.Ping=2]="Ping",e[e.GoAway=3]="GoAway"}(nb||(nb={})),function(e){e[e.SYN=1]="SYN",e[e.ACK=2]="ACK",e[e.FIN=4]="FIN",e[e.RST=8]="RST"}(rb||(rb={})),Object.values(rb).filter((e=>"string"!=typeof e));var sb;!function(e){e[e.NormalTermination=0]="NormalTermination",e[e.ProtocolError=1]="ProtocolError",e[e.InternalError=2]="InternalError"}(sb||(sb={}));const ib=2**24;class ob{source;buffer;frameInProgress;constructor(e){this.source=function(e){if(void 0!==e[Symbol.iterator]){const t=e[Symbol.iterator]();return t.return=void 0,{[Symbol.iterator]:()=>t}}if(void 0!==e[Symbol.asyncIterator]){const t=e[Symbol.asyncIterator]();return t.return=void 0,{[Symbol.asyncIterator]:()=>t}}throw new Error("a source must be either an iterable or an async iterable")}(e),this.buffer=new _r,this.frameInProgress=!1}async*emitFrames(){for await(const e of this.source)for(this.buffer.append(e);;){const e=this.readHeader();if(void 0===e)break;const{type:t,length:n}=e;t===nb.Data?(this.frameInProgress=!0,yield{header:e,readData:this.readBytes.bind(this,n)}):yield{header:e}}}readHeader(){if(this.frameInProgress)throw new pn("decoding frame already in progress","ERR_DECODE_IN_PROGRESS");if(this.buffer.length<12)return;const e=function(e){if(0!==e[0])throw new pn("Invalid frame version",jw);return{type:e[1],flag:(e[2]<<8)+e[3],streamID:e[4]*ib+(e[5]<<16)+(e[6]<<8)+e[7],length:e[8]*ib+(e[9]<<16)+(e[10]<<8)+e[11]}}(this.buffer.subarray(0,12));return this.buffer.consume(12),e}async readBytes(e){if(this.buffer.length<e)for await(const t of this.source)if(this.buffer.append(t),this.buffer.length>=e)break;const t=this.buffer.sublist(0,e);return this.buffer.consume(e),this.frameInProgress=!1,t}}function ab(e){const t=new Uint8Array(12);return t[1]=e.type,t[2]=e.flag>>>8,t[3]=e.flag,t[4]=e.streamID>>>24,t[5]=e.streamID>>>16,t[6]=e.streamID>>>8,t[7]=e.streamID,t[8]=e.length>>>24,t[9]=e.length>>>16,t[10]=e.length>>>8,t[11]=e.length,t}function cb(e){return null!=e?.then}function lb(e,t){let n=0;if(null!=e[Symbol.asyncIterator])return async function*(){for await(const r of e){const e=t(r,n++);cb(e)&&await e,yield r}}();const r=qr(e),{value:s,done:i}=r.next();if(!0===i)return function*(){}();const o=t(s,n++);if("function"==typeof o?.then)return async function*(){yield s;for await(const e of r){const r=t(e,n++);cb(r)&&await r,yield e}}();const a=t;return function*(){yield s;for(const e of r)a(e,n++),yield e}()}var ub;!function(e){e[e.Init=0]="Init",e[e.SYNSent=1]="SYNSent",e[e.SYNReceived=2]="SYNReceived",e[e.Established=3]="Established",e[e.Finished=4]="Finished"}(ub||(ub={}));class hb extends Lm{name;state;config;_id;sendWindowCapacity;sendWindowCapacityUpdate;recvWindow;recvWindowCapacity;epochStart;getRTT;sendFrame;constructor(e){super({...e,onEnd:t=>{this.state=ub.Finished,e.onEnd?.(t)}}),this.config=e.config,this._id=parseInt(e.id,10),this.name=e.name,this.state=e.state,this.sendWindowCapacity=eb,this.recvWindow=this.config.initialStreamWindowSize,this.recvWindowCapacity=this.recvWindow,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame,this.source=lb(this.source,(()=>{this.sendWindowUpdate()}))}async sendNewStream(){}async sendData(e,t={}){for(e=e.sublist();0!==e.byteLength;){if(0===this.sendWindowCapacity&&(this.log?.trace("wait for send window capacity, status %s",this.status),await this.waitForSendWindowCapacity(t),"closed"===this.status||"aborted"===this.status||"reset"===this.status))return void this.log?.trace("%s while waiting for send window capacity",this.status);const n=Math.min(this.sendWindowCapacity,this.config.maxMessageSize-12,e.length),r=this.getSendFlags();this.sendFrame({type:nb.Data,flag:r,streamID:this._id,length:n},e.sublist(0,n)),this.sendWindowCapacity-=n,e.consume(n)}}async sendReset(){this.sendFrame({type:nb.WindowUpdate,flag:rb.RST,streamID:this._id,length:0})}async sendCloseWrite(){const e=this.getSendFlags()|rb.FIN;this.sendFrame({type:nb.WindowUpdate,flag:e,streamID:this._id,length:0})}async sendCloseRead(){}async waitForSendWindowCapacity(e={}){if(this.sendWindowCapacity>0)return;let t,n;const r=()=>{"open"===this.status||"closing"===this.status?n(new pn("stream aborted","ERR_STREAM_ABORT")):t()};e.signal?.addEventListener("abort",r);try{await new Promise(((e,r)=>{this.sendWindowCapacityUpdate=()=>{e()},n=r,t=e}))}finally{e.signal?.removeEventListener("abort",r)}}handleWindowUpdate(e){this.log?.trace("stream received window update id=%s",this._id),this.processFlags(e.flag);const t=this.sendWindowCapacity;this.sendWindowCapacity+=e.length,0===t&&e.length>0&&this.sendWindowCapacityUpdate?.()}async handleData(e,t){if(this.log?.trace("stream received data id=%s",this._id),this.processFlags(e.flag),this.recvWindowCapacity<e.length)throw new pn("receive window exceeded",Yw,{available:this.recvWindowCapacity,recv:e.length});const n=await t();this.recvWindowCapacity-=e.length,this.sourcePush(n)}processFlags(e){(e&rb.ACK)===rb.ACK&&this.state===ub.SYNSent&&(this.state=ub.Established),(e&rb.FIN)===rb.FIN&&this.remoteCloseWrite(),(e&rb.RST)===rb.RST&&this.reset()}getSendFlags(){switch(this.state){case ub.Init:return this.state=ub.SYNSent,rb.SYN;case ub.SYNReceived:return this.state=ub.Established,rb.ACK;default:return 0}}sendWindowUpdate(){const e=this.getSendFlags(),t=Date.now(),n=this.getRTT();if(0===e&&n>-1&&t-this.epochStart<4*n&&(this.recvWindow=Math.min(2*this.recvWindow,this.config.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&0===e)return;const r=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:nb.WindowUpdate,flag:e,streamID:this._id,length:r})}}const db="/yamux/1.0.0";class pb{protocol=db;_components;_init;constructor(e,t={}){this._components=e,this._init=t}createStreamMuxer(e){return new fb(this._components,{...this._init,...e})}}class fb{protocol=db;source;sink;config;log;logger;closeController;nextStreamID;_streams;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;onIncomingStream;onStreamEnd;constructor(e,t){this.client="outbound"===t.direction,this.config={...tb,...t},this.logger=e.logger,this.log=this.logger.forComponent("libp2p:yamux"),function(e){if(e.keepAliveInterval<=0)throw new pn("keep-alive interval must be positive",Jw);if(e.maxInboundStreams<0)throw new pn("max inbound streams must be larger or equal 0",Jw);if(e.maxOutboundStreams<0)throw new pn("max outbound streams must be larger or equal 0",Jw);if(e.initialStreamWindowSize<eb)throw new pn("InitialStreamWindowSize must be larger or equal 256 kB",Jw);if(e.maxStreamWindowSize<e.initialStreamWindowSize)throw new pn("MaxStreamWindowSize must be larger than the InitialStreamWindowSize",Jw);if(e.maxStreamWindowSize>2**32-1)throw new pn("MaxStreamWindowSize must be less than equal MAX_UINT32",Jw);if(e.maxMessageSize<1024)throw new pn("MaxMessageSize must be greater than a kilobyte",Jw)}(this.config),this.closeController=new AbortController,this.closeController.signal,this.onIncomingStream=t.onIncomingStream,this.onStreamEnd=t.onStreamEnd,this._streams=new Map,this.source=dr({onEnd:()=>{this.log?.trace("muxer source ended"),this._streams.forEach((e=>{e.destroy()}))}}),this.sink=async e=>{const t=()=>{const t=Mm(e);if(null!=t.return){const e=t.return();null!=(n=e)&&"function"==typeof n.then&&e.catch((e=>{this.log?.("could not cause sink source to return",e)}))}var n};let n,r;try{const r=new ob(e);try{this.closeController.signal.addEventListener("abort",t);for await(const e of r.emitFrames())await this.handleFrame(e.header,e.readData)}finally{this.closeController.signal.removeEventListener("abort",t)}n=sb.NormalTermination}catch(e){const t=e.code;Qw.has(t)?(this.log?.error("protocol error in sink",e),n=sb.ProtocolError):(this.log?.error("internal error in sink",e),n=sb.InternalError),r=e}this.log?.trace("muxer sink ended"),null!=r?this.abort(r,n):await this.close({reason:n})},this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log?.trace("muxer created"),this.config.enableKeepAlive&&this.keepAliveLoop().catch((e=>this.log?.error("keepalive error: %s",e))),this.ping().catch((e=>this.log?.error("ping error: %s",e)))}get streams(){return Array.from(this._streams.values())}newStream(e){if(void 0!==this.remoteGoAway)throw new pn("muxer closed remotely",Xw);if(void 0!==this.localGoAway)throw new pn("muxer closed locally",Zw);const t=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.config.maxOutboundStreams)throw new pn("max outbound streams exceeded","ERROR_MAX_OUTBOUND_STREAMS_EXCEEDED");this.log?.trace("new outgoing stream id=%s",t);const n=this._newStream(t,e,ub.Init,"outbound");return this._streams.set(t,n),this.numOutboundStreams++,n.sendWindowUpdate(),n}async ping(){if(void 0!==this.remoteGoAway)throw new pn("muxer closed remotely",Xw);if(void 0!==this.localGoAway)throw new pn("muxer closed locally",Zw);if(void 0===this.activePing){let e=()=>{};this.activePing={id:this.nextPingID++,promise:new Promise(((t,n)=>{const r=()=>{n(new pn("muxer closed locally",Zw))};this.closeController.signal.addEventListener("abort",r,{once:!0}),e=()=>{this.closeController.signal.removeEventListener("abort",r),t()}})),resolve:e};const t=Date.now();this.sendPing(this.activePing.id);try{await this.activePing.promise}finally{delete this.activePing}const n=Date.now();this.rtt=n-t}else await this.activePing.promise;return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.closeController.signal.aborted)return;const t=e?.reason??sb.NormalTermination;if(this.log?.trace("muxer close reason=%s",t),null==e.signal){const t=AbortSignal.timeout(500);e={...e,signal:t}}try{await Promise.all([...this._streams.values()].map((async t=>t.close(e)))),this.sendGoAway(t),this._closeMuxer()}catch(e){this.abort(e)}}abort(e,t){if(!this.closeController.signal.aborted){t=t??sb.InternalError,this.log?.error("muxer abort reason=%s error=%s",t,e);for(const t of this._streams.values())t.abort(e);this.sendGoAway(t),this._closeMuxer()}}isClosed(){return this.closeController.signal.aborted}_closeMuxer(){this.closeController.abort(),this.source.end()}_newStream(e,t,n,r){if(null!=this._streams.get(e))throw new pn("Stream already exists",Ww,{id:e});const s=new hb({id:e.toString(),name:t,state:n,direction:r,sendFrame:this.sendFrame.bind(this),onEnd:()=>{this.closeStream(e),this.onStreamEnd?.(s)},log:this.logger.forComponent(`libp2p:yamux:${r}:${e}`),config:this.config,getRTT:this.getRTT.bind(this)});return s}closeStream(e){this.client===(e%2==0)?this.numInboundStreams--:this.numOutboundStreams--,this._streams.delete(e)}async keepAliveLoop(){const e=new Promise(((e,t)=>{this.closeController.signal.addEventListener("abort",t,{once:!0})}));for(this.log?.trace("muxer keepalive enabled interval=%s",this.config.keepAliveInterval);;){let t;try{await Promise.race([e,new Promise((e=>{t=setTimeout(e,this.config.keepAliveInterval)}))]),this.ping().catch((e=>this.log?.error("ping error: %s",e)))}catch(e){return void clearInterval(t)}}}async handleFrame(e,t){const{streamID:n,type:r,length:s}=e;if(this.log?.trace("received frame %o",e),0===n)switch(r){case nb.Ping:return void this.handlePing(e);case nb.GoAway:return void this.handleGoAway(s);default:throw new pn("Invalid frame type",qw,{header:e})}else switch(e.type){case nb.Data:case nb.WindowUpdate:return void await this.handleStreamMessage(e,t);default:throw new pn("Invalid frame type",qw,{header:e})}}handlePing(e){if(e.flag===rb.SYN)this.log?.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,rb.ACK);else{if(e.flag!==rb.ACK)throw new pn("Invalid frame flag",qw,{header:e});this.log?.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length)}}handlePingResponse(e){if(void 0===this.activePing)throw new pn("ping not requested",Hw);if(this.activePing.id!==e)throw new pn("ping doesn't match our id",zw);this.activePing.resolve()}handleGoAway(e){this.log?.trace("received GoAway reason=%s",sb[e]??"unknown"),this.remoteGoAway=e;for(const e of this._streams.values())e.reset();this._closeMuxer()}async handleStreamMessage(e,t){const{streamID:n,flag:r,type:s}=e;(r&rb.SYN)===rb.SYN&&this.incomingStream(n);const i=this._streams.get(n);if(void 0!==i)switch(s){case nb.WindowUpdate:return void i.handleWindowUpdate(e);case nb.Data:if(void 0===t)throw new Error("unreachable");return void await i.handleData(e,t);default:throw new Error("unreachable")}else if(s===nb.Data){if(this.log?.("discarding data for stream id=%s",n),void 0===t)throw new Error("unreachable");await t()}else this.log?.("frame for missing stream id=%s",n)}incomingStream(e){if(this.client!==(e%2==0))throw new pn("both endpoints are clients",Gw);if(this._streams.has(e))return;if(this.log?.trace("new incoming stream id=%s",e),void 0!==this.localGoAway)return void this.sendFrame({type:nb.WindowUpdate,flag:rb.RST,streamID:e,length:0});if(this.numInboundStreams>=this.config.maxInboundStreams)return this.log?.("maxIncomingStreams exceeded, forcing stream reset"),void this.sendFrame({type:nb.WindowUpdate,flag:rb.RST,streamID:e,length:0});const t=this._newStream(e,void 0,ub.SYNReceived,"inbound");this.numInboundStreams++,this._streams.set(e,t),this.onIncomingStream?.(t)}sendFrame(e,t){if(this.log?.trace("sending frame %o",e),e.type===nb.Data){if(void 0===t)throw new pn("invalid frame",qw);this.source.push(new _r(ab(e),t))}else this.source.push(ab(e))}sendPing(e,t=rb.SYN){t===rb.SYN?this.log?.trace("sending ping request pingId=%s",e):this.log?.trace("sending ping response pingId=%s",e),this.sendFrame({type:nb.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=sb.NormalTermination){this.log?.("sending GoAway reason=%s",sb[e]),this.localGoAway=e,this.sendFrame({type:nb.GoAway,flag:0,streamID:0,length:e})}}function gb(e={}){return t=>new pb(t,e)}function mb(e=0){return null!=globalThis.Buffer?.alloc?(t=globalThis.Buffer.alloc(e),null!=globalThis.Buffer?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t):new Uint8Array(e);var t}var yb;!function(e){let t;e.codec=()=>(null==t&&(t=Wt(((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.publicKey&&e.publicKey.byteLength>0&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.addrs)for(const n of e.addrs)t.uint32(18),t.bytes(n);!1!==n.lengthDelimited&&t.ldelim()}),((e,t)=>{const n={publicKey:mb(0),addrs:[]},r=null==t?e.len:e.pos+t;for(;e.pos<r;){const t=e.uint32();switch(t>>>3){case 1:n.publicKey=e.bytes();break;case 2:n.addrs.push(e.bytes());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>$t(t,e.codec()),e.decode=t=>j(t,e.codec())}(yb||(yb={}));class wb extends yn{[nn]=!0;[Symbol.toStringTag]="@libp2p/pubsub-peer-discovery";interval;listenOnly;topics;intervalId;components;log;constructor(e,t={}){super();const{interval:n,topics:r,listenOnly:s}=t;this.components=e,this.interval=n??1e4,this.listenOnly=s??!1,this.log=e.logger.forComponent("libp2p:discovery:pubsub"),Array.isArray(r)&&r.length>0?this.topics=r:this.topics=["_peer-discovery._p2p._pubsub"],this._onMessage=this._onMessage.bind(this)}isStarted(){return null!=this.intervalId}start(){}afterStart(){if(null!=this.intervalId)return;const e=this.components.pubsub;if(null==e)throw new Error("PubSub not configured");for(const t of this.topics)e.subscribe(t),e.addEventListener("message",this._onMessage);this.listenOnly||(this._broadcast(),this.intervalId=setInterval((()=>{this._broadcast()}),this.interval))}beforeStop(){const e=this.components.pubsub;if(null==e)throw new Error("PubSub not configured");for(const t of this.topics)e.unsubscribe(t),e.removeEventListener("message",this._onMessage)}stop(){null!=this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0)}_broadcast(){const e=this.components.peerId;if(null==e.publicKey)throw new Error("PeerId was missing public key");const t={publicKey:e.publicKey,addrs:this.components.addressManager.getAddresses().map((e=>e.bytes))},n=yb.encode(t),r=this.components.pubsub;if(null==r)throw new Error("PubSub not configured");for(const e of this.topics)0!==r.getSubscribers(e).length?(this.log("broadcasting our peer data on topic %s",e),r.publish(e,n)):this.log("skipping broadcasting our peer data on topic %s because there are no peers present",e)}_onMessage(e){if(!this.isStarted())return;const t=e.detail;if(!this.topics.includes(t.topic))return;const n=yb.decode(t.data);As(n.publicKey).then((e=>{e.equals(this.components.peerId)||(this.log("discovered peer %p on %s",e,t.topic),this.safeDispatchEvent("peer",{detail:{id:e,multiaddrs:n.addrs.map((e=>ar(e)))}}))})).catch((e=>{this.log.error(e)}))}}function bb(e={}){return t=>new wb(t,e)}const vb="circuit-relay-relay";BigInt(1<<17);const Eb="/libp2p/circuit/relay/0.2.0/hop",Sb="/libp2p/circuit/relay/0.2.0/stop",_b="ERR_RELAYED_DIAL";var Ib,Rb,Ab,Tb,kb,Db,Pb,Cb;function xb(e){const t=e*BigInt(1e3),n=(new Date).getTime();return Number(t-BigInt(n))}!function(e){let t,n;!function(e){e.RESERVE="RESERVE",e.CONNECT="CONNECT",e.STATUS="STATUS"}(e.Type||(e.Type={})),function(e){e[e.RESERVE=0]="RESERVE",e[e.CONNECT=1]="CONNECT",e[e.STATUS=2]="STATUS"}(t||(t={})),function(e){e.codec=()=>zt(t)}(e.Type||(e.Type={})),e.codec=()=>(null==n&&(n=Wt(((t,n,r={})=>{!1!==r.lengthDelimited&&n.fork(),null!=t.type&&(n.uint32(8),e.Type.codec().encode(t.type,n)),null!=t.peer&&(n.uint32(18),Ab.codec().encode(t.peer,n)),null!=t.reservation&&(n.uint32(26),Tb.codec().encode(t.reservation,n)),null!=t.limit&&(n.uint32(34),kb.codec().encode(t.limit,n)),null!=t.status&&(n.uint32(40),Db.codec().encode(t.status,n)),!1!==r.lengthDelimited&&n.ldelim()}),((t,n)=>{const r={},s=null==n?t.len:t.pos+n;for(;t.pos<s;){const n=t.uint32();switch(n>>>3){case 1:r.type=e.Type.codec().decode(t);break;case 2:r.peer=Ab.codec().decode(t,t.uint32());break;case 3:r.reservation=Tb.codec().decode(t,t.uint32());break;case 4:r.limit=kb.codec().decode(t,t.uint32());break;case 5:r.status=Db.codec().decode(t);break;default:t.skipType(7&n)}}return r}))),n),e.encode=t=>$t(t,e.codec()),e.decode=t=>j(t,e.codec())}(Ib||(Ib={})),function(e){let t,n;!function(e){e.CONNECT="CONNECT",e.STATUS="STATUS"}(e.Type||(e.Type={})),function(e){e[e.CONNECT=0]="CONNECT",e[e.STATUS=1]="STATUS"}(t||(t={})),function(e){e.codec=()=>zt(t)}(e.Type||(e.Type={})),e.codec=()=>(null==n&&(n=Wt(((t,n,r={})=>{!1!==r.lengthDelimited&&n.fork(),null!=t.type&&(n.uint32(8),e.Type.codec().encode(t.type,n)),null!=t.peer&&(n.uint32(18),Ab.codec().encode(t.peer,n)),null!=t.limit&&(n.uint32(26),kb.codec().encode(t.limit,n)),null!=t.status&&(n.uint32(32),Db.codec().encode(t.status,n)),!1!==r.lengthDelimited&&n.ldelim()}),((t,n)=>{const r={},s=null==n?t.len:t.pos+n;for(;t.pos<s;){const n=t.uint32();switch(n>>>3){case 1:r.type=e.Type.codec().decode(t);break;case 2:r.peer=Ab.codec().decode(t,t.uint32());break;case 3:r.limit=kb.codec().decode(t,t.uint32());break;case 4:r.status=Db.codec().decode(t);break;default:t.skipType(7&n)}}return r}))),n),e.encode=t=>$t(t,e.codec()),e.decode=t=>j(t,e.codec())}(Rb||(Rb={})),function(e){let t;e.codec=()=>(null==t&&(t=Wt(((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.id&&e.id.byteLength>0&&(t.uint32(10),t.bytes(e.id)),null!=e.addrs)for(const n of e.addrs)t.uint32(18),t.bytes(n);!1!==n.lengthDelimited&&t.ldelim()}),((e,t)=>{const n={id:new Uint8Array(0),addrs:[]},r=null==t?e.len:e.pos+t;for(;e.pos<r;){const t=e.uint32();switch(t>>>3){case 1:n.id=e.bytes();break;case 2:n.addrs.push(e.bytes());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>$t(t,e.codec()),e.decode=t=>j(t,e.codec())}(Ab||(Ab={})),function(e){let t;e.codec=()=>(null==t&&(t=Wt(((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.expire&&0n!==e.expire&&(t.uint32(8),t.uint64(e.expire)),null!=e.addrs)for(const n of e.addrs)t.uint32(18),t.bytes(n);null!=e.voucher&&(t.uint32(26),t.bytes(e.voucher)),!1!==n.lengthDelimited&&t.ldelim()}),((e,t)=>{const n={expire:0n,addrs:[]},r=null==t?e.len:e.pos+t;for(;e.pos<r;){const t=e.uint32();switch(t>>>3){case 1:n.expire=e.uint64();break;case 2:n.addrs.push(e.bytes());break;case 3:n.voucher=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>$t(t,e.codec()),e.decode=t=>j(t,e.codec())}(Tb||(Tb={})),function(e){let t;e.codec=()=>(null==t&&(t=Wt(((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.duration&&(t.uint32(8),t.uint32(e.duration)),null!=e.data&&(t.uint32(16),t.uint64(e.data)),!1!==n.lengthDelimited&&t.ldelim()}),((e,t)=>{const n={},r=null==t?e.len:e.pos+t;for(;e.pos<r;){const t=e.uint32();switch(t>>>3){case 1:n.duration=e.uint32();break;case 2:n.data=e.uint64();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>$t(t,e.codec()),e.decode=t=>j(t,e.codec())}(kb||(kb={})),function(e){e.UNUSED="UNUSED",e.OK="OK",e.RESERVATION_REFUSED="RESERVATION_REFUSED",e.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",e.PERMISSION_DENIED="PERMISSION_DENIED",e.CONNECTION_FAILED="CONNECTION_FAILED",e.NO_RESERVATION="NO_RESERVATION",e.MALFORMED_MESSAGE="MALFORMED_MESSAGE",e.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"}(Db||(Db={})),function(e){e[e.UNUSED=0]="UNUSED",e[e.OK=100]="OK",e[e.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",e[e.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",e[e.PERMISSION_DENIED=202]="PERMISSION_DENIED",e[e.CONNECTION_FAILED=203]="CONNECTION_FAILED",e[e.NO_RESERVATION=204]="NO_RESERVATION",e[e.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",e[e.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"}(Pb||(Pb={})),function(e){e.codec=()=>zt(Pb)}(Db||(Db={})),function(e){let t;e.codec=()=>(null==t&&(t=Wt(((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.relay&&e.relay.byteLength>0&&(t.uint32(10),t.bytes(e.relay)),null!=e.peer&&e.peer.byteLength>0&&(t.uint32(18),t.bytes(e.peer)),null!=e.expiration&&0n!==e.expiration&&(t.uint32(24),t.uint64(e.expiration)),!1!==n.lengthDelimited&&t.ldelim()}),((e,t)=>{const n={relay:new Uint8Array(0),peer:new Uint8Array(0),expiration:0n},r=null==t?e.len:e.pos+t;for(;e.pos<r;){const t=e.uint32();switch(t>>>3){case 1:n.relay=e.bytes();break;case 2:n.peer=e.bytes();break;case 3:n.expiration=e.uint64();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>$t(t,e.codec()),e.decode=t=>j(t,e.codec())}(Cb||(Cb={}));class Nb extends yn{peerId;peerStore;contentRouting;registrar;started;topologyId;log;constructor(e){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.contentRouting=e.contentRouting,this.registrar=e.registrar}isStarted(){return this.started}async start(){this.topologyId=await this.registrar.register(Eb,{notifyOnTransient:!0,onConnect:e=>{this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}afterStart(){this.discover().catch((e=>{this.log.error("error discovering relays",e)}))}stop(){null!=this.topologyId&&this.registrar.unregister(this.topologyId),this.started=!1}async discover(){this.log("searching peer store for relays");const e=await this.peerStore.all({filters:[e=>e.protocols.includes(Eb)],orders:[()=>Math.random()<.5?1:-1]});for(const t of e)this.log("found relay peer %p in content peer store",t.id),this.safeDispatchEvent("relay:discover",{detail:t.id});this.log("found %d relay peers in peer store",e.length);try{this.log("searching content routing for relays");const e=await async function(e){const t=(new TextEncoder).encode(e),n=await ft.digest(t);return wt.createV0(n)}("/libp2p/relay");let t=0;for await(const n of this.contentRouting.findProviders(e))if(n.multiaddrs.length>0&&!n.id.equals(this.peerId)){const e=n.id;t++,await this.peerStore.merge(e,{multiaddrs:n.multiaddrs}),this.log("found relay peer %p in content routing",e),this.safeDispatchEvent("relay:discover",{detail:e})}this.log("found %d relay peers in content routing",t)}catch(e){this.log.error("failed when finding relays on the network",e)}}}class Mb extends yn{peerId;connectionManager;transportManager;peerStore;events;reserveQueue;reservations;maxDiscoveredRelays;maxReservationQueueLength;reservationCompletionTimeout;started;log;constructor(e,t){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new zh,this.maxDiscoveredRelays=t?.discoverRelays??0,this.maxReservationQueueLength=t?.maxReservationQueueLength??100,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??1e4,this.started=!1,this.reserveQueue=new vf({concurrency:t?.reservationConcurrency??1,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("peer:disconnect",(e=>{this.#B(e.detail)}))}isStarted(){return this.started}start(){this.started=!0}stop(){this.reserveQueue.clear(),this.reservations.forEach((({timeout:e})=>{clearTimeout(e)})),this.reservations.clear(),this.started=!1}async addRelay(e,t){this.peerId.equals(e)?this.log("not trying to use self as relay"):this.reserveQueue.size>this.maxReservationQueueLength?this.log("not adding relay as the queue is full"):this.reserveQueue.has(e)?this.log("relay peer is already in the reservation queue"):(this.log("add relay %p",e),await this.reserveQueue.add((async()=>{try{const n=this.reservations.get(e);if(null!=n){if(xb(n.reservation.expire)>6e5)return void this.log("already have reservation on relay peer %p and it expires in more than 10 minutes",e);clearTimeout(n.timeout),this.reservations.delete(e)}if("discovered"===t&&[...this.reservations.values()].reduce(((e,t)=>("discovered"===t.type&&e++,e)),0)>=this.maxDiscoveredRelays)return void this.log("already have enough discovered relays");const r=AbortSignal.timeout(this.reservationCompletionTimeout),s=await this.connectionManager.openConnection(e,{signal:r});if(s.remoteAddr.protoNames().includes("p2p-circuit"))return void this.log("not creating reservation over relayed connection");const i=await this.#U(s,{signal:r});this.log("created reservation on relay peer %p",e);const o=xb(i.expire),a=Math.min(Math.max(o-3e5,3e4),Math.pow(2,31)-1),c=setTimeout((()=>{this.addRelay(e,t).catch((t=>{this.log.error("could not refresh reservation to relay %p",e,t)}))}),a);this.reservations.set(e,{timeout:c,reservation:i,type:t}),await this.peerStore.merge(e,{tags:{[vb]:{value:1,ttl:o}}}),await this.transportManager.listen([ar(`/p2p/${e.toString()}/p2p-circuit`)])}catch(t){this.log.error("could not reserve slot on %p",e,t);const n=this.reservations.get(e);null!=n&&clearTimeout(n.timeout),this.reservations.delete(e)}}),{peerId:e}))}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}async#U(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);const n=await e.newStream(Eb,t),r=Rw(n).pb(Ib);let s;await r.write({type:Ib.Type.RESERVE},t);try{s=await r.read(t)}catch(t){throw this.log.error("error parsing reserve message response from %p because",e.remotePeer,t),n.abort(t),t}finally{await n.close()}if(s.status===Db.OK&&null!=s.reservation){let t=!1;const n=e.remoteAddr.bytes;for(const e of s.reservation.addrs)if(_n(n,e)){t=!0;break}return t||s.reservation.addrs.push(n),s.reservation}const i=`reservation failed with status ${s.status??"undefined"}`;throw this.log.error(i),new Error(i)}#B(e){const t=this.reservations.get(e);null!=t&&(this.log("connection to relay %p closed, removing reservation from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),this.safeDispatchEvent("relay:removed",{detail:e}),this.reservations.size<this.maxDiscoveredRelays&&(this.log("not enough relays %d/%d",this.reservations.size,this.maxDiscoveredRelays),this.safeDispatchEvent("relay:not-enough-relays",{})))}}function Ob(e){const{stream:t,remoteAddr:n,logger:r}=e,s=r.forComponent("libp2p:stream:converter");let i=!1,o=!1;const a=t.close.bind(t);t.close=async e=>{await a(e),h(!0)};const c=t.abort.bind(t);t.abort=e=>{c(e),h(!0)};const l=t.sink.bind(t);t.sink=async e=>{try{await l(e)}catch(e){"aborted"!==e.type&&s.error("%s error in sink",n,e)}finally{o=!0,h()}};const u={log:s,sink:t.sink,source:async function*(){try{for await(const e of t.source)e instanceof Uint8Array?yield e:yield*e}finally{i=!0,h()}}(),remoteAddr:n,timeline:{open:Date.now(),close:void 0},close:t.close,abort:t.abort};function h(e){!0===e&&(i=!0,o=!0),i&&o&&null==u.timeline.close&&(u.timeline.close=Date.now())}return u}class Lb extends yn{connectionManager;relayStore;listeningAddrs;log;constructor(e){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.relayStore=e.relayStore,this.listeningAddrs=new zh,this.relayStore.addEventListener("relay:removed",this._onRemoveRelayPeer)}_onRemoveRelayPeer=e=>{this.#F(e.detail)};async listen(e){this.log("listen on %a",e);const t=e.decapsulate("/p2p-circuit"),n=await this.connectionManager.openConnection(t);if(!this.relayStore.hasReservation(n.remotePeer))return this.log("making reservation on peer %p",n.remotePeer),void await this.relayStore.addRelay(n.remotePeer,"configured");const r=this.relayStore.getReservation(n.remotePeer);if(null==r)throw new pn("Did not have reservation after making reservation","ERR_NO_RESERVATION");this.listeningAddrs.has(n.remotePeer)?this.log("already listening on relay %p",n.remotePeer):(this.listeningAddrs.set(n.remotePeer,r.addrs.map((e=>ar(e).encapsulate("/p2p-circuit")))),this.safeDispatchEvent("listening",{}))}getAddrs(){return[...this.listeningAddrs.values()].flat()}async close(){}#F(e){const t=this.listeningAddrs.has(e);this.log("relay peer removed %p - had reservation",e,t),this.listeningAddrs.delete(e),t&&(this.log.trace("removing relay event listener for peer %p",e),this.relayStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),this.safeDispatchEvent("close",{}))}}const Bb=300,Ub=300,Fb=3e4;class Vb{discovery;registrar;peerStore;connectionManager;transportManager;peerId;upgrader;addressManager;connectionGater;reservationStore;logger;maxInboundStopStreams;maxOutboundStopStreams;stopTimeout;started;log;constructor(e,t){this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.registrar=e.registrar,this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.logger=e.logger,this.peerId=e.peerId,this.upgrader=e.upgrader,this.addressManager=e.addressManager,this.connectionGater=e.connectionGater,this.maxInboundStopStreams=t.maxInboundStopStreams??Bb,this.maxOutboundStopStreams=t.maxOutboundStopStreams??Ub,this.stopTimeout=t.stopTimeout??Fb,null!=t.discoverRelays&&t.discoverRelays>0&&(this.discovery=new Nb(e),this.discovery.addEventListener("relay:discover",(e=>{this.reservationStore.addRelay(e.detail,"discovered").catch((t=>{this.log.error("could not add discovered relay %p",e.detail,t)}))}))),this.reservationStore=new Mb(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",(()=>{this.discovery?.discover().catch((e=>{this.log.error("could not discover relays",e)}))})),this.started=!1}isStarted(){return this.started}async start(){this.reservationStore.start(),await this.registrar.handle(Sb,(e=>{this.onStop(e).catch((t=>{this.log.error("error while handling STOP protocol",t),e.stream.abort(t)}))}),{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnTransientConnection:!0}),await(this.discovery?.start()),this.started=!0}afterStart(){this.discovery?.afterStart()}async stop(){this.discovery?.stop(),this.reservationStore.stop(),await this.registrar.unhandle(Sb),this.started=!1}[un]=!0;[Symbol.toStringTag]="libp2p/circuit-relay-v2";async dial(e,t={}){if(1!==e.protoCodes().filter((e=>290===e)).length){const t="Invalid circuit relay address";throw this.log.error(t,e),new pn(t,_b)}const n=e.toString().split("/p2p-circuit"),r=ar(n[0]),s=ar(n[n.length-1]),i=r.getPeerId(),o=s.getPeerId();if(null==i||null==o){const t=`Circuit relay dial to ${e.toString()} failed as address did not have peer ids`;throw this.log.error(t),new pn(t,_b)}const a=Is(i),c=Is(o);let l=!1;let u,h=this.connectionManager.getConnections(a)[0];null==h&&(await this.peerStore.merge(a,{multiaddrs:[r]}),h=await this.connectionManager.openConnection(a,t),l=!0);try{return u=await h.newStream(Eb),await this.connectV2({stream:u,connection:h,destinationPeer:c,destinationAddr:s,relayAddr:r,ma:e,disconnectOnFailure:l})}catch(e){throw this.log.error("circuit relay dial to destination %p via relay %p failed",c,a,e),null!=u&&u.abort(e),l&&await h.close(),e}}async connectV2({stream:e,connection:t,destinationPeer:n,destinationAddr:r,relayAddr:s,ma:i,disconnectOnFailure:o}){try{const t=Rw(e),o=t.pb(Ib);await o.write({type:Ib.Type.CONNECT,peer:{id:n.toBytes(),addrs:[ar(r).bytes]}});const a=await o.read();if(a.status!==Db.OK)throw new pn(`failed to connect via relay with status ${a?.status?.toString()??"undefined"}`,"ERR_HOP_REQUEST_FAILED");const c=Ob({stream:t.unwrap(),remoteAddr:i,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`),logger:this.logger});return this.log("new outbound transient connection %a",c.remoteAddr),await this.upgrader.upgradeOutbound(c,{transient:!0})}catch(e){throw this.log.error(`Circuit relay dial to destination ${n.toString()} via relay ${t.remotePeer.toString()} failed`,e),o&&await t.close(),e}}createListener(e){return function(e){return new Lb(e)}({connectionManager:this.connectionManager,relayStore:this.reservationStore,logger:this.logger})}listenFilter(e){return(e=Array.isArray(e)?e:[e]).filter((e=>zy.matches(e)))}dialFilter(e){return this.listenFilter(e)}async onStop({connection:e,stream:t}){if(!this.reservationStore.hasReservation(e.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.transportManager.listen([e.remoteAddr.encapsulate("/p2p-circuit")])}catch(e){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on",e)}const n=AbortSignal.timeout(this.stopTimeout),r=Rw(t).pb(Rb),s=await r.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",e.remotePeer,s.type),void 0===s?.type)return this.log.error("type was missing from circuit v2 stop protocol request from %s",e.remotePeer),await r.write({type:Rb.Type.STATUS,status:Db.MALFORMED_MESSAGE},{signal:n}),void await t.close();if(s.type!==Rb.Type.CONNECT)return this.log.error("invalid stop connect request via peer %p",e.remotePeer),await r.write({type:Rb.Type.STATUS,status:Db.UNEXPECTED_MESSAGE},{signal:n}),void await t.close();if(!(e=>{if(null==e.peer)return!1;try{e.peer.addrs.forEach(ar)}catch{return!1}return!0})(s))return this.log.error("invalid stop connect request via peer %p",e.remotePeer),await r.write({type:Rb.Type.STATUS,status:Db.MALFORMED_MESSAGE},{signal:n}),void await t.close();const i=Rs(s.peer.id);if(!0===await(this.connectionGater.denyInboundRelayedConnection?.(e.remotePeer,i)))return this.log.error("connection gater denied inbound relayed connection from %p",e.remotePeer),await r.write({type:Rb.Type.STATUS,status:Db.PERMISSION_DENIED},{signal:n}),void await t.close();this.log.trace("sending success response to %p",e.remotePeer),await r.write({type:Rb.Type.STATUS,status:Db.OK},{signal:n});const o=e.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),a=this.addressManager.getAddresses()[0],c=Ob({stream:r.unwrap().unwrap(),remoteAddr:o,localAddr:a,logger:this.logger});this.log("new inbound transient connection %a",c.remoteAddr),await this.upgrader.upgradeInbound(c,{transient:!0}),this.log("%s connection %a upgraded","inbound",c.remoteAddr)}}function Kb(e={}){return t=>new Vb(t,e)}const $b="/floodsub/1.0.0",qb="/meshsub/1.0.0",Hb="/meshsub/1.1.0",zb=5e3,Wb={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};var jb,Gb,Yb,Qb,Jb,Zb,Xb,ev,tv,nv,rv,sv;!function(e){let t;!function(e){let t;e.codec=()=>(null==t&&(t=Wt(((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.subscribe&&(t.uint32(8),t.bool(e.subscribe)),null!=e.topic&&(t.uint32(18),t.string(e.topic)),!1!==n.lengthDelimited&&t.ldelim()}),((e,t,n={})=>{const r={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:r.subscribe=e.bool();break;case 2:r.topic=e.string();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,n)=>j(t,e.codec(),n)}(e.SubOpts||(e.SubOpts={})),function(e){let t;e.codec=()=>(null==t&&(t=Wt(((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.from&&(t.uint32(10),t.bytes(e.from)),null!=e.data&&(t.uint32(18),t.bytes(e.data)),null!=e.seqno&&(t.uint32(26),t.bytes(e.seqno)),null!=e.topic&&""!==e.topic&&(t.uint32(34),t.string(e.topic)),null!=e.signature&&(t.uint32(42),t.bytes(e.signature)),null!=e.key&&(t.uint32(50),t.bytes(e.key)),!1!==n.lengthDelimited&&t.ldelim()}),((e,t,n={})=>{const r={topic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:r.from=e.bytes();break;case 2:r.data=e.bytes();break;case 3:r.seqno=e.bytes();break;case 4:r.topic=e.string();break;case 5:r.signature=e.bytes();break;case 6:r.key=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,n)=>j(t,e.codec(),n)}(e.Message||(e.Message={})),function(t){let n;t.codec=()=>(null==n&&(n=Wt(((t,n,r={})=>{if(!1!==r.lengthDelimited&&n.fork(),null!=t.ihave)for(const r of t.ihave)n.uint32(10),e.ControlIHave.codec().encode(r,n);if(null!=t.iwant)for(const r of t.iwant)n.uint32(18),e.ControlIWant.codec().encode(r,n);if(null!=t.graft)for(const r of t.graft)n.uint32(26),e.ControlGraft.codec().encode(r,n);if(null!=t.prune)for(const r of t.prune)n.uint32(34),e.ControlPrune.codec().encode(r,n);!1!==r.lengthDelimited&&n.ldelim()}),((t,n,r={})=>{const s={ihave:[],iwant:[],graft:[],prune:[]},i=null==n?t.len:t.pos+n;for(;t.pos<i;){const n=t.uint32();switch(n>>>3){case 1:if(null!=r.limits?.ihave&&s.ihave.length===r.limits.ihave)throw new jt('decode error - map field "ihave" had too many elements',"ERR_MAX_LENGTH");s.ihave.push(e.ControlIHave.codec().decode(t,t.uint32()));break;case 2:if(null!=r.limits?.iwant&&s.iwant.length===r.limits.iwant)throw new jt('decode error - map field "iwant" had too many elements',"ERR_MAX_LENGTH");s.iwant.push(e.ControlIWant.codec().decode(t,t.uint32()));break;case 3:if(null!=r.limits?.graft&&s.graft.length===r.limits.graft)throw new jt('decode error - map field "graft" had too many elements',"ERR_MAX_LENGTH");s.graft.push(e.ControlGraft.codec().decode(t,t.uint32()));break;case 4:if(null!=r.limits?.prune&&s.prune.length===r.limits.prune)throw new jt('decode error - map field "prune" had too many elements',"ERR_MAX_LENGTH");s.prune.push(e.ControlPrune.codec().decode(t,t.uint32()));break;default:t.skipType(7&n)}}return s}))),n),t.encode=e=>$t(e,t.codec()),t.decode=(e,n)=>j(e,t.codec(),n)}(e.ControlMessage||(e.ControlMessage={})),function(e){let t;e.codec=()=>(null==t&&(t=Wt(((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.topicID&&(t.uint32(10),t.string(e.topicID)),null!=e.messageIDs)for(const n of e.messageIDs)t.uint32(18),t.bytes(n);!1!==n.lengthDelimited&&t.ldelim()}),((e,t,n={})=>{const r={messageIDs:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:r.topicID=e.string();break;case 2:if(null!=n.limits?.messageIDs&&r.messageIDs.length===n.limits.messageIDs)throw new jt('decode error - map field "messageIDs" had too many elements',"ERR_MAX_LENGTH");r.messageIDs.push(e.bytes());break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,n)=>j(t,e.codec(),n)}(e.ControlIHave||(e.ControlIHave={})),function(e){let t;e.codec=()=>(null==t&&(t=Wt(((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.messageIDs)for(const n of e.messageIDs)t.uint32(10),t.bytes(n);!1!==n.lengthDelimited&&t.ldelim()}),((e,t,n={})=>{const r={messageIDs:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();if(t>>>3==1){if(null!=n.limits?.messageIDs&&r.messageIDs.length===n.limits.messageIDs)throw new jt('decode error - map field "messageIDs" had too many elements',"ERR_MAX_LENGTH");r.messageIDs.push(e.bytes())}else e.skipType(7&t)}return r}))),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,n)=>j(t,e.codec(),n)}(e.ControlIWant||(e.ControlIWant={})),function(e){let t;e.codec=()=>(null==t&&(t=Wt(((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.topicID&&(t.uint32(10),t.string(e.topicID)),!1!==n.lengthDelimited&&t.ldelim()}),((e,t,n={})=>{const r={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();if(t>>>3==1)r.topicID=e.string();else e.skipType(7&t)}return r}))),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,n)=>j(t,e.codec(),n)}(e.ControlGraft||(e.ControlGraft={})),function(t){let n;t.codec=()=>(null==n&&(n=Wt(((t,n,r={})=>{if(!1!==r.lengthDelimited&&n.fork(),null!=t.topicID&&(n.uint32(10),n.string(t.topicID)),null!=t.peers)for(const r of t.peers)n.uint32(18),e.PeerInfo.codec().encode(r,n);null!=t.backoff&&(n.uint32(24),n.uint64Number(t.backoff)),!1!==r.lengthDelimited&&n.ldelim()}),((t,n,r={})=>{const s={peers:[]},i=null==n?t.len:t.pos+n;for(;t.pos<i;){const n=t.uint32();switch(n>>>3){case 1:s.topicID=t.string();break;case 2:if(null!=r.limits?.peers&&s.peers.length===r.limits.peers)throw new jt('decode error - map field "peers" had too many elements',"ERR_MAX_LENGTH");s.peers.push(e.PeerInfo.codec().decode(t,t.uint32()));break;case 3:s.backoff=t.uint64Number();break;default:t.skipType(7&n)}}return s}))),n),t.encode=e=>$t(e,t.codec()),t.decode=(e,n)=>j(e,t.codec(),n)}(e.ControlPrune||(e.ControlPrune={})),function(e){let t;e.codec=()=>(null==t&&(t=Wt(((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.peerID&&(t.uint32(10),t.bytes(e.peerID)),null!=e.signedPeerRecord&&(t.uint32(18),t.bytes(e.signedPeerRecord)),!1!==n.lengthDelimited&&t.ldelim()}),((e,t,n={})=>{const r={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:r.peerID=e.bytes();break;case 2:r.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,n)=>j(t,e.codec(),n)}(e.PeerInfo||(e.PeerInfo={})),e.codec=()=>(null==t&&(t=Wt(((t,n,r={})=>{if(!1!==r.lengthDelimited&&n.fork(),null!=t.subscriptions)for(const r of t.subscriptions)n.uint32(10),e.SubOpts.codec().encode(r,n);if(null!=t.messages)for(const r of t.messages)n.uint32(18),e.Message.codec().encode(r,n);null!=t.control&&(n.uint32(26),e.ControlMessage.codec().encode(t.control,n)),!1!==r.lengthDelimited&&n.ldelim()}),((t,n,r={})=>{const s={subscriptions:[],messages:[]},i=null==n?t.len:t.pos+n;for(;t.pos<i;){const n=t.uint32();switch(n>>>3){case 1:if(null!=r.limits?.subscriptions&&s.subscriptions.length===r.limits.subscriptions)throw new jt('decode error - map field "subscriptions" had too many elements',"ERR_MAX_LENGTH");s.subscriptions.push(e.SubOpts.codec().decode(t,t.uint32()));break;case 2:if(null!=r.limits?.messages&&s.messages.length===r.limits.messages)throw new jt('decode error - map field "messages" had too many elements',"ERR_MAX_LENGTH");s.messages.push(e.Message.codec().decode(t,t.uint32()));break;case 3:s.control=e.ControlMessage.codec().decode(t,t.uint32());break;default:t.skipType(7&n)}}return s}))),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,n)=>j(t,e.codec(),n)}(jb||(jb={}));class iv{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,n){this.gossip=e,this.msgIdToStrFn=n;for(let e=0;e<t;e++)this.history[e]=[]}get size(){return this.msgs.size}put(e,t,n=!1){const{msgIdStr:r}=e;return!this.msgs.has(r)&&(this.msgs.set(r,{message:t,validated:n,originatingPeers:new Set,iwantCounts:new Map}),this.history[0].push({...e,topic:t.topic}),n||this.notValidatedCount++,!0)}observeDuplicate(e,t){const n=this.msgs.get(e);null==n||n.validated||n.originatingPeers.add(t)}get(e){return this.msgs.get(this.msgIdToStrFn(e))?.message}getWithIWantCount(e,t){const n=this.msgs.get(e);if(null==n)return null;const r=(n.iwantCounts.get(t)??0)+1;return n.iwantCounts.set(t,r),{msg:n.message,count:r}}getGossipIDs(e){const t=new Map;for(let n=0;n<this.gossip;n++)this.history[n].forEach((n=>{const r=this.msgs.get(n.msgIdStr);if(r?.validated&&e.has(n.topic)){let e=t.get(n.topic);null==e&&(e=[],t.set(n.topic,e)),e.push(n.msgId)}}));return t}validate(e){const t=this.msgs.get(e);if(null==t)return null;t.validated||this.notValidatedCount--;const{message:n,originatingPeers:r}=t;return t.validated=!0,t.originatingPeers=new Set,{message:n,originatingPeers:r}}shift(){this.history[this.history.length-1].forEach((e=>{const t=this.msgs.get(e.msgIdStr);null!=t&&(this.msgs.delete(e.msgIdStr),t.validated||this.notValidatedCount--)})),this.history.pop(),this.history.unshift([])}remove(e){const t=this.msgs.get(e);return null==t?null:(this.msgs.delete(e),t)}}function ov(e){switch(e){case ln.Ignore:return Qb.Ignore;case ln.Reject:return Qb.Reject;default:throw new Error("Unreachable")}}!function(e){e.StrictSign="StrictSign",e.StrictNoSign="StrictNoSign"}(Gb||(Gb={})),function(e){e[e.Signing=0]="Signing",e[e.Anonymous=1]="Anonymous"}(Yb||(Yb={})),function(e){e.Error="error",e.Ignore="ignore",e.Reject="reject",e.Blacklisted="blacklisted"}(Qb||(Qb={})),function(e){e.InvalidSignature="invalid_signature",e.InvalidSeqno="invalid_seqno",e.InvalidPeerId="invalid_peerid",e.SignaturePresent="signature_present",e.SeqnoPresent="seqno_present",e.FromPresent="from_present",e.TransformFailed="transform_failed"}(Jb||(Jb={})),function(e){e.duplicate="duplicate",e.invalid="invalid",e.valid="valid"}(Zb||(Zb={})),function(e){e.forward="forward",e.publish="publish"}(Xb||(Xb={})),function(e){e.Fanout="fanout",e.Random="random",e.Subscribed="subscribed",e.Outbound="outbound",e.NotEnough="not_enough",e.Opportunistic="opportunistic"}(ev||(ev={})),function(e){e.Dc="disconnected",e.BadScore="bad_score",e.Prune="prune",e.Excess="excess"}(tv||(tv={})),function(e){e.GraftBackoff="graft_backoff",e.BrokenPromise="broken_promise",e.MessageDeficit="message_deficit",e.IPColocation="IP_colocation"}(nv||(nv={})),function(e){e.LowScore="low_score",e.MaxIhave="max_ihave",e.MaxIasked="max_iasked"}(rv||(rv={})),function(e){e.graylist="graylist",e.publish="publish",e.gossip="gossip",e.mesh="mesh"}(sv||(sv={}));const av="ERR_INVALID_PEER_SCORE_PARAMS",cv={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:36e5},lv={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 uv(e={}){return{...cv,...e,topics:null!=e.topics?Object.entries(e.topics).reduce(((e,[t,n])=>(e[t]=function(e={}){return{...lv,...e}}(n),e)),{}):{}}}function hv(e){if(e.topicWeight<0)throw new pn("invalid topic weight; must be >= 0",av);if(0===e.timeInMeshQuantum)throw new pn("invalid TimeInMeshQuantum; must be non zero",av);if(e.timeInMeshWeight<0)throw new pn("invalid TimeInMeshWeight; must be positive (or 0 to disable)",av);if(0!==e.timeInMeshWeight&&e.timeInMeshQuantum<=0)throw new pn("invalid TimeInMeshQuantum; must be positive",av);if(0!==e.timeInMeshWeight&&e.timeInMeshCap<=0)throw new pn("invalid TimeInMeshCap; must be positive",av);if(e.firstMessageDeliveriesWeight<0)throw new pn("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)",av);if(0!==e.firstMessageDeliveriesWeight&&(e.firstMessageDeliveriesDecay<=0||e.firstMessageDeliveriesDecay>=1))throw new pn("invalid FirstMessageDeliveriesDecay; must be between 0 and 1",av);if(0!==e.firstMessageDeliveriesWeight&&e.firstMessageDeliveriesCap<=0)throw new pn("invalid FirstMessageDeliveriesCap; must be positive",av);if(e.meshMessageDeliveriesWeight>0)throw new pn("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)",av);if(0!==e.meshMessageDeliveriesWeight&&(e.meshMessageDeliveriesDecay<=0||e.meshMessageDeliveriesDecay>=1))throw new pn("invalid MeshMessageDeliveriesDecay; must be between 0 and 1",av);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesCap<=0)throw new pn("invalid MeshMessageDeliveriesCap; must be positive",av);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesThreshold<=0)throw new pn("invalid MeshMessageDeliveriesThreshold; must be positive",av);if(e.meshMessageDeliveriesWindow<0)throw new pn("invalid MeshMessageDeliveriesWindow; must be non-negative",av);if(0!==e.meshMessageDeliveriesWeight&&e.meshMessageDeliveriesActivation<1e3)throw new pn("invalid MeshMessageDeliveriesActivation; must be at least 1s",av);if(e.meshFailurePenaltyWeight>0)throw new pn("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)",av);if(0!==e.meshFailurePenaltyWeight&&(e.meshFailurePenaltyDecay<=0||e.meshFailurePenaltyDecay>=1))throw new pn("invalid MeshFailurePenaltyDecay; must be between 0 and 1",av);if(e.invalidMessageDeliveriesWeight>0)throw new pn("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)",av);if(e.invalidMessageDeliveriesDecay<=0||e.invalidMessageDeliveriesDecay>=1)throw new pn("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1",av)}const dv={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function pv(e={}){return{...dv,...e}}function fv(e,t,n=(()=>!0)){const r=new Set;if(t<=0)return r;for(const s of e){if(r.size>=t)break;n(s)&&(r.add(s),e.delete(s))}return r}class gv extends Map{getDefault;constructor(e){super(),this.getDefault=e}getOrDefault(e){let t=super.get(e);return void 0===t&&(t=this.getDefault(),this.set(e,t)),t}}function mv(e,t,n,r){let s=0;Object.entries(t.topics).forEach((([e,t])=>{const r=n.topics[e];if(void 0===r)return;let i=0;if(t.inMesh){let e=t.meshTime/r.timeInMeshQuantum;e>r.timeInMeshCap&&(e=r.timeInMeshCap),i+=e*r.timeInMeshWeight}let o=t.firstMessageDeliveries;if(o>r.firstMessageDeliveriesCap&&(o=r.firstMessageDeliveriesCap),i+=o*r.firstMessageDeliveriesWeight,t.meshMessageDeliveriesActive&&t.meshMessageDeliveries<r.meshMessageDeliveriesThreshold){const e=r.meshMessageDeliveriesThreshold-t.meshMessageDeliveries;i+=e*e*r.meshMessageDeliveriesWeight}i+=t.meshFailurePenalty*r.meshFailurePenaltyWeight;i+=t.invalidMessageDeliveries*t.invalidMessageDeliveries*r.invalidMessageDeliveriesWeight,s+=i*r.topicWeight})),n.topicScoreCap>0&&s>n.topicScoreCap&&(s=n.topicScoreCap);const i=n.appSpecificScore(e);if(s+=i*n.appSpecificWeight,t.knownIPs.forEach((e=>{if(n.IPColocationFactorWhitelist.has(e))return;const t=r.get(e),i=null!=t?t.size:0;if(i>n.IPColocationFactorThreshold){const e=i-n.IPColocationFactorThreshold;s+=e*e*n.IPColocationFactorWeight}})),t.behaviourPenalty>n.behaviourPenaltyThreshold){const e=t.behaviourPenalty-n.behaviourPenaltyThreshold;s+=e*e*n.behaviourPenaltyWeight}return s}function yv(e,t){t=t||{};this._capacity=t.capacity,this._head=0,this._tail=0,Array.isArray(e)?this._fromArray(e):(this._capacityMask=3,this._list=new Array(4))}yv.prototype.peekAt=function(e){var t=e;if(t===(0|t)){var n=this.size();if(!(t>=n||t<-n))return t<0&&(t+=n),t=this._head+t&this._capacityMask,this._list[t]}},yv.prototype.get=function(e){return this.peekAt(e)},yv.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]},yv.prototype.peekFront=function(){return this.peek()},yv.prototype.peekBack=function(){return this.peekAt(-1)},Object.defineProperty(yv.prototype,"length",{get:function(){return this.size()}}),yv.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)},yv.prototype.unshift=function(e){if(0===arguments.length)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)},yv.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}},yv.prototype.push=function(e){if(0===arguments.length)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)},yv.prototype.pop=function(){var e=this._tail;if(e!==this._head){var t=this._list.length;this._tail=e-1+t&this._capacityMask;var n=this._list[this._tail];return this._list[this._tail]=void 0,this._head<2&&e>1e4&&e<=t>>>2&&this._shrinkArray(),n}},yv.prototype.removeOne=function(e){var t=e;if(t===(0|t)&&this._head!==this._tail){var n=this.size(),r=this._list.length;if(!(t>=n||t<-n)){t<0&&(t+=n),t=this._head+t&this._capacityMask;var s,i=this._list[t];if(e<n/2){for(s=e;s>0;s--)this._list[t]=this._list[t=t-1+r&this._capacityMask];this._list[t]=void 0,this._head=this._head+1+r&this._capacityMask}else{for(s=n-1-e;s>0;s--)this._list[t]=this._list[t=t+1+r&this._capacityMask];this._list[t]=void 0,this._tail=this._tail-1+r&this._capacityMask}return i}}},yv.prototype.remove=function(e,t){var n,r=e,s=t;if(r===(0|r)&&this._head!==this._tail){var i=this.size(),o=this._list.length;if(!(r>=i||r<-i||t<1)){if(r<0&&(r+=i),1===t||!t)return(n=new Array(1))[0]=this.removeOne(r),n;if(0===r&&r+t>=i)return n=this.toArray(),this.clear(),n;var a;for(r+t>i&&(t=i-r),n=new Array(t),a=0;a<t;a++)n[a]=this._list[this._head+r+a&this._capacityMask];if(r=this._head+r&this._capacityMask,e+t===i){for(this._tail=this._tail-t+o&this._capacityMask,a=t;a>0;a--)this._list[r=r+1+o&this._capacityMask]=void 0;return n}if(0===e){for(this._head=this._head+t+o&this._capacityMask,a=t-1;a>0;a--)this._list[r=r+1+o&this._capacityMask]=void 0;return n}if(r<i/2){for(this._head=this._head+e+t+o&this._capacityMask,a=e;a>0;a--)this.unshift(this._list[r=r-1+o&this._capacityMask]);for(r=this._head-1+o&this._capacityMask;s>0;)this._list[r=r-1+o&this._capacityMask]=void 0,s--;e<0&&(this._tail=r)}else{for(this._tail=r,r=r+t+o&this._capacityMask,a=i-(t+e);a>0;a--)this.push(this._list[r++]);for(r=this._tail;s>0;)this._list[r=r+1+o&this._capacityMask]=void 0,s--}return this._head<2&&this._tail>1e4&&this._tail<=o>>>2&&this._shrinkArray(),n}}},yv.prototype.splice=function(e,t){var n=e;if(n===(0|n)){var r=this.size();if(n<0&&(n+=r),!(n>r)){if(arguments.length>2){var s,i,o,a=arguments.length,c=this._list.length,l=2;if(!r||n<r/2){for(i=new Array(n),s=0;s<n;s++)i[s]=this._list[this._head+s&this._capacityMask];for(0===t?(o=[],n>0&&(this._head=this._head+n+c&this._capacityMask)):(o=this.remove(n,t),this._head=this._head+n+c&this._capacityMask);a>l;)this.unshift(arguments[--a]);for(s=n;s>0;s--)this.unshift(i[s-1])}else{var u=(i=new Array(r-(n+t))).length;for(s=0;s<u;s++)i[s]=this._list[this._head+n+t+s&this._capacityMask];for(0===t?(o=[],n!=r&&(this._tail=this._head+n+c&this._capacityMask)):(o=this.remove(n,t),this._tail=this._tail-u+c&this._capacityMask);l<a;)this.push(arguments[l++]);for(s=0;s<u;s++)this.push(i[s])}return o}return this.remove(n,t)}}},yv.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0},yv.prototype.isEmpty=function(){return this._head===this._tail},yv.prototype.toArray=function(){return this._copyArray(!1)},yv.prototype._fromArray=function(e){var t=e.length,n=this._nextPowerOf2(t);this._list=new Array(n),this._capacityMask=n-1,this._tail=t;for(var r=0;r<t;r++)this._list[r]=e[r]},yv.prototype._copyArray=function(e,t){var n=this._list,r=n.length,s=this.length;if((t|=s)==s&&this._head<this._tail)return this._list.slice(this._head,this._tail);var i,o=new Array(t),a=0;if(e||this._head>this._tail){for(i=this._head;i<r;i++)o[a++]=n[i];for(i=0;i<this._tail;i++)o[a++]=n[i]}else for(i=this._head;i<this._tail;i++)o[a++]=n[i];return o},yv.prototype._growArray=function(){if(0!=this._head){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},yv.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1},yv.prototype._nextPowerOf2=function(e){var t=1<<Math.log(e)/Math.log(2)+1;return Math.max(t,4)};var wv,bv=Lr(yv);!function(e){e[e.unknown=0]="unknown",e[e.valid=1]="valid",e[e.invalid=2]="invalid",e[e.ignored=3]="ignored"}(wv||(wv={}));class vv{records;queue;constructor(){this.records=new Map,this.queue=new bv}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(null!=t)return t;t={status:wv.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);const n={msgId:e,expire:Date.now()+12e4};return this.queue.push(n),t}gc(){const e=Date.now();let t=this.queue.peekFront();for(;null!=t&&t.expire<e;)this.records.delete(t.msgId),this.queue.shift(),t=this.queue.peekFront()}clear(){this.records.clear(),this.queue.clear()}}class Ev{params;metrics;peerStats=new Map;peerIPs=new gv((()=>new Set));scoreCache=new Map;deliveryRecords=new vv;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,n,r){this.params=e,this.metrics=t,function(e){for(const[t,n]of Object.entries(e.topics))try{hv(n)}catch(e){throw new pn(`invalid score parameters for topic ${t}: ${e.message}`,av)}if(e.topicScoreCap<0)throw new pn("invalid topic score cap; must be positive (or 0 for no cap)",av);if(null===e.appSpecificScore||void 0===e.appSpecificScore)throw new pn("missing application specific score function",av);if(e.IPColocationFactorWeight>0)throw new pn("invalid IPColocationFactorWeight; must be negative (or 0 to disable)",av);if(0!==e.IPColocationFactorWeight&&e.IPColocationFactorThreshold<1)throw new pn("invalid IPColocationFactorThreshold; must be at least 1",av);if(e.behaviourPenaltyWeight>0)throw new pn("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)",av);if(0!==e.behaviourPenaltyWeight&&(e.behaviourPenaltyDecay<=0||e.behaviourPenaltyDecay>=1))throw new pn("invalid BehaviourPenaltyDecay; must be between 0 and 1",av);if(e.decayInterval<1e3)throw new pn("invalid DecayInterval; must be at least 1s",av);if(e.decayToZero<=0||e.decayToZero>=1)throw new pn("invalid DecayToZero; must be between 0 and 1",av)}(e),this.scoreCacheValidityMs=r.scoreCacheValidityMs,this.computeScore=r.computeScore??mv,this.log=n.forComponent("libp2p:gossipsub:score")}get size(){return this.peerStats.size}start(){null==this._backgroundInterval?(this._backgroundInterval=setInterval((()=>{this.background()}),this.params.decayInterval),this.log("started")):this.log("Peer score already running")}stop(){null!=this._backgroundInterval?(clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),this.log("stopped")):this.log("Peer score already stopped")}background(){this.refreshScores(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map((([e,t])=>[e,t])))}messageFirstSeenTimestampMs(e){const t=this.deliveryRecords.getRecord(e);return null!=t?t.firstSeenTsMs:null}refreshScores(){const e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach(((n,r)=>{n.connected?(Object.entries(n.topics).forEach((([n,r])=>{const s=this.params.topics[n];void 0!==s&&(r.firstMessageDeliveries*=s.firstMessageDeliveriesDecay,r.firstMessageDeliveries<t&&(r.firstMessageDeliveries=0),r.meshMessageDeliveries*=s.meshMessageDeliveriesDecay,r.meshMessageDeliveries<t&&(r.meshMessageDeliveries=0),r.meshFailurePenalty*=s.meshFailurePenaltyDecay,r.meshFailurePenalty<t&&(r.meshFailurePenalty=0),r.invalidMessageDeliveries*=s.invalidMessageDeliveriesDecay,r.invalidMessageDeliveries<t&&(r.invalidMessageDeliveries=0),r.inMesh&&(r.meshTime=e-r.graftTime,r.meshTime>s.meshMessageDeliveriesActivation&&(r.meshMessageDeliveriesActive=!0)))})),n.behaviourPenalty*=this.params.behaviourPenaltyDecay,n.behaviourPenalty<t&&(n.behaviourPenalty=0)):e>n.expire&&(this.removeIPsForPeer(r,n.knownIPs),this.peerStats.delete(r),this.scoreCache.delete(r))}))}score(e){this.metrics?.scoreFnCalls.inc();const t=this.peerStats.get(e);if(null==t)return 0;const n=Date.now(),r=this.scoreCache.get(e);if(null!=r&&r.cacheUntil>n)return r.score;this.metrics?.scoreFnRuns.inc();const s=this.computeScore(e,t,this.params,this.peerIPs),i=n+this.scoreCacheValidityMs;return null!=r?(this.metrics?.scoreCachedDelta.observe(Math.abs(s-r.score)),r.score=s,r.cacheUntil=i):this.scoreCache.set(e,{score:s,cacheUntil:i}),s}addPenalty(e,t,n){const r=this.peerStats.get(e);null!=r&&(r.behaviourPenalty+=t,this.metrics?.onScorePenalty(n))}addPeer(e){const t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){const n=this.peerStats.get(e);null!=n&&n.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){const n=this.peerStats.get(e);null!=n&&n.knownIPs.delete(t);const r=this.peerIPs.get(t);null!=r&&(r.delete(e),0===r.size&&this.peerIPs.delete(t))}removePeer(e){const t=this.peerStats.get(e);if(null!=t){if(this.score(e)>0)return this.removeIPsForPeer(e,t.knownIPs),void this.peerStats.delete(e);Object.entries(t.topics).forEach((([e,t])=>{t.firstMessageDeliveries=0;const n=this.params.topics[e].meshMessageDeliveriesThreshold;if(t.inMesh&&t.meshMessageDeliveriesActive&&t.meshMessageDeliveries<n){const e=n-t.meshMessageDeliveries;t.meshFailurePenalty+=e*e}t.inMesh=!1,t.meshMessageDeliveriesActive=!1})),t.connected=!1,t.expire=Date.now()+this.params.retainScore}}graft(e,t){const n=this.peerStats.get(e);if(null!=n){const e=this.getPtopicStats(n,t);null!=e&&(e.inMesh=!0,e.graftTime=Date.now(),e.meshTime=0,e.meshMessageDeliveriesActive=!1)}}prune(e,t){const n=this.peerStats.get(e);if(null!=n){const e=this.getPtopicStats(n,t);if(null!=e){const n=this.params.topics[t].meshMessageDeliveriesThreshold;if(e.meshMessageDeliveriesActive&&e.meshMessageDeliveries<n){const t=n-e.meshMessageDeliveries;e.meshFailurePenalty+=t*t}e.meshMessageDeliveriesActive=!1,e.inMesh=!1}}}validateMessage(e){this.deliveryRecords.ensureRecord(e)}deliverMessage(e,t,n){this.markFirstMessageDelivery(e,n);const r=this.deliveryRecords.ensureRecord(t),s=Date.now();r.status===wv.unknown?(r.status=wv.valid,r.validated=s,r.peers.forEach((t=>{t!==e.toString()&&this.markDuplicateMessageDelivery(t,n)}))):this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,s-r.firstSeenTsMs,wv[r.status])}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,n,r){switch(r){case Qb.Error:return void this.markInvalidMessageDelivery(e,n);case Qb.Blacklisted:return}const s=this.deliveryRecords.ensureRecord(t);if(s.status===wv.unknown){if(r===Qb.Ignore)return s.status=wv.ignored,void s.peers.clear();s.status=wv.invalid,this.markInvalidMessageDelivery(e,n),s.peers.forEach((e=>{this.markInvalidMessageDelivery(e,n)})),s.peers.clear()}else this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-s.firstSeenTsMs,wv[s.status])}duplicateMessage(e,t,n){const r=this.deliveryRecords.ensureRecord(t);if(!r.peers.has(e))switch(r.status){case wv.unknown:r.peers.add(e);break;case wv.valid:r.peers.add(e),this.markDuplicateMessageDelivery(e,n,r.validated);break;case wv.invalid:this.markInvalidMessageDelivery(e,n);case wv.ignored:}}markInvalidMessageDelivery(e,t){const n=this.peerStats.get(e);if(null!=n){const e=this.getPtopicStats(n,t);null!=e&&(e.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){const n=this.peerStats.get(e);if(null!=n){const e=this.getPtopicStats(n,t);if(null!=e){let n=this.params.topics[t].firstMessageDeliveriesCap;e.firstMessageDeliveries=Math.min(n,e.firstMessageDeliveries+1),e.inMesh&&(n=this.params.topics[t].meshMessageDeliveriesCap,e.meshMessageDeliveries=Math.min(n,e.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,n){const r=this.peerStats.get(e);if(null!=r){const e=void 0!==n?Date.now():0,s=this.getPtopicStats(r,t);if(null!=s&&s.inMesh){const r=this.params.topics[t];if(void 0!==n){const s=e-n,i=s>r.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,s,i),i)return}const i=r.meshMessageDeliveriesCap;s.meshMessageDeliveries=Math.min(i,s.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(const n of t){const t=this.peerIPs.get(n);null!=t&&(t.delete(e),0===t.size&&this.peerIPs.delete(n))}}getPtopicStats(e,t){let n=e.topics[t];return void 0!==n?n:void 0!==this.params.topics[t]?(n={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=n,n):null}}function Sv(e,t,n,r,s){let i=0;const o=new Map;if(Object.entries(t.topics).forEach((([e,t])=>{const r=s.get(e)??"unknown",a=n.topics[e];if(void 0===a)return;let c=o.get(r);null==c&&(c={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},o.set(r,c));let l=0,u=0,h=0,d=0,p=0;if(t.inMesh){l+=Math.max(t.meshTime/a.timeInMeshQuantum,a.timeInMeshCap)*a.timeInMeshWeight}let f=t.firstMessageDeliveries;if(f>a.firstMessageDeliveriesCap&&(f=a.firstMessageDeliveriesCap),u+=f*a.firstMessageDeliveriesWeight,t.meshMessageDeliveriesActive&&t.meshMessageDeliveries<a.meshMessageDeliveriesThreshold){const e=a.meshMessageDeliveriesThreshold-t.meshMessageDeliveries;h+=e*e*a.meshMessageDeliveriesWeight}d+=t.meshFailurePenalty*a.meshFailurePenaltyWeight;p+=t.invalidMessageDeliveries*t.invalidMessageDeliveries*a.invalidMessageDeliveriesWeight,i+=(l+u+h+d+p)*a.topicWeight,c.p1w+=l,c.p2w+=u,c.p3w+=h,c.p3bw+=d,c.p4w+=p})),n.topicScoreCap>0&&i>n.topicScoreCap){i=n.topicScoreCap;const e=n.topicScoreCap/i;for(const t of o.values())t.p1w*=e,t.p2w*=e,t.p3w*=e,t.p3bw*=e,t.p4w*=e}let a=0,c=0,l=0;a+=n.appSpecificScore(e)*n.appSpecificWeight,t.knownIPs.forEach((e=>{if(n.IPColocationFactorWhitelist.has(e))return;const t=r.get(e),s=null!=t?t.size:0;if(s>n.IPColocationFactorThreshold){const e=s-n.IPColocationFactorThreshold;c+=e*e*n.IPColocationFactorWeight}}));return l+=t.behaviourPenalty*t.behaviourPenalty*n.behaviourPenaltyWeight,i+=a+c+l,{byTopic:o,p5w:a,p6w:c,p7w:l,score:i}}class _v{rawStream;pushable;closeController;maxBufferSize;constructor(e,t,n){this.rawStream=e,this.pushable=dr(),this.closeController=new AbortController,this.maxBufferSize=n.maxBufferSize??1/0,this.closeController.signal.addEventListener("abort",(()=>{e.close().catch((t=>{e.abort(t)}))})),fr(this.pushable,this.rawStream).catch(t)}get protocol(){return this.rawStream.protocol}push(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(Mr.single(e))}pushPrefixed(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(e)}async close(){this.closeController.abort(),await this.pushable.return()}}class Iv{source;rawStream;closeController;constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.closeController.signal.addEventListener("abort",(()=>{e.close().catch((t=>{e.abort(t)}))})),this.source=fr(this.rawStream,(e=>$r(e,t)))}async close(){this.closeController.abort()}}class Rv{gossipsubIWantFollowupMs;msgIdToStrFn;metrics;promises=new Map;requestMsByMsg=new Map;requestMsByMsgExpire;constructor(e,t,n){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=n,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){const n=t[Math.floor(Math.random()*t.length)],r=this.msgIdToStrFn(n);let s=this.promises.get(r);null==s&&(s=new Map,this.promises.set(r,s));const i=Date.now();s.has(e)||(s.set(e,i+this.gossipsubIWantFollowupMs),null!=this.metrics&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(r)||this.requestMsByMsg.set(r,i)))}getBrokenPromises(){const e=Date.now(),t=new Map;let n=0;return this.promises.forEach(((r,s)=>{r.forEach(((s,i)=>{s<e&&(t.set(i,(t.get(i)??0)+1),r.delete(i),n++)})),0===r.size&&this.promises.delete(s)})),this.metrics?.iwantPromiseBroken.inc(n),t}deliverMessage(e,t=!1){this.trackMessage(e);const n=this.promises.get(e);null!=n&&(this.promises.delete(e),null!=this.metrics&&(this.metrics.iwantPromiseResolved.inc(1),t&&this.metrics.iwantPromiseResolvedFromDuplicate.inc(1),this.metrics.iwantPromiseResolvedPeers.inc(n.size)))}rejectMessage(e,t){this.trackMessage(e),t!==Qb.Error&&this.promises.delete(e)}clear(){this.promises.clear()}prune(){const e=Date.now()-this.requestMsByMsgExpire;let t=0;for(const[n,r]of this.requestMsByMsg.entries()){if(!(r<e))break;this.requestMsByMsg.delete(n),t++}this.metrics?.iwantMessagePruned.inc(t)}trackMessage(e){if(null!=this.metrics){const t=this.requestMsByMsg.get(e);void 0!==t&&(this.metrics.iwantPromiseDeliveryTime.observe((Date.now()-t)/1e3),this.requestMsByMsg.delete(e))}}}const Av=kt("libp2p-pubsub:");function Tv(e=[],t){return{subscriptions:[],messages:e,control:void 0!==t?{graft:t.graft??[],prune:t.prune??[],ihave:t.ihave??[],iwant:t.iwant??[]}:void 0}}function kv(e){return void 0===e.control&&(e.control={graft:[],prune:[],ihave:[],iwant:[]}),e}function Dv(e){if(e.length<=1)return e;for(let t=0;t<e.length;t++){const n=Math.floor(Math.random()*Math.floor(e.length)),r=e[t];e[t]=e[n],e[n]=r}return e}function Pv(e){return Yt(e,"base64")}function Cv(e){if("signed"!==e.type)throw new Error("expected signed message type");if(null==e.sequenceNumber)throw Error("missing seqno field");return((e,t)=>{const n=kt(t.toString(16).padStart(16,"0"),"base16"),r=new Uint8Array(e.length+n.length);return r.set(e,0),r.set(n,e.length),r})(e.from.toBytes(),e.sequenceNumber)}async function xv(e){return ft.encode(e.data)}var Nv,Mv;!function(e){e[e.ip4=4]="ip4",e[e.ip6=41]="ip6"}(Nv||(Nv={}));class Ov{entries=new Map;validityMs;constructor(e){this.validityMs=e.validityMs}get size(){return this.entries.size}put(e,t){return!!this.entries.has(e)||(this.entries.set(e,{value:t,validUntilMs:Date.now()+this.validityMs}),!1)}prune(){const e=Date.now();for(const[t,n]of this.entries.entries()){if(!(n.validUntilMs<e))break;this.entries.delete(t)}}has(e){return this.entries.has(e)}get(e){const t=this.entries.get(e);return null!=t&&t.validUntilMs>=Date.now()?t.value:void 0}clear(){this.entries.clear()}}!function(e){e[e.started=0]="started",e[e.stopped=1]="stopped"}(Mv||(Mv={}));class Lv extends yn{globalSignaturePolicy;multicodecs=[Hb,qb];publishConfig;dataTransform;peers=new Set;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=dr({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;components;directPeerInitial=null;static multicodec=Hb;opts;decodeRpcLimits;metrics;status={code:Mv.stopped};maxInboundStreams;maxOutboundStreams;runOnTransientConnection;allowedTopics;heartbeatTimer=null;constructor(e,t={}){super();const n={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,...t,scoreParams:uv(t.scoreParams),scoreThresholds:pv(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=n.decodeRpcLimits??Wb,this.globalSignaturePolicy=n.globalSignaturePolicy??an,n.fallbackToFloodsub&&this.multicodecs.push($b),this.log=e.logger.forComponent(n.debugName??"libp2p:gossipsub"),this.opts=n,this.direct=new Set(n.directPeers.map((e=>e.id.toString()))),this.seenCache=new Ov({validityMs:n.seenTTL}),this.publishedMessageIds=new Ov({validityMs:n.seenTTL}),null!=t.msgIdFn)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case an:this.msgIdFn=Cv;break;case cn:this.msgIdFn=xv;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(null!=t.fastMsgIdFn&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new Ov({validityMs:n.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??Pv,this.mcache=t.messageCache??new iv(n.mcacheGossip,n.mcacheLength,this.msgIdToStrFn),null!=t.dataTransform&&(this.dataTransform=t.dataTransform),null!=t.metricsRegister){if(null==t.metricsTopicStrToLabel)throw Error("Must set metricsTopicStrToLabel with metrics");const e=Math.max(...Object.values(n.scoreParams.topics).map((e=>e.meshMessageDeliveriesWindow)),1e3),r=function(e,t,n){return{protocolsEnabled:e.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:e.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:e.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:e.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEventsFanout:e.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:e.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:e.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:e.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:e.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:e.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:e.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:e.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:e.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:e.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:e.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:e.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:e.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:e.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:e.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),acceptedMessagesTotal:e.gauge({name:"gossipsub_accepted_messages_total",help:"Total accepted messages for each topic",labelNames:["topic"]}),ignoredMessagesTotal:e.gauge({name:"gossipsub_ignored_messages_total",help:"Total ignored messages for each topic",labelNames:["topic"]}),rejectedMessagesTotal:e.gauge({name:"gossipsub_rejected_messages_total",help:"Total rejected messages for each topic",labelNames:["topic"]}),unknownValidationResultsTotal:e.gauge({name:"gossipsub_unknown_validation_results_total",help:"Total unknown validation results for each topic",labelNames:["topic"]}),asyncValidationMcacheHit:e.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),asyncValidationDelayFromFirstSeenSec:e.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:e.gauge({name:"gossipsub_async_validation_unknown_first_seen_count_total",help:"Async validation report unknown first seen value for message"}),peerReadStreamError:e.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:e.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:e.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:e.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:e.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:e.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:e.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:e.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:e.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:e.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:e.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:e.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:e.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:e.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:e.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:e.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:e.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:e.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:e.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:e.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:e.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:e.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),msgPublishCount:e.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeersByTopic:e.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),directPeersPublishedTotal:e.gauge({name:"gossipsub_direct_peers_published_total",help:"Total direct peers that we publish a msg to",labelNames:["topic"]}),floodsubPeersPublishedTotal:e.gauge({name:"gossipsub_floodsub_peers_published_total",help:"Total floodsub peers that we publish a msg to",labelNames:["topic"]}),meshPeersPublishedTotal:e.gauge({name:"gossipsub_mesh_peers_published_total",help:"Total mesh peers that we publish a msg to",labelNames:["topic"]}),fanoutPeersPublishedTotal:e.gauge({name:"gossipsub_fanout_peers_published_total",help:"Total fanout peers that we publish a msg to",labelNames:["topic"]}),msgPublishBytes:e.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgPublishTime:e.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:e.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:e.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:e.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:e.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),prevalidationInvalidTotal:e.gauge({name:"gossipsub_pre_validation_invalid_total",help:"Total count of invalid messages received",labelNames:["topic"]}),prevalidationValidTotal:e.gauge({name:"gossipsub_pre_validation_valid_total",help:"Total count of valid messages received",labelNames:["topic"]}),prevalidationDuplicateTotal:e.gauge({name:"gossipsub_pre_validation_duplicate_total",help:"Total count of duplicate messages received",labelNames:["topic"]}),prevalidationUnknownTotal:e.gauge({name:"gossipsub_pre_validation_unknown_status_total",help:"Total count of unknown_status messages received",labelNames:["topic"]}),msgReceivedInvalid:e.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["error"]}),msgReceivedInvalidByTopic:e.gauge({name:"gossipsub_msg_received_invalid_by_topic_total",help:"Tracks specific invalid message by topic",labelNames:["topic"]}),duplicateMsgDeliveryDelay:e.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*n.maxMeshMessageDeliveriesWindowSec,.5*n.maxMeshMessageDeliveriesWindowSec,Number(n.maxMeshMessageDeliveriesWindowSec),2*n.maxMeshMessageDeliveriesWindowSec,4*n.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:e.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:e.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:e.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:e.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:e.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:e.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:e.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores"}),scoreWeights:e.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:e.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:e.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:e.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*n.behaviourPenaltyThreshold,.5*n.behaviourPenaltyThreshold,Number(n.behaviourPenaltyThreshold),2*n.behaviourPenaltyThreshold,4*n.behaviourPenaltyThreshold]}),ihaveRcvIgnored:e.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:e.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:e.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:e.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:e.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),iwantPromiseStarted:e.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:e.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:e.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:e.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:e.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:e.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:e.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*n.gossipPromiseExpireSec,Number(n.gossipPromiseExpireSec),2*n.gossipPromiseExpireSec,4*n.gossipPromiseExpireSec]}),iwantPromiseUntracked:e.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),connectedPeersBackoffSec:e.histogram({name:"gossipsub_connected_peers_backoff_seconds",help:"Backoff time in seconds",buckets:[1,2,4,10,20,60,120]}),cacheSize:e.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:e.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:e.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:e.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:e.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:t,toTopic(e){return this.topicStrToLabel.get(e)??e},onJoin(e){this.topicSubscriptionStatus.set({topicStr:e},1),this.meshPeerCounts.set({topicStr:e},0)},onLeave(e){this.topicSubscriptionStatus.set({topicStr:e},0),this.meshPeerCounts.set({topicStr:e},0)},onAddToMesh(e,t,n){const r=this.toTopic(e);switch(t){case ev.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:r},n);break;case ev.Random:this.meshPeerInclusionEventsRandom.inc({topic:r},n);break;case ev.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:r},n);break;case ev.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:r},n);break;case ev.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:r},n);break;case ev.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:r},n);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:r},n)}},onRemoveFromMesh(e,t,n){const r=this.toTopic(e);switch(t){case tv.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:r},n);break;case tv.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:r},n);break;case tv.Prune:this.meshPeerChurnEventsPrune.inc({topic:r},n);break;case tv.Excess:this.meshPeerChurnEventsExcess.inc({topic:r},n);break;default:this.meshPeerChurnEventsUnknown.inc({topic:r},n)}},onReportValidation(e,t,n){if(this.asyncValidationMcacheHit.inc({hit:null!=e?"hit":"miss"}),null!=e){const n=this.toTopic(e.message.topic);switch(t){case ln.Accept:this.acceptedMessagesTotal.inc({topic:n});break;case ln.Ignore:this.ignoredMessagesTotal.inc({topic:n});break;case ln.Reject:this.rejectedMessagesTotal.inc({topic:n});break;default:this.unknownValidationResultsTotal.inc({topic:n})}}null!=n?this.asyncValidationDelayFromFirstSeenSec.observe((Date.now()-n)/1e3):this.asyncValidationUnknownFirstSeen.inc()},onScorePenalty(e){this.scoringPenalties.inc({penalty:e},1)},onIhaveRcv(e,t,n){const r=this.toTopic(e);this.ihaveRcvMsgids.inc({topic:r},t),this.ihaveRcvNotSeenMsgids.inc({topic:r},n)},onIwantRcv(e,t){for(const[t,n]of e){const e=this.toTopic(t);this.iwantRcvMsgids.inc({topic:e},n)}this.iwantRcvDonthaveMsgids.inc(t)},onForwardMsg(e,t){const n=this.toTopic(e);this.msgForwardCount.inc({topic:n},1),this.msgForwardPeers.inc({topic:n},t)},onPublishMsg(e,t,n,r,s){const i=this.toTopic(e);this.msgPublishCount.inc({topic:i},1),this.msgPublishBytes.inc({topic:i},n*r),this.msgPublishPeersByTopic.inc({topic:i},n),this.directPeersPublishedTotal.inc({topic:i},t.direct),this.floodsubPeersPublishedTotal.inc({topic:i},t.floodsub),this.meshPeersPublishedTotal.inc({topic:i},t.mesh),this.fanoutPeersPublishedTotal.inc({topic:i},t.fanout),this.msgPublishTime.observe({topic:i},s/1e3)},onMsgRecvPreValidation(e){const t=this.toTopic(e);this.msgReceivedPreValidation.inc({topic:t},1)},onMsgRecvError(e){const t=this.toTopic(e);this.msgReceivedError.inc({topic:t},1)},onPrevalidationResult(e,t){const n=this.toTopic(e);switch(t){case Zb.duplicate:this.prevalidationDuplicateTotal.inc({topic:n});break;case Zb.invalid:this.prevalidationInvalidTotal.inc({topic:n});break;case Zb.valid:this.prevalidationValidTotal.inc({topic:n});break;default:this.prevalidationUnknownTotal.inc({topic:n})}},onMsgRecvInvalid(e,t){const n=this.toTopic(e),r=t.reason===Qb.Error?t.error:t.reason;this.msgReceivedInvalid.inc({error:r},1),this.msgReceivedInvalidByTopic.inc({topic:n},1)},onDuplicateMsgDelivery(e,t,n){const r=this.toTopic(e);this.duplicateMsgDeliveryDelay.observe({topic:r},t/1e3),n&&this.duplicateMsgLateDelivery.inc({topic:r},1)},onPublishDuplicateMsg(e){const t=this.toTopic(e);this.duplicateMsgIgnored.inc({topic:t},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(e,t){this.rpcRecvBytes.inc(t),this.rpcRecvCount.inc(1),null!=e.subscriptions&&this.rpcRecvSubscription.inc(e.subscriptions.length),null!=e.messages&&this.rpcRecvMessage.inc(e.messages.length),null!=e.control&&(this.rpcRecvControl.inc(1),null!=e.control.ihave&&this.rpcRecvIHave.inc(e.control.ihave.length),null!=e.control.iwant&&this.rpcRecvIWant.inc(e.control.iwant.length),null!=e.control.graft&&this.rpcRecvGraft.inc(e.control.graft.length),null!=e.control.prune&&this.rpcRecvPrune.inc(e.control.prune.length))},onRpcSent(e,t){if(this.rpcSentBytes.inc(t),this.rpcSentCount.inc(1),null!=e.subscriptions&&this.rpcSentSubscription.inc(e.subscriptions.length),null!=e.messages&&this.rpcSentMessage.inc(e.messages.length),null!=e.control){const t=e.control.ihave?.length??0,n=e.control.iwant?.length??0,r=e.control.graft?.length??0,s=e.control.prune?.length??0;t>0&&this.rpcSentIHave.inc(t),n>0&&this.rpcSentIWant.inc(n),r>0&&this.rpcSentGraft.inc(r),s>0&&this.rpcSentPrune.inc(s),(t>0||n>0||r>0||s>0)&&this.rpcSentControl.inc(1)}},registerScores(e,t){let n=0,r=0,s=0,i=0;for(const o of e)o>=t.graylistThreshold&&n++,o>=t.publishThreshold&&r++,o>=t.gossipThreshold&&s++,o>=0&&i++;this.peersByScoreThreshold.set({threshold:sv.graylist},n),this.peersByScoreThreshold.set({threshold:sv.publish},r),this.peersByScoreThreshold.set({threshold:sv.gossip},s),this.peersByScoreThreshold.set({threshold:sv.mesh},i),this.score.set(e)},registerScoreWeights(e){for(const[t,n]of e.byTopic)this.scoreWeights.set({topic:t,p:"p1"},n.p1w),this.scoreWeights.set({topic:t,p:"p2"},n.p2w),this.scoreWeights.set({topic:t,p:"p3"},n.p3w),this.scoreWeights.set({topic:t,p:"p3b"},n.p3bw),this.scoreWeights.set({topic:t,p:"p4"},n.p4w);this.scoreWeights.set({p:"p5"},e.p5w),this.scoreWeights.set({p:"p6"},e.p6w),this.scoreWeights.set({p:"p7"},e.p7w)},registerScorePerMesh(e,t){const n=new Map;e.forEach(((e,t)=>{const r=this.topicStrToLabel.get(t)??"unknown";let s=n.get(r);null==s&&(s=new Set,n.set(r,s)),e.forEach((e=>s?.add(e)))}));for(const[e,r]of n){const n=[];r.forEach((e=>{n.push(t.get(e)??0)})),this.scorePerMesh.set({topic:e},n)}}}}(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:n.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:e/1e3});r.mcacheSize.addCollect((()=>{this.onScrapeMetrics(r)}));for(const e of this.multicodecs)r.protocolsEnabled.set({protocol:e},1);this.metrics=r}else this.metrics=null;this.gossipTracer=new Rv(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new Ev(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:n.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnTransientConnection=t.runOnTransientConnection,this.allowedTopics=null!=n.allowedTopics?new Set(n.allowedTopics):null}getPeers(){return[...this.peers.keys()].map((e=>Is(e)))}isStarted(){return this.status.code===Mv.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=await async function(e,t){switch(e){case an:{if(null==t)throw Error("Must provide PeerId");if(null==t.privateKey)throw Error("Cannot sign message, no private key present");if(null==t.publicKey)throw Error("Cannot sign message, no public key present");const e=await ql(t.privateKey);return{type:Yb.Signing,author:t,key:t.publicKey,privateKey:e}}case cn:return{type:Yb.Anonymous};default:throw new Error(`Unknown signature policy "${e}"`)}}(this.globalSignaturePolicy,this.components.peerId),this.outboundInflightQueue=dr({objectMode:!0}),fr(this.outboundInflightQueue,(async e=>{for await(const{peerId:t,connection:n}of e)await this.createOutboundStream(t,n)})).catch((e=>{this.log.error("outbound inflight queue error",e)})),await Promise.all(this.opts.directPeers.map((async e=>{await this.components.peerStore.merge(e.id,{multiaddrs:e.addrs})})));const e=this.components.registrar;await Promise.all(this.multicodecs.map((async t=>e.handle(t,this.onIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}))));const t={onConnect:this.onPeerConnected.bind(this),onDisconnect:this.onPeerDisconnected.bind(this),notifyOnTransient:this.runOnTransientConnection},n=await Promise.all(this.multicodecs.map((async n=>e.register(n,t)))),r=setTimeout(this.runHeartbeat,100);this.status={code:Mv.started,registrarTopologyIds:n,heartbeatTimeout:r,hearbeatStartMs:Date.now()+100},this.score.start(),this.directPeerInitial=setTimeout((()=>{Promise.resolve().then((async()=>{await Promise.all(Array.from(this.direct).map((async e=>this.connect(e))))})).catch((e=>{this.log(e)}))}),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!==Mv.started)return;const{registrarTopologyIds:e}=this.status;this.status={code:Mv.stopped},this.opts.tagMeshPeers&&(this.removeEventListener("gossipsub:graft",this.tagMeshPeer),this.removeEventListener("gossipsub:prune",this.untagMeshPeer));const t=this.components.registrar;await Promise.all(this.multicodecs.map((async e=>t.unhandle(e)))),e.forEach((e=>{t.unregister(e)})),this.outboundInflightQueue.end();const n=[];for(const e of this.streamsOutbound.values())n.push(e.close());this.streamsOutbound.clear();for(const e of this.streamsInbound.values())n.push(e.close());this.streamsInbound.clear(),await Promise.all(n),this.peers.clear(),this.subscriptions.clear(),null!=this.heartbeatTimer&&(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(),null!=this.fastMsgIdCache&&this.fastMsgIdCache.clear(),null!=this.directPeerInitial&&clearTimeout(this.directPeerInitial),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream({stream:e,connection:t}){if(!this.isStarted())return;const n=t.remotePeer;this.addPeer(n,t.direction,t.remoteAddr),this.createInboundStream(n,e),this.outboundInflightQueue.push({peerId:n,connection:t})}onPeerConnected(e,t){this.metrics?.newConnectionCount.inc({status:t.status}),this.isStarted()&&"open"===t.status&&(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;const n=e.toString();if(this.peers.has(n)&&!this.streamsOutbound.has(n))try{const r=new _v(await t.newStream(this.multicodecs,{runOnTransientConnection:this.runOnTransientConnection}),(e=>{this.log.error("outbound pipe error",e)}),{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(n,r);const s=r.protocol;s===$b&&this.floodsubPeers.add(n),this.metrics?.peersPerProtocol.inc({protocol:s},1),this.subscriptions.size>0&&(this.log("send subscriptions to",n),this.sendSubscriptions(n,Array.from(this.subscriptions),!0))}catch(e){this.log.error("createOutboundStream error",e)}}createInboundStream(e,t){if(!this.isStarted())return;const n=e.toString();if(!this.peers.has(n))return;const r=this.streamsInbound.get(n);void 0!==r&&(this.log("replacing existing inbound steam %s",n),r.close().catch((e=>{this.log.error(e)}))),this.log("create inbound stream %s",n);const s=new Iv(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(n,s),this.pipePeerReadStream(e,s.source).catch((e=>{this.log(e)}))}addPeer(e,t,n){const r=e.toString();if(!this.peers.has(r)){this.log("new peer %p",e),this.peers.add(r),this.score.addPeer(r);const s=function(e){for(const t of e.tuples())switch(t[0]){case Nv.ip4:case Nv.ip6:return Fn(t[0],t[1])}return null}(n);null!==s?this.score.addIP(r,s):this.log("Added peer has no IP in current address %s %s",r,n.toString()),this.outbound.has(r)||this.outbound.set(r,"outbound"===t)}}removePeer(e){const t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);const n=this.streamsOutbound.get(t),r=this.streamsInbound.get(t);null!=n&&this.metrics?.peersPerProtocol.inc({protocol:n.protocol},-1),n?.close().catch((e=>{this.log.error(e)})),r?.close().catch((e=>{this.log.error(e)})),this.streamsOutbound.delete(t),this.streamsInbound.delete(t);for(const e of this.topics.values())e.delete(t);for(const[e,n]of this.mesh)n.delete(t)&&this.metrics?.onRemoveFromMesh(e,tv.Dc,1);for(const e of this.fanout.values())e.delete(t);this.floodsubPeers.delete(t),this.gossip.delete(t),this.control.delete(t),this.outbound.delete(t),this.score.removePeer(t),this.acceptFromWhitelist.delete(t)}get started(){return this.status.code===Mv.started}getMeshPeers(e){const t=this.mesh.get(e);return null!=t?Array.from(t):[]}getSubscribers(e){const t=this.topics.get(e);return(null!=t?Array.from(t):[]).map((e=>Is(e)))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await fr(t,(async t=>{for await(const n of t)try{const t=n.subarray(),r=jb.decode(t,{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}}}});if(this.metrics?.onRpcRecv(r,t.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,r)}catch(e){this.metrics?.onRpcRecvError(),this.log(e)}else this.handleReceivedRpc(e,r).catch((e=>{this.metrics?.onRpcRecvError(),this.log(e)}))}catch(e){this.metrics?.onRpcDataError(),this.log(e)}}))}catch(t){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(t,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){if(!this.acceptFrom(e.toString()))return this.log("received message from unacceptable peer %p",e),void this.metrics?.rpcRecvNotAccepted.inc();const n=null!=t.subscriptions?t.subscriptions.length:0,r=null!=t.messages?t.messages.length:0;let s=0,i=0,o=0,a=0;if(null!=t.control&&(null!=t.control.ihave&&(s=t.control.ihave.length),null!=t.control.iwant&&(i=t.control.iwant.length),null!=t.control.graft&&(o=t.control.graft.length),null!=t.control.prune&&(a=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${n} messages ${r} ihave ${s} iwant ${i} graft ${o} prune ${a}`),null!=t.subscriptions&&t.subscriptions.length>0){const n=[];t.subscriptions.forEach((t=>{const r=t.topic,s=!0===t.subscribe;if(null!=r){if(null!=this.allowedTopics&&!this.allowedTopics.has(r))return;this.handleReceivedSubscription(e,r,s),n.push({topic:r,subscribe:s})}})),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:n}})}for(const n of t.messages){if(null!=this.allowedTopics&&!this.allowedTopics.has(n.topic))continue;const t=this.handleReceivedMessage(e,n).catch((e=>{this.metrics?.onMsgRecvError(n.topic),this.log(e)}));this.opts.awaitRpcMessageHandler&&await t}null!=t.control&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,n){this.log("subscription update from %p topic %s",e,t);let r=this.topics.get(t);null==r&&(r=new Set,this.topics.set(t,r)),n?r.add(e.toString()):r.delete(e.toString())}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);const n=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,n.code);const r=n.code;switch(r){case Zb.duplicate:return this.score.duplicateMessage(e.toString(),n.msgIdStr,t.topic),this.gossipTracer.deliverMessage(n.msgIdStr,!0),void this.mcache.observeDuplicate(n.msgIdStr,e.toString());case Zb.invalid:if(null!=n.msgIdStr){const r=n.msgIdStr;this.score.rejectMessage(e.toString(),r,t.topic,n.reason),this.gossipTracer.rejectMessage(r,n.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);return void this.metrics?.onMsgRecvInvalid(t.topic,n);case Zb.valid:if(this.score.validateMessage(n.messageId.msgIdStr),this.gossipTracer.deliverMessage(n.messageId.msgIdStr),this.mcache.put(n.messageId,t,!this.opts.asyncValidation),this.subscriptions.has(t.topic)){this.components.peerId.equals(e)&&!this.opts.emitSelf||(super.dispatchEvent(new bn("gossipsub:message",{detail:{propagationSource:e,msgId:n.messageId.msgIdStr,msg:n.msg}})),super.dispatchEvent(new bn("message",{detail:n.msg})))}this.opts.asyncValidation||this.forwardMessage(n.messageId.msgIdStr,t,e.toString());break;default:throw new Error(`Invalid validation result: ${r}`)}}async validateReceivedMessage(e,t){const n=this.fastMsgIdFn?.(t),r=void 0!==n?this.fastMsgIdCache?.get(n):void 0;if(null!=r)return{code:Zb.duplicate,msgIdStr:r};const s=await async function(e,t){switch(e){case cn:return null!=t.signature?{valid:!1,error:Jb.SignaturePresent}:null!=t.seqno?{valid:!1,error:Jb.SeqnoPresent}:null!=t.key?{valid:!1,error:Jb.FromPresent}:{valid:!0,message:{type:"unsigned",topic:t.topic,data:t.data??new Uint8Array(0)}};case an:{if(null==t.seqno)return{valid:!1,error:Jb.InvalidSeqno};if(8!==t.seqno.length)return{valid:!1,error:Jb.InvalidSeqno};if(null==t.signature)return{valid:!1,error:Jb.InvalidSignature};if(null==t.from)return{valid:!1,error:Jb.InvalidPeerId};let e,n;try{e=Rs(t.from)}catch(e){return{valid:!1,error:Jb.InvalidPeerId}}if(null!=t.key){if(n=Kl(t.key),void 0!==e.publicKey&&!_n(n.bytes,e.publicKey))return{valid:!1,error:Jb.InvalidPeerId}}else{if(null==e.publicKey)return{valid:!1,error:Jb.InvalidPeerId};n=Kl(e.publicKey)}const r={from:t.from,data:t.data,seqno:t.seqno,topic:t.topic,signature:void 0,key:void 0},s=In([Av,jb.Message.encode(r)]);return await n.verify(s,t.signature)?{valid:!0,message:{type:"signed",from:e,data:t.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${Yt(t.seqno,"base16")}`),topic:t.topic,signature:t.signature,key:t.key??$l(n)}}:{valid:!1,error:Jb.InvalidSignature}}default:throw new Error("Unreachable")}}(this.globalSignaturePolicy,t);if(!s.valid)return{code:Zb.invalid,reason:Qb.Error,error:s.error};const i=s.message;try{null!=this.dataTransform&&(i.data=this.dataTransform.inboundTransform(t.topic,i.data))}catch(e){return this.log("Invalid message, transform failed",e),{code:Zb.invalid,reason:Qb.Error,error:Jb.TransformFailed}}const o=await this.msgIdFn(i),a=this.msgIdToStrFn(o),c={msgId:o,msgIdStr:a};if(void 0!==n&&null!=this.fastMsgIdCache){this.fastMsgIdCache.put(n,a)&&this.metrics?.fastMsgIdCacheCollision.inc()}if(this.seenCache.has(a))return{code:Zb.duplicate,msgIdStr:a};this.seenCache.put(a);const l=this.topicValidators.get(t.topic);if(null!=l){let t;try{t=await l(e,i)}catch(e){const n=e.code;"ERR_TOPIC_VALIDATOR_IGNORE"===n&&(t=ln.Ignore),t="ERR_TOPIC_VALIDATOR_REJECT"===n?ln.Reject:ln.Ignore}if(t!==ln.Accept)return{code:Zb.invalid,reason:ov(t),msgIdStr:a}}return{code:Zb.valid,messageId:c,msg:i}}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,n){this.sendRpc(e,{subscriptions:t.map((e=>({topic:e,subscribe:n}))),messages:[]})}async handleControlMessage(e,t){if(void 0===t)return;const n=null!=t.ihave?this.handleIHave(e,t.ihave):[],r=null!=t.iwant?this.handleIWant(e,t.iwant):[],s=null!=t.graft?await this.handleGraft(e,t.graft):[];if(null!=t.prune&&await this.handlePrune(e,t.prune),0===n.length&&0===r.length&&0===s.length)return;const i=this.sendRpc(e,Tv(r,{iwant:n,prune:s})),o=n[0]?.messageIDs;null!=o&&(i?this.gossipTracer.addPromise(e,o):this.metrics?.iwantPromiseUntracked.inc(1))}acceptFrom(e){if(this.direct.has(e))return!0;const t=Date.now(),n=this.acceptFromWhitelist.get(e);if(null!=n&&n.messagesAccepted<128&&n.acceptUntil>=t)return n.messagesAccepted+=1,!0;const r=this.score.score(e);return r>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),r>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){if(0===t.length)return[];const n=this.score.score(e);if(n<this.opts.scoreThresholds.gossipThreshold)return this.log("IHAVE: ignoring peer %s with score below threshold [ score = %d ]",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:rv.LowScore}),[];const r=(this.peerhave.get(e)??0)+1;if(this.peerhave.set(e,r),r>10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,r),this.metrics?.ihaveRcvIgnored.inc({reason:rv.MaxIhave}),[];const s=this.iasked.get(e)??0;if(s>=zb)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,s),this.metrics?.ihaveRcvIgnored.inc({reason:rv.MaxIasked}),[];const i=new Map;if(t.forEach((({topicID:e,messageIDs:t})=>{if(null==e||null==t||!this.mesh.has(e))return;let n=0;t.forEach((e=>{const t=this.msgIdToStrFn(e);this.seenCache.has(t)||(i.set(t,e),n++)})),this.metrics?.onIhaveRcv(e,t.length,n)})),0===i.size)return[];let o=i.size;o+s>zb&&(o=zb-s),this.log("IHAVE: Asking for %d out of %d messages from %s",o,i.size,e);let a=Array.from(i.values());return Dv(a),a=a.slice(0,o),this.iasked.set(e,s+o),[{messageIDs:a}]}handleIWant(e,t){if(0===t.length)return[];const n=this.score.score(e);if(n<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,n),[];const r=new Map,s=new Map;let i=0;return t.forEach((({messageIDs:t})=>{t?.forEach((t=>{const n=this.msgIdToStrFn(t),o=this.mcache.getWithIWantCount(n,e);null!=o?(s.set(o.msg.topic,1+(s.get(o.msg.topic)??0)),o.count>3?this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,t):r.set(n,o.msg)):i++}))})),this.metrics?.onIwantRcv(s,i),0===r.size?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",r.size,e),Array.from(r.values()))}async handleGraft(e,t){const n=[],r=this.score.score(e),s=Date.now();let i=this.opts.doPX;if(t.forEach((({topicID:t})=>{if(null==t)return;const o=this.mesh.get(t);if(null==o)return void(i=!1);if(o.has(e))return;const a=this.backoff.get(t)?.get(e);if(this.direct.has(e))this.log("GRAFT: ignoring request from direct peer %s",e),n.push(t),i=!1;else if("number"==typeof a&&s<a){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,nv.GraftBackoff),i=!1;const r=a+this.opts.graftFloodThreshold-this.opts.pruneBackoff;s<r&&this.score.addPenalty(e,1,nv.GraftBackoff),this.addBackoff(e,t),n.push(t)}else r<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,r,t),n.push(t),i=!1,this.addBackoff(e,t)):o.size>=this.opts.Dhi&&!this.outbound.get(e)?(n.push(t),this.addBackoff(e,t)):(this.log("GRAFT: Add mesh link from %s in %s",e,t),this.score.graft(e,t),o.add(e),this.metrics?.onAddToMesh(t,ev.Subscribed,1));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:t,direction:"inbound"}})})),0===n.length)return[];return Promise.all(n.map((async t=>this.makePrune(e,t,i,false))))}async handlePrune(e,t){const n=this.score.score(e);for(const{topicID:r,backoff:s,peers:i}of t){if(null==r)continue;const t=this.mesh.get(r);if(null==t)return;this.log("PRUNE: Remove mesh link to %s in %s",e,r),this.score.prune(e,r),t.has(e)&&(t.delete(e),this.metrics?.onRemoveFromMesh(r,tv.Prune,1)),"number"==typeof s&&s>0?this.doAddBackoff(e,r,1e3*s):this.addBackoff(e,r),null!=i&&i.length>0&&(n<this.opts.scoreThresholds.acceptPXThreshold?this.log("PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]",e,n,r):await this.pxConnect(i)),this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:r,direction:"inbound"}})}}addBackoff(e,t){this.doAddBackoff(e,t,this.opts.pruneBackoff)}doAddBackoff(e,t,n){let r=this.backoff.get(t);null==r&&(r=new Map,this.backoff.set(t,r));const s=Date.now()+n;(r.get(e)??0)<s&&r.set(e,s)}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,nv.BrokenPromise)}))}clearBackoff(){if(this.heartbeatTicks%15!=0)return;const e=Date.now();this.backoff.forEach(((t,n)=>{t.forEach(((n,r)=>{n+1*this.opts.heartbeatInterval<e&&t.delete(r)})),0===t.size&&this.backoff.delete(n)}))}async directConnect(){const e=[];this.direct.forEach((t=>{this.streamsOutbound.has(t)||e.push(t)})),await Promise.all(e.map((async e=>this.connect(e))))}async pxConnect(e){e.length>this.opts.prunePeers&&(Dv(e),e=e.slice(0,this.opts.prunePeers));const t=[];await Promise.all(e.map((async e=>{if(null==e.peerID)return;const n=Rs(e.peerID),r=n.toString();if(!this.peers.has(r))if(null!=e.signedPeerRecord)try{if(!await this.components.peerStore.consumePeerRecord(e.signedPeerRecord,n))return void this.log("bogus peer record obtained through px: could not add peer record to address book");t.push(r)}catch(e){this.log("bogus peer record obtained through px: invalid signature or not a peer record")}else t.push(r)}))),0!==t.length&&await Promise.all(t.map((async e=>this.connect(e))))}async connect(e){this.log("Initiating connection with %s",e);const t=Is(e),n=await this.components.connectionManager.openConnection(t);for(const e of this.multicodecs)for(const r of this.components.registrar.getTopologies(e))r.onConnect?.(t,n)}subscribe(e){if(this.status.code!==Mv.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(const t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==Mv.started)throw new Error("Pubsub is not started");const t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(const t of this.peers.keys())this.sendSubscriptions(t,[e],!1);this.leave(e)}join(e){if(this.status.code!==Mv.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);const t=new Set,n=this.backoff.get(e),r=this.fanout.get(e);if(null!=r&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),r.forEach((e=>{this.direct.has(e)||!(this.score.score(e)>=0)||null!=n&&n.has(e)||t.add(e)})),this.metrics?.onAddToMesh(e,ev.Fanout,t.size)),t.size<this.opts.D){const r=t.size;this.getRandomGossipPeers(e,this.opts.D,(e=>!t.has(e)&&!this.direct.has(e)&&this.score.score(e)>=0&&(null==n||!n.has(e)))).forEach((e=>{t.add(e)})),this.metrics?.onAddToMesh(e,ev.Random,t.size-r)}this.mesh.set(e,t),t.forEach((t=>{this.log("JOIN: Add mesh link to %s in %s",t,e),this.sendGraft(t,e)}))}leave(e){if(this.status.code!==Mv.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);const t=this.mesh.get(e);null!=t&&(Promise.all(Array.from(t).map((async t=>{this.log("LEAVE: Remove mesh link to %s in %s",t,e),await this.sendPrune(t,e)}))).catch((e=>{this.log("Error sending prunes to mesh peers",e)})),this.mesh.delete(e))}selectPeersToForward(e,t,n){const r=new Set,s=this.topics.get(e);null!=s&&(this.direct.forEach((e=>{s.has(e)&&t!==e&&!n?.has(e)&&r.add(e)})),this.floodsubPeers.forEach((e=>{s.has(e)&&t!==e&&!n?.has(e)&&this.score.score(e)>=this.opts.scoreThresholds.publishThreshold&&r.add(e)})));const i=this.mesh.get(e);return null!=i&&i.size>0&&i.forEach((e=>{t===e||n?.has(e)||r.add(e)})),r}selectPeersToPublish(e){const t=new Set,n={direct:0,floodsub:0,mesh:0,fanout:0},r=this.topics.get(e);if(null!=r)if(this.opts.floodPublish)r.forEach((e=>{this.direct.has(e)?(t.add(e),n.direct++):this.score.score(e)>=this.opts.scoreThresholds.publishThreshold&&(t.add(e),n.floodsub++)}));else{this.direct.forEach((e=>{r.has(e)&&(t.add(e),n.direct++)})),this.floodsubPeers.forEach((e=>{r.has(e)&&this.score.score(e)>=this.opts.scoreThresholds.publishThreshold&&(t.add(e),n.floodsub++)}));const s=this.mesh.get(e);if(null!=s&&s.size>0)s.forEach((e=>{t.add(e),n.mesh++}));else{const r=this.fanout.get(e);if(null!=r&&r.size>0)r.forEach((e=>{t.add(e),n.fanout++}));else{const r=this.getRandomGossipPeers(e,this.opts.D,(e=>this.score.score(e)>=this.opts.scoreThresholds.publishThreshold));r.size>0&&(this.fanout.set(e,r),r.forEach((e=>{t.add(e),n.fanout++})))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:n}}forwardMessage(e,t,n,r){null!=n&&this.score.deliverMessage(n,e,t.topic);const s=this.selectPeersToForward(t.topic,n,r);s.forEach((e=>{this.sendRpc(e,Tv([t]))})),this.metrics?.onForwardMsg(t.topic,s.size)}async publish(e,t,n){const r=Date.now(),s=null!=this.dataTransform?this.dataTransform.outboundTransform(e,t):t;if(null==this.publishConfig)throw Error("PublishError.Uninitialized");const{raw:i,msg:o}=await async function(e,t,n,r){switch(e.type){case Yb.Signing:{const s={from:e.author.toBytes(),data:r,seqno:Lo(8),topic:t,signature:void 0,key:void 0},i=In([Av,jb.Message.encode(s)]);return s.signature=await e.privateKey.sign(i),s.key=e.key,{raw:s,msg:{type:"signed",from:e.author,data:n,sequenceNumber:BigInt(`0x${Yt(s.seqno,"base16")}`),topic:t,signature:s.signature,key:s.key}}}case Yb.Anonymous:return{raw:{from:void 0,data:r,seqno:void 0,topic:t,signature:void 0,key:void 0},msg:{type:"unsigned",data:n,topic:t}};default:throw new Error("Unreachable")}}(this.publishConfig,e,t,s),a=await this.msgIdFn(o),c=this.msgIdToStrFn(a),l=n?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(c)){if(l)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}const{tosend:u,tosendCount:h}=this.selectPeersToPublish(e),d=this.opts.emitSelf&&this.subscriptions.has(e),p=n?.allowPublishToZeroTopicPeers??this.opts.allowPublishToZeroTopicPeers;if(0===u.size&&!p&&!d)throw Error("PublishError.NoPeersSubscribedToTopic");this.seenCache.put(c),this.mcache.put({msgId:a,msgIdStr:c},i,!0),this.publishedMessageIds.put(c);const f=n?.batchPublish??this.opts.batchPublish,g=Tv([i]);if(f)this.sendRpcInBatch(u,g);else for(const e of u){this.sendRpc(e,g)||u.delete(e)}const m=Date.now()-r;return this.metrics?.onPublishMsg(e,h,u.size,null!=i.data?i.data.length:0,m),d&&(u.add(this.components.peerId.toString()),super.dispatchEvent(new bn("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:c,msg:o}})),super.dispatchEvent(new bn("message",{detail:o}))),{recipients:Array.from(u.values()).map((e=>Is(e)))}}sendRpcInBatch(e,t){const n=jb.encode(t),r=Mr.single(n);for(const s of e){const i=this.streamsOutbound.get(s);if(null!=i){try{i.pushPrefixed(r)}catch(t){e.delete(s),this.log.error(`Cannot send rpc to ${s}`,t)}this.metrics?.onRpcSent(t,n.length)}else this.log(`Cannot send RPC to ${s} as there is no open stream to it available`),e.delete(s)}}reportMessageValidationResult(e,t,n){let r;if(n===ln.Accept){if(r=this.mcache.validate(e),null!=r){const{message:n,originatingPeers:s}=r;this.score.deliverMessage(t,e,n.topic),this.forwardMessage(e,r.message,t,s)}}else if(r=this.mcache.remove(e),null!=r){const s=ov(n),{message:i,originatingPeers:o}=r;this.score.rejectMessage(t,e,i.topic,s);for(const t of o)this.score.rejectMessage(t,e,i.topic,s)}const s=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(r,n,s)}sendGraft(e,t){const n=Tv([],{graft:[{topicID:t}]});this.sendRpc(e,n)}async sendPrune(e,t){const n=Tv([],{prune:[await this.makePrune(e,t,this.opts.doPX,!0)]});this.sendRpc(e,n)}sendRpc(e,t){const n=this.streamsOutbound.get(e);if(null==n)return this.log(`Cannot send RPC to ${e} as there is no open stream to it available`),!1;const r=this.control.get(e);null!=r&&(this.piggybackControl(e,t,r),this.control.delete(e));const s=this.gossip.get(e);null!=s&&(this.piggybackGossip(e,t,s),this.gossip.delete(e));const i=jb.encode(t);try{n.push(i)}catch(t){return this.log.error(`Cannot send rpc to ${e}`,t),null!=r&&this.control.set(e,r),null!=s&&this.gossip.set(e,s),!1}if(this.metrics?.onRpcSent(t,i.length),null!=t.control?.graft)for(const n of t.control?.graft)null!=n.topicID&&this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:n.topicID,direction:"outbound"}});if(null!=t.control?.prune)for(const n of t.control?.prune)null!=n.topicID&&this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:n.topicID,direction:"outbound"}});return!0}piggybackControl(e,t,n){const r=kv(t);for(const t of n.graft)null!=t.topicID&&this.mesh.get(t.topicID)?.has(e)&&r.control.graft.push(t);for(const t of n.prune)null==t.topicID||this.mesh.get(t.topicID)?.has(e)||r.control.prune.push(t)}piggybackGossip(e,t,n){kv(t).control.ihave=n}async sendGraftPrune(e,t,n){const r=this.opts.doPX,s=!1;for(const[i,o]of e){const e=o.map((e=>({topicID:e})));let a=[];const c=t.get(i);null!=c&&(a=await Promise.all(c.map((async e=>this.makePrune(i,e,r&&!n.get(i),s)))),t.delete(i)),this.sendRpc(i,Tv([],{graft:e,prune:a}))}for(const[e,i]of t){const t=await Promise.all(i.map((async t=>this.makePrune(e,t,r&&!n.get(e),s))));this.sendRpc(e,Tv([],{prune:t}))}}emitGossip(e){const t=this.mcache.getGossipIDs(new Set(e.keys()));for(const[n,r]of e)this.doEmitGossip(n,r,t.get(n)??[])}doEmitGossip(e,t,n){if(0===n.length)return;if(Dv(n),n.length>zb&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",n.length),0===t.size)return;let r=this.opts.Dlazy;const s=.25*t.size;let i=t;s>r&&(r=s),r>i.size?r=i.size:i=Dv(Array.from(i)).slice(0,r),i.forEach((t=>{let r=n;n.length>zb&&(r=Dv(r.slice()).slice(0,zb)),this.pushGossip(t,{topicID:e,messageIDs:r})}))}flush(){for(const[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,Tv([],{ihave:t}));for(const[e,t]of this.control.entries()){this.control.delete(e);const n=Tv([],{graft:t.graft,prune:t.prune});this.sendRpc(e,n)}}pushGossip(e,t){this.log("Add gossip to %s",e);const n=this.gossip.get(e)??[];this.gossip.set(e,n.concat(t))}async makePrune(e,t,n,r){if(this.score.prune(e,t),this.streamsOutbound.get(e)?.protocol===qb)return{topicID:t,peers:[]};const s=r?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,i=s/1e3;if(this.doAddBackoff(e,t,s),!n)return{topicID:t,peers:[],backoff:i};const o=this.getRandomGossipPeers(t,this.opts.prunePeers,(t=>t!==e&&this.score.score(t)>=0)),a=await Promise.all(Array.from(o).map((async e=>{const t=Is(e);let n;try{n=await this.components.peerStore.get(t)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}return{peerID:t.toBytes(),signedPeerRecord:n?.peerRecordEnvelope}})));return{topicID:t,peers:a,backoff:i}}runHeartbeat=()=>{const e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch((e=>{this.log("Error running heartbeat",e)})).finally((()=>{if(null!=e&&e(),this.status.code===Mv.started){clearTimeout(this.status.heartbeatTimeout);let e=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;e<.25*this.opts.heartbeatInterval&&(e+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,e)}}))};async heartbeat(){const{D:e,Dlo:t,Dhi:n,Dscore:r,Dout:s,fanoutTTL:i}=this.opts;this.heartbeatTicks++;const o=new Map,a=e=>{let t=o.get(e);return void 0===t&&(t=this.score.score(e),o.set(e,t)),t},c=new Map,l=new Map,u=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.applyIwantPenalties(),this.heartbeatTicks%this.opts.directConnectTicks==0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();const h=new Map;this.mesh.forEach(((i,o)=>{const d=this.topics.get(o),p=new Set,f=new Set;if(h.set(o,f),null!=d){const e=Dv(Array.from(d)),t=this.backoff.get(o);for(const n of e){const e=this.streamsOutbound.get(n);if(null!=e&&this.multicodecs.includes(e.protocol)&&!i.has(n)&&!this.direct.has(n)){const e=a(n);(null==t||!t.has(n))&&e>=0&&p.add(n),e>=this.opts.scoreThresholds.gossipThreshold&&f.add(n)}}}const g=(e,t)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",e,o),this.addBackoff(e,o),i.delete(e),a(e)>=this.opts.scoreThresholds.gossipThreshold&&f.add(e),this.metrics?.onRemoveFromMesh(o,t,1);const n=l.get(e);null==n?l.set(e,[o]):n.push(o)},m=(e,t)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",e,o),this.score.graft(e,o),i.add(e),f.delete(e),this.metrics?.onAddToMesh(o,t,1);const n=c.get(e);null==n?c.set(e,[o]):n.push(o)};if(i.forEach((e=>{const t=a(e);t<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",e,t,o),g(e,tv.BadScore),u.set(e,!0))})),i.size<t){const t=function(e,t){return fv(e,t,(()=>!0))}(p,e-i.size);t.forEach((e=>{m(e,ev.NotEnough)}))}if(i.size>n){let t=Array.from(i);t.sort(((e,t)=>a(t)-a(e))),t=t.slice(0,r).concat(Dv(t.slice(r)));let n=0;if(t.slice(0,e).forEach((e=>{this.outbound.get(e)&&n++})),n<s){const r=e=>{const n=t[e];for(let n=e;n>0;n--)t[n]=t[n-1];t[0]=n};if(n>0){let s=n;for(let n=1;n<e&&s>0;n++)this.outbound.get(t[n])&&(r(n),s--)}let s=e-n;for(let n=e;n<t.length&&s>0;n++)this.outbound.get(t[n])&&(r(n),s--)}t.slice(e).forEach((e=>{g(e,tv.Excess)}))}if(i.size>=t){let e=0;if(i.forEach((t=>{this.outbound.get(t)&&e++})),e<s){fv(p,s-e,(e=>!0===this.outbound.get(e))).forEach((e=>{m(e,ev.Outbound)}))}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks==0&&i.size>1){const e=Array.from(i).sort(((e,t)=>a(e)-a(t))),t=Math.floor(i.size/2),n=a(e[t]);if(n<this.opts.scoreThresholds.opportunisticGraftThreshold){const e=fv(p,this.opts.opportunisticGraftPeers,(e=>a(e)>n));for(const t of e)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",t,o),m(t,ev.Opportunistic)}}}));const d=Date.now();this.fanoutLastpub.forEach(((e,t)=>{e+i<d&&(this.fanout.delete(t),this.fanoutLastpub.delete(t))})),this.fanout.forEach(((t,n)=>{const r=this.topics.get(n);t.forEach((e=>{(!r?.has(e)||a(e)<this.opts.scoreThresholds.publishThreshold)&&t.delete(e)}));const s=this.topics.get(n),i=[],o=new Set;if(h.set(n,o),null!=s){const e=Dv(Array.from(s));for(const n of e){const e=this.streamsOutbound.get(n);if(null!=e&&this.multicodecs.includes(e.protocol)&&!t.has(n)&&!this.direct.has(n)){const e=a(n);e>=this.opts.scoreThresholds.publishThreshold&&i.push(n),e>=this.opts.scoreThresholds.gossipThreshold&&o.add(n)}}}if(t.size<e){const n=e-t.size;i.slice(0,n).forEach((e=>{t.add(e),o?.delete(e)}))}})),this.emitGossip(h),await this.sendGraftPrune(c,l,u),this.flush(),this.mcache.shift(),this.dispatchEvent(new bn("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,n=(()=>!0)){const r=this.topics.get(e);if(null==r)return new Set;let s=[];return r.forEach((e=>{const t=this.streamsOutbound.get(e);null!=t&&this.multicodecs.includes(t.protocol)&&n(e)&&s.push(e)})),s=Dv(s),t>0&&s.length>t&&(s=s.slice(0,t)),new Set(s)}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;const n=Date.now();e.connectedPeersBackoffSec.reset();for(const r of this.backoff.values()){t+=r.size;for(const[t,s]of r.entries())this.peers.has(t)&&e.connectedPeersBackoffSec.observe(Math.max(0,s-n)/1e3)}e.cacheSize.set({cache:"backoff"},t);for(const[t,n]of this.topics)e.topicPeersCount.set({topicStr:t},n.size);for(const[t,n]of this.mesh)e.meshPeerCounts.set({topicStr:t},n.size);const r=[],s=new Map;e.behaviourPenalty.reset();for(const t of this.peers.keys()){const n=this.score.score(t);r.push(n),s.set(t,n),e.behaviourPenalty.observe(this.score.peerStats.get(t)?.behaviourPenalty??0)}e.registerScores(r,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,s);const i=function(e,t,n,r,s){const i={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(const o of e){const e=t.get(o);if(null!=e){const t=Sv(o,e,n,r,s);for(const[e,n]of t.byTopic){let t=i.byTopic.get(e);null==t&&(t={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},i.byTopic.set(e,t)),t.p1w.push(n.p1w),t.p2w.push(n.p2w),t.p3w.push(n.p3w),t.p3bw.push(n.p3bw),t.p4w.push(n.p4w)}i.p5w.push(t.p5w),i.p6w.push(t.p6w),i.p7w.push(t.p7w),i.score.push(t.score)}else i.p5w.push(0),i.p6w.push(0),i.p7w.push(0),i.score.push(0)}return i}(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(i)}tagMeshPeer=e=>{const{peerId:t,topic:n}=e.detail;this.components.peerStore.merge(Is(t),{tags:{[n]:{value:100}}}).catch((e=>{this.log.error("Error tagging peer %s with topic %s",t,n,e)}))};untagMeshPeer=e=>{const{peerId:t,topic:n}=e.detail;this.components.peerStore.merge(Is(t),{tags:{[n]:void 0}}).catch((e=>{this.log.error("Error untagging peer %s with topic %s",t,n,e)}))}}function Bv(e={}){return t=>new Lv(t,e)}var Uv;!function(e){let t;e.codec=()=>(null==t&&(t=Wt(((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.protocolVersion&&(t.uint32(42),t.string(e.protocolVersion)),null!=e.agentVersion&&(t.uint32(50),t.string(e.agentVersion)),null!=e.publicKey&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.listenAddrs)for(const n of e.listenAddrs)t.uint32(18),t.bytes(n);if(null!=e.observedAddr&&(t.uint32(34),t.bytes(e.observedAddr)),null!=e.protocols)for(const n of e.protocols)t.uint32(26),t.string(n);null!=e.signedPeerRecord&&(t.uint32(66),t.bytes(e.signedPeerRecord)),!1!==n.lengthDelimited&&t.ldelim()}),((e,t)=>{const n={listenAddrs:[],protocols:[]},r=null==t?e.len:e.pos+t;for(;e.pos<r;){const t=e.uint32();switch(t>>>3){case 5:n.protocolVersion=e.string();break;case 6:n.agentVersion=e.string();break;case 1:n.publicKey=e.bytes();break;case 2:n.listenAddrs.push(e.bytes());break;case 4:n.observedAddr=e.bytes();break;case 3:n.protocols.push(e.string());break;case 8:n.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>$t(t,e.codec()),e.decode=t=>j(t,e.codec())}(Uv||(Uv={}));const Fv={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:8192,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnTransientConnection:!0,concurrency:32};async function Vv(e,t,n,r,s){if(n("received identify from %p",r.remotePeer),null==s)throw new pn("message was null or undefined","ERR_INVALID_MESSAGE");const i={};if(s.listenAddrs.length>0&&(i.addresses=s.listenAddrs.map((e=>({isCertified:!1,multiaddr:ar(e)})))),s.protocols.length>0&&(i.protocols=s.protocols),null!=s.publicKey){i.publicKey=s.publicKey;if(!(await As(s.publicKey)).equals(r.remotePeer))throw new pn("public key did not match remote PeerId","ERR_INVALID_PUBLIC_KEY")}let o;if(null!=s.signedPeerRecord){n("received signedPeerRecord from %p",r.remotePeer);let t=s.signedPeerRecord;const a=await Qh.openAndCertify(t,ed.DOMAIN);let c,l=ed.createFromProtobuf(a.payload);if(!l.peerId.equals(a.peerId))throw new pn("signing key does not match PeerId in the PeerRecord","ERR_INVALID_SIGNING_KEY");if(!r.remotePeer.equals(l.peerId))throw new pn("signing key does not match remote PeerId","ERR_INVALID_PEER_RECORD_KEY");try{c=await e.get(l.peerId)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}if(null!=c&&(i.metadata=c.metadata,null!=c.peerRecordEnvelope)){const e=await Qh.createFromProtobuf(c.peerRecordEnvelope),r=ed.createFromProtobuf(e.payload);r.seqNumber>=l.seqNumber&&(n("sequence number was lower or equal to existing sequence number - stored: %d received: %d",r.seqNumber,l.seqNumber),l=r,t=c.peerRecordEnvelope)}i.peerRecordEnvelope=t,i.addresses=l.multiaddrs.map((e=>({isCertified:!0,multiaddr:e}))),o={seq:l.seqNumber,addresses:l.multiaddrs}}else n("%p did not send a signed peer record",r.remotePeer);if(n("patching %p with",r.remotePeer,i),await e.patch(r.remotePeer,i),null!=s.agentVersion||null!=s.protocolVersion){const t={};null!=s.agentVersion&&(t.AgentVersion=kt(s.agentVersion)),null!=s.protocolVersion&&(t.ProtocolVersion=kt(s.protocolVersion)),n("merging %p metadata",r.remotePeer,t),await e.merge(r.remotePeer,{metadata:t})}const a={peerId:r.remotePeer,protocolVersion:s.protocolVersion,agentVersion:s.agentVersion,publicKey:s.publicKey,listenAddrs:s.listenAddrs.map((e=>ar(e))),observedAddr:null==s.observedAddr?void 0:ar(s.observedAddr),protocols:s.protocols,signedPeerRecord:o,connection:r};return t.safeDispatchEvent("peer:identify",{detail:a}),a}class Kv{host;protocol;started;timeout;peerId;peerStore;registrar;addressManager;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;events;runOnTransientConnection;log;constructor(e,t){var n,r;this.protocol=t.protocol,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.events=e.events,this.log=t.log,this.timeout=t.timeout??Fv.timeout,this.maxInboundStreams=t.maxInboundStreams??Fv.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??Fv.maxOutboundStreams,this.maxMessageSize=t.maxMessageSize??Fv.maxMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??Fv.maxObservedAddresses,this.runOnTransientConnection=t.runOnTransientConnection??Fv.runOnTransientConnection,this.host={protocolVersion:`${t.protocolPrefix??Fv.protocolPrefix}/0.1.0`,agentVersion:(n=e.nodeInfo,r=t.agentVersion,null!=r||(r=`${n.name}/${n.version}`,my||fy?r+=` UserAgent=${globalThis.process.version}`:(py||yy||gy||wy)&&(r+=` UserAgent=${globalThis.navigator.userAgent}`)),r)}}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:kt(this.host.agentVersion),ProtocolVersion:kt(this.host.protocolVersion)}}),await this.registrar.handle(this.protocol,(e=>{this.handleProtocol(e).catch((e=>{this.log.error(e)}))}),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.protocol),this.started=!1}}class $v extends Kv{connectionManager;concurrency;constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??Fv.protocolPrefix}/id/push/1.0.0`,log:e.logger.forComponent("libp2p:identify-push")}),this.connectionManager=e.connectionManager,this.concurrency=t.concurrency??Fv.concurrency,(t.runOnSelfUpdate??Fv.runOnSelfUpdate)&&e.events.addEventListener("self:peer:update",(e=>{this.push().catch((e=>{this.log.error(e)}))}))}async push(){if(!this.isStarted())return;const e=this.addressManager.getAddresses().map((e=>e.decapsulateCode(Un("p2p").code))),t=new ed({peerId:this.peerId,multiaddrs:e}),n=await Qh.seal(t,this.peerId),r=this.registrar.getProtocols(),s=await this.peerStore.get(this.peerId),i=Yt(s.metadata.get("AgentVersion")??kt(this.host.agentVersion)),o=Yt(s.metadata.get("ProtocolVersion")??kt(this.host.protocolVersion)),a=this;await Md(Lf(async function*(){for(const t of a.connectionManager.getConnections()){(await a.peerStore.get(t.remotePeer)).protocols.includes(a.protocol)&&(yield async()=>{let s;const c=AbortSignal.timeout(a.timeout);try{s=await t.newStream(a.protocol,{signal:c,runOnTransientConnection:a.runOnTransientConnection});const l=Rw(s,{maxDataLength:a.maxMessageSize}).pb(Uv);await l.write({listenAddrs:e.map((e=>e.bytes)),signedPeerRecord:n.marshal(),protocols:r,agentVersion:i,protocolVersion:o},{signal:c}),await s.close({signal:c})}catch(e){a.log.error("could not push identify update to peer",e),s?.abort(e)}})}}(),{concurrency:this.concurrency}))}async handleProtocol(e){const{connection:t,stream:n}=e;try{if(this.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");const e={signal:AbortSignal.timeout(this.timeout)},r=Rw(n,{maxDataLength:this.maxMessageSize}).pb(Uv),s=await r.read(e);await n.close(e),await Vv(this.peerStore,this.events,this.log,t,s)}catch(e){return this.log.error("received invalid message",e),void n.abort(e)}this.log("handled push from %p",t.remotePeer)}}class qv extends Kv{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??Fv.protocolPrefix}/id/1.0.0`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??Fv.runOnConnectionOpen)&&e.events.addEventListener("connection:open",(e=>{const t=e.detail;this.identify(t).catch((e=>{this.log.error("error during identify trigged by connection:open",e)}))}))}async _identify(e,t={}){let n;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{n=await e.newStream(this.protocol,{...t,runOnTransientConnection:this.runOnTransientConnection});const r=Rw(n,{maxDataLength:this.maxMessageSize}).pb(Uv),s=await r.read(t);return await n.close(t),s}catch(e){throw this.log.error("error while reading identify message",e),n?.abort(e),e}}async identify(e,t={}){const n=await this._identify(e,t),{publicKey:r,protocols:s,observedAddr:i}=n;if(null==r)throw new pn("public key was missing from identify message","ERR_MISSING_PUBLIC_KEY");const o=await As(r);if(!e.remotePeer.equals(o))throw new pn("identified peer does not match the expected peer","ERR_INVALID_PEER");if(this.peerId.equals(o))throw new pn("identified peer is our own peer id?","ERR_INVALID_PEER");const a=function(e){if(null!=e&&e.length>0)try{return ar(e)}catch{}}(i);return this.log("identify completed for peer %p and protocols %o",o,s),this.log("our observed address is %a",a),null!=a&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(this.log("storing our observed address %a",a),this.addressManager.addObservedAddr(a)),Vv(this.peerStore,this.events,this.log,e,n)}async handleProtocol(e){const{connection:t,stream:n}=e,r=AbortSignal.timeout(this.timeout);try{const e=this.peerId.publicKey??new Uint8Array(0),s=await this.peerStore.get(this.peerId),i=this.addressManager.getAddresses().map((e=>e.decapsulateCode(Un("p2p").code)));let o=s.peerRecordEnvelope;if(i.length>0&&null==o){const e=new ed({peerId:this.peerId,multiaddrs:i});o=(await Qh.seal(e,this.peerId)).marshal().subarray()}let a=t.remoteAddr.bytes;gp.matches(t.remoteAddr)||(a=void 0);const c=Rw(n).pb(Uv);await c.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:e,listenAddrs:i.map((e=>e.bytes)),signedPeerRecord:o,observedAddr:a,protocols:s.protocols},{signal:r}),await n.close({signal:r})}catch(e){this.log.error("could not respond to identify request",e),n.abort(e)}}}function Hv(e={}){return t=>new qv(t,e)}function zv(e={}){return t=>new $v(t,e)}const Wv=36e5,jv=36*Wv,Gv="/dht/provider",Yv=Wv,Qv=20,Jv=3;var Zv,Xv,eE,tE,nE,rE,sE,iE;function oE(e){const t=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0"),r=String(e.getUTCDate()).padStart(2,"0"),s=String(e.getUTCHours()).padStart(2,"0"),i=String(e.getUTCMinutes()).padStart(2,"0"),o=String(e.getUTCSeconds()).padStart(2,"0"),a=e.getUTCMilliseconds();return`${t}-${n}-${r}T${s}:${i}:${o}.${String(1e3*a*1e3).padStart(9,"0")}Z`}!function(e){let t;e.codec=()=>(null==t&&(t=Wt(((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.key&&e.key.byteLength>0&&(t.uint32(10),t.bytes(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),null!=e.timeReceived&&""!==e.timeReceived&&(t.uint32(42),t.string(e.timeReceived)),!1!==n.lengthDelimited&&t.ldelim()}),((e,t,n={})=>{const r={key:m(0),value:m(0),timeReceived:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:r.key=e.bytes();break;case 2:r.value=e.bytes();break;case 5:r.timeReceived=e.string();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,n)=>j(t,e.codec(),n)}(Zv||(Zv={}));class aE{key;value;timeReceived;constructor(e,t,n){if(!(e instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(t instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=e,this.value=t,this.timeReceived=n}serialize(){return Zv.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:oE(this.timeReceived)}}static deserialize(e){const t=Zv.decode(e);return new aE(t.key,t.value,new Date(t.timeReceived))}static fromDeserialized(e){const t=function(e){const t=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),n=String(e).trim().match(t);if(null==n)throw new Error("Invalid format");const r=parseInt(n[1],10),s=parseInt(n[2],10)-1,i=parseInt(n[3],10),o=parseInt(n[4],10),a=parseInt(n[5],10),c=parseInt(n[6],10),l=parseInt(n[7].slice(0,-6),10);return new Date(Date.UTC(r,s,i,o,a,c,l))}(e.timeReceived);if(null==e.key)throw new Error("key missing from deserialized object");if(null==e.value)throw new Error("value missing from deserialized object");return new aE(e.key,e.value,t)}}function cE(e,t={}){const n={...e,name:"SEND_QUERY",type:0,messageName:e.type,messageType:e.type};return t.onProgress?.(new bn("kad-dht:query:send-query",{detail:n})),n}function lE(e,t={}){const n={...e,name:"PEER_RESPONSE",type:1,messageName:e.messageType,closer:null!=e.closer?e.closer:[],providers:null!=e.providers?e.providers:[]};return t.onProgress?.(new bn("kad-dht:query:peer-response",{detail:n})),n}function uE(e,t={}){const n={...e,name:"FINAL_PEER",type:2};return t.onProgress?.(new bn("kad-dht:query:final-peer",{detail:n})),n}function hE(e,t={}){const n={...e,name:"QUERY_ERROR",type:3};return t.onProgress?.(new bn("kad-dht:query:query-error",{detail:n})),n}function dE(e,t={}){const n={...e,name:"PROVIDER",type:4};return t.onProgress?.(new bn("kad-dht:query:provider",{detail:n})),n}function pE(e,t={}){const n={...e,name:"VALUE",type:5};return t.onProgress?.(new bn("kad-dht:query:value",{detail:n})),n}function fE(e,t={}){const n={...e,name:"DIAL_PEER",type:7};return t.onProgress?.(new bn("kad-dht:query:dial-peer",{detail:n})),n}!function(e){let t;e.codec=()=>(null==t&&(t=Wt(((e,t,n={})=>{!1!==n.lengthDelimited&&t.fork(),null!=e.key&&(t.uint32(10),t.bytes(e.key)),null!=e.value&&(t.uint32(18),t.bytes(e.value)),null!=e.author&&(t.uint32(26),t.bytes(e.author)),null!=e.signature&&(t.uint32(34),t.bytes(e.signature)),null!=e.timeReceived&&(t.uint32(42),t.string(e.timeReceived)),!1!==n.lengthDelimited&&t.ldelim()}),((e,t)=>{const n={},r=null==t?e.len:e.pos+t;for(;e.pos<r;){const t=e.uint32();switch(t>>>3){case 1:n.key=e.bytes();break;case 2:n.value=e.bytes();break;case 3:n.author=e.bytes();break;case 4:n.signature=e.bytes();break;case 5:n.timeReceived=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>$t(t,e.codec()),e.decode=t=>j(t,e.codec())}(Xv||(Xv={})),function(e){e.PUT_VALUE="PUT_VALUE",e.GET_VALUE="GET_VALUE",e.ADD_PROVIDER="ADD_PROVIDER",e.GET_PROVIDERS="GET_PROVIDERS",e.FIND_NODE="FIND_NODE",e.PING="PING"}(eE||(eE={})),function(e){e[e.PUT_VALUE=0]="PUT_VALUE",e[e.GET_VALUE=1]="GET_VALUE",e[e.ADD_PROVIDER=2]="ADD_PROVIDER",e[e.GET_PROVIDERS=3]="GET_PROVIDERS",e[e.FIND_NODE=4]="FIND_NODE",e[e.PING=5]="PING"}(tE||(tE={})),function(e){e.codec=()=>zt(tE)}(eE||(eE={})),function(e){e.NOT_CONNECTED="NOT_CONNECTED",e.CONNECTED="CONNECTED",e.CAN_CONNECT="CAN_CONNECT",e.CANNOT_CONNECT="CANNOT_CONNECT"}(nE||(nE={})),function(e){e[e.NOT_CONNECTED=0]="NOT_CONNECTED",e[e.CONNECTED=1]="CONNECTED",e[e.CAN_CONNECT=2]="CAN_CONNECT",e[e.CANNOT_CONNECT=3]="CANNOT_CONNECT"}(rE||(rE={})),function(e){e.codec=()=>zt(rE)}(nE||(nE={})),function(e){let t;e.codec=()=>(null==t&&(t=Wt(((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.id&&e.id.byteLength>0&&(t.uint32(10),t.bytes(e.id)),null!=e.multiaddrs)for(const n of e.multiaddrs)t.uint32(18),t.bytes(n);null!=e.connection&&(t.uint32(24),nE.codec().encode(e.connection,t)),!1!==n.lengthDelimited&&t.ldelim()}),((e,t)=>{const n={id:m(0),multiaddrs:[]},r=null==t?e.len:e.pos+t;for(;e.pos<r;){const t=e.uint32();switch(t>>>3){case 1:n.id=e.bytes();break;case 2:n.multiaddrs.push(e.bytes());break;case 3:n.connection=nE.codec().decode(e);break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>$t(t,e.codec()),e.decode=t=>j(t,e.codec())}(sE||(sE={})),function(e){let t;e.codec=()=>(null==t&&(t=Wt(((e,t,n={})=>{if(!1!==n.lengthDelimited&&t.fork(),null!=e.type&&0!==tE[e.type]&&(t.uint32(8),eE.codec().encode(e.type,t)),null!=e.clusterLevel&&(t.uint32(80),t.int32(e.clusterLevel)),null!=e.key&&(t.uint32(18),t.bytes(e.key)),null!=e.record&&(t.uint32(26),t.bytes(e.record)),null!=e.closer)for(const n of e.closer)t.uint32(66),sE.codec().encode(n,t);if(null!=e.providers)for(const n of e.providers)t.uint32(74),sE.codec().encode(n,t);!1!==n.lengthDelimited&&t.ldelim()}),((e,t)=>{const n={type:eE.PUT_VALUE,closer:[],providers:[]},r=null==t?e.len:e.pos+t;for(;e.pos<r;){const t=e.uint32();switch(t>>>3){case 1:n.type=eE.codec().decode(e);break;case 10:n.clusterLevel=e.int32();break;case 2:n.key=e.bytes();break;case 3:n.record=e.bytes();break;case 8:n.closer.push(sE.codec().decode(e,e.uint32()));break;case 9:n.providers.push(sE.codec().decode(e,e.uint32()));break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>$t(t,e.codec()),e.decode=t=>j(t,e.codec())}(iE||(iE={}));const gE={pk:function(e,t){return 0}};async function mE(e,t){const n=t.key,r=Yt(n).split("/");if(r.length<3)return;const s=e[r[1].toString()];if(null==s){const e=`No validator available for key type "${r[1]}"`;throw new pn(e,"ERR_INVALID_RECORD_KEY_TYPE")}await s(n,t.value)}const yE={pk:async(e,t)=>{if(!(e instanceof Uint8Array))throw new pn('"key" must be a Uint8Array',"ERR_INVALID_RECORD_KEY_NOT_BUFFER");if(e.byteLength<5)throw new pn("invalid public key record","ERR_INVALID_RECORD_KEY_TOO_SHORT");if("/pk/"!==Yt(e.subarray(0,4)))throw new pn("key was not prefixed with /pk/","ERR_INVALID_RECORD_KEY_BAD_PREFIX");if(!_n(e.slice(4),(await ft.digest(t)).bytes))throw new pn("public key does not match passed in key","ERR_INVALID_RECORD_HASH_MISMATCH")}},wE=kt("/pk/");function bE(e){return{...e,multiaddrs:e.multiaddrs.filter((e=>{const[[t,n]]=e.stringTuples();if(53===t||54===t||55===t)return"localhost"!==n;if(4!==t&&6!==t)return!1;if(null==n)return!1;const r=Qd(n);return null==r||!r}))}}async function vE(e){return(await ft.digest(e)).digest}async function EE(e){return vE(e.toBytes())}function SE(e){return new Xt(`/dht/record/${Yt(e,"base32")}`,!1)}function _E(e,t){const n=new Date;return new aE(e,t,n).serialize()}class IE{log;components;validators;selectors;peerRouting;queryManager;network;constructor(e,t){const{validators:n,selectors:r,peerRouting:s,queryManager:i,network:o,logPrefix:a}=t;this.components=e,this.log=e.logger.forComponent(`${a}:content-fetching`),this.validators=n,this.selectors=r,this.peerRouting=s,this.queryManager=i,this.network=o}async getLocal(e){this.log("getLocal %b",e);const t=SE(e);this.log("fetching record for key %k",t);const n=await this.components.datastore.get(t);this.log("found %k in local datastore",t);const r=aE.deserialize(n);return await mE(this.validators,r),r}async*sendCorrectionRecord(e,t,n,r={}){this.log("sendCorrection for %b",e);const s=_E(e,n);for(const{value:i,from:o}of t){if(_n(i,n)){this.log("record was ok");continue}if(this.components.peerId.equals(o)){try{const t=SE(e);this.log(`Storing corrected record for key ${t.toString()}`),await this.components.datastore.put(t,s.subarray())}catch(e){this.log.error("Failed error correcting self",e)}continue}let t=!1;const a={type:eE.PUT_VALUE,key:e,record:s};for await(const e of this.network.sendRequest(o,a,r))"PEER_RESPONSE"===e.name&&null!=e.record&&_n(e.record.value,aE.deserialize(s).value)&&(t=!0),yield e;t||(yield hE({from:o,error:new pn("value not put correctly","ERR_PUT_VALUE_INVALID")},r)),this.log.error("Failed error correcting entry")}}async*put(e,t,n={}){this.log("put key %b value %b",e,t);const r=_E(e,t),s=SE(e);this.log(`storing record for key ${s.toString()}`),await this.components.datastore.put(s,r.subarray()),yield*fr(this.peerRouting.getClosestPeers(e,{signal:n.signal}),(t=>Hr(t,(t=>async()=>{if("FINAL_PEER"!==t.name)return[t];const s=[],i={type:eE.PUT_VALUE,key:e,record:r};this.log("send put to %p",t.peer.id);for await(const e of this.network.sendRequest(t.peer.id,i,n))s.push(e),"PEER_RESPONSE"===e.name&&(null!=e.record&&_n(e.record.value,aE.deserialize(r).value)||s.push(hE({from:t.peer.id,error:new pn("value not put correctly","ERR_PUT_VALUE_INVALID")},n)));return s}))),(e=>Lf(e,{ordered:!1,concurrency:Jv})),(async function*(e){for await(const t of e)yield*t}))}async*get(e,t={}){this.log("get %b",e);const n=[];for await(const r of this.getMany(e,t))"VALUE"===r.name&&n.push(r),yield r;if(0===n.length)return;const r=n.map((e=>e.value));let s=0;try{s=function(e,t,n){if(0===n.length)throw new pn("No records given","ERR_NO_RECORDS_RECEIVED");const r=Yt(t).split("/");if(r.length<3)throw new pn("Record key does not have a selector function","ERR_NO_SELECTOR_FUNCTION_FOR_RECORD_KEY");const s=e[r[1].toString()];if(null==s){const e=`No selector function configured for key type "${r[1]}"`;throw new pn(e,"ERR_UNRECOGNIZED_KEY_PREFIX")}return 1===n.length?0:s(t,n)}(this.selectors,e,r)}catch(e){if("ERR_NO_SELECTOR_FUNCTION_FOR_RECORD_KEY"!==e.code)throw e}const i=r[s];if(this.log("GetValue %b %b",e,i),null==i)throw new pn("best value was not found","ERR_NOT_FOUND");yield*this.sendCorrectionRecord(e,n,i,t),yield n[s]}async*getMany(e,t={}){this.log("getMany values for %b",e);try{const n=await this.getLocal(e);yield pE({value:n.value,from:this.components.peerId},t)}catch(t){this.log("error getting local value for %b",e,t)}const n=this;yield*this.queryManager.run(e,(async function*({peer:r,signal:s}){for await(const i of n.peerRouting.getValueOrPeers(r,e,{signal:s}))yield i,"PEER_RESPONSE"===i.name&&null!=i.record&&(yield pE({from:r,value:i.record.value},t))}),t)}}function RE(e){if(null==e.id)throw new Error("Invalid peer in message");return{id:Rs(e.id),multiaddrs:(e.multiaddrs??[]).map((e=>ar(e)))}}class AE{log;components;network;peerRouting;queryManager;routingTable;providers;constructor(e,t){const{network:n,peerRouting:r,queryManager:s,routingTable:i,providers:o,logPrefix:a}=t;this.components=e,this.log=e.logger.forComponent(`${a}:content-routing`),this.network=n,this.peerRouting=r,this.queryManager=s,this.routingTable=i,this.providers=o}async*provide(e,t,n={}){this.log("provide %s",e);const r=e.multihash.bytes;await this.providers.addProvider(e,this.components.peerId);const s={type:eE.ADD_PROVIDER,key:r,providers:[(i={id:this.components.peerId,multiaddrs:t},{id:i.id.toBytes(),multiaddrs:(i.multiaddrs??[]).map((e=>e.bytes)),connection:o})]};var i,o;let a=0;const c=t=>async()=>{if("FINAL_PEER"!==t.name)return[t];const r=[];this.log("putProvider %s to %p",e,t.peer.id);try{this.log("sending provider record for %s to %p",e,t.peer.id);for await(const i of this.network.sendMessage(t.peer.id,s,n))"PEER_RESPONSE"===i.name&&(this.log("sent provider record for %s to %p",e,t.peer.id),a++),r.push(i)}catch(e){this.log.error("error sending provide record to peer %p",t.peer.id,e),r.push(hE({from:t.peer.id,error:e},n))}return r};yield*fr(this.peerRouting.getClosestPeers(r,n),(e=>Hr(e,(e=>c(e)))),(e=>Lf(e,{ordered:!1,concurrency:Jv})),(async function*(e){for await(const t of e)yield*t})),this.log("sent provider records to %d peers",a)}async*findProviders(e,t){const n=this.routingTable.kBucketSize;let r=0;const s=e.multihash.bytes,i=this;this.log("findProviders %c",e);const o=await this.providers.getProviders(e);if(o.length>0){const e=[];for(const t of o.slice(0,n))try{const n=await this.components.peerStore.get(t);e.push({id:t,multiaddrs:n.addresses.map((({multiaddr:e})=>e))})}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e;this.log("no peer store entry for %p",t)}if(yield lE({from:this.components.peerId,messageType:eE.GET_PROVIDERS,providers:e},t),yield dE({from:this.components.peerId,providers:e},t),r+=e.length,r>=n)return}const a=async function*({peer:e,signal:n}){const r={type:eE.GET_PROVIDERS,key:s};yield*i.network.sendRequest(e,r,{...t,signal:n})},c=new Wh(o);for await(const i of this.queryManager.run(s,a,t))if(yield i,"PEER_RESPONSE"===i.name){this.log("Found %d provider entries for %c and %d closer peers",i.providers.length,e,i.closer.length);const s=[];for(const e of i.providers)c.has(e.id)||(c.add(e.id),s.push(e));if(s.length>0&&(yield dE({from:i.from,providers:s},t),r+=s.length,r>=n))return}}}class TE{movingAverage;variance;deviation;forecast;timespan;previousTime;constructor(e){this.timespan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timespan)}push(e,t=Date.now()){if(null!=this.previousTime){const n=this.alpha(t,this.previousTime),r=e-this.movingAverage,s=n*r;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+r*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*r}else this.movingAverage=e;this.previousTime=t}}class kE{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new TE(e.interval??5e3),this.failure=new TE(e.interval??5e3),this.next=new TE(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??2,this.timeoutMultiplier=e.timeoutMultiplier??1.2,this.minTimeout=e.minTimeout??2e3,null!=e.metricName&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){const t=Math.max(Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(t),r=Ts([e.signal,n]);return r.start=Date.now(),r.timeout=t,r}cleanUp(e){const t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}}class DE extends yn{log;protocol;running;components;timeout;constructor(e,t){super();const{protocol:n}=t;this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:network`),this.running=!1,this.protocol=n,this.timeout=new kE({...t.timeout??{},metrics:e.metrics,metricName:`${t.logPrefix.replaceAll(":","_")}_network_message_send_times_milliseconds`})}async start(){this.running||(this.running=!0)}async stop(){this.running=!1}isStarted(){return this.running}async*sendRequest(e,t,n={}){if(!this.running)return;const r=t.type;if(null==r)throw new jt("Message type was missing","ERR_INVALID_PARAMETERS");let s;this.log("sending %s to %p",t.type,e),yield fE({peer:e},n),yield cE({to:e,type:r},n);const i=this.timeout.getTimeoutSignal(n);n={...n,signal:i};try{const r=await this.components.connectionManager.openConnection(e,n);s=await r.newStream(this.protocol,n);const i=await this._writeReadMessage(s,t,n);s.close(n).catch((t=>{this.log.error("error closing stream to %p",e,t),s?.abort(t)})),yield lE({from:e,messageType:i.type,closer:i.closer.map(RE),providers:i.providers.map(RE),record:null==i.record?void 0:aE.deserialize(i.record)},n)}catch(r){s?.abort(r),this.log.error("could not send %s to %p",t.type,e,r),yield hE({from:e,error:r},n)}finally{this.timeout.cleanUp(i)}}async*sendMessage(e,t,n={}){if(!this.running)return;const r=t.type;if(null==r)throw new jt("Message type was missing","ERR_INVALID_PARAMETERS");let s;this.log("sending %s to %p",t.type,e),yield fE({peer:e},n),yield cE({to:e,type:r},n);const i=this.timeout.getTimeoutSignal(n);n={...n,signal:i};try{const i=await this.components.connectionManager.openConnection(e,n);s=await i.newStream(this.protocol,n),await this._writeMessage(s,t,n),s.close(n).catch((t=>{this.log.error("error closing stream to %p",e,t),s?.abort(t)})),yield lE({from:e,messageType:r},n)}catch(t){s?.abort(t),yield hE({from:e,error:t},n)}finally{this.timeout.cleanUp(i)}}async _writeMessage(e,t,n){const r=Rw(e);await r.write(t,iE,n),await r.unwrap().close(n)}async _writeReadMessage(e,t,n){const r=Rw(e);await r.write(t,iE,n);const s=await r.read(iE,n);return await r.unwrap().close(n),s.closer.forEach((e=>{this.safeDispatchEvent("peer",{detail:RE(e)})})),s.providers.forEach((e=>{this.safeDispatchEvent("peer",{detail:RE(e)})})),s}}function PE(e,t){if(e.byteLength!==t.byteLength)throw new Error("Inputs should have the same length");for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return e[n]<t[n]?-1:1;return 0}class CE{originDhtKey;capacity;peerDistances;constructor(e,t){this.originDhtKey=e,this.capacity=t,this.peerDistances=[]}get length(){return this.peerDistances.length}get peers(){return this.peerDistances.map((e=>e.peer))}async add(e){const t=await EE(e.id);this.addWitKadId(e,t)}addWitKadId(e,t){if(null!=this.peerDistances.find((t=>t.peer.id.equals(e.id))))return;const n={peer:e,distance:ym(this.originDhtKey,t)};this.peerDistances.push(n),this.peerDistances.sort(((e,t)=>PE(e.distance,t.distance))),this.peerDistances=this.peerDistances.slice(0,this.capacity)}async isCloser(e){if(0===this.length)return!0;return-1===PE(ym(await EE(e),this.originDhtKey),this.peerDistances[this.peerDistances.length-1].distance)}async anyCloser(e){return 0!==e.length&&Promise.any(e.map((async e=>this.isCloser(e))))}}class xE{log;routingTable;network;validators;queryManager;peerStore;peerId;constructor(e,t){const{routingTable:n,network:r,validators:s,queryManager:i,logPrefix:o}=t;this.routingTable=n,this.network=r,this.validators=s,this.queryManager=i,this.peerStore=e.peerStore,this.peerId=e.peerId,this.log=e.logger.forComponent(`${o}:peer-routing`)}async findPeerLocal(e){let t;const n=await this.routingTable.find(e);if(null!=n){this.log("findPeerLocal found %p in routing table",e);try{t=await this.peerStore.get(n)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}}if(null==t)try{t=await this.peerStore.get(e)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}if(null!=t)return this.log("findPeerLocal found %p in peer store",e),{id:t.id,multiaddrs:t.addresses.map((e=>e.multiaddr))}}async*_getValueSingle(e,t,n={}){const r={type:eE.GET_VALUE,key:t};yield*this.network.sendRequest(e,r,n)}async*getPublicKeyFromNode(e,t={}){const n=function(e){return In([wE,e.toBytes()])}(e);for await(const r of this._getValueSingle(e,n,t))if(yield r,"PEER_RESPONSE"===r.name&&null!=r.record){const n=await As($l({bytes:r.record.value}));if(!n.equals(e))throw new pn("public key does not match id","ERR_PUBLIC_KEY_DOES_NOT_MATCH_ID");if(null==n.publicKey)throw new pn("public key missing","ERR_PUBLIC_KEY_MISSING");yield pE({from:e,value:n.publicKey},t)}throw new pn(`Node not responding with its public key: ${e.toString()}`,"ERR_INVALID_RECORD")}async*findPeer(e,t={}){if(this.log("findPeer %p",e),!1!==t.useCache){const n=await this.findPeerLocal(e);if(null!=n)return this.log("found local"),void(yield uE({from:this.peerId,peer:n},t))}let n=!1;if(!1!==t.useNetwork){const r=this,s=async function*({peer:n,signal:s}){const i={type:eE.FIND_NODE,key:e.toBytes()};for await(const o of r.network.sendRequest(n,i,{...t,signal:s}))if(yield o,"PEER_RESPONSE"===o.name){const n=o.closer.find((t=>t.id.equals(e)));null!=n&&(yield uE({from:o.from,peer:n},t))}};for await(const r of this.queryManager.run(e.toBytes(),s,t))"FINAL_PEER"===r.name&&(n=!0),yield r}n||(yield hE({from:this.peerId,error:new pn("Not found","ERR_NOT_FOUND")},t))}async*getClosestPeers(e,t={}){this.log("getClosestPeers to %b",e);const n=await vE(e),r=this.routingTable.closestPeers(n),s=this,i=new CE(n,this.routingTable.kBucketSize);await Promise.all(r.map((async e=>{await i.add({id:e,multiaddrs:[]})})));const o=async function*({peer:n,signal:r}){s.log("closerPeersSingle %s from %p",Yt(e,"base32"),n);const i={type:eE.FIND_NODE,key:e};yield*s.network.sendRequest(n,i,{...t,signal:r})};for await(const n of this.queryManager.run(e,o,t))"PEER_RESPONSE"===n.name&&await Promise.all(n.closer.map((async e=>{await i.add(e)}))),yield n;this.log("found %d peers close to %b",i.length,e);for(const e of i.peers)yield uE({from:this.peerId,peer:e},t)}async*getValueOrPeers(e,t,n={}){for await(const r of this._getValueSingle(e,t,n)){if("PEER_RESPONSE"===r.name&&null!=r.record)try{await this._verifyRecordOnline(r.record)}catch(e){const t="invalid record received, discarded";this.log(t),yield hE({from:r.from,error:new pn(t,"ERR_INVALID_RECORD")},n);continue}yield r}}async _verifyRecordOnline(e){if(null==e.timeReceived)throw new pn("invalid record received","ERR_INVALID_RECORD");await mE(this.validators,new aE(e.key,e.value,e.timeReceived))}async getCloserPeersOffline(e,t){const n=await vE(e),r=this.routingTable.closestPeers(n),s=[];for(const e of r)if(!e.equals(t))try{const t=await this.peerStore.get(e);s.push({id:e,multiaddrs:t.addresses.map((({multiaddr:e})=>e))})}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}return s.length>0?this.log("getCloserPeersOffline found %d peer(s) closer to %b than %p",s.length,e,t):this.log("getCloserPeersOffline could not find peer closer to %b than %p with %d peers in the routing table",e,t,this.routingTable.size),s}}class NE{log;datastore;cache;cleanupInterval;provideValidity;syncQueue;started;cleaner;constructor(e,t={}){const{cacheSize:n,cleanupInterval:r,provideValidity:s}=t;this.log=e.logger.forComponent("libp2p:kad-dht:providers"),this.datastore=e.datastore,this.cleanupInterval=r??Yv,this.provideValidity=s??864e5,this.cache=Kp(n??256),this.syncQueue=new xh({concurrency:1}),this.started=!1}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cleaner=setInterval((()=>{this._cleanup().catch((e=>{this.log.error(e)}))}),this.cleanupInterval))}async stop(){this.started=!1,null!=this.cleaner&&(clearInterval(this.cleaner),this.cleaner=void 0)}async _cleanup(){await this.syncQueue.add((async()=>{const e=Date.now();let t=0,n=0;const r=new Map,s=this.datastore.batch(),i=this.datastore.query({prefix:Gv});for await(const e of i)try{const{cid:i,peerId:o}=OE(e.key),a=LE(e.value).getTime(),c=Date.now(),l=c-a,u=l>this.provideValidity;if(this.log("comparing: %d - %d = %d > %d %s",c,a,l,this.provideValidity,u?"(expired)":""),u){n++,s.delete(e.key);const t=r.get(i)??new Set;t.add(o),r.set(i,t)}t++}catch(e){this.log.error(e.message)}r.size>0?(this.log("deleting %d / %d entries",n,t),await s.commit()):this.log("nothing to delete");for(const[e,t]of r){const n=ME(e),r=this.cache.get(n);if(null!=r){for(const e of t)r.delete(e);0===r.size?this.cache.remove(n):this.cache.set(n,r)}}this.log("Cleanup successful (%dms)",Date.now()-e)}))}async _getProvidersMap(e){const t=ME(e);let n=this.cache.get(t);return null==n&&(n=await async function(e,t){const n=new Map,r=e.query({prefix:ME(t)});for await(const e of r){const{peerId:t}=OE(e.key);n.set(t,LE(e.value))}return n}(this.datastore,e),this.cache.set(t,n)),n}async addProvider(e,t){await this.syncQueue.add((async()=>{this.log("%p provides %s",t,e);const n=await this._getProvidersMap(e);this.log("loaded %s provs",n.size);const r=new Date;n.set(t.toString(),r);const s=ME(e);this.cache.set(s,n),await async function(e,t,n,r){const s=[ME(t),"/",n.toString()].join(""),i=new Xt(s),o=P(r.getTime());await e.put(i,o)}(this.datastore,e,t,r)}))}async getProviders(e){return this.syncQueue.add((async()=>{this.log("get providers for %s",e);return[...(await this._getProvidersMap(e)).keys()].map((e=>Is(e)))}),{throwOnTimeout:!0})}}function ME(e){const t="string"==typeof e?e:Yt(e.multihash.bytes,"base32");return`${Gv}/${t}`}function OE(e){const t=e.toString().split("/");if(5!==t.length)throw new Error(`incorrectly formatted provider entry key in datastore: ${e.toString()}`);return{cid:t[3],peerId:t[4]}}function LE(e){return new Date(C(e))}class BE{disjointPaths;alpha;shutDownController;running;queries;logger;peerId;connectionManager;routingTable;initialQuerySelfHasRun;logPrefix;metrics;constructor(e,t){const{disjointPaths:n=Qv,alpha:r=Jv,logPrefix:s}=t;this.logPrefix=s,this.disjointPaths=n??Qv,this.running=!1,this.alpha=r??Jv,this.queries=0,this.initialQuerySelfHasRun=t.initialQuerySelfHasRun,this.routingTable=t.routingTable,this.logger=e.logger,this.peerId=e.peerId,this.connectionManager=e.connectionManager,null!=e.metrics&&(this.metrics={runningQueries:e.metrics.registerMetric(`${s.replaceAll(":","_")}_running_queries`),queryTime:e.metrics.registerMetric(`${s.replaceAll(":","_")}_query_time_seconds`)}),this.shutDownController=new AbortController,this.shutDownController.signal}isStarted(){return this.running}async start(){this.running=!0,this.shutDownController=new AbortController,this.shutDownController.signal}async stop(){this.running=!1,this.shutDownController.abort()}async*run(e,t,n={}){if(!this.running)throw new Error("QueryManager not started");const r=this.metrics?.queryTime.timer();if(null==n.signal){const e=AbortSignal.timeout(18e4);n={...n,signal:e}}const s=new AbortController,i=Ts([this.shutDownController.signal,s.signal,n.signal]);s.signal;const o=this.logger.forComponent(`${this.logPrefix}:query:`+Yt(e,"base58btc")),a=Date.now();let c=!1;try{!0!==n.isSelfQuery&&null!=this.initialQuerySelfHasRun&&(o("waiting for initial query-self query before continuing"),await Rr(this.initialQuerySelfHasRun.promise,i),this.initialQuerySelfHasRun=void 0),o("query:start"),this.queries++,this.metrics?.runningQueries.update(this.queries);const r=await vE(e),s=this.routingTable.closestPeers(r),a=s.slice(0,Math.min(this.disjointPaths,s.length));if(0===s.length)return void o.error("Running query with no peers");const l=new Wh,u=a.map(((r,s)=>async function*(e){const{key:t,startingPeer:n,ourPeerId:r,signal:s,query:i,alpha:o,pathIndex:a,numPaths:c,queryFuncTimeout:l,log:u,peersSeen:h,connectionManager:d}=e,p=new bf({concurrency:o,sort:(e,t)=>PE(e.options.distance,t.options.distance)}),f=await vE(t);!function n(o,g){if(null==o)return;h.add(o);const m=ym(g,f);p.add((async()=>{const g=[s];null!=l&&g.push(AbortSignal.timeout(l));const y=Ts(g);try{for await(const e of i({key:t,peer:o,signal:y,pathIndex:a,numPaths:c})){if(y.aborted)return;if("PEER_RESPONSE"===e.name)for(const s of e.closer){if(h.has(s.id)){u("already seen %p in query",s.id);continue}if(r.equals(s.id)){u("not querying ourselves");continue}if(!await d.isDialable(s.multiaddrs)){u("not querying undialable peer");continue}const e=await EE(s.id);-1===PE(ym(e,f),m)?(u("querying closer peer %p",s.id),n(s.id,e)):u("skipping %p as they are not closer to %b than %p",s.id,t,o)}p.safeDispatchEvent("completed",{detail:e})}}catch(t){if(!s.aborted)return hE({from:o,error:t},e)}finally{y.clear()}}),{distance:m}).catch((e=>{u.error(e)}))}(n,await EE(n));try{for await(const e of p.toGenerator({signal:s}))null!=e&&(yield e)}catch(e){if(s.aborted)throw new pn("Query aborted","ERR_QUERY_ABORTED");throw e}}({key:e,startingPeer:r,ourPeerId:this.peerId,signal:i,query:t,pathIndex:s,numPaths:a.length,alpha:this.alpha,queryFuncTimeout:n.queryFuncTimeout,log:o,peersSeen:l,onProgress:n.onProgress,connectionManager:this.connectionManager})));for await(const e of pr(...u)){if("QUERY_ERROR"===e.name&&o.error("query error",e.error),"PEER_RESPONSE"===e.name)for(const t of[...e.closer,...e.providers])await this.connectionManager.isDialable(t.multiaddrs)&&await this.routingTable.add(t.id);yield e}c=!0}catch(e){if(this.running||"ERR_QUERY_ABORTED"!==e.code)throw e}finally{c||(o("query exited early"),s.abort()),i.clear(),this.queries--,this.metrics?.runningQueries.update(this.queries),null!=r&&r(),o("query:done in %dms",Date.now()-a)}}}function UE(e){if(null!=e[Symbol.asyncIterator])return(async()=>{let t=0;for await(const n of e)t++;return t})();{let t=0;for(const n of e)t++;return t}}class FE{log;peerId;peerRouting;routingTable;count;interval;initialInterval;queryTimeout;started;timeoutId;controller;initialQuerySelfHasRun;querySelfPromise;constructor(e,t){const{peerRouting:n,logPrefix:r,count:s,interval:i,queryTimeout:o,routingTable:a}=t;this.peerId=e.peerId,this.log=e.logger.forComponent(`${r}:query-self`),this.started=!1,this.peerRouting=n,this.routingTable=a,this.count=s??Qv,this.interval=i??3e5,this.initialInterval=t.initialInterval??1e3,this.queryTimeout=o??5e3,this.initialQuerySelfHasRun=t.initialQuerySelfHasRun}isStarted(){return this.started}start(){this.started||(this.started=!0,clearTimeout(this.timeoutId),this.timeoutId=setTimeout((()=>{this.querySelf().catch((e=>{this.log.error("error running self-query",e)}))}),this.initialInterval))}stop(){this.started=!1,null!=this.timeoutId&&clearTimeout(this.timeoutId),null!=this.controller&&this.controller.abort()}async querySelf(){if(this.started){if(null!=this.querySelfPromise)return this.log("joining existing self query"),this.querySelfPromise.promise;if(this.querySelfPromise=cr(),this.started){this.controller=new AbortController;const e=AbortSignal.timeout(this.queryTimeout),t=Ts([this.controller.signal,e]);this.controller.signal;try{0===this.routingTable.size&&(this.log("routing table was empty, waiting for some peers before running query"),await gw(this.routingTable,"peer:add",{signal:t})),this.log("run self-query, look for %d peers timing out after %dms",this.count,this.queryTimeout);const e=Date.now(),n=await fr(this.peerRouting.getClosestPeers(this.peerId.toBytes(),{signal:t,isSelfQuery:!0}),(e=>Bd(e,this.count)),(async e=>UE(e)));this.log("self-query found %d peers in %dms",n,Date.now()-e)}catch(e){this.log.error("self-query error",e)}finally{t.clear(),null!=this.initialQuerySelfHasRun&&(this.initialQuerySelfHasRun.resolve(),this.initialQuerySelfHasRun=void 0)}}this.querySelfPromise.resolve(),this.querySelfPromise=void 0,this.started&&(this.timeoutId=setTimeout((()=>{this.querySelf().catch((e=>{this.log.error("error running self-query",e)}))}),this.interval))}else this.log("skip self-query because we are not started")}}function VE(e,t){if(!(t instanceof Uint8Array))throw new TypeError(e+" is not a Uint8Array");if(32!==t.byteLength)throw new TypeError(e+" had incorrect length")}function KE(e){return Array.isArray(e?.peers)}class $E extends yn{root;localPeer;prefixLength;splitThreshold;kBucketSize;numberOfNodesToPing;constructor(e){super(),this.localPeer=e.localPeer,this.prefixLength=e.prefixLength,this.kBucketSize=e.kBucketSize??qE,this.splitThreshold=e.splitThreshold??this.kBucketSize,this.numberOfNodesToPing=e.numberOfNodesToPing??3,VE("options.localPeer.kadId",e.localPeer.kadId),this.root={prefix:"",depth:0,peers:[]}}add(e){VE("peer.kadId",e?.kadId);const t=this._determineBucket(e.kadId);if(!(this._indexOf(t,e.kadId)>-1))return t.peers.length===this.splitThreshold&&t.depth<this.prefixLength?(this._split(t),void this.add(e)):t.peers.length<this.kBucketSize?(t.peers.push(e),void this.safeDispatchEvent("added",{detail:e})):void this.safeDispatchEvent("ping",{detail:{oldContacts:t.peers.slice(0,this.numberOfNodesToPing),newContact:e}})}*closest(e,t=this.kBucketSize){const n=new CE(e,t);for(const e of this.toIterable())n.addWitKadId({id:e.peerId,multiaddrs:[]},e.kadId);yield*Hr(n.peers,(e=>e.id))}count(){return function e(t){if(KE(t))return t.peers.length;let n=0;return null!=t.left&&(n+=e(t.left)),null!=t.right&&(n+=e(t.right)),n}(this.root)}get(e){const t=this._determineBucket(e),n=this._indexOf(t,e);return t.peers[n]}remove(e){const t=this._determineBucket(e),n=this._indexOf(t,e);if(n>-1){const e=t.peers.splice(n,1)[0];this.safeDispatchEvent("removed",{detail:e})}}*toIterable(){yield*function*e(t){KE(t)?yield*t.peers:(yield*e(t.left),yield*e(t.right))}(this.root)}distance(e,t){return BigInt("0x"+Yt(ym(e,t),"base16"))}_determineBucket(e){const t=Yt(e,"base2").substring(0,this.prefixLength);return function e(n,r=0){return KE(n)?n:e("0"===t[r]?n.left:n.right,r+1)}(this.root)}_indexOf(e,t){return e.peers.findIndex((e=>function(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0,r=e.length;n<r;++n)if(e[n]!==t[n])return!1;return!0}(e.kadId,t)))}_split(e){const t=e.depth+1,n={prefix:"0",depth:t,peers:[]},r={prefix:"1",depth:t,peers:[]};for(const s of e.peers){"0"===Yt(s.kadId,"base2")[t]?n.peers.push(s):r.peers.push(s)}delete e.peers,e.left=n,e.right=r}}const qE=20;class HE extends yn{kBucketSize;kb;pingQueue;log;components;prefixLength;splitThreshold;pingTimeout;pingConcurrency;running;protocol;tagName;tagValue;metrics;constructor(e,t){super(),this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:routing-table`),this.kBucketSize=t.kBucketSize??qE,this.pingTimeout=t.pingTimeout??1e4,this.pingConcurrency=t.pingConcurrency??10,this.running=!1,this.protocol=t.protocol,this.tagName=t.tagName??"kad-close",this.tagValue=t.tagValue??50,this.prefixLength=t.prefixLength??32,this.splitThreshold=t.splitThreshold??qE,this.pingQueue=new vf({concurrency:this.pingConcurrency,metricName:`${t.logPrefix.replaceAll(":","_")}_ping_queue`,metrics:this.components.metrics}),this.pingQueue.addEventListener("error",(e=>{this.log.error("error pinging peer",e.detail)})),null!=this.components.metrics&&(this.metrics={routingTableSize:this.components.metrics.registerMetric(`${t.logPrefix.replaceAll(":","_")}_routing_table_size`),routingTableKadBucketTotal:this.components.metrics.registerMetric(`${t.logPrefix.replaceAll(":","_")}_routing_table_kad_bucket_total`),routingTableKadBucketAverageOccupancy:this.components.metrics.registerMetric(`${t.logPrefix.replaceAll(":","_")}_routing_table_kad_bucket_average_occupancy`),routingTableKadBucketMaxDepth:this.components.metrics.registerMetric(`${t.logPrefix.replaceAll(":","_")}_routing_table_kad_bucket_max_depth`)})}isStarted(){return this.running}async start(){this.running=!0;const e=new $E({localPeer:{kadId:await EE(this.components.peerId),peerId:this.components.peerId},kBucketSize:this.kBucketSize,prefixLength:this.prefixLength,splitThreshold:this.splitThreshold,numberOfNodesToPing:1});this.kb=e,e.addEventListener("ping",(e=>{this._onPing(e).catch((e=>{this.log.error("could not process k-bucket ping event",e)}))}));let t=0;for(const e of await this.components.peerStore.all())if(e.protocols.includes(this.protocol)){const n=await EE(e.id);this.kb.add({kadId:n,peerId:e.id}),t++}this.log("added %d peer store peers to the routing table",t),this._tagPeers(e)}async stop(){this.running=!1,this.pingQueue.clear(),this.kb=void 0}_tagPeers(e){let t=new Wh;const n=function(e,t=100){let n;return()=>{clearTimeout(n),n=setTimeout((()=>{e()}),t)}}((()=>{const n=new Wh(e.closest(e.localPeer.kadId,qE)),r=n.difference(t),s=t.difference(n);Promise.resolve().then((async()=>{for(const e of r)await this.components.peerStore.merge(e,{tags:{[this.tagName]:{value:this.tagValue}}});for(const e of s)await this.components.peerStore.merge(e,{tags:{[this.tagName]:void 0}})})).catch((e=>{this.log.error("Could not update peer tags",e)})),t=n}));e.addEventListener("added",(e=>{n(),this.safeDispatchEvent("peer:add",{detail:e.detail.peerId})})),e.addEventListener("removed",(e=>{n(),this.safeDispatchEvent("peer:remove",{detail:e.detail.peerId})}))}async _onPing(e){if(!this.running)return;const{oldContacts:t,newContact:n}=e.detail,r=(await Promise.all(t.map((async e=>{const t=this.pingQueue.find(e.peerId);return null!=t?t.join():this.pingQueue.add((async()=>{let t;try{const n={signal:AbortSignal.timeout(this.pingTimeout)};this.log("pinging old contact %p",e.peerId);const r=await this.components.connectionManager.openConnection(e.peerId,n);t=await r.newStream(this.protocol,n);const s=Rw(t);await s.write({type:eE.PING},iE,n);const i=await s.read(iE,n);if(await s.unwrap().close(),i.type!==eE.PING)throw new pn(`Incorrect message type received, expected PING got ${i.type}`,"ERR_BAD_PING_RESPONSE");return!0}catch(n){return this.running&&null!=this.kb&&(this.log.error("could not ping peer %p",e.peerId,n),this.log("evicting old contact after ping failed %p",e.peerId),this.kb.remove(e.kadId)),t?.abort(n),!1}finally{this.metrics?.routingTableSize.update(this.size)}}),{peerId:e.peerId})})))).filter((e=>e)).length;this.running&&r<t.length&&null!=this.kb&&(this.log("adding new contact %p",n.peerId),this.kb.add(n))}get size(){return null==this.kb?0:this.kb.count()}async find(e){const t=await EE(e);return this.kb?.get(t)?.peerId}closestPeer(e){const t=this.closestPeers(e,1);if(t.length>0)return t[0]}closestPeers(e,t=this.kBucketSize){return null==this.kb?[]:[...this.kb.closest(e,t)]}async add(e){if(null==this.kb)throw new Error("RoutingTable is not started");const t=await EE(e);this.kb.add({kadId:t,peerId:e}),this.log("added %p with kad id %b",e,t),this.updateMetrics()}async remove(e){if(null==this.kb)throw new Error("RoutingTable is not started");const t=await EE(e);this.kb.remove(t),this.updateMetrics()}updateMetrics(){if(null==this.metrics||null==this.kb)return;let e=0,t=0,n=0;!function r(s){if(KE(s))return s.depth>n&&(n=s.depth),t++,void(e+=s.peers.length);r(s.left),r(s.right)}(this.kb.root),this.metrics.routingTableSize.update(e),this.metrics.routingTableKadBucketTotal.update(t),this.metrics.routingTableKadBucketAverageOccupancy.update(Math.round(e/t)),this.metrics.routingTableKadBucketMaxDepth.update(n)}}var zE=[77591,22417,43971,28421,740,29829,71467,228973,196661,78537,27689,36431,44415,14362,19456,106025,96308,2882,49509,21149,87173,131409,75844,23676,121838,30291,17492,2953,7564,110620,129477,127283,53113,72417,165166,109690,21200,102125,24049,71504,90342,25307,72039,26812,26715,32264,133800,71161,88956,171987,51779,24425,16671,30251,186294,247761,14202,2121,8465,35024,4876,85917,169730,3638,256836,96184,943,18678,6583,52907,35807,112254,214097,18796,11595,9243,23554,887,268203,382004,24590,111335,11625,16619,29039,102425,69006,97976,92362,32552,63717,41433,128974,137630,59943,10019,13986,35430,33665,108037,43799,43280,38195,29078,58629,18265,14425,46832,235538,40830,77881,110717,58937,3463,325358,51300,47623,117252,19007,10170,20540,91237,294813,4951,79841,56232,36270,128547,69209,66275,100156,32063,73531,34439,80937,28892,44466,88595,216307,32583,49620,16605,82127,45807,21630,78726,20235,40163,111007,96926,5567,72083,21665,58844,39419,179767,48328,42662,51550,5251,37811,49608,81056,50854,55513,20922,18891,197409,164656,32593,71449,220474,58919,85682,67854,13758,35066,3565,61905,214793,119572,141419,21504,10302,27354,67003,46131,32668,15165,64871,34450,17821,2757,11452,34189,5160,12257,85523,560,53385,65887,119549,135620,312353,115979,122356,10867,193231,124537,54783,90675,120791,4715,142253,50943,17271,43358,25331,4917,120566,34580,12878,33786,160528,32523,4869,301307,104817,81491,23276,8832,97911,31265,52065,7998,49622,9715,43998,34091,84587,20664,69041,29419,53205,10838,58288,116145,6185,5154,141795,35924,21307,144738,43730,12085,8279,10002,119,133779,199668,72938,31768,39176,67875,38453,9700,44144,4121,116048,41733,12868,82669,92308,128,34262,11332,7712,90764,36141,13553,71312,77470,117314,96549,49135,23602,54468,28605,6327,62308,17171,67531,21319,14105,894,107722,46157,8503,51069,100472,45138,15246,14577,35609,191464,1757,13364,161349,32067,91705,81144,52339,5408,91066,21983,14157,100545,4372,26630,129112,1423,29676,213626,4397,88436,99190,6877,49958,26122,114348,60661,29818,293118,50042,179738,16400,163423,89627,31040,43973,36638,45952,5153,1894,109322,1898,134021,12402,112077,68309,190269,69866,31938,107383,11522,105232,11248,14868,39852,71707,186525,16530,38162,106212,11700,5130,16608,26998,59586,108399,230033,43683,48135,82179,2073,5015,196684,189293,16378,23452,8301,35640,11632,214551,29240,57644,33137,91949,55157,52384,117313,5090,17717,89668,49363,82238,241035,66216,29066,184088,97206,62820,26595,4241,135635,173672,8202,459,71355,146294,29587,3008,135385,141203,14803,6634,45094,69362,50925,546,51884,62011,83296,234584,44515,56050,89476,87751,19373,12691,149923,19794,13833,35846,87557,58339,2884,19145,25647,12224,11024,77338,64608,122297,53025,7205,36189,36294,170779,21750,7739,173883,75192,35664,224240,113121,30181,26267,27036,117827,92015,106516,55628,203549,67949,60462,60844,35911,20457,1820,920,19773,8738,73173,181993,38521,98254,76257,46008,92796,5384,26868,151566,22124,2411,15919,186872,180021,28099,152961,78811,80237,62352,102653,74259,184890,16792,123702,224945,29940,19512,75283,14059,112691,92811,233329,20411,138569,53341,109802,50600,134528,66747,5529,166531,31578,64732,67189,1596,126357,967,167999,206598,109752,119431,207825,78791,91938,10301,27311,24233,252343,28831,32812,66002,112267,90895,8786,8095,16824,22866,21813,60507,174833,19549,130985,117051,52110,6938,81923,123864,38061,919,18680,53534,46739,112893,161529,85429,26761,11900,81121,91968,15390,217947,56524,1713,6654,37089,85630,138866,61850,16491,75577,16884,98296,73523,6140,44645,6062,36366,29844,57946,37932,42472,5266,20834,19309,33753,127182,134259,35810,41805,45878,312001,14881,47757,49251,120050,44252,3708,25856,107864,120347,1228,36550,41682,34496,47025,8393,173365,246526,12894,161607,35670,90785,126572,2095,124731,157033,58694,554,12786,9642,4817,16136,47864,174698,66992,4639,69284,10625,40710,27763,51738,30404,264105,137904,109882,52487,42824,57514,2740,10479,146799,107390,16586,88038,174951,9410,16185,44158,5568,40658,46108,12763,97385,26175,108859,664,230732,67470,46663,14395,50750,141320,93140,15361,47997,55784,6791,307840,118569,107326,18056,58281,260415,54691,8790,73332,45633,7511,45674,143373,14031,11799,94491,35646,96544,14560,26049,32983,25791,83814,42094,231370,63955,139212,2359,169908,3108,183486,105867,28197,32941,124968,26402,88267,149768,23053,3078,19091,52924,25383,19209,111548,97361,3959,24880,235061,9099,24921,161254,151405,20508,7159,34381,20133,11434,74036,19974,34769,36585,1076,22454,17354,38727,235160,111547,96454,117448,156940,91330,37299,7310,26915,117060,51369,22620,61861,322264,106850,111694,15091,2624,40345,300446,177064,1707,27389,54792,327783,132669,183543,59003,17744,20603,151134,106923,53084,71803,279424,319816,11579,21946,16728,38274,72711,5085,83391,88646,40159,25027,34680,10752,12988,54126,30365,18338,100445,230674,44874,84974,143877,123253,139372,28082,91477,144002,13096,219729,46016,50029,42377,14601,6660,58244,58978,23918,88206,113611,64452,17541,41032,10942,12021,49189,10978,40175,37156,10947,71709,106894,112538,57007,137486,150608,152719,40615,7746,279716,13101,19524,28708,40578,72320,1096,182051,94527,51275,22833,45164,81917,77519,48508,5421,140302,37845,149830,5587,27579,5357,428725,248187,6326,206760,39814,32585,89923,44341,288753,284443,96368,31201,94189,119504,20359,52073,103216,179,27934,32801,96035,34111,34309,101326,18198,20704,210266,37643,27880,141873,106e3,19414,56614,167714,66483,107885,86602,4379,20796,75467,4987,5017,118857,26003,34308,114428,29198,6686,29697,73632,3739,69795,16798,41504,7207,30722,21436,36735,28067,28545,3239,11221,36031,41889,100010,19247,317673,29495,174554,6424,129725,53845,94986,7955,59676,2604,191497,19735,102214,62954,23844,11872,179525,261436,34492,428,78404,142035,16747,17246,27578,37021,33672,57944,26056,135760,2369,61674,122066,31327,19374,157065,40553,130982,69619,71290,38855,72100,92903,95940,51422,165999,65713,57873,50726,7288,20272,2081,42326,22624,81120,57914,79352,19447,1684,72302,11774,302559,161481,96396,13692,414988,3721,79066,56627,46883,21150,11747,12184,5856,113458,176117,84416,52079,27933,3354,59765,141359,2212,216309,2555,23458,196722,142463,45701,44548,28798,19418,215,29916,9396,10574,114226,84475,13520,18694,34056,4524,90302,62930,13539,19407,77209,7728,38088,9535,2263,23875,183945,17750,26274,67172,10585,28042,22199,7478,51331,66030,26774,192929,31434,25850,50197,52926,178158,4679,181256,70184,229600,9959,105594,72158,73974,2726,35085,78087,23284,35568,51713,155676,5401,27254,11966,17569,223253,71993,103357,111477,55722,30504,26034,46774,35392,36285,214814,41143,163465,1051,16094,81044,6636,76489,179102,20712,39178,35683,125177,54219,30617,52994,25324,50123,2543,87529,58995,10688,125199,12388,60158,125481,131646,7642,133350,65874,3438,97277,101450,10075,56344,116821,50778,60547,98016,106135,13859,14255,16300,77373,173521,8285,45932,37426,4054,114295,55947,7703,39114,52,51119,128135,19714,60715,9554,50492,88180,2823,118271,52993,122625,97919,23859,37895,25040,33614,32102,20431,3577,9275,15686,43031,157741,110358,1884,40291,125391,13736,5008,64881,87336,77381,70711,43032,49155,118587,70494,4318,10168,30126,12580,10524,280104,104001,145413,2862,84140,6603,106005,13566,12780,11251,42830,571,179910,82443,13146,469,42714,32591,265217,424024,92553,54721,134100,6007,15242,114681,59030,16718,85465,200214,85982,55174,165013,23493,56964,82529,109150,32706,27568,82442,5350,14976,13165,44890,60021,21343,33978,17264,4655,22328,27819,75730,16567,55483,14510,17926,45827,150609,3704,7385,272531,161543,76904,122163,52405,2039,19165,41623,14423,228354,3369,176360,85491,7122,35789,303724,4465,13628,2233,55311,118771,20713,10006,221519,45115,71021,35650,29775,7337,10864,20665,21142,1746,15080,1624,32449,10905,105743,229797,7701,3940,22997,178467,57208,389057,39683,59403,63344,63125,54847,69691,18336,56448,3362,37202,18282,29648,138224,35867,10495,5911,28814,26653,31514,176702,26550,45621,11734,4525,40543,73944,121080,27858,155561,14887,44670,30742,8796,107455,113472,56369,75581,183777,240095,133699,153299,8768,160464,26058,49078,103971,21875,71486,44888,17156,9678,89541,123019,102337,3972,83930,21245,87852,109660,287918,183019,686,10100,39177,283941,11274,24736,26793,26214,25995,77011,141580,4070,23742,46285,46632,30700,26669,19056,35951,115575,174034,56097,35463,87425,24575,44245,38701,82317,85922,281616,100333,147697,61503,7730,84330,8530,59917,61597,17173,9092,32658,90288,193136,39023,20381,56654,31132,7779,1919,1375,117128,30819,11169,40938,23935,115201,101155,151034,4835,11231,74550,89388,59951,91704,107312,167882,115062,12732,72738,88703,464019,158267,57995,60496,737,14371,123867,4174,243339,159946,7568,16025,134556,110916,38103,191,80226,88794,29688,27230,10454,76308,57647,77409,113483,66864,14745,19808,12023,46583,84805,16015,17102,2231,20611,3547,95740,250131,34559,108894,8498,15853,159169,148920,20942,2813,93160,45188,210613,45531,52587,149062,39782,28194,57849,60965,84954,89766,84453,100927,16501,27658,165311,103841,54192,207341,19558,20084,319622,5672,205467,98462,61849,36279,13609,147177,24726,165015,209489,59591,31157,6551,117580,75060,141146,277310,21072,22023,106474,63041,137443,122965,68371,5383,42146,98961,113467,30863,23794,4843,99630,30392,82679,13699,241612,33601,93146,24319,18643,32155,95669,40440,15333,34089,67799,142144,58245,38633,114531,117400,77861,188726,5507,2568,8853,10987,107222,2663,2421,11530,13345,30075,41785,118661,104786,17459,12490,16281,71936,193555,17431,5944,71758,26485,77317,20803,367167,158,7362,93430,11735,172445,46002,11532,54482,930,62911,2235,23004,179236,4764,101859,208113,22477,55163,95579,14098,67320,162556,90709,156949,3826,57492,4025,34092,87442,104565,6718,186015,28214,14209,10039,107186,233912,58877,81637,55265,39828,6194,145813,50831,105849,4974,88319,122296,10272,197216,95714,51540,72418,23324,91555,8743,140452,250249,51666,34124,7229,38592,129641,78169,174242,22464,149964,51450,14034,10026,95376,26190,120062,14401,8700,265,31386,143573,7203,229889,61567,4227,140981,2466,72052,10787,10062,30958,6099,38471,30103,23202,208101,70847,467,58934,32271,32984,36637,24107,30771,17109,73353,13650,2098,157040,67366,66904,106018,265380,107238,18535,44025,32681,144983,62505,91295,56120,3082,77508,10322,63023,36700,81885,224127,16721,45023,239261,111272,13852,7866,149243,204199,32309,22084,42029,38316,126644,104973,14406,43454,67322,61310,15789,40285,24026,181047,6301,70927,23319,115823,27248,66693,115875,278566,63007,146844,56841,59007,87368,180001,22370,42114,80605,12022,10374,308,25079,14689,12618,63368,7936,264973,212291,136713,95999,105801,18965,32075,48700,52230,35119,96912,32992,8586,16606,101333,101812,14969,39930,759,193090,27387,42914,12937,5058,62646,64528,38624,25743,37502,3716,4435,30352,178687,26461,132611,42002,138442,35833,59582,16345,8048,60319,49349,309,47800,49739,90482,26405,34470,63786,32479,85028,39866,47846,11649,23934,29466,2816,42864,31828,7410,74885,49632,47629,111801,90749,19536,18767,105764,59606,21223,10746,76298,22220,39408,7190,79654,64856,11602,82156,272765,17079,70089,245473,51813,184407,384678,1576,122249,5064,27481,6188,25790,74361,27541,318284,45430,31488,620,93579,45723,192118,22670,51913,4162,70244,35966,26397,16199,50899,209613,121702,287507,2993,36101,132229,67345,33062,76295,118628,78705,52316,34375,107083,107454,44863,127561,33964,3073,154010,190914,55967,39074,6272,31047,5550,41123,26154,98638,47110,19998,148091,50229,31329,59900,195442,19106,61347,73497,70015,682,45850,25776,38022,148951,6288,37411,232526,109277,27286,32342,9262,5220,16651,23175,46740,129438,78614,121925,66914,88710,127952,5563,21500,34521,10739,14863,191006,62956,17359,16749,67027,56284,69134,43301,35039,58883,54466,60823,404451,75743,59856,86979,7923,34273,83785,32142,7693,268986,197428,282681,17049,22346,22990,92245,107180,3357,37104,96724,49153,7683,31197,43267,82231,164276,23696,20848,188364,22309,24821,158707,1018,22514,70922,27792,45589,59709,10765,736,35218,63479,51987,24275,63588,55361,92929,81964,4658,20122,12330,44058,13065,311456,72224,8337,211229,38979,22590,138478,52757,32595,133600,8838,31549,94412,43391,90056,1585,94802,127271,6223,31889,137038,132910,2165,57616,230152,6080,10748,36737,74579,134062,50525,180532,119270,34556,76155,82394,52595,29258,31435,87820,67996,26943,183878,38007,2410,13526,180297,69856,3503,187396,167700,7838,16701,9199,56267,3661,37407,65994,23767,5708,62508,221700,67088,86978,46776,84434,32088,5612,9149,88244,21685,95151,46750,189612,2979,506311,2594,3628,40074,105039,78243,28523,6651,38058,71999,30992,12764,68261,108991,6165,26450,61961,13400,22426,7490,60890,109623,2070,12958,50355,67979,257096,7213,42578,52121,35716,65461,7516,124758,39268,302,64712,14977,1467,219452,2840,34229,11121,21602,19270,63574,8024,1532,17331,79839,78885,52029,180767,57957,6069,91265,61380,55767,8927,32881,287603,22149,35029,68876,6428,199567,46926,13412,104132,21434,366616,45060,110046,81924,128910,45886,52821,130416,29416,77342,21762,67329,121432,79924,11724,38625,81006,102033,28338,13326,3250,82056,82526,38212,21112,12382,111495,3263,7414,86274,93490,40844,30224,45212,24019,48411,71367,24941,76729,57776,3769,38114,202019,197745,31953,237533,33270,201580,255648,100798,44741,32241,98468,106931,10085,15090,170358,33154,66787,18819,69760,25061,234005,82660,6295,131975,16874,9076,4094,25005,17740,40908,19533,220019,44330,99792,50040,19619,13950,55228,24423,31253,95308,103177,184795,28590,82285,5059,3210,75525,49894,70007,56178,10580,36051,139681,21617,98736,3555,106306,164189,37352,63915,47824,24883,145530,61904,28444,11483,19837,145446,30420,112972,85939,11835,191233,2262,20705,58630,1753,148334,1197,144714,6887,11223,107667,60879,77914,4151,57417,81594,96681,169430,1784,20444,95138,254041,27038,596,7117,72808,13759,3353,126776,21074,55322,27081,36942,39547,139830,179275,4453,713,8722,71399,19204,25785,22794,23923,104114,11291,25458,102309,88396,75288,230440,206396,104551,58447,130857,37247,94734,31548,176529,226077,65159,20104,10096,66881,94191,237909,27109,37404,1520,27421,25220,113003,23423,24884,50585,6286,231877,150800,11789,3226,90004,60642,5053,202400,61442,132531,175329,57138,30116,103847,9973,75367,16452,32360,59119,21246,10191,164804,23305,61051,37348,154530,13214,5468,50403,66754,130976,50559,80515,14436,155492,84017,5472,43107,41240,2890,90431,70188,382,76234,48040,50211,281038,237007,32115,142178,1536,22761,96429,1811,31243,1679,49143,55209,17402,235054,61494,7462,77030,34925,87609,78002,9499,9027,73289,201078,101379,63544,27666,5469,10642,30029,49816,132979,95620,58086,351930,116300,2110,2043,30845,6154,11279,16727,4122,2277,27281,4971,3650,39060,61970,65951,39674,75686,38151,11370,130809,177895,32665,63725,122267,7857,39618,118483,44792,157755,178624,136994,24260,41308,22471,12404,21707,12486,30473,52781,50246,20247,39065,909,56825,103158,128603,31542,1089,41935,32744,12428,37963,84420,33134,72921,208449,42622,168151,127335,147107,46699,38216,12591,94342,85814,31423,24944,2605,87542,67473,192551,4496,56321,91819,17630,6300,256183,114569,202090,33209,35289,34897,24967,40520,43470,5344,10199,34810,14283,10381,10017,62923,49924,23233,64539,13051,35686,19698,11570,135555,120868,44924,87065,52318,52335,47586,140906,245885,109834,78668,9065,46990,25258,72022,61243,40838,4545,146387,10537,11557,17470,36930,68104,46711,24264,79401,81043,18225,120488,24746,84338,81652,28266,13776,21878,46973,1047,230465,73357,95777,24973,210160,62210,58404,110633,169651,6937,41870,9909,26822,191062,76553,27519,96256,239070,2478,205678,67955,58532,20601,50120,19148,78501,195724,110740,8249,109665,27446,30568,57631,31425,49752,32820,65504,50079,3663,102256,219898,23849,211315,14645,4359,91767,9528,12449,49366,7941,49763,107848,8930,27086,50686,9744,10447,81935,39513,46514,1670,29229,6172,22312,137280,97759,9806,14445,22976,56458,73391,34983,93760,174219,52573,33149,59747,2429,136277,75123,165263,91040,7446,57632,48633,97140,246081,84766,151684,79918,93268,120346,54059,54875,77858,32996,103590,45276,11968,19600,25849,17159,132907,42828,16817,4913,99462,103303,27395,5737,74184,20749,21160,14377,77062,131403,158735,10999,27799,77785,9320,34366,51593,61070,33746,47048,29268,36675,30262,53297,9832,82e3,20188,122292,39917,7331,18160,68301,185935,134830,15031,4935,10004,165845,185534,46923,30109,44134,122631,18874,22903,112790,26561,18549,348902,82871,140345,255565,135390,63556,103747,145055,179600,145662,296111,61661,211987,23952,52342,126343,48450,32919,44277,82185,9591,62139,205363,376969,394874,108461,18040,120885,14798,39863,16571,16794,58271,81025,55206,14640,118656,6361,44092,85970,6262,153863,108244,180200,72264,79947,38044,10050,5735,61221,80712,5471,115689,11391,11661,184257,20010,60116,30320,19327,134598,45455,27542,18004,125092,452272,1549,91523,46567,180063,156026,2608,11174,58848,37788,65907,80194,30490,5786,40775,119519,106241,11323,156297,8425,61495,2617,29675,2425,59886,112582,49142,59618,4863,50597,86710,50650,168632,27693,85641,83643,18993,25768,84284,28090,93592,36627,312804,43381,9887,9402,100931,97165,3311,173330,66805,28935,4963,184460,3201,78102,19126,21607,37496,24938,22615,16153,32862,134792,153318,61120,6067,2812,12826,12792,23825,37559,64662,202250,102694,155488,85881,149193,46233,65383,15521,106982,11358,176786,25752,39717,34208,24510,32464,77742,39371,72028,138229,60688,71386,102834,132477,2208,11548,63670,271279,28351,30338,38620,32491,99845,143885,152266,13252,2825,178663,108097,1775,78201,14897,113573,163346,62292,171129,22183,96598,38733,64971,166776,117445,9968,146393,44677,74867,20908,97328,12761,25656,26785,9148,112344,26115,99176,110121,22437,49547,6180,79320,5835,31392,43328,33377,75870,119860,69497,80273,7325,155219,43167,111173,28347,20222,3763,71752,55041,47252,14618,28088,15012,97805,194698,54636,2036,41349,6173,96604,61530,51859,43782,13361,24334,22668,24792,7070,23441,16789,3209,36211,208475,26242,32880,122181,182407,21444,31060,88459,29929,77907,12716,10934,97005,20599,31690,8403,58445,30303,22700,10336,86731,103115,337709,72556,46788,112566,47684,67089,53548,36874,56487,41387,125985,26893,40071,106683,73712,18787,40105,72992,67246,137276,50802,36790,70328,138827,22466,39263,183295,29858,50975,9322,57397,10654,24364,30383,55799,41600,23584,127295,296610,129078,143558,244131,86397,36049,1085,80677,3820,108139,5476,34767,24683,7758,13060,7239,131671,250593,59556,103392,29810,4188,252323,39404,116877,7651,43600,40338,13554,157253,39196,25978,144387,61211,234,50104,6129,10449,93777,9240,356378,274148,4439,72970,3724,147770,78680,62570,115877,40027,40547,36817,224392,64609,34795,165027,67440,2477,37206,23431,50754,164797,46018,94995,170982,27051,7957,22767,3674,27900,56419,18930,60701,41302,2692,84749,339721,61996,111094,80221,50129,1045,8153,62945,19202,8250,37208,37418,32560,79477,41106,88569,33963,36693,5892,30570,1581,66471,49647,11922,160717,29442,5643,114865,82962,95982,132098,22633,22838,94726,54556,28566,205039,162340,33216,16849,35847,221339,94851,26533,71469,1805,3804,12935,45483,71020,36310,65381,192960,34240,35165,59773,1248,46954,155332,96864,4246,388800,16129,57133,74592,44807,442014,38203,42574,80818,91592,26377,36424,65760,977,77387,22628,147610,28018,30561,98454,6969,119628,63648,18170,36854,26601,64018,22027,37279,51395,152934,21153,9430,58760,194742,5330,55115,34158,28917,174111,13171,122326,1526,43896,66094,25325,4234,148354,11450,275,18999,112191,44365,22723,68409,8733,57746,96565,75007,14196,108844,29475,88599,177563,100792,106156,86323,93726,14248,135341,194131,40126,47099,14779,8272,39597,95983,171398,65882,28052,10393,47213,40689,22120,72212,106829,34964,109146,753,648,21660,30047,17527,181025,5619,145357,4085,216883,9359,186951,24779,53931,24545,36197,223296,62628,168101,4243,107313,30321,26642,13049,51059,31027,107912,807,73550,26551,84369,122422,165872,49754,74213,234264,33151,52014,33100,87183,22365,52500,40013,23302,5652,72723,21404,26107,48434,587,94049,168493,96418,32871,70860,31709,25128,443,71597,166253,15670,70994,26341,133675,28280,75491,54756,47955,56028,26182,11952,113272,472197,64640,110753,17919,337,50642,22576,142,87371,53391,93210,126694,15285,19642,85667,14148,1506,42092,52962,33243,11970,20734,135843,57044,58880,13002,219134,22876,64754,232519,4257,43120,321573,24799,64526,124728,52579,81472,70831,276848,17403,74359,23021,182101,74597,23744,148267,12055,7976,5349,11772,67540,167347,65318,18720,127832,108238,22828,90233,9987,259080,118185,73209,79270,13775,90100,137742,90799,70569,15699,19961,9087,67475,57872,39731,8810,134897,131868,146849,19898,3334,2281,167061,91073,60356,467742,74712,188,53179,137679,92769,29241,9537,132595,80119,1041,88962,5976,40171,44911,102859,139059,104558,98987,47761,19272,71472,113864,175377,73338,10857,23402,23758,1591,139864,5644,4076,118760,16427,134198,18853,20291,100849,37423,22038,36677,19071,195521,57445,11069,31869,55718,66882,148490,44,41296,75242,49704,166810,9906,20943,122258,49112,105667,15969,10344,6408,187694,21399,72742,58970,14867,14376,81889,41856,23225,15042,56993,16074,131389,74276,72407,53875,383108,53597,37363,68993,44854,122548,430927,198279,38430,80409,12245,2981,628,2818,17760,37437,238229,7968,46892,2200,3730,34190,65983,37959,112291,87850,70827,6522,20750,73913,111621,41652,19587,2780,58668,25916,85259,18200,168962,95781,42445,102050,7776,57662,103313,47742,96358,41964,66174,100396,29069,204735,19679,27978,7479,40264,22534,61183,36081,107436,58223,14680,23002,101311,24716,124108,12908,5646,31750,40380,14215,232799,102772,14122,96775,61398,50917,12096,149880,67833,598749,124194,155871,49216,790,14677,65319,56917,7440,145744,95701,12206,49405,129269,76199,45732,9767,11058,9047,210885,11051,7392,26307,2130,8132,147526,20802,232698,115660,50060,59789,57344,107623,80343,112676,23291,9866,160971,34032,118291,15719,59730,164911,28975,2659,58046,78480,21854,66209,53863,109085,116045,29021,46481,107552,22130,18764,70254,31272,11300,52460,43933,84738,20721,53869,190840,79673,105300,7561,321817,66924,13940,33281,101046,183181,32176,71878,5678,62924,79535,56646,40303,19559,27703,93042,73368,42187,3670,37376,46440,7023,36816,109628,20680,5940,276440,275233,170848,112093,136996,14984,20226,111441,77693,112960,48577,39370,55707,50314,123404,26570,54281,61372,123391,4857,35928,246740,132507,106646,44241,7196,92258,9825,37688,51197,303141,5590,15476,132986,10955,85782,34486,26696,7991,28813,18858,39546,11703,11365,38185,5716,93555,11925,40121,60002,6985,10976,171384,3887,43394,13337,56346,6381,252336,39573,75042,53711,1028,31781,44295,95925,131713,7214,68125,43571,70954,213234,1628,8760,13391,65485,17320,56038,1710,25248,60803,57399,19839,3870,326,281556,50945,72400,21460,316244,75619,56246,98775,481,13513,55765,50427,7388,123519,32929,57908,27124,61316,101097,57467,30228,48792,10788,20402,37318,50526,155730,34456,158065,145305,17832,43733,64052,4506,35072,205355,177028,184004,187081,68616,35938,83703,10367,36892,93186,260137,51934,89970,4985,23445,26755,21558,7948,78741,23376,124405,85594,68596,57536,49351,12619,56593,132668,99924,109728,71844,71935,196018,65464,17617,14987,89701,143773,33997,8687,22701,33258,2914,4436,72108,85610,9671,49067,2327,82988,1361,1672,44033,35777,30269,24057,10605,82236,616,15793,13919,47249,112086,116698,9484,80207,90574,33304,68624,93127,56101,42210,160929,4827,38995,38095,4701,125119,5027,33680,9236,231236,14135,87837,23318,70261,78893,30151,81482,14332,1084,74256,27532,46644,79185,3148,62615,6981,55672,31668,36825,1849,14536,37446,14738,23779,43058,162749,72199,1168,21346,5592,85932,85302,9668,18351,57135,150360,2080,228015,77953,34670,119302,151751,31009,106725,84265,45214,59289,74178,113071,263206,111009,4021,44449,188119,192629,123592,392506,292847,114487,12831,205858,9852,20780,79648,75767,357014,97721,18166,21005,67950,33226,204009,16536,2987,11335,66717,144910,47950,17262,55060,15063,2934,51038,26775,178497,66008,3427,49433,128592,20036,157553,63861,3089,23015,51210,28696,35933,49942,71135,231518,99620,17248,21835,176536,20676,16944,38700,165831,233253,295625,36723,13023,52745,10907,19423,67972,125868,95473,82875,1183,108455,52685,33417,64095,21433,52438,33191,127809,44505,211823,7810,2752,95548,162031,7185,91196,47563,61721,33359,17897,23682,42806,178101,22874,49707,199897,75419,82456,8618,11171,79712,116847,18783,44190,46564,5346,59046,95032,7893,14916,3214,26800,24172,121453,34362,10250,17408,18888,4840,68696,22831,13162,36005,32512,14800,62357,41723,45046,27247,37486,5372,2564,34261,298500,66509,133920,89138,31305,117697,19097,108304,81386,84106,23802,46411,63304,946,51417,41777,41041,19501,115864,60743,294354,37955,94165,18116,1156,17937,20645,57114,90804,58042,48643,92288,9861,2557,88546,61333,101008,12853,5148,87856,4152,144503,73841,18718,9789,147565,10846,42085,12789,30223,8993,56352,67203,2448,28215,6052,23540,126319,75933,36689,80235,23231,23561,21383,38800,77548,102798,21234,31468,158608,46188,63960,191679,8051,67014,11185,170078,42186,28827,34777,41930,212079,12421,34750,24111,110344,73918,45171,70826,141949,40063,23979,24254,37309,26724,27179,24718,83648,54938,14591,17425,29525,102675,48975,48654,12316,8929,60640,41709,50168,63264,89812,50716,48632,38755,138583,160123,55579,71829,24230,233277,46322,39650,166388,34718,24108,98252,7031,106695,62498,18258,35062,217827,78731,34824,33354,19520,60852,2432,60224,8587,2836,62955,702,20227,42285,40560,95592,62486,11094,53035,143291,18842,46177,77994,1770,9657,107422,172915,32655,128716,25886,25164,156740,119928,165875,85817,11007,89110,33956,12652,65156,180266,8494,36889,19958,20955,96,1264,118288,135769,44754,86671,5632,19026,168220,289120,33569,93821,66144,70635,7687,5642,2714,55445,56636,71545,184182,93133,7332,37389,12643,52315,22729,11014,158742,17050,152889,50178,34601,41945,52136,9948,26914,63548,95721,115951,40759,8960,158258,38938,49232,48325,42234,81523,253019,66128,40978,20048,238048,38760,62928,122560,118532,43687,137472,163689,26680,9878,17448,51035,16211,60834,36749,29178,14241,59868,150086,2305,26477,42422,34342,165341,83279,33894,14257,29928,12743,13957,125571,89134,66712,10952,16507,147839,30146,7249,16565,45399,39874,114565,215780,31990,230881,171477,102,196546,44538,10880,84948,281705,86651,10617,31395,2342,453658,43569,60561,132901,21845,17727,58556,258242,22262,58728,4008,77997,11806,37431,30599,81375,109137,185787,114085,217292,97453,169085,30593,60212,11544,102056,65580,2384,91655,4855,95725,7295,157994,16228,20669,53276,141590,105246,17334,25440,76067,17967,39321,38911,11362,28559,63807,21627,26468,85816,40120,1025,15234,58319,69516,66512,124548,75845,78873,22137,46681,51242,85683,32909,76747,35555,43396,101465,1765,73094,1077,2962,39028,66777,57831,42048,15828,13962,36041,63657,52412,5242,58846,2141,5506,219012,134451,3936,182230,17558,17153,152237,22621,49377,170216,35257,68233,65374,6510,11126,212151,7184,2480,22517,3437,33073,30156,16557,3768,55067,86829,91e3,12350,148650,66017,79424,70885,49066,28250,21369,51213,34533,11510,3258,18176,18465,84413,6315,36411,163765,4346,356,107618,598,13727,285026,162695,8749,14583,7132,63521,184253,32378,25991,5604,30961,53675,4874,84693,5086,34811,26978,56564,7904,33519,51221,113942,69253,6664,125563,22055,220680,102008,742,51930,19494,176108,44424,35123,13025,75685,11759,74335,22250,181453,131147,16984,132115,154311,11991,76452,52609,85351,196,30969,9198,74919,2529,56838,71779,29187,116304,3504,62330,41190,86153,28393,254926,104228,105189,13264,84359,3574,12415,8534,57147,10175,188174,59504,60932,66318,16407,107921,17638,99103,49278,28403,39786,145865,8462,3558,43406,142271,29139,21989,36552,93955,72365,7176,13556,106185,37957,321774,17782,129017,51154,27938,24952,1935,39366,2791,33489,41582,56078,24558,9311,5449,218786,27808,190429,68013,36020,86003,29735,3404,87348,119357,115714,2324,86796,81973,40992,43376,93621,28784,16808,36367,2517,2909,191926,24978,55303,53308,205724,60068,3098,21375,64784,23949,26579,63121,12319,80145,39967,97861,6757,70143,67642,37082,34698,69140,122883,46151,62187,80934,429,19437,135071,137885,222647,13331,154065,327,61778,74257,40116,37493,14855,85079,237641,42342,102164,199965,71204,4662,29368,5042,113914,122214,8955,13149,102503,43173,5659,163787,69003,307084,63392,171080,21390,81918,86666,36622,24126,28887,5736,28054,207170,163428,79891,346467,95363,38980,111806,80828,9200,19288,294896,114468,87405,111715,141705,7015,72754,68463,48738,243147,33397,101210,37051,98801,82847,20397,4940,185559,18716,54718,83491,11725,40803,1128,12128,23060,5174,7745,67007,46701,1571,27807,180186,256996,18975,16837,7877,212758,250379,15440,87954,57755,24719,124057,83461,258,50864,8874,29038,71289,31627,15429,9005,4061,113851,107716,82819,13651,79656,117851,17539,111446,12938,39724,190787,4352,15402,21070,62708,8539,23777,73853,13552,38810,86117,16285,56400,1718,75342,142863,29033,378,110113,180321,32586,23606,26393,160984,207987,23783,8406,16904,24596,47274,11693,46539,60524,78595,48423,31718,20170,9009,146268,15183,191060,172765,1349,138436,37365,10970,40509,225817,20021,70394,152138,21541,66559,66544,89352,2725,17258,91345,7313,3815,115868,8660,40362,4071,103524,39388,118275,21950,6549,38226,32754,209574,29201,43495,18028,20296,40597,18370,47520,202450,24134,2219,8195,69545,38041,136934,46374,19041,159811,84865,58620,846,98749,13569,30714,97246,32186,4479,27355,92973,35214,151491,75963,37631,1561,27200,238083,23182,60756,12291,25766,39355,102333,87362,65741,59906,19538,201575,48772,102938,24438,292580,39964,66366,9004,61379,50548,37622,38732,28379,68180,76622,17488,69849,5963,7219,48143,43413,55358,540,58691,29506,19245,52193,48621,5518,13048,118625,44755,191081,42061,89197,2259,60665,66994,71210,51232,3585,142096,55024,7892,8345,58653,463307,65658,64319,137941,136323,53499,12746,43492,6978,95163,29925,60175,5128,7352,41463,184756,121146,20473,18426,4598,5309,54580,14277,121151,10691,56711,43880,63409,76682,11830,172218,264898,32632,66536,81062,31649,25788,92774,60222,11100,63159,9432,224657,25240,53613,152,138620,163829,2397,85345,12501,37507,64932,38575,43522,65789,80198,78796,35226,3851,108891,73311,3060,28391,93671,39663,46142,30982,66041,37281,68157,26553,71872,81142,211527,39747,118119,22695,2859,11066,20232,168911,7933,197005,17066,111071,44434,133994,120798,12766,227798,45756,132852,29917,36076,55352,65281,129800,41958,18944,84678,18580,168093,132621,39997,54092,27740,32354,3770,114118,103242,43918,15899,18574,145944,3190,123469,219903,24169,100571,62403,16776,92779,14535,17168,16475,14304,37231,1712,28218,242754,61688,28980,1318,51359,222657,99200,67989,31772,23932,35351,201251,49041,27306,19128,40135,3986,77333,19649,120683,151927,21081,7076,78375,77501,101599,8011,89585,96715,58179,5378,102138,106793,26051,217276,4197,16297,27014,46721,13322,22806,5278,29629,70632,9647,71519,58818,40603,128530,8903,36770,56900,31483,26935,43845,34265,34920,87658,6114,84767,64250,47318,50720,19264,162514,33357,13117,6705,46696,75032,71054,87004,42035,69138,11903,99854,102328,19611,34525,69312,6431,49842,101600,133178,108751,41829,89939,225664,48916,99556,9195,130387,5960,36857,116724,53518,94002,39077,53996,6945,22261,64291,8314,152785,57588,16522,9091,5048,87671,35441,39509,1945,12423,158923,178413,37549,14095,1475,73188,62878,4819,24012,68534,42606,4010,120809,57497,59564,101758,103718,32701,80116,12345,95834,46918,21468,53213,15665,31200,3867,5140,96013,250744,21016,10069,13968,35449,180829,27683,39704,59956,22893,3115,26293,32785,75934,62445,141162,62720,2018,83638,19949,114012,95006,3330,99829,130935,309272,9565,55874,121727,37017,23586,319858,40970,27602,8625,112329,61060,100088,118525,25922,16232,1907,60671,51583,44553,80993,5262,94679,8676,940,20736,11823,3020,16476,12340,152600,97416,3703,25744,66826,16245,16876,46446,84798,74227,176020,45192,61955,75496,23946,23626,40372,26036,6149,11822,30582,16541,41914,82385,232823,40921,80773,14930,3631,7517,39619,4348,36180,126106,138939,62611,1477,113512,47321,25052,14546,118881,29060,23589,128322,36795,18401,137921,104699,267929,36194,172791,18113,4766,188215,30083,332586,94089,5805,77909,22194,68234,154976,43220,40660,70001,184893,138095,11128,103010,22663,5108,212615,8485,5565,49222,54614,26530,42639,16319,55062,152662,105595,21114,22216,10294,68158,10436,86950,7206,62115,3977,3657,59874,456,118617,18156,106663,112229,80992,17442,8217,55551,5133,34344,251927,51153,39364,201321,7816,66803,23057,156724,145664,14276,95705,979,2796,6875,13429,212525,50602,26276,28284,3424,19465,52397,46963,31420,51399,206476,92317,48851,637,100820,83349,10317,60227,21972,6908,282439,32857,224767,95629,83882,42106,87338,69757,29840,68709,37665,45244,114577,49188,175943,54009,186746,106158,70168,3358,234002,50555,9221,129338,9562,20118,32923,78479,118280,65752,4977,10474,102174,60947,129006,10570,83451,8598,8078,159367,123785,80438,16742,5905,5281,181513,42402,6977,163136,93179,42191,14968,50421,112401,105440,33456,57347,121611,4221,94954,36517,24046,27796,6255,33394,72990,135408,116627,1233,57874,25654,95419,68156,401399,313338,55208,45573,93124,119251,47200,38196,11909,130667,45391,73904,64964,167846,4137,115606,52036,62214,7969,160925,7187,1132,134835,40309,73195,64494,80472,444841,61111,26500,45323,40743,53625,52797,22659,15631,29739,36706,28841,39147,102836,26794,10536,14845,87305,45874,12241,127587,83833,57183,79722,30844,41304,84655,20825,92500,3722,25655,27811,10157,81634,31362,34088,92487,70123,22190,185100,72658,139035,192523,88241,2078,230490,44528,85638,100198,22088,29982,291233,241062,13865,4445,137791,37835,107218,31726,19718,38234,72528,23046,19177,66695,5109,17251,28077,5617,21554,47839,72425,133825,1486,73065,181275,141508,21768,62971,63082,2512,34200,9904,120309,6392,91243,68416,268253,41199,116757,138551,185526,41246,28986,4093,19057,17295,4148,245766,122360,35356,112075,20301,75441,10998,7977,19769,62922,937,63547,100196,26427,157820,20983,236696,22935,8140,90315,156004,47204,140973,7726,45097,52725,22636,23436,257282,105247,522,88389,216031,202204,46812,211666,19693,68828,81691,45925,11256,30292,372,5236,167826,88328,232776,151611,5360,82104,18841,80393,25465,18285,20320,72377,31730,33160,45803,38715,27705,37379,24163,18360,103586,4015,32305,269494,91252,20080,36567,54650,7797,57073,12650,31164,42209,6375,261663,105528,81661,106002,2800,5375,17247,43151,4442,15727,194619,100855,144898,62320,78465,39929,16454,1967,28311,61363,17219,9395,8745,121445,76939,80385,162380,22009,54191,44248,16299,122830,48151,74429,78291,64755,14238,44966,2511,17712,67954,93583,829,105899,49935,84750,11591,33185,85447,42717,27409,208542,28965,62052,52525,5597,25694,65594,16343,63224,276188,12475,9331,127507,38522,57287,24128,133161,79723,105548,133695,48917,27558,43278,46520,13778,141954,110785,83366,17715,46317,105763,66298,147013,41086,94180,16478,220447,44611,730,19722,78975,117889,125643,26254,16574,18480,65006,15806,38549,246418,46052,36056,8440,34984,30170,3163,59800,4458,115442,4283,41970,33507,104078,1653,22,121158,276486,3655,6338,24048,133421,23641,2161,24422,36006,8086,10675,181474,12307,29514,59143,14729,52509,87128,122470,19446,80852,33314,24573,119864,14237,9652,57779,6612,51851,15284,98871,90581,124466,156831,21190,22015,71380,161906,87247,69201,18392,17908,108470,72962,40719,14338,17911,95260,43339,20610,78916,20710,72451,11315,31448,17263,58853,178878,48111,116002,45497,80506,82605,85880,36300,121755,25215,36118,301929,88728,405223,276136,553,34704,212438,49970,78329,922,20711,25036,257130,38295,145369,18128,15385,30829,55656,48345,8012,3561,28004,122041,192900,58338,112508,41085,29976,87040,47117,23905,4336,92061,138880,97407,42083,172121,6256,25192,172671,5,93568,1420,12677,31605,56743,40620,6015,78415,231077,31298,80026,13902,19048,24924,170586,32955,176119,87859,36731,6773,27711,24658,26475,115216,133207,93250,95820,88522,8317,5714,124047,55219,86860,19677,23961,22928,162209,8904,225992,359835,56084,96201,29392,96558,86071,93643,55114,13347,8183,95129,82012,2017,123336,34219,115554,157159,47747,101684,41008,18735,193781,104151,226906,7552,179874,124113,31159,21162,44010,14771,51268,166128,31382,73124,77438,92830,205709,12113,1292,38937,13114,1334,2118,15597,69581,14449,21934,76618,48728,67038,14967,51495,24243,87736,147249,26720,11119,46063,43749,5843,44147,152629,133428,65703,14269,45604,57982,28672,55616,45957,8438,95433,37698,220862,132034,39456,61870,4161,26501,73560,56418,9845,4654,20916,10456,88920,119358,9015,65931,96507,48029,38534,21676,109081,43078,34943,25089,6131,28766,23665,5477,10255,16695,67,45778,42443,42770,29534,23733,100513,62617,42630,48746,14191,43753,50295,26007,8792,57243,43119,54725,164253,58250,112304,131796,25165,4651,3188,24831,47748,3705,19540,13211,102095,5593,18699,23666,32005,117571,33541,60584,74573,86311,99443,25172,27222,168938,7143,11853,53560,18834,19960,86522,28217,53266,117700,72989,34323,18721,66450,34346,74056,47217,202002,46269,9429,68582,75458,37823,82843,96652,32549,145144,27958,19820,158086,31955,201406,135379,31207,192545,12950,51704,9094,248263,76147,64028,110009,79407,89345,99284,223492,47966,26848,15359,201137,2861,110507,71231,72297,31851,118777,71039,151051,240855,16333,50766,14727,7939,4149,80908,418780,88378,59276,1327,7284,38576,79814,65820,42199,84860,49574,62596,12396,70598,40117,8648,7994,16836,7630,14047,359699,106878,525,29037,28064,13380,11675,50669,74216,103539,180314,27449,56299,172344,19274,7301,246099,32043,19422,36506,129317,6806,30140,4614,46639,66926,932,86600,6322,27847,233103,10541,39025,34887,3517,12972,26220,2031,66561,115015,48658,47596,12714,33845,3893,16165,35237,89983,14769,11962,147224,47018,29977,27979,5552,82338,86023,131368,1218,24853,237840,132193,15455,40873,3668,65351,53388,15229,59889,272245,47934,11858,34347,18038,90853,86981,300602,19343,114181,29362,84921,6095,106059,79472,38015,1206,48741,6208,8e4,21916,17423,6002,108083,24479,34931,56661,9511,26995,100694,163853,35997,81254,58321,18919,171890,86877,91341,74503,70477,53412,7027,59281,39892,131302,5864,15947,61301,67466,162369,47956,27874,35624,282324,21270,111847,102548,41482,30955,116737,28264,8592,55458,22301,75090,29821,30697,51709,3041,19208,8038,24634,30467,87509,126428,19389,18814,152686,20701,83474,45832,80891,105808,11378,153223,120770,98186,150633,49838,9141,12755,30962,5260,74490,21256,31678,65062,33326,289838,187831,20595,89768,2805,58535,10844,70085,12090,2451,138068,98544,24461,4511,6754,41684,28203,3383,65355,82833,30161,83924,234361,128424,28921,222594,33975,125491,34069,11508,67464,144226,41850,98703,34371,7901,21254,38398,65651,23549,53883,213340,123269,12028,71764,177701,28758,2623,68395,11549,15232,68603,9660,63116,36079,57093,31198,20475,48467,89984,35619,186847,107469,31389,43631,73867,41949,68841,114250,1605,30564,63403,17588,27680,99533,12641,70325,50428,73426,78379,11855,91651,72081,91720,60198,15743,12065,83398,140046,6761,46598,45900,5068,886,62448,148968,37347,19405,9680,15819,43496,63370,75667,163700,37639,3633,22774,34341,183131,134335,37200,23915,7054,14194,12970,26438,13350,285521,25594,8219,104410,91039,168804,138480,149734,15907,33818,61132,60082,4622,110187,56736,13551,73571,3945,73463,65498,17758,263266,17593,2710,27585,54469,38200,45367,63754,28881,3473,12791,98287,31895,65787,4463,94536,24951,36332,59901,28803,52130,86403,7668,181822,74831,18977,9850,177206,145485,109798,7292,31421,26280,77211,58511,12507,127004,11113,147,8729,56208,43066,79926,129937,31345,83947,39915,46146,98763,42566,1337,13192,18323,105163,80570,117753,16555,72883,11077,159438,40764,70933,83329,26066,12276,72059,21655,173836,126713,69454,153482,91585,70644,102558,110483,6764,127864,190133,3961,101798,20945,71138,82402,90884,69669,44753,923,16939,59700,164258,25969,27082,31399,43846,6306,246093,51342,6153,151581,202801,182731,56475,162188,89426,141356,14355,121815,27536,28023,65257,77523,106668,127314,24947,12790,38796,169698,23555,10725,44573,183083,42088,62716,43265,105958,32050,44067,50118,1668,3874,6243,318411,16599,1691,94999,52378,28671,216728,123258,2059,34969,69225,5913,136280,171443,141515,91662,22175,135282,80020,92270,1663,4808,4482,3495,34691,5226,109830,108512,17342,107488,11606,123190,100247,29666,146527,113014,15794,30894,13224,39585,243192,22351,9903,7836,47699,11078,25468,122291,48821,26780,122679,75521,81450,630,4895,92900,55074,74293,17441,3563,111657,103102,51613,12318,52370,36191,68245,34269,40445,41354,122901,168604,182500,62012,42557,11259,24428,115113,86345,12362,3909,78430,86852,134602,20459,47853,93879,22577,7659,3688,38555,13349,17381,56715,91639,12493,10895,92438,3142,37057,28928,2004,36427,32268,34222,209974,10432,67436,41989,173518,107930,27079,62729,30908,55558,5828,45031,14902,53546,8204,144263,60255,14520,88212,86582,109589,69356,8064,47449,8505,66558,16886,4844,52817,111260,215129,12941,91118,650,20770,6273,73089,40618,62790,2873,35002,14023,97208,19386,102646,36993,143736,135457,35385,113601,17893,32627,84439,100619,56016,6581,57264,172160,45452,111710,203627,70131,24100,322787,1996,35665,70078,22358,90922,83658,4097,63200,58499,14542,99153,52159,6615,12414,63415,31986,16823,1579,65405,137809,8841,16898,48082,259,33014,42375,12260,179850,73667,91389,98882,29532,17311,326251,41092,5928,20742,44964,48019,43505,9317,49265,6643,192712,48424,163487,19861,20113,70848,31928,105333,23685,78563,14638,54755,7158,24142,44018,20774,125255,20331,24280,10163,1285,2336,39851,4299,117269,46714,63816,87779,159624,11731,9971,990,137317,108831,50994,74554,162680,23640,131597,146962,170620,34829,91205,21184,1913,63616,18427,93136,156592,17519,67565,115882,138220,78622,88535,18115,2711,33554,109492,54298,971,24914,25863,36363,45715,27099,194995,14299,178181,111488,72395,322385,157719,130787,11897,81843,83999,11369,49280,118604,40922,61332,110343,53407,75639,40582,300440,54722,25637,13694,48248,48278,194521,56203,52779,48783,72627,10953,376,16733,280238,26351,230789,15132,25168,137270,3588,63704,73376,94031,74284,19443,159557,9697,39901,13351,119050,15406,146455,3460,29556,75195,37673,102524,92329,47289,98413,15311,100684,56345,7116,95480,11590,7200,167,23610,58426,17730,136656,27944,53151,2701,8824,103124,3017,90744,113588,53216,79736,65940,26931,498,29568,80540,143543,21292,1740,59268,16561,180816,42323,50174,40890,52866,10703,57169,4700,17191,4424,93511,49698,166650,26972,48631,165169,82879,69326,202970,4007,2376,231325,139592,22119,62851,37504,68816,58345,67398,186643,43331,277416,53749,15746,23102,17432,4793,151138,48822,54265,48203,198688,14305,54287,2291,18018,113378,123260,7180,97549,87027,120085,2920,76080,8190,102005,5641,64580,14955,59802,54028,58884,19367,81779,412567,85957,97053,103637,78871,29364,27637,141728,4767,30686,112738,130146,42745,12730,105040,14844,232,210944,36581,152317,135543,29744,3129,55647,58149,46319,27265,17499,28005,59948,7170,34138,5702,293047,110892,408,91760,218674,18469,46095,81403,14389,4610,35672,73060,11006,74848,104820,118143,190357,20043,105358,141735,5115,27093,45924,123073,52599,29433,9616,238350,78610,24851,58858,26769,31969,24613,18294,4982,32735,39639,143563,112073,202205,12567,4873,88601,44897,81503,101648,81362,34662,85277,17574,48173,21435,221188,40215,39576,80786,26544,64668,81841,10731,37733,247986,149188,127703,495,18382,54388,72446,43071,30974,198723,89608,41360,190,33045,8386,31658,19992,237838,119015,137622,50890,100913,6460,116233,267230,26621,104129,65114,14190,41542,14888,85962,23342,23041,26453,43725,71809,45186,4770,46452,53894,56616,221286,18973,9038,109299,55365,19366,26863,18808,60909,69353,41738,83463,12100,68561,72860,3980,13796,49340,12332,31311,27418,4255,53430,18976,45523,510,14224,30477,26581,4530,3651,101663,139840,22709,150861,31996,63923,120623,262522,3076,10528,2929,14672,130238,18087,9816,121894,100308,25085,55111,14565,18952,53293,2042,369988,23674,61789,133529,28783,108293,35477,47119,36448,71049,40015,33055,78598,198442,1833,159937,40654,77444,189245,113153,8621,18599,38553,35223,166072,2375,11659,21786,89523,6032,12116,63046,159398,18454,3678,32521,47626,11411,103527,38896,42946,15696,26370,10185,8413,37080,165583,4331,63555,14907,72220,50056,6623,62236,36565,49783,10049,17503,100581,55951,146244,24724,9626,17969,25524,109300,173965,99994,101056,46459,43647,53737,277968,8347,123521,74858,33829,44762,77574,877,81377,222525,123532,30602,43881,53145,2973,16284,81940,61281,127044,63620,9875,14756,114829,19032,9202,52759,119141,23928,120551,19607,3599,33401,76821,73233,117430,39968,36539,7071,5446,121735,194059,15206,45283,6706,15603,65615,1207,165723,92275,34773,104447,8396,32353,205240,164323,13600,60555,79205,25532,22907,33410,57480,107111,69630,32137,47832,70913,33161,20321,2371,117348,10714,86246,1625,11763,17900,268,78457,99175,97940,101092,86660,32221,14041,128504,125080,53744,124263,31017,13897,403,31859,21964,5633,111630,5547,77329,17961,18241,84995,25984,12983,67491,62168,47262,5241,297,51191,7351,8967,147212,82060,16821,782,11033,82431,62957,5026,43459,77963,203477,53528,6247,191852,87774,74164,215654,13467,1522,219964,28589,244104,16242,117821,67725,72570,156792,17186,15979,26990,44128,193014,35276,57125,16212,166451,68017,6905,77608,16364,53777,75921,76426,37975,26203,269296,64099,84122,12077,38533,830,4407,20139,963,43028,38902,42911,37503,83343,85045,16979,1165,60835,137387,58380,86990,110066,134540,56331,193845,81238,17922,163093,38744,110641,12502,56404,34862,26865,125964,12965,111648,25547,7771,27196,136980,9555,29551,107158,57885,18831,37705,35505,101742,13970,102109,62548,124657,23328,11124,89592,146376,248050,6241,22033,18337,80685,29898,11908,216623,67721,106162,146610,21377,15085,91552,42041,62560,122532,125336,102365,121537,142559,29693,223919,11515,110495,18776,22494,5895,185059,103592,229351,51220,100102,37027,257855,29359,54123,36066,106493,12244,79258,32002,432,56205,94836,90182,6726,14762,29391,48938,26864,38083,60364,3310,60192,14766,205567,57504,110760,22649,24666,46333,21517,3430,13135,28873,27052,158809,11597,20529,6695,23138,22960,37137,45574,6545,305877,43423,26153,24769,59844,14501,10430,134352,56169,13213,103432,49523,35181,13435,12408,129475,64620,230854,77390,51990,15653,83248,33466,44571,117828,51481,2187,10559,68019,18021,54895,48247,18354,33737,4554,108595,37288,39767,116707,9175,3726,108877,21616,83684,49862,1938,8543,276466,20134,108498,48770,102254,31914,131520,185291,100559,51890,209,19526,76471,50544,71814,99351,8172,198526,28816,20419,9109,98389,136777,76479,75596,30635,165417,48216,120220,25955,211071,39314,24308,32164,2559,146280,43403,9233,17947,90585,1786,86920,125662,2457,64741,32152,32918,122882,78538,44001,31723,56426,23375,103172,88177,145697,52506,49319,68016,31664,41488,18486,110400,7030,28241,986,109199,19900,42147,56864,65287,49183,7858,24e3,30453,840,16673,25907,68916,89927,6309,158335,36407,199737,130464,13137,59603,201778,195292,21015,42466,179062,172561,89492,11075,180407,31868,72493,20998,60217,9865,19530,39274,130266,54539,21623,12535,13505,40641,73375,4087,85633,2153,3117,70680,55788,92096,47509,98493,37490,271936,151475,3032,16171,96642,34106,78425,125761,19591,3366,19316,54508,24183,50786,194248,91528,33253,34622,108355,41741,705,3814,3883,108929,13203,67831,10142,59754,68208,29128,84820,56880,38794,24972,48571,40821,40476,18137,164254,24064,236309,79181,11282,395,39169,2013,51587,28551,9645,701,109513,115899,113566,12762,62045,58322,103726,41343,40866,244102,143816,2490,70346,40973,52618,15412,30720,104315,38917,42027,93676,17513,107418,20706,123890,13399,97727,24044,87962,65606,44250,98044,65276,74790,101473,19350,91570,1326,87790,172042,7577,100813,86896,85891,41512,108130,27794,14875,71431,12835,156250,58135,3759,22476,42176,115873,34686,56523,73643,108505,51491,20838,12721,32863,45700,29496,13700,34294,55360,29206,155942,123812,7706,163234,203,132720,49358,144431,8130,175788,35818,3270,76832,25710,54095,97274,28779,94621,74396,19092,128242,58067,20885,14670,93255,15107,63291,23654,126900,129421,59294,262659,9798,3251,67344,28600,44629,50672,29072,26999,31526,23183,49175,165843,175455,17282,175411,32022,45989,30298,90690,78118,83156,23749,35636,31317,7069,80381,94561,133756,14960,97404,6138,41065,78041,32843,16601,34123,9559,146529,123377,96395,54441,42012,84257,123541,10745,22139,106459,11720,150883,172651,154996,110538,4728,53447,25704,2009,71152,119354,21166,66604,1429,216162,8637,122250,63520,27180,29172,36124,276428,107787,77184,4680,14952,104903,24418,14793,51561,52931,8371,26342,48526,7118,92066,67280,40653,8847,34597,105438,14198,50163,61188,146286,50315,41205,170829,161496,585,197359,95056,1687,365794,91349,48507,5804,49263,5146,104902,96365,117343,132222,46084,96919,16875,8073,262381,79982,52663,13928,16056,153908,15145,109256,132308,18763,24904,167644,13618,40750,18686,147124,114709,150038,52849,2938,12568,48617,8778,5459,44202,44591,74914,17183,248689,13878,7822,80060,23116,194037,18487,2067,7798,43077,33678,244028,31320,74273,2794,19466,8218,36280,183997,48124,19416,29656,19280,98734,7715,18311,30701,133602,150307,126956,7378,2933,79903,13178,12593,86571,26604,92446,13574,44205,65699,427599,21118,8245,14407,27877,47936,33542,7916,26460,117762,21596,37818,2249,127359,209394,60044,47677,308089,36791,154971,31417,6998,150042,174360,12255,43009,29335,48739,3912,101398,53340,2580,146939,151295,45360,125275,15273,45383,27456,48761,23314,8750,60801,85823,104759,27894,123685,66968,39480,26917,55290,83305,2696,98390,57569,145853,340733,4919,20024,52268,30884,7413,203685,70989,112855,4129,50536,349518,68205,332641,159581,135361,236026,37563,176404,64899,6578,122033,63871,1850,85234,82089,66124,74145,121098,107351,12687,36881,117334,13136,14698,85933,93866,18047,32620,310,15094,46e3,88451,23632,36645,27940,87618,80520,58892,20976,27702,140090,96075,67841,103292,238964,87778,107338,17019,83427,67522,7302,8261,47570,116787,8730,80484,61772,174422,56005,131193,52875,14588,28471,59817,9586,15720,158155,51307,109734,15196,11025,59331,3884,52626,102602,84797,25158,27314,4437,20488,76214,189248,35023,114952,157376,2827,62439,102878,129749,36405,10329,109339,108633,36662,1254,13267,5470,87105,58004,15397,10434,159667,21864,52022,179464,3013,32147,31496,116832,18494,105502,129227,107267,50033,13481,9954,24267,22141,16257,116154,36185,950,115685,11305,176708,2048,178671,112573,287867,162328,497663,95170,50979,193861,50987,30368,136257,31830,46549,15119,169876,23788,17462,249887,57377,1949,35448,14791,43769,210091,3783,34612,282103,88380,245190,5457,20491,98908,11402,86899,117916,16028,162584,60644,320177,156096,31065,55876,22e3,77655,9992,23397,13757,317623,63978,215255,2443,17648,93231,27388,104529,93807,55505,140477,12046,112040,70887,40152,94365,112353,25063,114679,266061,71248,119555,15589,2244,617,14129,211431,70110,100652,7777,4383,85911,89221,21010,120615,58357,86405,37554,41647,18,15143,69662,60491,14714,186134,148344,42347,5410,168175,44535,42449,343894,129417,99682,20659,27272,140483,63455,222159,17536,13722,42637,62324,11976,114691,148109,2283,32057,182393,4295,147364,33705,2075,44303,30274,28331,63740,69740,29148,10346,44862,33716,73937,153333,12930,38784,247159,2515,41053,20256,83368,256189,54639,115240,5096,24661,175419,153552,26516,141,138176,63885,34115,47222,55709,2765,28479,38875,236608,12229,22921,77291,54426,45388,2860,57787,114579,295139,105782,17826,71066,19119,54364,69385,16568,12323,28057,33346,34919,124763,155533,101386,31644,8627,49001,303600,29868,63213,9103,77280,71333,9696,138789,37059,24823,5057,21352,32368,114208,56803,19424,10445,58514,8661,209508,26187,171838,10460,63454,14016,122504,41328,21329,46618,32493,38225,7855,31763,7945,29876,8734,6438,24205,97490,139977,130740,47323,33195,85390,57194,13813,60600,21313,96251,7699,27584,170521,139271,1363,4402,336738,129223,84983,69150,13147,3590,163929,207225,155260,55916,20288,4503,8398,98490,11773,27512,37113,84976,86558,28365,11756,116005,182148,13733,115313,47644,67208,85069,9347,14995,226141,14704,101835,41159,35314,13113,63526,214039,29978,50446,83339,17440,129441,72522,118641,97816,24907,73844,15717,118884,167255,96509,162793,30847,36849,51297,78974,77793,10427,1873,2972,9999,35074,28190,64297,146836,46298,60038,163007,108919,61219,2403,75022,127339,4233,110389,69022,9833,128097,88016,79390,222936,22570,94657,28462,56956,38803,81536,30474,152794,19566,16481,147408,74574,81895,20731,1918,1366,76367,187321,54494,24366,21690,61696,33283,107477,77499,31112,414383,74362,18463,218441,120929,59848,258629,201924,69269,454,19989,13054,59894,3623,58908,20681,35723,78523,102680,38988,184112,108087,50944,132704,52966,21699,18860,96349,201411,82697,85395,95658,5093,6427,177894,44191,32755,26961,155739,6249,31310,81030,26574,84311,120155,86730,113535,7424,48888,13516,45747,98098,20077,183995,81945,43210,26704,40420,75831,45648,11180,6855,57927,65528,124096,34851,2598,156633,107572,127352,38169,123845,60142,62722,105584,232364,23211,68120,1601,22169,89299,747,258039,80572,7258,152249,11862,101204,8834,121434,33761,19175,133142,46343,40178,48723,3589,41977,30210,38868,62257,10087,82658,87827,90646,16415,47552,351723,28298,72225,91146,272760,1701,11295,1652,109651,300747,51863,198800,29446,11794,32345,37538,22356,33102,37590,113544,37970,11478,179743,25454,103417,59905,221970,105196,145604,7817,164809,102360,16974,75840,255333,56902,6659,1954,645,59400,67769,7689,18675,5215,13793,20536,27852,3387,29523,259718,16860,94625,43143,29245,15848,233581,22685,63631,78557,22836,133302,84513,1348,51826,47129,98836,58284,1830,1749,94642,10933,6145,12506,10975,13879,103781,144434,10268,28409,32346,52968,121567,107374,77268,23686,35097,10501,155275,15303,47136,21102,168741,55332,90385,15996,84817,681,137803,25054,142275,6163,38175,8056,124296,240642,65621,4934,178205,16101,62803,60964,18230,100622,76465,44689,14545,9543,47514,16852,93380,28048,12047,107106,37575,101485,77047,57326,34819,96137,76916,6469,46264,115983,75768,87668,69942,13027,165,8373,114231,26434,52844,42799,182044,23580,146254,38081,43236,33883,146220,382894,14606,46035,36481,166621,35417,95382,2957,59384,60428,36358,66343,75378,22267,22950,83528,17577,56474,25285,4619,179691,75355,95836,53295,34588,171410,4487,14679,84208,44015,18562,109133,54101,11531,86052,174479,303157,28095,9953,35642,14564,39802,16145,77606,117406,53038,121117,53624,22062,1212,7632,127157,237292,189087,10478,127345,102515,181997,86752,87623,10966,121602,68783,68681,83042,114380,138349,191305,67176,50085,39016,1427,42384,1412,67118,122616,72389,25260,2237,13576,137346,19938,20304,2191,68759,5373,61364,238507,75814,23931,69565,38993,131741,38364,12528,87762,5679,129853,5310,186831,32653,90338,260176,389531,108118,26843,43985,50175,30563,25106,56965,18130,140428,4542,165503,117991,24219,229605,1819,129663,1240,3797,76093,18398,71339,51919,93043,27175,47060,216257,6483,35051,1217,16512,80798,129064,13225,69339,8548,237079,72298,2575,34280,51379,117910,55671,53345,247552,29486,39328,140821,34681,57045,60177,5004,90269,78522,2479,322607,48474,61296,13057,31558,4678,59271,6699,27044,31988,35944,12503,83480,4389,136508,3781,114121,70279,4488,155829,42214,2898,68191,75695,305850,45041,74344,106509,30087,17429,93292,12477,290,23080,114802,35714,18751,26554,105424,17775,2144,2412,100610,65192,113975,52975,180272,135050,129815,76238,106483,21440,63186,4260,46189,9711,28249,4169,23429,23390,8324,141585,63809,67668,38457,38063,39226,59972,1189,203916,62368,14403,16949,61767,85801,1739,40147,35049,76757,33124,62102,15780,103593,103009,53484,22952,67973,114645,6566,5245,50462,7601,8288,3513,194571,80276,1908,54592,5124,58571,2513,6800,273997,193904,1119,17991,117245,2508,129156,82366,26278,71465,63341,56943,39662,106116,94966,156875,9736,2204,122308,94418,27134,1280,24539,49022,45314,3764,50904,46424,30699,28087,293839,9400,33646,40165,822,147499,50263,116179,29085,11863,31314,5578,17797,5104,12454,1604,15342,219206,10232,67800,94261,25872,13565,90339,78971,75377,26649,41184,47695,11514,35369,20767,14227,41953,309396,148270,147938,33074,14453,27499,109019,39018,25738,240196,158931,52820,8612,95853,21524,137010,84901,70869,70021,116794,48404,38771,6732,1070,70990,187297,49140,5238,576,3564,253975,16027,16483,2811,37775,19034,25259,4053,2e3,70083,95774,19713,33431,92703,91314,42381,288770,48194,95985,3991,77418,13406,241328,245086,56533,35275,62725,9246,51924,70181,95331,16163,31410,79016,39312,120878,119371,275987,80124,27712,9186,220,23598,146167,85209,68238,282190,57048,31273,30555,80913,17594,75779,59160,135002,101219,189377,29225,96735,60126,62522,104e3,27620,86814,17240,147533,11001,5425,43682,410,49460,87270,69480,46315,59448,1816,76201,9431,11788,87960,29063,65539,47347,11678,33846,7008,196704,9895,6753,8633,120892,59970,572824,115934,6646,202559,892,48351,37611,251282,57823,67263,57750,26527,34485,90747,7685,88370,6144,64182,1709,41969,21458,62327,181657,49247,225330,122600,114574,107124,85361,111833,63243,71420,15655,191178,72430,18063,51425,54002,12364,53225,86557,18193,97580,41232,138398,67821,128724,8944,233212,101353,52099,42127,14006,120107,32789,32132,3498,18123,33758,56058,5779,128760,59888,98869,18445,84702,51911,13234,218379,20093,39031,8074,70195,20708,23462,24355,131384,60189,26390,10403,41060,7140,10781,49410,42261,87202,82566,41663,43105,60276,2768,5733,74176,28329,2297,145430,131632,83615,122915,105441,655,224102,5284,136426,67763,16294,188511,32538,61049,27893,3394,13951,159099,28542,17930,145360,9492,190122,32285,78855,26440,13570,58648,73908,4239,124561,2444,74172,53131,11468,10794,73566,11623,35343,64710,30481,4163,10328,38309,29901,10538,154377,76132,92405,24839,11679,3465,13449,11637,7824,2337,57754,1260,14458,41118,19878,38661,13416,159180,37074,163164,54137,28627,52134,184900,8520,40385,29546,30502,22386,66527,107458,6850,24022,47983,30603,35083,8934,304066,39500,9,28261,33026,77251,9374,44833,116312,34990,29236,63563,125639,135405,165398,159055,55690,88141,69643,236964,31983,25572,20436,36746,60896,31850,16179,11828,5888,3043,66368,9750,31167,7915,53111,36430,1333,64344,93659,20061,60596,180191,51630,6792,30244,43509,101058,22409,420,44210,109783,43223,27030,72477,72831,32679,29235,7675,47556,12258,39907,149412,84926,118247,24692,71717,105038,86009,45941,41189,89453,29856,52543,30627,226798,67303,59230,67415,34408,1367,99685,16867,128419,52147,4111,125381,117881,16173,44093,102224,31575,23234,24870,83790,127407,239098,3200,994,1255,100903,242275,117266,55116,38205,16140,29662,11307,40414,208793,123355,56470,4862,75600,30119,58218,70828,24075,26974,7802,192353,4851,5475,78720,66596,3409,28573,64396,30381,30690,59859,88256,5406,99945,103064,34463,37727,24238,86643,60088,4057,23741,5967,162904,38240,28356,93858,25510,122879,6897,3278,7057,11971,4400,35461,211413,21395,59615,39471,87233,55795,128426,3051,22470,41950,14705,3974,180108,80476,78442,204996,91987,15634,67610,139015,142373,35611,51134,10387,4353,153456,57749,181039,14183,68447,151532,21107,36452,20551,3186,46247,46383,129666,88736,140662,146243,2066,8360,7978,64818,106963,17896,47801,10723,114821,223295,74192,3293,3393,16987,74064,11277,91622,4270,29828,27951,387869,103235,1374,61988,120083,477,145892,128378,11779,211263,61354,18221,17869,46530,83061,108538,157981,90608,67199,95080,49064,195814,12302,66307,10348,231346,160732,112859,63633,146558,21271,31037,198802,47622,12862,95710,3910,77850,73961,85585,34752,61e3,4082,24595,103679,71107,8208,79568,150019,16615,24961,139857,32664,197366,4559,54735,32696,4126,162019,75698,13916,70108,159638,19834,9349,24675,175560,49643,18206,52459,27992,10809,88865,401975,133172,29e3,34558,30915,3658,25834,42430,36562,125265,18182,10155,40149,97082,208980,19575,60853,90529,66545,9600,789,46420,2317,88593,55595,98980,115302,5742,169155,1073,177901,3472,11189,63711,78643,65472,50459,127979,93,42202,67053,21720,157650,11145,141378,42033,22824,85705,79114,35584,15974,1510,54172,28562,12451,104226,19190,97151,73024,20948,5151,81741,21499,29006,84183,198074,54003,45120,170125,26240,35177,28389,64863,79974,60778,176915,232183,45342,2038,80253,41564,40703,32689,5430,100689,5366,23007,134279,14266,26712,73993,24934,64242,52113,102887,61801,46415,201049,54251,62133,122757,164883,30815,139966,2319,30842,766,13362,10287,134518,86111,81665,82440,28333,43019,18963,8804,161944,23439,102144,101145,80029,39052,248708,30350,117340,11878,128467,974,138625,63961,5237,74778,61834,67040,43814,13690,65947,33809,232476,115258,181745,28824,94013,9510,10246,93722,81976,7217,114383,3493,16014,69045,72692,12145,80981,9507,6692,1620,60820,330444,35474,33962,4797,7053,295463,46445,27026,12491,77988,49524,35675,90947,29114,166705,101385,133782,32704,6186,84595,176031,185623,45966,151302,63069,1699,107491,947,15458,74452,196212,6046,10498,12163,10239,35191,243951,9277,9090,29539,54460,22820,26514,112549,60372,51753,48756,21812,70861,260326,41,44222,10441,16961,48148,138771,216194,5914,52153,53400,212036,56519,26245,10117,45888,15294,138019,90913,26368,43842,42111,23348,6082,194845,161089,156206,51546,11647,30759,302912,262094,8635,78876,26535,35283,54183,31183,85484,147873,12989,5197,6356,72894,65347,20150,27370,73787,1493,45918,12366,190217,20724,13858,10981,67449,81213,7553,14115,72242,271517,11842,48310,88743,143726,22177,3290,243231,58452,62937,12592,1654,40066,33477,13751,9921,128442,15868,7106,75236,83773,10775,36938,10482,170465,17368,17469,161508,32752,98340,800,19824,264456,3901,87319,2867,26782,9630,113102,185815,24197,44584,86366,40224,3636,140916,31731,267731,9567,53678,72984,29389,27963,17106,50282,284911,60170,8322,12608,23374,89652,5268,39044,229766,8869,151350,31436,177342,12269,183212,120418,116270,2843,78888,69192,7865,184099,1086,129897,18383,70508,20242,18508,229924,124569,35749,50589,55626,9884,83115,40971,30671,18135,14452,38861,17844,201826,5549,26413,17189,13561,38539,10679,143331,3314,36785,171194,49685,187713,67506,4618,104039,17060,195080,50648,33159,19238,67559,134840,28599,157523,17130,38064,117398,94355,31918,13575,34538,40326,13997,3494,348283,62481,26862,3603,104426,244363,153709,112487,304612,199674,41239,35545,54869,293005,28223,26277,26899,4533,18518,15492,38587,80488,70485,160395,263,60162,11382,222152,4696,250751,51921,182609,10707,48463,46243,1227,49111,111564,46502,33342,56846,68541,63559,858,139927,16654,229375,76759,26478,33205,95828,23399,92945,2637,35630,28470,143992,50214,14174,21456,166191,65665,1711,21594,78019,97599,111701,36,147151,110246,189022,43021,30397,40757,131935,42065,73335,48039,26596,28984,15102,2361,7421,202167,69744,43766,52826,3642,83304,33873,75140,63169,192389,36551,92748,13039,123959,233220,21738,84447,77230,20228,187852,19095,25799,92136,108774,29237,53947,2299,118106,2687,8830,42331,202924,33667,2023,73763,30704,19363,19779,16737,35629,48081,24068,101013,162338,291912,13749,24745,328289,167679,70086,48299,23306,16732,17801,43322,54589,3586,63653,43624,53474,925,109177,251316,43805,13082,19511,86565,142182,92461,17117,101033,103319,64589,4022,4351,235897,5352,82705,107142,46391,156084,5860,61365,10558,13045,7717,18357,33922,12590,33065,6928,46993,783,46937,67846,8952,26295,6107,119656,18799,17458,50747,4229,179559,112727,118080,20683,41464,125468,51560,49749,44231,7359,35339,62988,136487,67015,5208,29150,24956,105186,48858,6143,18097,6972,16404,73489,58742,97196,36357,164616,5834,32267,13746,147733,15113,132091,34127,106298,39729,106426,22294,9780,15602,36213,71502,42808,66802,599,60755,5851,39120,67363,108623,126368,72770,91263,32486,30596,151717,7951,52002,43103,11768,68942,40901,39344,24037,127500,116890,48403,16926,86750,17745,48648,159545,34460,58419,5634,114317,67865,31462,23352,24010,98185,125708,69686,68337,13610,26271,70691,2980,4768,27225,102402,75453,28106,8104,6931,1176,6274,6475,112635,22498,6176,238686,26832,28893,90319,14441,15682,15087,39517,45270,109134,104440,45965,47645,81772,7876,52683,87720,12898,4505,185665,2769,113401,15664,57592,105229,137381,97059,119268,6876,43309,33886,128363,35476,144249,67013,143587,83367,25703,91436,59347,53236,2289,16519,19844,46309,58558,99834,23313,218816,231303,36388,51333,183535,109792,139277,54306,90139,18235,8275,32710,37677,82464,86025,92204,88842,117723,37570,128723,234242,76350,73795,34896,148247,58424,11105,11744,45746,63372,17118,49772,199520,81902,38004,22911,33752,3125,1995,53792,4689,26909,108150,146062,69674,41811,161444,84855,8999,28561,16731,93937,3189,21967,24890,22943,1356,145300,51569,28802,517,118679,31703,40607,48098,108854,25003,10233,73969,177495,5248,24516,215347,146192,48712,60626,69188,40735,5866,586,101541,6509,47590,52129,5969,222045,110933,25733,24223,65339,62812,2414,155418,35819,16022,78423,43138,20995,128255,240673,46745,236093,72176,57085,97841,61248,107,36068,193177,105427,55726,215229,20446,47228,100420,87091,14429,121708,23605,21157,187721,21880,2997,203976,99166,95068,25877,7724,98925,83401,4829,13182,18229,13718,239662,38653,116505,153497,30589,89029,38962,181302,43853,78872,180301,4786,248240,7401,106136,112590,77745,19731,60880,77789,125748,135487,5975,48627,34084,12419,215770,47557,254582,10364,106495,21856,67539,88981,38805,21428,48732,42316,12149,16078,52808,25327,51322,33850,51147,12253,122354,46077,56483,254553,115417,81834,150991,94662,86668,7381,12841,100650,18218,15741,22372,68294,50705,15535,84660,61887,22553,72299,31361,24824,17743,46820,64288,31582,77006,111674,116384,30760,80920,86149,77192,51979,79691,60342,122805,103800,240873,160744,233114,78962,54920,8608,3484,316104,72548,24337,5088,230040,21926,10172,36838,26,86221,83458,102176,12062,17571,41929,41170,28428,68239,41750,103930,2634,18313,53019,34825,97837,63115,24606,73157,152474,14715,91439,37033,109806,140259,30668,174760,380,135597,95673,136073,65073,134249,13829,17279,122305,4420,46444,10237,64848,203623,70728,10349,182885,65075,24519,25783,40318,34139,22222,63394,55266,102764,41422,20126,65100,90408,53640,35128,48932,11192,38935,96839,34782,39492,19396,41332,6250,5511,19492,51304,25936,104466,54099,73771,86115,5080,7669,30891,111700,13931,25276,72289,135447,14820,258641,25265,31005,281179,75286,393,95359,14623,13584,6680,101227,80173,44933,76666,54542,13244,39348,458,25379,109451,134348,81143,6959,65554,12027,51311,8716,57589,140731,28467,23316,17272,30458,25980,55229,77197,83798,28302,114784,7428,34548,26241,14712,39336,103304,18928,54080,12870,334,87722,15208,16895,142098,114262,39820,83913,57817,28682,7721,14900,108672,11250,62246,42849,415188,1724,26555,24549,25505,26443,107450,145899,61035,43528,6901,60726,65906,267741,21338,147590,42079,18924,73017,135236,15393,5206,4026,84185,1531,5988,113890,82647,303391,7386,69844,71611,189865,76523,31877,13315,19314,198575,32821,1928,67641,25913,104475,103489,3297,70391,18406,15446,113347,19295,93790,27856,1792,167471,116449,8541,4408,41757,63233,25765,86680,64501,27034,24816,34975,6079,4486,49693,36229,16917,21581,62426,27862,11612,54284,35702,194034,355,24277,48262,87411,70504,310164,118018,12516,47559,43502,57433,107139,9290,66533,80863,14634,34312,91725,28606,21342,67241,72355,43244,375789,37402,174015,105070,8342,44167,67494,1890,16365,11723,271002,1865,47918,8350,45564,27742,25110,125803,8553,49504,81925,62211,4534,15491,19011,80373,206920,667,102405,128623,245524,5553,113309,192739,65766,19567,22832,261958,29679,21293,71134,20962,105123,24721,860,21752,33448,18372,157167,94822,35770,173224,232737,75729,28937,46828,28062,25453,5207,140366,36665,30652,6169,67920,150458,92040,23186,184604,92330,20891,176492,49427,27828,38305,42495,143982,49560,25503,90043,29747,65328,47830,12932,11068,77721,9003,25213,94205,140426,46090,89945,138173,192691,33329,112232,129905,35709,27514,1841,19957,31411,127476,53572,17497,173549,55063,175135,19841,69314,5192,237921,117660,150697,4060,273045,50414,98940,65348,153665,164423,58804,156695,48994,213928,86036,28608,8355,39574,34540,16927,135680,18374,151587,10830,53805,16878,16623,4282,48030,8537,14986,46102,13062,72897,72,33050,108227,39451,45935,651,113320,40535,95176,57450,48843,5003,19019,10407,211163,3848,1068,4988,32091,30095,41692,15099,43602,107434,50744,7627,171349,16313,150832,352665,207750,33937,38256,51091,156e3,87889,90663,84175,24908,114900,50365,31494,83829,5398,169342,47521,54818,18935,8356,43094,41212,174536,10082,92550,6678,60614,23355,69721,14796,34149,128830,58187,3179,208,40325,28399,225029,401412,51150,31580,207268,6657,10993,69818,64282,289845,23308,12961,38447,6681,52944,31855,2572,47646,120728,179148,37240,45196,218274,4816,3695,21961,50084,35209,18073,51452,27004,6100,33941,1377,84831,171214,85,141510,9078,99227,32610,6417,11718,49868,65579,87902,73018,49062,46280,61742,21512,40862,107733,15941,29168,157765,144919,14487,5767,158014,140070,7241,573,71584,16921,223566,40331,179473,35081,47926,140885,41508,52104,59180,42310,32811,29048,123517,102413,80208,10104,14746,12649,153641,126022,37965,113017,4171,83,142592,2809,6362,50416,71323,116894,260776,16204,1524,5760,30351,12658,20703,54403,36083,45408,74772,4946,14485,50759,111222,10890,2195,167147,92962,130534,16283,177256,35016,15472,210156,151187,73922,117691,43250,52051,37392,24811,24358,30830,5775,818,21969,1476,127322,151783,58392,31021,106913,65215,89407,90802,28531,11690,20234,95249,44602,37256,18707,11928,5161,4410,26571,51903,49768,22008,25252,65780,209499,68769,203726,13249,137363,48845,86823,6658,5674,31881,1083,1823,108676,34518,166752,13791,14287,91576,91429,8665,11529,26401,16191,91972,30964,5254,28486,54697,79613,66520,18447,22870,45203,194466,22822,51703,12278,76716,44595,73455,33546,12235,144843,36154,51247,11116,33040,3180,225753,60864,1972,28469,12891,28879,10338,144157,56294,353058,38302,41447,87532,110616,27065,168438,6557,1213,50804,144643,24817,2390,136531,38174,247513,16190,4059,122791,131994,137430,39506,57650,16305,5188,54309,106128,20628,88071,67394,395446,250285,66176,91254,1399,114196,43915,60230,44853,27206,106353,43013,18733,345105,226453,51202,16607,57106,117175,35492,10476,89598,127439,15187,39624,13688,61570,10615,31111,59370,6238,175252,32143,224492,41388,95408,34384,148238,78307,38959,9340,160091,61443,15737,11216,41244,170,38299,102443,113097,26382,14027,33707,3957,76300,66160,19431,18900,6952,1717,108656,82206,188021,257335,27295,43999,41210,31777,46956,57457,12657,11489,15697,48060,204748,53583,82422,284790,30503,137341,8120,19615,220311,15991,10217,63424,9808,67431,70976,98221,4491,15177,28535,144789,751,13230,2394,1504,33977,132104,30316,22230,931,97193,185240,24826,22687,174322,15307,22988,1390,188745,180325,29580,59068,74903,18994,29195,79,15436,7622,38462,11566,138710,44828,45774,37768,99236,68137,84083,19282,22698,17134,74807,126662,173497,46248,16938,119735,3212,28292,213652,49013,9975,32180,45660,86250,4801,68788,95490,77482,113751,11994,44624,94452,46839,128497,100316,5798,58588,73184,202987,65417,37790,88524,1606,43156,97964,105717,34947,11203,100060,37742,130074,93653,107799,94311,196106,41347,8035,10780,16390,27883,118236,167395,1979,25006,19375,31628,18916,144723,78502,114047,103107,86492,107686,5844,20934,206963,23556,22591,16562,146333,20167,10471,117434,33085,2863,9740,36669,41849,37271,22790,18209,28979,8231,12952,54408,21731,25130,45208,55748,138120,75826,414,29593,9925,292865,25999,683,123149,7036,92159,86055,61827,103680,23176,54918,58466,57578,13305,5709,86479,16697,31064,17660,200919,10770,49793,33423,32370,52047,16488,62555,6459,8426,83493,7763,59725,82812,18628,67760,79405,68557,9612,7673,28102,56517,69620,171797,32458,29541,15870,81109,32080,207644,71495,21202,11039,91036,61230,2810,130800,32260,4613,60590,37112,75214,33979,126402,155062,30642,63875,12810,194463,82799,47664,16725,36685,43367,61099,449,172150,102867,21691,301838,36745,7130,18671,57316,34852,38034,54182,35578,65900,99486,19771,3456,2658,16914,99866,28390,28109,8262,21147,34353,20006,4228,137085,1675,203023,283196,198286,214375,163329,290603,152574,40471,83506,30068,14730,23177,131539,34759,27668,32178,71896,104799,116305,85430,119262,42860,25160,8911,23428,49437,105322,6519,16203,6349,74711,1230,38045,8540,75165,44736,25909,51026,317034,4984,32281,91312,27060,44431,17817,45363,155937,239085,35697,59784,91993,29531,126740,213757,76560,167776,285273,24262,8237,65030,41160,74437,48804,118916,13159,37842,1031,75349,1478,11655,108777,23435,277425,101734,67469,70231,124711,43532,28514,65526,54956,1e3,21882,17728,25302,40952,52214,149632,1999,2111,3259,63362,89961,220561,39777,26335,9063,10572,12416,34551,34623,38604,24723,5947,15588,69927,66252,119177,69173,46629,28714,70715,212408,20521,406913,74380,11716,50659,50862,37009,88460,130101,7210,53853,538,65120,151950,55806,163748,52837,13153,21100,16674,64536,6091,138201,44837,58547,3723,163,2177,32288,85454,34033,8497,14282,25742,10535,10741,79559,117493,243787,49337,100718,79495,40139,42956,7551,55433,15421,31509,23034,45081,547,61176,53434,328001,8470,36263,30145,4519,74173,53935,11845,73774,60211,78025,3,4102,73782,109293,315332,48412,26683,13714,6865,20128,18490,104141,325,39470,171970,115860,15707,7268,73301,74336,31370,2368,111827,107757,136231,142844,97138,96638,84053,38691,23801,1588,10573,122098,77039,240,186135,146101,11996,18143,112963,46171,155836,348769,47795,121213,116266,132515,3344,144804,31286,99187,255838,129694,35894,48779,55235,148582,71967,65282,15174,13920,47080,6147,108242,157593,125025,7136,1286,28957,127956,28402,98813,20805,7532,109417,40610,5041,32958,15142,18408,108596,33543,50517,27748,80114,233434,91447,487,37094,100048,30541,43477,10639,89862,155868,37667,8726,60684,237903,73408,99589,12190,38739,97348,3914,13594,2680,149016,13907,30171,28343,23530,115225,61104,35821,147679,14337,4297,244282,24085,326976,56428,7851,21303,131620,71446,83253,68692,111870,5224,15813,38197,49026,45057,13660,3306,76345,40671,27905,91072,996,68527,62085,91351,122634,55109,168209,2024,27560,112707,17352,8306,167115,169921,166958,5031,46020,11844,67284,19130,76185,6920,32849,5450,14610,22451,21002,17392,31872,66682,84796,13709,40210,59898,12029,8719,53564,21462,91884,21647,88379,194428,12754,37797,132826,160016,22567,54383,53186,77611,31107,8339,4694,19185,90355,23597,17222,140675,28442,23668,55977,9128,61555,28774,155229,17658,9390,24379,69357,15752,127381,239631,62460,93181,55913,45133,140155,18676,25249,33164,29581,82837,67223,22362,29975,7317,52813,1943,29613,20012,207130,49617,49651,5636,15334,36313,29226,28084,95247,72072,19e3,224932,15811,114,32127,38097,37508,88507,37225,27359,91626,12193,69279,20608,11055,88156,92808,2152,57259,55275,72789,24475,104414,1708,9882,3818,48661,66897,1631,34806,227930,85815,87753,18321,250664,72733,25107,206797,50891,8082,196411,92596,96764,152823,65514,22819,387277,62176,51225,40329,15563,189,3659,73670,64357,51793,275136,33482,86653,74615,67058,11318,125720,15388,22388,8267,1730,102663,170910,40784,7144,85373,13040,7088,94309,583,44224,140424,77439,18496,164026,36578,4722,9151,5824,63365,26510,35199,40500,79277,32495,44614,35233,9566,203293,152144,7097,2330,183480,98629,13423,330887,44130,68600,30939,97829,31012,345465,56747,94879,4939,160027,149761,99423,46099,32251,15332,8761,96094,128555,5763,235318,222223,55729,30241,55420,201746,3987,81382,8259,49325,23287,7719,24633,251100,92311,18591,110533,64759,170260,393860,7175,21144,132887,3593,75346,101277,91109,16387,259187,11627,57459,173829,44694,55780,49797,89192,120443,62622,3904,14814,23887,1027,112258,64955,99800,11132,66353,36202,48624,18158,88481,96882,43059,11040,2455,7077,21651,181159,99126,100434,61388,68186,19161,110468,120052,8819,55324,41494,7014,37689,3618,87729,92615,207943,9823,128657,12587,15857,6379,67628,51216,71775,157617,63244,1503,3864,218754,110864,5769,21492,7243,1192,87921,85529,31512,18537,42698,35350,73510,84474,34301,8991,21013,35034,566,38832,19838,35586,37216,39413,55006,12178,59742,856,84563,6900,25632,17437,49786,30723,13847,70845,4044,7843,23944,235976,55530,48942,6518,20939,73769,192653,52936,95207,23895,132542,142982,22632,87452,48042,54018,178468,10728,26230,23559,363,81269,142012,5718,346258,31456,84333,246476,51018,66692,101804,120570,39962,30373,70593,2864,60541,19425,54209,104092,7201,31545,48018,25865,15442,46257,40443,8328,6451,111782,47527,97754,33046,470,245116,31095,39,91934,87208,73470,36708,36521,12801,70624,36272,8892,79768,12427,55454,103756,5908,52390,62962,22720,141138,94634,41689,128402,126390,6628,106394,35527,134394,82727,254651,194502,148064,89549,3202,28359,957,21954,27906,49840,142747,8307,24206,48978,1186,71728,133038,71474,91306,6333,110959,74600,70387,18983,62609,56057,22970,1147,135850,1321,28834,3578,59715,102227,32827,81415,99952,55636,257598,390,22702,35701,85872,402916,39216,189795,14929,19467,10112,144422,61514,5279,63421,134686,41436,8424,51925,10598,132295,124416,4604,194739,210929,57866,31829,51626,50007,9976,91878,61906,56168,81906,60918,61859,40017,23059,16887,40927,62064,12785,32893,32913,21782,93965,20169,44387,79084,38463,11457,93950,27127,157050,2697,337088,5116,54128,48255,33279,8821,27352,25515,124022,65710,28906,38557,33390,1722,104435,72215,38551,12094,30978,25113,6671,37355,175109,42862,98024,65406,221276,59624,118012,64637,78760,86697,21426,1639,40350,12584,67193,84144,31396,7863,143011,69629,63112,9454,28666,65798,46372,134721,6314,51402,30837,151922,2847,38676,38008,92823,136245,17540,5504,109295,205242,37606,5211,214892,1586,20670,208711,137743,19328,40652,16995,20023,14657,154919,34422,12996,13918,38221,47690,16398,2959,37680,89122,6721,198469,91876,172043,83898,101992,26084,94570,3635,76958,22853,76497,38266,176590,168403,44464,142840,79180,184594,1984,41806,83147,11985,6546,366068,59732,24533,271505,8736,39084,222992,93429,28962,58985,86665,8432,30028,14548,32439,54424,165029,55175,27458,69046,121277,46168,33732,20661,24581,135574,123110,37556,79260,72611,16957,12939,46162,58238,44907,72936,253758,41324,32518,96480,11949,124438,65280,43256,34107,53533,43531,37037,28366,45970,32741,173438,6121,194202,62969,26355,30314,58370,28455,1848,50519,82830,90393,21761,295490,10936,256940,133568,44050,20269,4089,27457,21610,219460,36743,14821,101388,52005,13124,30979,140816,167362,26054,18458,60789,34917,40447,26606,33422,9066,3452,83614,5761,20263,137238,25038,91310,101,52322,74548,42572,38084,214054,186568,31802,17665,30620,141936,37730,14420,4265,187218,49640,188208,51441,55388,96452,66659,40869,42039,60967,221027,19234,178581,29105,96050,9165,196118,157335,3738,40354,117436,2965,34136,59659,15570,50843,230035,31444,71260,43886,18316,5387,38500,168508,17406,32174,8828,103373,143806,90367,3560,18719,122310,16508,26719,2541,105429,6645,37998,73190,10591,235916,49737,87112,233941,53188,32193,79154,4544,52905,126477,7580,63501,57314,3216,31337,6541,103083,60846,49,9756,15481,1355,43840,14319,13743,27486,10222,73114,230718,418644,16706,6674,279748,23058,45273,295831,86306,2743,5535,88773,21829,35253,120938,31153,3169,16839,42847,8751,80974,33942,36867,35514,16485,26474,77775,56877,5391,48346,3882,108713,31403,27804,55248,26235,43821,136104,40118,175507,28034,203908,18732,1788,34030,106427,36958,54359,7251,44936,15356,69139,455,157915,22173,140291,50348,43275,82066,49621,54952,15216,36226,96695,66855,6936,1987,8227,196087,4631,68827,99004,47541,110265,17953,147605,110242,58520,31312,38724,329975,642,3155,34497,75937,6207,73843,6120,17249,51429,117746,3218,910,68961,319671,14938,29555,34700,1649,66673,72268,9655,76800,153087,6941,210168,27130,35398,1780,73242,3135,56689,19556,165307,8765,35967,121458,13333,70453,17350,117253,22265,13340,44265,39869,441,3742,135025,23581,33309,16543,17731,13291,157637,283005,21408,101360,63887,52312,83873,5338,233779,23759,186949,34531,177320,38069,156465,91004,19353,59852,68160,14891,1338,1072,29823,1950,28901,81407,313445,73038,84807,162348,240257,37162,138934,16111,58013,41253,102951,16457,96056,19541,56402,67217,41638,94381,89674,29481,37456,80815,151579,13937,13683,132537,19699,134545,67020,29816,222341,141235,427578,48868,129557,233342,23077,87871,16213,18728,16184,9469,37913,19680,2798,171356,178328,13216,50049,72690,71904,124644,55455,7504,29052,41036,266546,19899,30391,188755,8659,59469,16,104298,112943,53865,76203,138226,68857,139953,14125,107625,119795,173133,4398,50273,48808,54390,16466,122086,31835,67035,50971,48859,7508,46427,66477,73021,84615,39985,83076,46779,201569,53336,36443,60865,168164,143810,51393,25548,169307,32896,24485,38424,21837,29087,275813,51674,6714,64883,46169,187369,55186,76192,12852,12018,62134,31067,118303,16542,12125,10579,4928,26291,43854,7091,10946,253716,109062,39283,17261,113012,258512,47764,125126,32646,55892,80279,201623,149872,3192,385,1208,48750,5376,58738,22335,5427,82416,47811,32435,143086,38930,94128,59975,156037,37977,38224,62485,7698,50405,71027,16462,21559,136153,34131,107506,162069,63703,3101,215029,40407,4178,3774,9187,80019,17880,97926,67579,2600,18405,8351,47924,86638,70820,92206,86453,29610,42241,119200,3198,15466,67813,57863,35454,4779,99518,4649,104641,144269,33730,38073,65864,6838,109456,193298,154007,5623,45741,30846,182578,25573,157224,1543,58575,138703,146140,44971,49356,18275,59064,20300,13122,11848,24453,11973,9797,86843,2919,25530,49210,1130,161220,76788,75373,85604,34926,36014,17777,17255,51533,11676,92226,51845,119859,21525,5936,18507,28050,1140,31418,14857,34207,47859,10750,36382,32079,106909,59426,87757,38393,110042,15965,97104,33757,35344,97993,53979,33651,45407,41884,82515,173089,7177,58371,35365,47543,51927,35587,10670,23544,29306,84233,39976,76076,62097,9007,8668,28119,78281,120790,19835,143020,54968,18670,64959,20649,34469,42570,33001,136570,87796,120044,1106,58700,63951,127623,12805,83057,40212,31773,49850,7361,54336,347524,101314,23751,19569,48791,29174,49369,20467,7465,75842,38281,623,112457,60210,28849,51003,94720,6426,90047,85560,43761,3579,85105,34607,90410,118528,7224,42907,111163,18168,6960,161135,191298,5247,100584,127552,171568,20121,91173,12636,54615,20199,63730,98105,2396,40387,14438,125012,4765,33235,12865,45299,37728,82098,77872,114037,59253,19675,24838,398016,102561,11446,17069,57508,178277,65836,99941,26114,2585,271882,136866,50126,11027,155648,118367,14585,8910,123015,335383,40434,41016,53021,14439,87098,176860,201543,121888,2358,9286,5739,22666,54270,37884,169381,33984,93859,16124,89364,72207,51639,76366,99029,65812,2198,12147,174891,194289,6986,30252,88822,21284,11445,288337,160821,33034,100869,43852,25761,52882,1144,103809,1924,84458,86079,43411,13542,139276,18141,34978,41298,7276,26481,173800,33210,17951,142652,33616,33677,2210,19941,98568,2486,192414,80136,12058,235883,50963,249638,29572,27221,47034,6124,72107,63346,97620,158513,299699,40388,23235,37176,224244,198386,121323,67992,23827,63170,17838,106622,158590,26807,5345,23489,91891,55474,74834,37981,13058,5977,72552,34706,26828,145172,19904,21367,34043,960,77092,91381,4733,47446,7680,41697,5170,16960,14741,46101,13656,473,51842,37433,11103,11551,121951,13191,97536,165932,50397,51628,129028,9069,44885,6590,59195,47045,32940,225472,90345,21833,13303,29407,96615,141951,5198,6028,18395,7181,3861,14966,156358,167182,36529,55253,25942,173153,30959,27261,50691,150176,162201,38467,48462,80602,42163,118482,168,108756,26011,17166,54149,456538,22512,91374,13816,90358,131615,18132,226707,1824,28139,26860,42253,93877,77351,65575,8980,80574,22020,27948,40422,91324,76376,13528,39281,91685,82215,122541,144066,1983,193851,17283,26320,2739,194978,4790,26845,42627,61300,65815,174612,55133,4200,191130,79771,158321,52280,166796,221620,62461,11278,4067,88152,83409,31717,121367,13522,47325,37945,10406,174348,249321,154101,64912,29938,51775,17220,15776,166138,78890,84425,54121,42861,16368,24572,291647,10197,32073,22651,11677,97509,26952,35787,18424,41910,71614,94977,72318,41594,70024,275419,37702,60199,7335,39107,61315,18271,18394,33768,87884,104277,123724,7277,56288,71981,189803,49320,3352,6798,14240,8954,69220,94433,57372,28620,68863,193727,85575,42309,41667,67689,42081,22543,44824,12719,28540,114236,101553,27638,27296,4300,5353,4663,19379,94098,3758,95888,95144,80344,87320,28447,259518,12718,71391,152731,37063,24132,31911,104896,15672,103782,1521,4945,72541,23717,122632,15619,87175,206120,29428,189780,61416,28350,44457,972,1175,47233,198738,95789,41907,21953,97034,59341,22864,53713,16873,32971,20693,20954,31336,21477,16169,38370,16412,9019,3841,24599,21938,17085,6484,81198,76413,5849,72514,12320,65247,276175,37234,59796,52642,16312,57349,198507,94148,46134,18958,125552,1747,18725,151873,14901,5490,68287,29470,3689,64794,40814,26018,25692,54450,2703,88278,124886,173087,174e3,24159,179477,24276,46004,201876,209202,445,52876,31948,30206,157610,39180,18439,44124,50469,5774,96278,222758,200216,50290,45486,20435,46986,46276,140133,142326,15569,13363,47522,92583,2182,7135,16853,22998,30272,4952,63263,35623,39096,53789,44864,20053,110392,124213,4630,16087,28221,127787,25839,77481,44693,13464,113146,6983,27069,55717,50102,4760,7107,26186,66507,59145,36032,104182,71328,29425,64317,50781,47465,94298,69706,74899,22754,120756,25108,93077,56834,73286,39928,16218,41699,176763,7555,70819,50083,26895,23315,26014,16773,123079,41712,5719,31516,90427,158540,85051,183128,40864,27505,55392,9058,45224,96857,30901,136622,96557,56304,120061,11501,151448,5773,89743,7769,86069,2935,18471,41628,10114,33660,110170,49479,26745,92846,33221,26731,18795,87076,8550,2100,29972,120289,3077,72490,33784,2630,208722,50861,63483,79029,6419,39467,14302,45286,64207,9686,67513,44170,1050,77246,59266,17055,53801,7150,11111,42432,4278,94579,362117,36175,42902,41933,39002,98489,22913,74161,84773,57036,17556,162288,74485,178760,93867,73635,128860,50362,261,67455,80001,46080,35662,4368,25247,19230,74393,22588,1822,27682,235324,13798,85998,13194,235067,23514,71669,147632,23191,134748,214683,105101,1518,25489,247114,7380,54842,26922,3971,26361,20844,68642,170517,77339,123255,8963,77818,150998,48466,36806,2732,23261,11741,236162,18243,126216,28690,50546,16385,92760,197383,246558,201295,88255,67588,71687,176076,172653,169058,33906,63747,24835,157621,43338,30050,46152,132741,2770,51371,94835,6614,15112,11749,56936,1250,19027,399017,58036,100215,23388,55815,308768,124152,94803,9521,64186,8971,28,30427,62163,7616,103838,35079,29203,131235,7743,17389,10882,37420,61460,228512,85363,41581,131077,62822,119647,10130,54445,26925,19968,29016,24446,74028,24176,61448,67185,9254,8563,119129,9771,99184,37716,39514,10532,221512,258753,218630,55980,23394,32141,61924,66749,32411,3741,36475,26678,77010,44946,91203,128749,116953,20476,49625,53116,13735,102335,29376,51946,83407,67892,59212,34685,21083,1546,112982,32972,74397,1078,190545,16082,86140,58591,89611,101531,10061,105104,76319,20035,17551,52611,169061,190842,100780,23907,90413,115619,9675,34710,193435,49443,129734,11183,258877,16318,136182,126808,44635,27304,192375,2599,125648,47051,12091,23814,721,58800,40137,66726,97930,60877,74487,7942,54326,9841,41428,13762,8211,85383,6950,99177,79806,201786,296464,124087,13144,29741,41721,47634,55088,254286,106408,17041,99064,12942,64086,45233,14005,2612,55827,255,7984,13980,38574,12776,46654,73499,249951,2101,26676,25996,132326,116415,119062,50449,31033,23038,11589,179252,20007,14860,129270,21143,17796,144715,60106,70758,69842,34674,282133,44014,16774,57268,38528,24053,46373,201667,28327,471023,51889,102667,21193,114909,84132,69317,96723,67969,16134,68145,15058,28765,32035,2524,101089,98664,25045,76571,14957,86040,118506,262428,154764,81573,39681,283900,73287,127825,544,80448,52347,38512,175971,15180,45467,33086,46552,48894,81107,43213,36672,54025,76703,8053,7608,13299,56619,20752,238099,54164,105133,1444,32942,953,37564,8e3,66316,119463,106817,404,13667,149108,128597,31267,10269,49836,106150,1484,52330,76965,160486,171648,38456,31263,22424,37738,66245,67467,143369,60471,75610,20895,115528,86070,60854,40796,49347,18989,15030,11371,37578,15779,79867,10187,86462,46402,155626,93200,40229,7090,57547,108053,99598,11088,47505,41218,206017,2173,20988,30219,22919,80563,57566,42369,93141,41675,2407,182519,120495,27154,16702,29456,14349,7958,16688,117177,140375,42467,261919,74916,153569,10836,34742,49526,7621,105997,12212,2270,392377,7755,17959,25086,232152,138791,33847,13860,35316,5811,1344,71259,50452,207539,92635,50359,5821,33674,30255,2086,2587,96264,17543,42,6029,9580,43007,139248,82831,12917,29607,25786,51467,42137,85161,100698,31561,88989,121990,278500,3602,109344,37982,15279,116442,28936,30880,87894,58079,128661,126731,67392,28051,146885,4861,16216,97344,42827,147561,153948,22684,21335,47685,1853,43349,15185,59642,10229,25520,187921,108972,5579,98037,24945,6697,19193,63734,137934,75056,89740,19767,224268,56138,63643,151661,39313,70618,84031,89723,84074,13703,85626,35460,8867,64845,3439,57906,99776,63968,49270,81130,34356,16210,23547,36446,34090,140028,72439,2221,22163,57058,363492,113754,18913,95451,48663,54464,54037,176097,68425,3023,34906,29482,117389,341780,80431,58330,16753,92616,60907,94846,147486,4498,48646,7773,46801,7778,18946,464978,47558,33223,177444,7328,15626,63337,94700,11743,9351,255024,39098,16447,42647,96230,39769,58840,10068,63439,35800,65843,58823,413844,9156,51258,7434,61791,85018,6872,3692,28096,7121,33024,6009,75532,31997,192535,9661,3304,9547,14753,31987,25314,55689,15896,20430,39472,31340,99744,25398,115569,54883,28719,205423,23071,57855,64638,149867,25671,82403,37616,20668,39989,77996,74948,140555,175248,64810,36515,46595,4958,248773,24045,28728,136673,168704,20804,114833,100325,27135,21205,96151,153134,45992,7093,13992,76047,1980,19432,145001,75159,87462,17710,1013,45556,34297,144882,20648,26061,11319,129567,108555,18872,464580,33386,22717,65948,167189,5603,135042,79542,8801,202632,18114,91882,5973,5239,67315,4431,60916,47819,71693,32597,32606,18183,45072,80329,76385,24749,51305,40314,156514,14693,130345,13168,66214,18029,12858,34801,27628,14544,10823,40522,40185,33739,148694,23548,9923,61012,28859,17933,19442,34364,99849,164107,141167,30629,21054,6744,36491,8096,42474,41706,155060,30650,10600,163442,1143,96655,61390,52359,7559,51568,64256,203854,4467,22453,14504,436398,7878,6980,8293,63610,293747,16167,35763,19627,147603,15419,18032,110744,51346,33681,54571,40472,48615,39073,21604,13754,173027,92560,11083,47299,63062,11813,52007,29883,9734,139722,15953,1550,20651,13616,49306,16113,90089,92326,7584,30712,72424,164858,6831,152871,55746,197721,34167,196442,6022,112107,55215,7538,123381,4920,43539,77165,8939,50392,34192,20225,79762,22505,58667,40770,29788,97180,82835,4568,8579,13273,363569,35898,49983,436,36598,3237,131691,62418,35591,8101,4073,379438,65218,76072,33887,2968,27573,212619,288680,68278,72851,150504,217896,6913,121339,22017,35340,51072,43616,75043,31437,10833,81487,4364,22968,41454,106687,85446,19863,109625,149241,524,141850,214404,54376,657,237023,9401,108137,53800,32474,49712,53334,126876,27337,45552,177696,8269,15036,12097,42240,2328,125374,119295,99715,2500,19624,39441,27220,102691,60957,94543,39101,18566,67362,13975,78230,25017,34017,239007,90027,39351,41681,35354,43822,1043,916,58587,141983,94818,38799,75459,41114,67432,16195,36606,59568,22272,126769,31424,68659,12287,134302,257977,5756,207285,95637,47248,117689,19583,77451,22373,12200,54993,117118,34244,29386,34562,53819,71267,64172,77665,49368,7716,59301,25749,45426,194789,17297,2650,1766,32501,45198,20403,20984,6600,14171,94604,19037,5402,29896,9938,59935,109708,88081,145182,44844,39167,352626,164173,35374,45982,6122,154,73419,220487,53834,53601,17992,8609,229321,5610,68098,66815,71012,95069,140968,27396,8957,134489,24656,86659,56598,134852,17316,123838,255436,6613,41610,138033,81452,32023,32396,123687,63398,8693,29712,30407,19296,121188,3551,36099,20032,111948,56624,16547,27453,35916,15378,52039,56849,13489,22214,73177,53097,277349,2157,14029,187886,10260,141743,246460,91880,50869,3788,49486,133566,54950,33120,129337,53768,18333,9525,26902,312251,10297,9020,70759,16647,112432,59260,84609,9818,82766,73569,468,46001,75780,55028,52106,11498,43645,108069,17150,17753,29417,16705,31799,9606,289,122254,115975,8620,6133,255357,56908,14456,133464,43554,79224,11247,29630,160,12756,25464,65960,350428,62521,321796,100359,67358,35169,46172,113128,48988,88868,31094,33266,6847,60887,98188,49659,69117,92977,220228,13947,80181,35103,62170,97351,13475,2440,199768,19498,36597,46971,25234,67806,62881,84717,73648,181966,10488,94149,21550,26655,63436,48375,14405,165650,9621,24439,28043,42735,4490,29963,56674,45373,1934,262446,50855,67098,26898,5261,52696,40644,33900,9440,180286,87162,22940,19704,26936,69769,10254,101759,27406,12243,48e3,73926,113215,54935,5726,192787,4312,106216,9366,11550,52949,23457,212271,277152,133895,108374,6191,96477,29980,218916,58024,54696,40853,91124,65894,91170,65908,252552,6793,29212,15389,44516,122515,52617,35058,9017,103536,39510,49136,19242,130652,662077,74699,47024,31422,8517,73351,24399,13867,128360,4810,4434,61779,111983,61036,17798,110240,59722,102960,39688,10001,23803,23039,176498,56659,44814,134295,17188,77577,74466,226175,102472,154333,63900,111747,18062,41171,79669,32773,408933,42562,28931,30907,107388,43487,2946,240310,23938,24354,319,184983,7927,6488,1422,10790,68809,68209,64775,4361,202,17123,59634,51200,44391,18188,17843,2619,74278,3230,9540,47187,21702,36274,56894,43907,16310,34790,16866,6150,5561,13587,107545,108873,126867,86986,28640,33427,19017,5762,80637,17430,46903,2047,131055,25958,13558,5444,47152,13900,44563,122857,45348,70863,39593,54332,38068,33637,318,40310,143467,18502,24520,11377,62013,28942,27246,28269,83545,17999,59015,90707,30065,15161,34720,1263,37008,2012,6060,98575,92933,5721,299,199555,24578,29223,2985,743,115825,109523,136657,47454,26378,53586,3733,174945,93340,244456,5693,37386,28782,89767,27545,23573,18798,136425,34320,84778,20041,48453,38215,7477,71958,40621,8773,5874,187927,105965,51100,43533,18083,8443,10180,43597,2003,183999,69689,12216,129696,146188,62389,34044,68410,12765,43273,26949,266807,3345,34477,79197,5688,47539,213110,21634,22257,50092,32222,42346,39530,63668,98,134978,74022,5152,59088,174145,37220,9934,9545,118937,5724,87240,19875,15784,40143,23263,87513,181654,285152,37881,263241,4966,43934,10433,186657,6470,74416,225854,25908,142677,246262,32280,6192,75890,45546,143264,135305,29742,47013,77787,11732,126658,8763,37950,21806,57557,113464,89465,108995,164574,23894,22996,23169,15369,23117,17642,130607,40503,36239,280990,44666,9981,40427,147487,26869,168452,32886,32991,46798,240839,15111,70502,65697,88548,44145,28701,48767,31139,206777,35659,181164,166262,14554,171445,31786,66523,76607,17956,6507,31279,90476,116611,167918,6560,1243,115324,80128,41867,55897,187323,37069,32596,189444,145931,13390,105530,65709,26805,6999,55714,41300,22915,68951,22138,21120,22264,10058,19945,33635,56123,99085,10032,5818,6016,46649,57476,35264,94413,112522,262288,93686,83038,14341,23204,28807,66084,77987,6101,126673,7133,38126,5923,122091,170240,97772,46874,215746,43948,41622,3272,55596,8332,146411,251315,13533,8561,81521,115449,48616,175175,2063,186556,3036,134537,75772,29728,82360,22973,186559,86348,89100,38388,82297,45610,2613,87082,9986,177812,57884,23591,47485,42543,33582,44713,74439,257444,252451,31825,35631,38540,33066,5147,13973,4343,51830,70378,22827,26448,95560,36896,241741,48067,203953,298860,61620,20450,3220,67272,6586,107662,100160,108684,6929,57226,4762,7457,1320,40404,77204,99309,62750,208653,59977,44e3,74315,34332,5819,172217,64904,114077,18147,84012,1791,98456,90930,21446,116669,103938,7422,85140,59713,5768,326211,16239,75411,13229,29398,10758,236107,1539,112472,95979,152154,151294,306,21196,38146,10700,6891,84282,109646,56492,40539,6589,119491,51354,30685,140209,136906,29622,73617,49553,70525,51671,166869,139616,74395,37439,49595,45678,11959,33211,86560,52434,9282,62690,112155,130810,5243,108261,99970,265613,72551,80049,6391,33365,90721,66737,69872,87011,1860,9032,112544,60905,37371,89015,140351,19076,850,373531,2802,36725,218795,72062,28990,16550,24614,7815,6187,26336,33373,32162,42791,73555,32062,23386,10244,56392,49442,27076,136262,12412,14883,1134,33675,97153,199281,15608,100152,74072,47942,254301,36451,16026,10687,65067,56708,254030,30290,50490,13864,57941,259331,35588,23485,43486,24869,21620,92971,22072,88645,1048,182050,13343,32452,14825,19509,3325,216938,45740,99716,189082,53740,78245,25609,24311,176777,47340,308354,40669,66085,14102,125339,9225,128709,97207,1271,200933,78439,113451,88975,18324,46521,11819,18570,141756,72512,170020,52754,63550,118515,103073,93330,32736,50499,14722,31600,68452,398867,29316,172786,18417,104924,2606,5670,84818,16288,67106,59580,82929,607401,291,85829,359,15897,35830,50696,65630,52672,22115,356968,29895,40837,231192,34024,38957,26722,406,23335,124952,72068,68804,13268,147101,164740,276569,162596,66943,11569,26654,66358,4777,23229,102127,5848,978,2921,59666,5371,28212,90108,42938,39320,2499,4271,108792,33510,125072,71653,65239,38250,66357,38577,13964,86251,35708,50755,36010,29448,12209,3844,38222,206337,100876,67827,137088,14167,252225,84163,195270,1306,5703,54198,779,46802,22028,51124,86759,70560,113164,35685,162145,45471,34561,422,2611,6464,47486,19223,38246,9191,18331,89942,243642,212364,15893,17518,22617,6409,30046,126182,59716,36560,104428,18846,26592,19458,50793,147333,30826,1388,27647,10922,14495,33545,19269,135828,39727,41601,46931,233379,49169,131130,182112,16276,82381,118209,142445,128310,19672,28740,82907,33436,3118,102206,28723,24819,41937,38854,5157,3881,111491,1142,9776,421673,152241,29309,14961,87854,6054,15424,3796,82656,54996,2108,55367,239450,154525,9643,118103,106041,64601,68549,48707,30266,25772,18740,9462,229669,91798,112152,191327,14493,72828,8175,66636,236474,25817,87351,129027,76653,20422,22983,71240,27846,44661,12399,46158,77704,53101,35032,11072,17300,109294,33638,24408,1895,11241,760,17584,82479,125877,63150,141075,34259,23274,81698,15732,43577,48340,91584,14688,16379,24481,150280,96420,262050,48635,43727,61819,56268,72003,88178,17281,79912,13218,122519,125295,166396,11811,2171,118930,67746,17636,178278,174656,95661,173039,83845,79689,17473,98555,127696,203415,54730,22925,232239,9309,12136,175026,20740,180188,10747,39816,314017,266131,10040,175732,112550,220651,31974,37393,888,23008,86799,4303,64905,148467,75337,251,3284,370102,50264,9835,5438,23655,4481,29851,329,12855,7162,64931,78141,12804,42372,296771,83547,18624,34874,86271,3360,48665,77735,88767,11463,63527,28889,22258,29140,194315,113924,25499,6406,31334,1845,4802,49184,43455,35469,127594,92970,61038,115005,38840,87761,106838,8811,20572,55637,11162,96721,132425,108925,2948,125457,36356,3502,75270,27622,127192,2561,123095,49394,61155,16897,110064,9699,89448,53356,19628,220310,21622,83036,9885,112214,6087,26713,17901,161912,91492,3440,68594,9266,92238,8087,6866,150194,72175,80701,13459,31836,43243,239700,95846,44749,50647,21945,230538,120612,132371,244604,5193,105637,34661,41341,68775,85393,1874,8771,33718,49672,77403,595452,99507,6490,58895,128742,7704,39239,73217,43816,62824,37804,199976,22361,80005,87514,94832,14089,4574,139975,59142,75523,100268,43906,53442,15152,2547,186002,17011,19513,204282,3343,60568,128318,119250,4298,51871,41336,71759,21921,45074,98169,145889,99427,11350,1237,5520,28799,7803,53702,21026,136352,38293,128690,12158,90132,44600,10184,26957,39459,126025,78904,82999,59373,39301,150198,120529,153042,20177,50089,14764,271571,30530,123161,38975,101562,22941,5648,124654,109243,69817,71675,49162,106884,21241,107795,30258,16572,188262,141456,7688,60718,8271,11044,32440,104608,103419,236109,93156,43293,128929,42107,67180,25201,115254,185488,130954,72813,167547,20537,39969,38432,22582,184022,1139,27199,5655,17767,97412,122606,209377,27070,35871,326617,188954,42680,73512,80911,22629,3011,95021,315242,157737,383,41821,41808,19335,27950,15674,25677,110950,35375,76835,59108,57370,35262,16569,160415,37706,78086,32041,49691,137143,9782,172080,50148,77917,6323,10110,69172,17711,21795,59511,76184,135114,31046,132319,59105,157578,20549,80778,57649,158421,65143,4575,72235,21899,10797,92745,34035,106079,80159,4508,78304,25350,75457,46458,32937,25623,47,8531,104751,84953,8138,36508,187199,66310,115274,13253,32461,38536,1916,42007,187160,35055,26325,84394,35963,94216,45590,97782];class WE{log;peerRouting;routingTable;refreshInterval;refreshQueryTimeout;commonPrefixLengthRefreshedAt;refreshTimeoutId;constructor(e,t){const{peerRouting:n,routingTable:r,refreshInterval:s,refreshQueryTimeout:i,logPrefix:o}=t;this.log=e.logger.forComponent(`${o}:routing-table:refresh`),this.peerRouting=n,this.routingTable=r,this.refreshInterval=s??3e5,this.refreshQueryTimeout=i??3e4,this.commonPrefixLengthRefreshedAt=[],this.refreshTable=this.refreshTable.bind(this)}async afterStart(){this.log(`refreshing routing table every ${this.refreshInterval}ms`),this.refreshTable(!0)}async stop(){null!=this.refreshTimeoutId&&clearTimeout(this.refreshTimeoutId)}refreshTable(e=!1){this.log("refreshing routing table");const t=this._maxCommonPrefix(),n=this._getTrackedCommonPrefixLengthsForRefresh(t);this.log(`max common prefix length ${t}`),this.log(`tracked CPLs [ ${n.map((e=>e.toISOString())).join(", ")} ]`),Promise.all(n.map((async(r,s)=>{try{if(await this._refreshCommonPrefixLength(s,r,e),0===this._numPeersForCpl(t)){const t=Math.min(2*(s+1),n.length-1);for(let n=s+1;n<t+1;n++)try{await this._refreshCommonPrefixLength(n,r,e)}catch(e){this.log.error(e)}}}catch(e){this.log.error(e)}}))).catch((e=>{this.log.error(e)})).then((()=>{this.refreshTimeoutId=setTimeout(this.refreshTable,this.refreshInterval),null!=this.refreshTimeoutId.unref&&this.refreshTimeoutId.unref()})).catch((e=>{this.log.error(e)}))}async _refreshCommonPrefixLength(e,t,n){if(!n&&t.getTime()>Date.now()-this.refreshInterval)return void this.log("not running refresh for cpl %s as time since last refresh not above interval",e);const r=await this._generateRandomPeerId(e);this.log("starting refreshing cpl %s with key %p (routing table size was %s)",e,r,this.routingTable.size);const s=AbortSignal.timeout(this.refreshQueryTimeout),i=await UE(this.peerRouting.getClosestPeers(r.toBytes(),{signal:s}));this.log(`found ${i} peers that were close to imaginary peer %p`,r),this.log("finished refreshing cpl %s with key %p (routing table size is now %s)",e,r,this.routingTable.size)}_getTrackedCommonPrefixLengthsForRefresh(e){e>15&&(e=15);const t=[];for(let n=0;n<=e;n++)t[n]=this.commonPrefixLengthRefreshedAt[n]??new Date;return t}async _generateRandomPeerId(e){if(null==this.routingTable.kb)throw new Error("Routing table not started");const t=Lo(2),n=(t[1]<<8)+t[0];return Rs(await this._makePeerId(this.routingTable.kb.localPeer.kadId,n,e))}async _makePeerId(e,t,n){if(n>15)throw new Error("Cannot generate peer ID for common prefix length greater than 15");const r=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(0,!1),s=65535<<16-(n+1),i=zE[(r^32768>>n)&s|t&~s],o=new ArrayBuffer(34),a=new DataView(o,0,o.byteLength);return a.setUint8(0,ft.code),a.setUint8(1,32),a.setUint32(2,i,!1),new Uint8Array(a.buffer,a.byteOffset,a.byteLength)}_maxCommonPrefix(){let e=0;for(const t of this._prefixLengths())t>e&&(e=t);return e}_numPeersForCpl(e){let t=0;for(const n of this._prefixLengths())n===e&&t++;return t}*_prefixLengths(){if(null!=this.routingTable.kb)for(const{kadId:e}of this.routingTable.kb.toIterable()){const t=ym(this.routingTable.kb.localPeer.kadId,e);let n=0;for(const e of t){if(0!==e)break;n++}yield n}}}class jE{providers;log;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:add-provider`),this.providers=t.providers}async handle(e,t){if(this.log("start"),null==t.key||0===t.key.length)throw new pn("Missing key","ERR_MISSING_KEY");let n;try{n=wt.decode(t.key)}catch(e){throw new pn("Invalid CID","ERR_INVALID_CID")}null!=t.providers&&0!==t.providers.length||this.log.error("no providers found in message"),await Promise.all(t.providers.map((async t=>{e.equals(t.id)?t.multiaddrs.length<1?this.log("no valid addresses for provider %p. Ignore",e):(this.log("received provider %p for %s (addrs %s)",e,n,t.multiaddrs.map((e=>ar(e).toString()))),await this.providers.addProvider(n,Rs(t.id))):this.log("invalid provider peer %p from %p",t.id,e)})))}}class GE{peerRouting;peerInfoMapper;peerId;addressManager;log;constructor(e,t){const{peerRouting:n,logPrefix:r}=t;this.log=e.logger.forComponent(`${r}:rpc:handlers:find-node`),this.peerId=e.peerId,this.addressManager=e.addressManager,this.peerRouting=n,this.peerInfoMapper=t.peerInfoMapper}async handle(e,t){if(this.log("incoming request from %p for peers closer to %b",e,t.key),null==t.key)throw new pn("Invalid FIND_NODE message received - key was missing","ERR_INVALID_MESSAGE");const n=await this.peerRouting.getCloserPeersOffline(t.key,e);_n(this.peerId.toBytes(),t.key)&&n.push({id:this.peerId,multiaddrs:this.addressManager.getAddresses().map((e=>e.decapsulateCode(Un("p2p").code)))});const r={type:eE.FIND_NODE,clusterLevel:t.clusterLevel,closer:n.map(this.peerInfoMapper).filter((({multiaddrs:e})=>e.length)).map((e=>({id:e.id.toBytes(),multiaddrs:e.multiaddrs.map((e=>e.bytes))}))),providers:[]};return 0===r.closer.length&&this.log("could not find any peers closer to %b than %p",t.key,e),r}}class YE{peerRouting;providers;peerStore;peerInfoMapper;log;constructor(e,t){const{peerRouting:n,providers:r,logPrefix:s}=t;this.log=e.logger.forComponent(`${s}:rpc:handlers:get-providers`),this.peerStore=e.peerStore,this.peerRouting=n,this.providers=r,this.peerInfoMapper=t.peerInfoMapper}async handle(e,t){if(null==t.key)throw new pn("Invalid GET_PROVIDERS message received - key was missing","ERR_INVALID_MESSAGE");let n;try{n=wt.decode(t.key)}catch(e){throw new pn("Invalid CID","ERR_INVALID_CID")}this.log("%p asking for providers for %s",e,n);const[r,s]=await Promise.all([this.providers.getProviders(n),this.peerRouting.getCloserPeersOffline(t.key,e)]),i=await this._getPeers(r),o=await this._getPeers(s.map((({id:e})=>e))),a={type:eE.GET_PROVIDERS,key:t.key,clusterLevel:t.clusterLevel,closer:o.map(this.peerInfoMapper).filter((({multiaddrs:e})=>e.length)).map((e=>({id:e.id.toBytes(),multiaddrs:e.multiaddrs.map((e=>e.bytes))}))),providers:i.map(this.peerInfoMapper).filter((({multiaddrs:e})=>e.length)).map((e=>({id:e.id.toBytes(),multiaddrs:e.multiaddrs.map((e=>e.bytes))})))};return this.log("got %s providers %s closerPeers",a.providers.length,a.closer.length),a}async _getAddresses(e){return[]}async _getPeers(e){const t=[];for(const n of e)try{const e=await this.peerStore.get(n),r=this.peerInfoMapper({id:n,multiaddrs:e.addresses.map((({multiaddr:e})=>e))});r.multiaddrs.length>0&&t.push(r)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}return t}}class QE{peerStore;datastore;peerRouting;log;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:get-value`),this.peerStore=e.peerStore,this.datastore=e.datastore,this.peerRouting=t.peerRouting}async handle(e,t){const n=t.key;if(this.log("%p asked for key %b",e,n),null==n||0===n.length)throw new pn("Invalid key","ERR_INVALID_KEY");const r={type:eE.GET_VALUE,key:n,clusterLevel:t.clusterLevel,closer:[],providers:[]};if(function(e){return"/pk/"===Yt(e.subarray(0,4))}(n)){this.log("is public key");const e=function(e){return Rs(e.subarray(4))}(n);let t;try{const n=await this.peerStore.get(e);if(null==n.id.publicKey)throw new pn("No public key found in key book","ERR_NOT_FOUND");t=n.id.publicKey}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}if(null!=t)return this.log("returning found public key"),r.record=new aE(n,t,new Date).serialize(),r}const[s,i]=await Promise.all([this._checkLocalDatastore(n),this.peerRouting.getCloserPeersOffline(n,e)]);return null!=s&&(this.log("had record for %b in local datastore",n),r.record=s.serialize()),i.length>0&&(this.log("had %s closer peers in routing table",i.length),r.closer=i.map((e=>({id:e.id.toBytes(),multiaddrs:e.multiaddrs.map((e=>e.bytes))})))),r}async _checkLocalDatastore(e){this.log("checkLocalDatastore looking for %b",e);const t=SE(e);let n;try{n=await this.datastore.get(t)}catch(e){if("ERR_NOT_FOUND"===e.code)return;throw e}const r=aE.deserialize(n);if(null==r)throw new pn("Invalid record","ERR_INVALID_RECORD");if(!(null==r.timeReceived||Date.now()-r.timeReceived.getTime()>jv))return r;await this.datastore.delete(t)}}class JE{log;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:ping`)}async handle(e,t){return this.log("ping from %p",e),t}}class ZE{components;validators;log;constructor(e,t){const{validators:n}=t;this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:put-value`),this.validators=n}async handle(e,t){const n=t.key;if(this.log("%p asked us to store value for key %b",e,n),null==t.record){const t=`Empty record from: ${e.toString()}`;throw this.log.error(t),new pn(t,"ERR_EMPTY_RECORD")}try{const e=aE.deserialize(t.record);await mE(this.validators,e),e.timeReceived=new Date;const r=SE(e.key);await this.components.datastore.put(r,e.serialize().subarray()),this.log("put record for %b into datastore under key %k",n,r)}catch(e){this.log("did not put record for key %b into datastore %o",n,e)}return t}}class XE{handlers;routingTable;log;constructor(e,t){const{providers:n,peerRouting:r,validators:s,logPrefix:i,peerInfoMapper:o}=t;this.log=e.logger.forComponent(`${i}:rpc`),this.routingTable=t.routingTable,this.handlers={[eE.GET_VALUE.toString()]:new QE(e,{peerRouting:r,logPrefix:i}),[eE.PUT_VALUE.toString()]:new ZE(e,{validators:s,logPrefix:i}),[eE.FIND_NODE.toString()]:new GE(e,{peerRouting:r,logPrefix:i,peerInfoMapper:o}),[eE.ADD_PROVIDER.toString()]:new jE(e,{providers:n,logPrefix:i}),[eE.GET_PROVIDERS.toString()]:new YE(e,{peerRouting:r,providers:n,logPrefix:i,peerInfoMapper:o}),[eE.PING.toString()]:new JE(e,{logPrefix:i})}}async handleMessage(e,t){try{await this.routingTable.add(e)}catch(e){this.log.error("Failed to update the kbucket store",e)}const n=this.handlers[t.type];if(null!=n)return n.handle(e,t);this.log.error(`no handler found for message type: ${t.type}`)}onIncomingStream(e){Promise.resolve().then((async()=>{const{stream:t,connection:n}=e,r=n.remotePeer;try{await this.routingTable.add(r)}catch(e){this.log.error(e)}const s=this;await fr(t,(e=>$r(e)),(async function*(e){for await(const t of e){const e=iE.decode(t);s.log("incoming %s from %p",e.type,r);const n=await s.handleMessage(r,e);null!=n&&(yield iE.encode(n))}}),(e=>Mr(e)),t)})).catch((e=>{this.log.error(e)}))}}class eS extends yn{log;components;protocol;running;registrarId;constructor(e,t){super();const{protocol:n,logPrefix:r}=t;this.components=e,this.log=e.logger.forComponent(`${r}:topology-listener`),this.running=!1,this.protocol=n}isStarted(){return this.running}async start(){this.running||(this.running=!0,this.registrarId=await this.components.registrar.register(this.protocol,{onConnect:e=>{this.log("observed peer %p with protocol %s",e,this.protocol),this.dispatchEvent(new bn("peer",{detail:e}))}}))}async stop(){this.running=!1,null!=this.registrarId&&(this.components.registrar.unregister(this.registrarId),this.registrarId=void 0)}}class tS{dht;constructor(e){this.dht=e}async provide(e,t={}){await Md(this.dht.provide(e,t))}async*findProviders(e,t={}){for await(const n of this.dht.findProviders(e,t))"PROVIDER"===n.name&&(yield*n.providers)}async put(e,t,n){await Md(this.dht.put(e,t,n))}async get(e,t){for await(const n of this.dht.get(e,t))if("VALUE"===n.name)return n.value;throw new pn("Not found","ERR_NOT_FOUND")}}class nS{dht;constructor(e){this.dht=e}async findPeer(e,t={}){for await(const n of this.dht.findPeer(e,t))if("FINAL_PEER"===n.name)return n.peer;throw new pn("Not found","ERR_NOT_FOUND")}async*getClosestPeers(e,t={}){for await(const n of this.dht.getClosestPeers(e,t))"FINAL_PEER"===n.name&&(yield n.peer)}}class rS extends yn{protocol;routingTable;providers;network;peerRouting;components;log;running;kBucketSize;clientMode;validators;selectors;queryManager;contentFetching;contentRouting;routingTableRefresh;rpc;topologyListener;querySelf;maxInboundStreams;maxOutboundStreams;dhtContentRouting;dhtPeerRouting;peerInfoMapper;constructor(e,t){super();const{kBucketSize:n,clientMode:r,validators:s,selectors:i,querySelfInterval:o,protocol:a,logPrefix:c,pingTimeout:l,pingConcurrency:u,maxInboundStreams:h,maxOutboundStreams:d,providers:p}=t,f=c??"libp2p:kad-dht";this.running=!1,this.components=e,this.log=e.logger.forComponent(f),this.protocol=a??"/ipfs/kad/1.0.0",this.kBucketSize=n??20,this.clientMode=r??!0,this.maxInboundStreams=h??32,this.maxOutboundStreams=d??64,this.peerInfoMapper=t.peerInfoMapper??bE,this.routingTable=new HE(e,{kBucketSize:n,pingTimeout:l,pingConcurrency:u,protocol:this.protocol,logPrefix:f}),this.providers=new NE(e,p??{}),this.validators={...yE,...s},this.selectors={...gE,...i},this.network=new DE(e,{protocol:this.protocol,logPrefix:f});const g=cr();!0===t.allowQueryWithZeroPeers&&g.resolve(),this.queryManager=new BE(e,{disjointPaths:Math.ceil(this.kBucketSize/2),logPrefix:f,initialQuerySelfHasRun:g,routingTable:this.routingTable}),this.peerRouting=new xE(e,{routingTable:this.routingTable,network:this.network,validators:this.validators,queryManager:this.queryManager,logPrefix:f}),this.contentFetching=new IE(e,{validators:this.validators,selectors:this.selectors,peerRouting:this.peerRouting,queryManager:this.queryManager,network:this.network,logPrefix:f}),this.contentRouting=new AE(e,{network:this.network,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,providers:this.providers,logPrefix:f}),this.routingTableRefresh=new WE(e,{peerRouting:this.peerRouting,routingTable:this.routingTable,logPrefix:f}),this.rpc=new XE(e,{routingTable:this.routingTable,providers:this.providers,peerRouting:this.peerRouting,validators:this.validators,logPrefix:f,peerInfoMapper:this.peerInfoMapper}),this.topologyListener=new eS(e,{protocol:this.protocol,logPrefix:f}),this.querySelf=new FE(e,{peerRouting:this.peerRouting,interval:o,initialInterval:t.initialQuerySelfInterval,logPrefix:f,initialQuerySelfHasRun:g,routingTable:this.routingTable}),this.network.addEventListener("peer",(e=>{const t=e.detail;this.onPeerConnect(t).catch((e=>{this.log.error("could not add %p to routing table",t.id,e)})),this.dispatchEvent(new bn("peer",{detail:t}))})),this.topologyListener.addEventListener("peer",(e=>{const t=e.detail;Promise.resolve().then((async()=>{const e=await this.components.peerStore.get(t),n={id:t,multiaddrs:e.addresses.map((({multiaddr:e})=>e)),protocols:e.protocols};await this.onPeerConnect(n)})).catch((e=>{this.log.error("could not add %p to routing table",t,e)}))})),this.dhtPeerRouting=new nS(this),this.dhtContentRouting=new tS(this),null==t.clientMode&&e.events.addEventListener("self:peer:update",(e=>{this.log("received update of self-peer info"),Promise.resolve().then((async()=>{const t=e.detail.peer.addresses.some((({multiaddr:e})=>function(e){const t=e.stringTuples();for(const e of t)if(290===e[0])return!1;if(54===t[0][0]||55===t[0][0]||56===t[0][0])return!0;if(4===t[0][0]||41===t[0][0]){const e=Qd(`${t[0][1]}`);return null==e||!e}return!1}(e))),n=this.getMode();t&&"client"===n?await this.setMode("server"):"server"!==n||t||await this.setMode("client")})).catch((e=>{this.log.error("error setting dht server mode",e)}))}))}get[tn](){return this.dhtContentRouting}get[on](){return this.dhtPeerRouting}get[nn](){return this}async onPeerConnect(e){if(this.log("peer %p connected",e.id),0!==(e=this.peerInfoMapper(e)).multiaddrs.length)try{await this.routingTable.add(e.id)}catch(t){this.log.error("could not add %p to routing table",e.id,t)}else this.log("ignoring %p as there were no valid addresses in %s after filtering",e.id,e.multiaddrs.map((e=>e.toString())))}isStarted(){return this.running}getMode(){return this.clientMode?"client":"server"}async setMode(e){await this.components.registrar.unhandle(this.protocol),"client"===e?(this.log("enabling client mode"),this.clientMode=!0):(this.log("enabling server mode"),this.clientMode=!1,await this.components.registrar.handle(this.protocol,this.rpc.onIncomingStream.bind(this.rpc),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}))}async start(){this.running=!0,await this.setMode(this.clientMode?"client":"server"),await async function(...e){const t=[];for(const n of e)vn(n)&&t.push(n);await Promise.all(t.map((async e=>{null!=e.beforeStart&&await e.beforeStart()}))),await Promise.all(t.map((async e=>{await e.start()}))),await Promise.all(t.map((async e=>{null!=e.afterStart&&await e.afterStart()})))}(this.querySelf,this.providers,this.queryManager,this.network,this.routingTable,this.topologyListener,this.routingTableRefresh)}async stop(){this.running=!1,await async function(...e){const t=[];for(const n of e)vn(n)&&t.push(n);await Promise.all(t.map((async e=>{null!=e.beforeStop&&await e.beforeStop()}))),await Promise.all(t.map((async e=>{await e.stop()}))),await Promise.all(t.map((async e=>{null!=e.afterStop&&await e.afterStop()})))}(this.querySelf,this.providers,this.queryManager,this.network,this.routingTable,this.routingTableRefresh,this.topologyListener)}async*put(e,t,n={}){yield*this.contentFetching.put(e,t,n)}async*get(e,t={}){yield*this.contentFetching.get(e,t)}async*provide(e,t={}){yield*this.contentRouting.provide(e,this.components.addressManager.getAddresses(),t)}async*findProviders(e,t={}){yield*this.contentRouting.findProviders(e,t)}async*findPeer(e,t={}){yield*this.peerRouting.findPeer(e,t)}async*getClosestPeers(e,t={}){yield*this.peerRouting.getClosestPeers(e,t)}async refreshRoutingTable(){this.routingTableRefresh.refreshTable(!0)}}var sS;function iS(e){return t=>new rS(t,e)}!function(e){e[e.SEND_QUERY=0]="SEND_QUERY",e[e.PEER_RESPONSE=1]="PEER_RESPONSE",e[e.FINAL_PEER=2]="FINAL_PEER",e[e.QUERY_ERROR=3]="QUERY_ERROR",e[e.PROVIDER=4]="PROVIDER",e[e.VALUE=5]="VALUE",e[e.ADD_PEER=6]="ADD_PEER",e[e.DIAL_PEER=7]="DIAL_PEER"}(sS||(sS={}));const oS=fs("libp2p:simple-metrics");class aS{value=0;update(e){this.value=e}increment(e=1){this.value+=e}decrement(e=1){this.value-=e}reset(){this.value=0}timer(){const e=Date.now();return()=>{this.value=Date.now()-e}}}class cS{values={};update(e){Object.entries(e).forEach((([e,t])=>{this.values[e]=t}))}increment(e){Object.entries(e).forEach((([e,t])=>{this.values[e]=this.values[e]??0;const n="number"==typeof t?t:1;this.values[e]+=Number(n)}))}decrement(e){Object.entries(e).forEach((([e,t])=>{this.values[e]=this.values[e]??0;const n="number"==typeof t?t:1;this.values[e]-=Number(n)}))}reset(){this.values={}}timer(e){const t=Date.now();return()=>{this.values[e]=Date.now()-t}}}class lS{metrics=new Map;transferStats;started;interval;intervalMs;onMetrics;constructor(e,t){this.started=!1,this._emitMetrics=this._emitMetrics.bind(this),this.intervalMs=t.intervalMs??1e3,this.onMetrics=t.onMetrics,this.transferStats=new Map}isStarted(){return this.started}start(){this.started=!0,this.interval=setInterval(this._emitMetrics,this.intervalMs)}stop(){this.started=!1,clearInterval(this.interval)}_emitMetrics(){Promise.resolve().then((async()=>{const e={};for(const[t,n]of this.metrics.entries())e[t]=n instanceof aS?n.value:n instanceof cS?n.values:await n();this.onMetrics(structuredClone(e))})).catch((e=>{oS.error("could not invoke onMetrics callback",e)}))}_incrementValue(e,t){const n=this.transferStats.get(e)??0;this.transferStats.set(e,n+t)}_track(e,t){const n=this,r=e.sink;e.sink=async function(e){await r(lb(e,(e=>{n._incrementValue(`${t} sent`,e.byteLength)})))};const s=e.source;e.source=lb(s,(e=>{n._incrementValue(`${t} received`,e.byteLength)}))}trackMultiaddrConnection(e){this._track(e,"global")}trackProtocolStream(e,t){null!=e.protocol&&this._track(e,e.protocol)}registerMetric(e,t={}){if(null==e||""===e.trim())throw new Error("Metric name is required");if(null!=t?.calculate)return void this.metrics.set(e,t.calculate);const n=new aS;return this.metrics.set(e,n),n}registerMetricGroup(e,t={}){if(null==e||""===e.trim())throw new Error("Metric name is required");if(null!=t?.calculate)return void this.metrics.set(e,t.calculate);const n=new cS;return this.metrics.set(e,n),n}registerCounter(e,t={}){if(null==e||""===e.trim())throw new Error("Metric name is required");if(null!=t?.calculate)return void this.metrics.set(e,t.calculate);const n=new aS;return this.metrics.set(e,n),n}registerCounterGroup(e,t={}){if(null==e||""===e.trim())throw new Error("Metric name is required");if(null!=t?.calculate)return void this.metrics.set(e,t.calculate);const n=new cS;return this.metrics.set(e,n),n}}function uS(e){return t=>new lS(t,e)}
83
83
  //! WebPEER.js -- https://github.com/nuzulul/webpeerjs
84
- class hS{#V;#K;#$;#q;#H;#z;#W;#j;#G;#Y;#Q;#J;#Z;#X;#ee;#te;#ne;#re;#se;#ie;#oe;#ae;#ce;#le;#ue;id;status;IPFS;address;peers;constructor(e,r,a,c,l){this.#V=e,this.#H=r,this.#le=c,this.#z=new Map,this.#K=new Map,this.#$=[],this.#q=new Map,this.#W=new Map,this.#j=!1,this.#G=new Map,this.address=[],this.#Y={},this.#Q=new Map,this.#J=[],this.#Z=new Map,this.#X=new Map,this.#ee=new Map,this.#te=[],this.#ne=!0,this.#re=new Map,this.#ie=new Map,this.#oe=(new Date).getTime(),this.#ae=(new Date).getTime(),this.#ce=[],this.#se=new Map,this.#ue=0,this.peers=this.#J,this.status=function(e){return e.status}(this.#V),this.status="unconnected",this.IPFS=function(e,t){return{libp2p:e,discoveredPeers:t}}(this.#V,this.#K),this.id=this.#V.peerId.toString();for(const e of o)this.#V.services.pubsub.subscribe(e);for(const e of s)this.#V.services.pubsub.subscribe(e);this.#V.addEventListener("peer:connect",(async e=>{const t=e.detail.toString(),n=this.#V.getConnections().map((e=>({id:e.remotePeer.toString(),addr:e.remoteAddr.toString()}))).find((e=>e.id==t)).addr;if(f.includes(t)&&(this.#X.has(t)&&!this.#X.get(t).includes("/wss/")||!n.includes("webtransport")||await this.#H.put(new Xt(t),(new TextEncoder).encode(n))),this.#X.set(t,n),p.includes(t)&&setTimeout((()=>{this.#he(),this.#de(),setTimeout((()=>{this.#he(),this.#de()}),5e3)}),1e3),this.#$.includes(t)){setTimeout((()=>{this.#pe()}),1e4),setTimeout((()=>{this.#pe()}),15e3);let e=[n];if(this.#Q.has(t)){const n={addrs:e,last:(new Date).getTime()};this.#Q.set(t,n)}else if(this.#ae<1e4){this.#fe(t);const n={addrs:e,last:(new Date).getTime()};this.#Q.set(t,n),this.#ge()}}})),this.#V.services.pubsub.addEventListener("message",(e=>{if("signed"===e.detail.type){const n=e.detail.topic,r=e.detail.from.toString();try{if((n===o||i.includes(n))&&(this.#ae=(new Date).getTime()),i.includes(n)){const e=(new Date).getTime(),t=15e3;e-this.#oe>t&&this.#de(),this.#oe=e}if(this.#$.includes(r)){if(this.#Q.has(r)){const e=this.#Q.get(r).addrs,t={addrs:e,last:(new Date).getTime()};this.#Q.set(r,t)}else if(this.#ae<1e4){this.#fe(r);const e=this.#q.get(r),t={addrs:e,last:(new Date).getTime()};this.#Q.set(r,t),this.#ge()}if(!this.#me(r))if(this.#X.has(r)){let e=[];const t=ar(this.#X.get(r));e.push(t),this.#ye(e)}else if(this.#K.has(r)){const e=this.#K.get(r);let t=[];for(const n of e){if(!n.includes("webrtc"))continue;const e=ar(n);t.push(e)}this.#ye(t)}else if(this.#Q.has(r)){const e=this.#Q.get(r).addrs;let t=[];for(const n of e){if(!n.includes("webrtc"))continue;const e=ar(n);t.push(e)}this.#ye(t)}}const s=Gt.decode(e.detail.data);if(s.addrs.length>1&&this.#V.getPeers().length<50){let e=[];for(const t of s.addrs){const n=ar(t);n.toString().includes("webtransport")&&n.toString().includes("certhash")&&e.push(n)}this.#ye(e)}const a=jr(s.addrs[0]),c=JSON.parse(a),l=c.prefix,u=c.room,h=c.rooms,d=c.message,p=c.msgId,f=c.signal,g=c.id,m=c.address;if(g!=r)return;if(l===t){if(this.#ae=(new Date).getTime(),this.#$.includes(g)||this.#$.push(g),this.#Q.has(g))m&&m.length>0&&this.#q.set(g,m);else{this.#fe(g);const e={addrs:m,last:(new Date).getTime()};this.#Q.set(g,e),m&&m.length>0&&this.#q.set(g,m),this.#ge()}if(u&&this.#Y[u]&&(this.#Y[u].members.includes(g)||this.#Q.has(g)&&(this.#Y[u].members.push(g),this.#Y[u].onMembers(this.#Y[u].members)),d)){const e=p+g;let t=0,n=(new Date).getTime();this.#se.has(g)&&(t=this.#se.get(g));const r=1e3;!this.#re.has(e)&&n-t>r&&(this.#re.set(e,n),this.#se.set(g,n),this.#Y[u].onMessage(d,g))}if(h)for(const e of h)this.#Y[e]&&(this.#Y[e].members.includes(g)||this.#Q.has(g)&&(this.#Y[e].members.push(g),this.#Y[e].onMembers(this.#Y[e].members)));f&&"announce"==f&&setTimeout((()=>{this.#pe("")}),1e3)}else if("hybrid"===l){const e=25;if(m.length>0&&(!this.#X.has(g)||this.#Q.size<e)){let e=[];for(const t of m){const n=ar(t);e.push(n)}this.#ye(e)}}}catch(e){}}})),this.#V.addEventListener("peer:discovery",(e=>{const t=e.detail.multiaddrs,n=e.detail.id;if(0!=t.length){let r=[];for(const s of t){let i;i=t.toString().includes(e.detail.id.toString())?s.toString():s.toString()+"/p2p/"+n,r.push(i)}if(this.#K.set(n.toString(),r),t.toString().includes("certhash")&&t.toString().includes("webtransport")&&t.toString().includes("p2p-circuit")&&!this.#X.has(n)){let e=[];for(const t of r){if(!t.includes("webrtc"))continue;const n=ar(t);e.push(n)}this.#ye(e)}}})),this.#V.addEventListener("peer:disconnect",(async e=>{const t=e.detail.string;if(this.#ee.has(t)){let e=this.#ee.get(t);if(e++,this.#ee.set(t,e),e>5){if(d.includes(t))return}else if(e>10&&(this.#z.has(t)&&this.#z.delete(t),!this.#$.includes(t)&&!this.#G.has(t)))return}else this.#ee.set(t,0);let n=[];for(const e of this.#ie.values())n.push(e.id);if(this.#$.includes(t)){let e=[];const n=ar(this.#X.get(t));e.push(n),this.#ye(e)}else if(this.#G.has(t)){const e=this.#X.get(t);if(e.includes("/wss/"))return;let n=[];const r=ar(e);n.push(r),this.#ye(n)}else if(n.includes(t)){let e=[];const n=ar(this.#X.get(t));e.push(n),this.#ye(e)}else{ar(this.#X.get(t))}})),this.#V.addEventListener("self:peer:update",(({detail:{peer:e}})=>{const t=e.id.toString(),n=[];e.addresses.forEach((e=>{const r=e.multiaddr.toString()+"/p2p/"+t;r.includes("webtransport")&&r.includes("certhash")&&n.push(r)})),n.reverse(),this.address=n,this.#pe(),this.#he()})),this.#V.addEventListener("peer:identify",(async e=>{const t=e.detail.peerId.toString();if(d.includes(t)){if(e.detail.connection.remoteAddr.toString().includes("/wss/")){let n=[],r=[];for(const s of e.detail.listenAddrs){if(!s.toString().includes("webtransport"))continue;const e=s.toString()+"/p2p/"+t,i=ar(e);n.push(e),r.push(i)}this.#G.set(t,n),await this.#V.hangUp(Is(t)),this.#ye(r)}}if(e.detail.protocols.includes(n)){const t=e.detail.peerId.toString();let n=[];for(const r of e.detail.listenAddrs){const e=r.toString()+"/p2p/"+t;ar(e),e.includes("webtransport")&&n.push(e)}if(this.#Q.has(t)){const e={addrs:n,last:(new Date).getTime()};this.#Q.set(t,e)}const r="peer-exchange";this.#we(t,r)}})),this.#be(),this.#ve(),this.#Ee(),this.#Se(),this.#_e(),a((e=>{const t=function(e){if(Qr)return{isDialEnabled:rs,isAutoDialEnabled:is};try{const t=e.libp2p_webtransport_dialer_events_total,n=(t.pending??0)-(es.pending??0),r=(t.ready_error??0)-(es.ready_error??0),s=(t.noise_error??0)-(es.noise_error??0),i=(t.upgrade_error??0)-(es.upgrade_error??0),o=(t.close??0)-(es.close??0),a=(t.ready??0)-(es.ready??0),c=(t.abort??0)-(es.abort??0),l=(t.ready_timeout??0)-(es.ready_timeout??0),u=(t.noise_timeout??0)-(es.noise_timeout??0),h=(t.open??0)-(es.open??0),d=(t.remote_close??0)-(es.remote_close??0);Xr.pending+=n,Xr.pending-=l,Xr.pending-=u,Xr.pending-=r,Xr.pending-=s,Xr.pending-=i,Xr.pending-=h,Xr.open+=h,Xr.open-=o,Xr.open-=d,Xr.open-=c,Xr.ready_error=r,Xr.noise_error=s,Xr.upgrade_error=i,Xr.ready_timeout=l,Xr.noise_timeout=u,Xr.close=o,Xr.abort=c,Xr.remote_close=d,Zr.success+=a,Zr.readyErrored+=r,Zr.noiseErrored+=s,Zr.upgradeErrored+=i,Zr.readyTimedout+=l,Zr.noiseTimedout+=u;const p=Zr.readyErrored+Zr.noiseErrored+Zr.upgradeErrored,f=Zr.readyTimedout+Zr.noiseTimedout;if(es=t,ts=p+f,ns>ts&&setTimeout((()=>{is&&(os+=ns-ts),rs&&(ss+=ns-ts)}),3e5),ns=ts,ts-ss>55&&rs&&(rs=!1,console.warn("Peer dial is temporary disabled"),is&&(is=!1,console.warn("Peer autodial is temporary disabled")),setTimeout((()=>{rs||(rs=!0,ss=ts,console.warn("Peer dial is resumed"),is||(is=!0,os=ts,console.warn("Peer autodial is resumed")))}),36e4)),ts-os>45&&is){is=!1,console.warn("Peer autodial is temporary disabled");const e=ts;setTimeout((()=>{!is&&rs&&(is=!0,os=ts,console.warn("Peer autodial is resumed"),rs&&(ss=e))}),36e4)}return{isDialEnabled:rs,isAutoDialEnabled:is}}catch{console.debug("Metrics error")}}(e);this.#ne=t.isDialEnabled,l(t.isAutoDialEnabled)})),setTimeout((()=>{this.#Ie(),setInterval((()=>{this.#Ie()}),5e3)}),1e4),setInterval((()=>{this.#Re()}),5e3),setInterval((()=>{this.#he(),this.#Ae(),this.#Te(),this.#ke()}),1e4)}#De=()=>{};onConnect=e=>this.#De=e;#Pe=()=>{};onDisconnect=e=>this.#Pe=e;joinRoom=e=>{if(this.#Y[e])return[this.#Y[e].sendMessage,this.#Y[e].listenMessage,this.#Y[e].onMembersChange];if(!e)throw Wr("room is required");{let n=[];n=o,this.#Y[e]={onMessage:()=>{},listenMessage:t=>this.#Y[e]={...this.#Y[e],onMessage:t},sendMessage:async r=>{const s=(new Date).getTime();if(s-this.#ue<1e3)throw Wr("can not send more than 1 message/s");this.#ue=s;const i=(new Date).getTime(),o=Gr(JSON.stringify({prefix:t,room:e,message:r,id:this.#V.peerId.toString(),msgId:i}));if(o.byteLength>102400)throw Wr("message too large");const a={publicKey:this.#V.peerId.publicKey,addrs:[o]},c=Gt.encode(a);for(const e of n)await this.#V.services.pubsub.publish(e,c)},members:[this.id],onMembers:()=>{},onMembersChange:t=>{this.#Y[e]={...this.#Y[e],onMembers:t},this.#Y[e].onMembers(this.#Y[e].members),this.#pe()}}}return[this.#Y[e].sendMessage,this.#Y[e].listenMessage,this.#Y[e].onMembersChange]};dial(e){let t=[];const n=ar(e);t.push(n),this.#ye(t)}plugin(e){e(this)}#ke(){for(const e of this.#re)e[1]>6e4&&this.#re.delete(e[0])}#Ae(){let e=!1;for(const t of p)this.#me(t)&&(e=!0);if(!e)for(const e of p)if("connected"!==this.status&&this.#X.has(e)){let t=[];const n=ar(this.#X.get(e));t.push(n),this.#ye(t)}}#Te(){if("connected"===this.status)return;if(this.#q.size<1)return;const e=Array.from(this.#q.keys()),t=e[Math.floor(Math.random()*e.length)],n=this.#q.get(t);let r=[];for(const e of n){const t=ar(e);r.push(t)}this.#ye(r)}#fe(e){this.#ce.includes(e)||(this.#ce.push(e),this.#De(e),setTimeout((()=>{const t=this.#ce.indexOf(e);t>-1&&this.#ce.splice(t,1)}),5e3))}#ge(){this.#J.length=0;for(const e of this.#Q){const t={id:e[0],address:e[1].addrs};this.#J.push(t)}this.#Q.size>0?this.status="connected":this.status="unconnected",this.#pe()}async#_e(){await this.#V.handle(n,(async({connection:e,stream:t})=>{try{const r=await fr(t.source,(e=>$r(e)),(e=>Hr(e,(e=>jr(e.subarray())))),(async function(e){let t="";for await(const n of e)t+=n.toString();return t})),s=e.remotePeer.toString();let i=JSON.parse(r),o={protocol:n,command:null,data:null};if("peer-exchange"===i.command){if(i.protocol==n){const t=[e.remoteAddr.toString()];if(this.#Q.has(s)){const e={addrs:t,last:(new Date).getTime()};this.#Q.set(s,e)}else{this.#$.includes(s)||this.#$.push(s),this.#fe(s);const e={addrs:t,last:(new Date).getTime()};this.#Q.set(s,e),this.#ge()}}if(null!=i.data){this.#ie.set(s,i.data);let e=[];const t=ar(i.data.addr),n=i.data.id;e.push(t),this.#ye(e),this.#z.has(n)}const t=Array.from(this.#z.keys()),r=t[Math.floor(Math.random()*t.length)],a=this.#z.get(r);o.command=i.command,o.data={id:r,addr:a}}fr(JSON.stringify(o),(e=>Hr(e,(e=>Gr(e)))),(e=>Mr(e)),t.sink)}catch(e){}}),{maxInboundStreams:100,maxOutboundStreams:100,runOnTransientConnection:h}),await this.#V.register(n,{})}async#we(e,t){const r=this.#V.getConnections().map((e=>({id:e.remotePeer.toString(),addr:e.remoteAddr.toString()}))).find((t=>t.id==e)).addr,s=ar(r);let i={protocol:n,command:null,data:null};if("peer-exchange"===t){if(this.#ie.has(e))return;const n=Array.from(this.#z.keys()),r=n[Math.floor(Math.random()*n.length)],s=this.#z.get(r);i.command=t,i.data={id:r,addr:s}}const o=JSON.stringify(i);try{const t=await this.#V.dialProtocol(s,n,{runOnTransientConnection:h}),i=await fr(o,(e=>Hr(e,(e=>Gr(e)))),(e=>Mr(e)),t,(e=>$r(e)),(e=>Hr(e,(e=>jr(e.subarray())))),(async function(e){let t="";for await(const n of e)t+=n.toString();return t})),a=JSON.parse(i);if(a.protocol==n){const t=[r];if(this.#Q.has(e)){const n={addrs:t,last:(new Date).getTime()};this.#Q.set(e,n)}else{this.#$.includes(e)||this.#$.push(e),this.#fe(e);const n={addrs:t,last:(new Date).getTime()};this.#Q.set(e,n),this.#ge()}}if("peer-exchange"==a.command&&null!=a.data){this.#ie.set(e,a.data);let t=[];const n=ar(a.data.addr),r=a.data.id;t.push(n),this.#ye(t),this.#z.has(r)}}catch(e){}}async#Ce(){if(navigator.onLine&&this.#ne)for(const e of p)if(!this.#me(e)&&!this.#X.has(e)){const t=Is(e);for await(const e of this.#V.services.aminoDHT.findPeer(t))if("FINAL_PEER"===e.name){let t=[],n=[];const r=e.peer.id.toString();for(const s of e.peer.multiaddrs){const e=s.toString()+"/p2p/"+r,i=ar(e);n.push(e),t.push(i)}this.#G.set(r,n),this.#me(r)||this.#ye(t)}}}#Re(){const e=(new Date).getTime();for(const t of this.#Q){const n=t[0],r=e-t[1].last;if(r>1e4&&!this.#me(n)||r>6e4){this.#Q.delete(n),this.#ge(),this.#Pe(n);const e=Object.keys(this.#Y);for(const t of e)if(this.#Y[t].members.includes(n)){const e=this.#Y[t].members.indexOf(n);this.#Y[t].members.splice(e,1),this.#Y[t].onMembers(this.#Y[t].members)}}}}#me(e){let t=[];for(const e of this.#V.getPeers())t.push(e.toString());return!!t.includes(e)}async#ye(e){if(e.length>0){const t=e[0].toString().split("/").pop();if(this.#te.map((e=>e[0].toString().split("/").pop())).includes(t))return;if("connected"===this.status&&d.includes(t))return;const n=this.#Q.size,r=this.#V.getPeers().length,s=r-n,i=25;if(this.#$.includes(t)){if(n>i)return}else if(s>i-5||r>45){let e=[];for(const t of this.#V.getPeers())e.push(t.toString());const n=e[Math.floor(Math.random()*e.length)];p.includes(t)||await this.#V.hangUp(Is(n))}this.#$.includes(t)||f.includes(t)||p.includes(t)?this.#te.unshift(e):this.#te.push(e)}}#Ie(){if(!this.#ne||!navigator.onLine||"hidden"===document.visibilityState&&"ontouchstart"in document.documentElement)return;let e=[];for(const t of this.#V.getDialQueue()){const n=t.peerId.string;e.push(n)}if(!(e.length>5))for(let t=0;t<5;t++){const t=this.#te.shift();if(!(null!=t&&t.length>0))break;{const n=t[0].toString().split("/").pop();if(this.#me(n))continue;if(e.includes(n))continue;this.#xe(t),this.#j&&this.#Ne(t)}}}async#he(){const e=s,t=JSON.stringify({prefix:"hybrid",id:this.#V.peerId.toString(),address:this.address}),n={publicKey:this.#V.peerId.publicKey,addrs:[Gr(t)]},r=Gt.encode(n);for(const t of e)await this.#V.services.pubsub.publish(t,r)}async#de(){let e=[];e=o;const n=JSON.stringify({prefix:t,signal:"announce",id:this.#V.peerId.toString(),address:this.address,rooms:Object.keys(this.#Y)}),r={publicKey:this.#V.peerId.publicKey,addrs:[Gr(n)]},s=Gt.encode(r);for(const t of e)await this.#V.services.pubsub.publish(t,s)}async#pe(){let e=[];e=o;const n=JSON.stringify({prefix:t,signal:"ping",id:this.#V.peerId.toString(),address:this.address,rooms:Object.keys(this.#Y)}),r={publicKey:this.#V.peerId.publicKey,addrs:[Gr(n)]},s=Gt.encode(r);for(const t of e)await this.#V.services.pubsub.publish(t,s)}#Se(){setInterval((()=>{const e=f,t=Math.floor(Math.random()*e.length);let n=[];n.push(e[t]);for(const e of p)n.push(e);for(const e of n)if(null!=e&&!this.#me(e))if(this.#X.has(e)){let t=[];const n=ar(this.#X.get(e));t.push(n),this.#ye(t)}else if(this.#G.has(e)){let t=[];const n=this.#G.get(e);for(const e of n){const n=ar(e);t.push(n)}this.#ye(t)}else{const t=g,n=t.findIndex((t=>t.Peers[0].ID==e));if(n>-1){const r=t[n].Peers[0].Addrs;let s=[];for(const t of r){const n=ar(t+"/p2p/"+e);s.push(n)}this.#ye(s)}}}),45e3)}async#Ee(){for await(const{key:e,value:t}of this.#H.query({})){const n=e.toString().split("/")[1],r=(new TextDecoder).decode(t);this.#z.set(n,r)}setInterval((async()=>{const e=this.#V.getConnections();for(const t of e){const e=t.remotePeer,n=t.remoteAddr,r=t.timeline.upgraded,s=3e5,i=(new Date).getTime();if(i-r>s){const t=n.toString(),r=e.toString();this.#$.includes(r)||f.includes(r)||this.#z.has(r)||t.includes("p2p-circuit")||!t.includes("webtransport")||(await this.#H.put(new Xt(r),(new TextEncoder).encode(t)),this.#z.set(r,t))}if(i-r>6e4){const t=e.toString();this.#W.has(t)||this.#W.set(t,0)}}for(const e of this.#z){const t=e[0],n=e[1];if(this.#me(t))this.#Z.set(t,0);else{if(this.#Z.has(t)){let e=this.#Z.get(t);if(e++,this.#Z.set(t,e),e>5){this.#X.has(t)||f.includes(t)||!navigator.onLine||setTimeout((async()=>{this.#z.has(t)&&!this.#X.has(t)&&(this.#z.delete(t),await this.#H.delete(new Xt(t)))}),6e4);continue}}else this.#Z.set(t,0);let e=[];const r=ar(n);e.push(r),this.#ye(e)}}const t=Array.from(this.#W.keys());for(const e of t)if(this.#me(e))this.#W.set(e,0);else{let t=this.#W.get(e);if(t<15||t<25&&this.#G.has(e)){let n=[];const r=ar(this.#X.get(e));n.push(r),this.#ye(n),t++,this.#W.set(e,t)}}}),15e3)}#ve(){setInterval((()=>{0==this.#V.getPeers().length&&this.#be()}),12e4)}#be(){setTimeout((()=>{this.#Me(),setTimeout((()=>{this.#Oe()}),2e4),setTimeout((()=>{this.#Ce()}),3e4),setTimeout((()=>{0==this.#V.getPeers().length&&(this.#Le(),setTimeout((()=>{this.#Ce()}),3e4),setTimeout((()=>{0==this.#V.getPeers().length&&(this.#Be(),setTimeout((()=>{this.#Ce()}),15e3),setTimeout((()=>{0==this.#V.getPeers().length&&(this.#Ue(),setTimeout((()=>{this.#Ce()}),15e3),setTimeout((()=>{0==this.#V.getPeers().length&&(this.#Fe(),setTimeout((()=>{this.#Ce()}),15e3))}),u))}),u))}),u))}),u)}),5e3)}async#Me(){if(!navigator.onLine)return;if(!this.#ne)return;let e=!0;for(const t of f)if(this.#z.has(t)){e=!1;let n=[],r=[];const s=t,i=this.#z.get(t),o=ar(i);r.push(i),n.push(o),this.#G.set(s,r),this.#me(s)||this.#ye(n)}if(e)for(const e of f){const t=qh(a),n=await Yr(t.getPeers(Is(e)));if(!n)continue;const r=n.Addrs,s=n.ID;let i=[],o=[];for(const e of r){const t=e.toString()+"/p2p/"+s.toString(),n=ar(t);o.push(t),i.push(n)}this.#G.set(s,o),this.#me(s)||this.#ye(i)}}async#Oe(){if(!navigator.onLine)return;if(!this.#ne)return;let e=!0;for(const t of f)if(this.#z.has(t)&&(e=!1),!this.#X.has(t)&&(this.#z.has(t)||e)){const e=qh(a),n=await Yr(e.getPeers(Is(t)));if(!n){navigator.onLine&&await this.#H.delete(new Xt(t));continue}const r=n.Addrs,s=n.ID;let i=[],o=[];for(const e of r){const t=e.toString()+"/p2p/"+s.toString(),n=ar(t);o.push(t),i.push(n)}this.#G.set(s,o),this.#me(s)||this.#ye(i)}}async#Le(){if(!navigator.onLine)return;if(!this.#ne)return;const e=qh(a),t=f,n=await Promise.all(t.map((t=>Yr(e.getPeers(Is(t))))));for(const e of n){if(!e)return;const t=e.Addrs,n=e.ID;let r=[],s=[];for(const e of t){const t=e.toString()+"/p2p/"+n.toString(),i=ar(t);s.push(t),r.push(i)}this.#G.set(n,s),this.#me(n)||this.#ye(r)}}#Be(){if(!navigator.onLine)return;if(!this.#ne)return;const e=g;for(const t of e){const e=t.Peers[0].Addrs,n=t.Peers[0].ID;let r=[],s=[];for(const t of e){if(!t.includes("wss"))continue;const e=t+"/p2p/"+n,i=ar(e);s.push(e),r.push(i)}this.#G.set(n,s),this.#j=!0,this.#le(!0),this.#me(n)||this.#ye(r)}}async#Ue(){if(!navigator.onLine)return;if(!this.#ne)return;const e=c,t=l,n=await fetch(e+"?name="+t+"&type=txt"),r=(await n.json()).Answer,s=[];for(const e of r){const t=e.data.split("/").pop();s.push(t)}const i=qh(a),o=await Promise.all(s.map((e=>Yr(i.getPeers(Is(e))))));for(const e of o){const t=e.Addrs,n=e.ID;let r=[],s=[];for(const e of t){const t=e.toString()+"/p2p/"+n.toString(),i=ar(t);s.push(t),r.push(i)}this.#G.set(n,s),this.#j=!0,this.#le(!0),this.#me(n)||this.#ye(r)}}async#Fe(){if(console.log("#dialKnownDNSonly()"),!navigator.onLine)return;if(!this.#ne)return;const e=c,t=l,n=await fetch(e+"?name="+t+"&type=txt"),r=(await n.json()).Answer;for(const e of r){const t=e.data.split("/"),n=t.pop(),r="_dnsaddr."+t[2];this.#Ve(n,r)}}async#Ve(e,t){const n=c,r=await fetch(n+"?name="+t+"&type=txt"),s=(await r.json()).Answer;let i=[],o=[];for(const e of s){const t=e.data.split("=")[1],n=ar(t);i.push(n),o.push(t)}this.#j=!0,this.#le(!0),this.#G.set(e,o),this.#G.set(e,o),this.#me(e)||(this.#ye(i),this.#Ne(i))}async#xe(e){const t=e.filter((e=>e.protoNames().includes("webtransport")&&e.protoNames().includes("certhash")));for(const e of t)try{return void await this.#V.dial(e)}catch(e){}}async#Ne(e){const t=e.filter((e=>e.protoNames().includes("wss")));for(const e of t)try{return void await this.#V.dial(e)}catch(e){}}static async createWebpeer(){const e=new _g(r);await e.open();const t=g;for(const e of t){const t=e.Peers[0].Addrs;e.Peers[0].ID;for(const e of t)e.includes("webtransport")&&e.includes("certhash")}let n=()=>{};let s=!1,o=()=>{};o=e=>{s=e};let a=!0,c=()=>{};(e=>{c=e})((e=>{a=e}));let l=[];l.push("/webrtc");const u="stun:stun.l.google.com:19302",d="stun:global.stun.twilio.com:3478",p=atob("dHVybjp0dXJuMDEuYnJpZS5maTo1MzQ5"),f=atob("YnJpZQ=="),m=atob("Zmk="),y=atob("dHVybjpyZWxheTEuZXhwcmVzc3R1cm4uY29tOjM0Nzg="),w=atob("ZWZJSllZNjdDNElRMzFZQUlP"),b=atob("Vk01SmdhODlkYjJaWU9aSA==");async function v(e,t,n,r,s){return new Promise((i=>{let o=!1,a=!1;const c=setTimeout((()=>{let e=[];e.push(o),e.push(a),i(e)}),s);function l(){if(o&&a){let e=[];e.push(o),e.push(a),clearTimeout(c),i(e)}}const u=new RTCPeerConnection({iceServers:[{urls:e},{urls:t,username:n,credential:r}]});u.onicecandidate=s=>{s.candidate&&("srflx"==s.candidate.type&&(o={urls:e},l()),"relay"==s.candidate.type&&(a={urls:t,username:n,credential:r},l()))},u.onicecandidateerror=e=>{console.debug(e)},u.createDataChannel("webpeerjs"),u.createOffer().then((e=>u.setLocalDescription(e)))}))}let E=await v(u,p,f,m,5e3);E[0]||E[1]?E[0]&&!E[1]?E=await v(u,y,w,b,5e3):!E[0]&&E[1]&&(E=await v(d,p,f,m,5e3)):E=await v(d,y,w,b,5e3),E.forEach((function(e,t){e||this.splice(t,1)}),E);let S={};arguments.length>0?S=arguments[0]:S.rtcConfiguration={iceServers:E};const _=await async function(e={}){const t=await Xf(e);return!1!==e.start&&await t.start(),t}({addresses:{listen:l},transports:[zm(),Jy(),(I={rtcConfiguration:S.rtcConfiguration},e=>new Nw(e,I)),Kb({discoverRelays:1,reservationConcurrency:1,maxReservationQueueLength:3})],connectionManager:{maxConnections:50,minConnections:0,autoDialInterval:6e4,autoDialConcurrency:0,autoDialMaxQueueLength:0,autoDialPriority:1e3,autoDialDiscoveredPeersDebounce:6e4,maxParallelDials:3,dialTimeout:5e3,maxIncomingPendingConnections:5,maxDialQueueLength:10,inboundConnectionThreshold:3,maxPeerAddrsToDial:2,inboundUpgradeTimeout:5e3},connectionEncryption:[Nm()],streamMuxers:[gb({maxInboundStreams:100,maxOutboundStreams:100})],connectionGater:{filterMultiaddrForPeer:async(e,t)=>{const n=t.toString();return!n.includes("/ip4/127.0.0.1")&&!n.includes("/ip6/")&&(n.includes("/ws/")||n.includes("/wss/")?s:a)},denyDialMultiaddr:async e=>{const t=e.toString();return!(!t.includes("/ip4/127.0.0.1")&&!t.includes("/ip6/"))||(t.includes("/ws/")||t.includes("/wss/")?!s:!a)}},peerDiscovery:[bb({interval:5e3,topics:i,listenOnly:!1})],services:{pubsub:Bv({allowPublishToZeroTopicPeers:!0,msgIdFn:Jr,ignoreDuplicatePublishError:!0,runOnTransientConnection:h}),identify:Hv(),identifyPush:zv(),aminoDHT:iS({protocol:"/ipfs/kad/1.0.0",peerInfoMapper:bE,clientMode:!1}),dcutr:$w()},peerStore:{persistence:!0,threshold:1},metrics:uS({onMetrics:e=>{n(e)},intervalMs:1e3})});var I;return await _.services.aminoDHT.setMode("server"),new hS(_,e,(e=>n=e),o,c)}}
84
+ class hS{#V;#K;#$;#q;#H;#z;#W;#j;#G;#Y;#Q;#J;#Z;#X;#ee;#te;#ne;#re;#se;#ie;#oe;#ae;#ce;#le;#ue;id;status;IPFS;address;peers;constructor(e,r,a,c,l){this.#V=e,this.#H=r,this.#le=c,this.#z=new Map,this.#K=new Map,this.#$=[],this.#q=new Map,this.#W=new Map,this.#j=!1,this.#G=new Map,this.address=[],this.#Y={},this.#Q=new Map,this.#J=[],this.#Z=new Map,this.#X=new Map,this.#ee=new Map,this.#te=[],this.#ne=!0,this.#re=new Map,this.#ie=new Map,this.#oe=(new Date).getTime(),this.#ae=(new Date).getTime(),this.#ce=[],this.#se=new Map,this.#ue=0,this.peers=this.#J,this.status=function(e){return e.status}(this.#V),this.status="unconnected",this.IPFS=function(e,t){return{libp2p:e,discoveredPeers:t}}(this.#V,this.#K),this.id=this.#V.peerId.toString();for(const e of o)this.#V.services.pubsub.subscribe(e);for(const e of s)this.#V.services.pubsub.subscribe(e);this.#V.addEventListener("peer:connect",(async e=>{const t=e.detail.toString(),n=this.#V.getConnections().map((e=>({id:e.remotePeer.toString(),addr:e.remoteAddr.toString()}))).find((e=>e.id==t)).addr;if(f.includes(t)&&(this.#X.has(t)&&!this.#X.get(t).includes("/wss/")||!n.includes("webtransport")||await this.#H.put(new Xt(t),(new TextEncoder).encode(n))),this.#X.set(t,n),p.includes(t)&&setTimeout((()=>{this.#he(),this.#de(),setTimeout((()=>{this.#he(),this.#de()}),5e3)}),1e3),this.#$.includes(t)){setTimeout((()=>{this.#pe()}),1e4),setTimeout((()=>{this.#pe()}),15e3);let e=[n];if(this.#Q.has(t)){if(this.#ae<1e4){const n={addrs:e,last:(new Date).getTime()};this.#Q.set(t,n)}}else if(this.#ae<1e4){this.#fe(t);const n={addrs:e,last:(new Date).getTime()};this.#Q.set(t,n),this.#ge()}}})),this.#V.services.pubsub.addEventListener("message",(e=>{if("signed"===e.detail.type){const n=e.detail.topic,r=e.detail.from.toString();try{if((n===o||i.includes(n))&&(this.#ae=(new Date).getTime()),i.includes(n)){const e=(new Date).getTime(),t=15e3;e-this.#oe>t&&this.#de(),this.#oe=e}if(this.#$.includes(r)){if(this.#Q.has(r)){if(this.#ae<1e4){const e=this.#Q.get(r).addrs,t={addrs:e,last:(new Date).getTime()};this.#Q.set(r,t)}}else if(this.#ae<1e4){this.#fe(r);const e=this.#q.get(r),t={addrs:e,last:(new Date).getTime()};this.#Q.set(r,t),this.#ge()}if(!this.#me(r))if(this.#X.has(r)){let e=[];const t=ar(this.#X.get(r));e.push(t),this.#ye(e)}else if(this.#K.has(r)){const e=this.#K.get(r);let t=[];for(const n of e){if(!n.includes("webrtc"))continue;const e=ar(n);t.push(e)}this.#ye(t)}else if(this.#Q.has(r)){const e=this.#Q.get(r).addrs;let t=[];for(const n of e){if(!n.includes("webrtc"))continue;const e=ar(n);t.push(e)}this.#ye(t)}}const s=Gt.decode(e.detail.data);if(s.addrs.length>1&&this.#V.getPeers().length<30){let e=[];for(const t of s.addrs){const n=ar(t);n.toString().includes("webtransport")&&n.toString().includes("certhash")&&e.push(n)}this.#ye(e)}const a=jr(s.addrs[0]),c=JSON.parse(a),l=c.prefix,u=c.room,h=c.rooms,d=c.message,p=c.msgId,f=c.signal,g=c.id,m=c.address;if(g!=r)return;if(l===t){if(this.#ae=(new Date).getTime(),this.#$.includes(g)||this.#$.push(g),this.#Q.has(g)){let e=this.#Q.get(g).addrs;m&&(e=m);const t={addrs:e,last:(new Date).getTime()};this.#Q.set(g,t),m&&m.length>0&&this.#q.set(g,m)}else{this.#fe(g);const e={addrs:m,last:(new Date).getTime()};this.#Q.set(g,e),m&&m.length>0&&this.#q.set(g,m),this.#ge()}if(u&&this.#Y[u]&&(this.#Y[u].members.includes(g)||this.#Q.has(g)&&(this.#Y[u].members.push(g),this.#Y[u].onMembers(this.#Y[u].members)),d)){const e=p+g;let t=0,n=(new Date).getTime();this.#se.has(g)&&(t=this.#se.get(g));const r=1e3;!this.#re.has(e)&&n-t>r&&(this.#re.set(e,n),this.#se.set(g,n),this.#Y[u].onMessage(d,g))}if(h)for(const e of h)this.#Y[e]&&(this.#Y[e].members.includes(g)||this.#Q.has(g)&&(this.#Y[e].members.push(g),this.#Y[e].onMembers(this.#Y[e].members)));f&&"announce"==f&&setTimeout((()=>{this.#pe("")}),1e3)}else if("hybrid"===l){const e=15;if(m.length>0&&(!this.#X.has(g)||this.#Q.size<e)){let e=[];for(const t of m){const n=ar(t);e.push(n)}this.#ye(e)}}}catch(e){}}})),this.#V.addEventListener("peer:discovery",(e=>{const t=e.detail.multiaddrs,n=e.detail.id;if(0!=t.length){let r=[];for(const s of t){let i;i=t.toString().includes(e.detail.id.toString())?s.toString():s.toString()+"/p2p/"+n,r.push(i)}if(this.#K.set(n.toString(),r),t.toString().includes("certhash")&&t.toString().includes("webtransport")&&t.toString().includes("p2p-circuit")&&!this.#X.has(n)){let e=[];for(const t of r){if(!t.includes("webrtc"))continue;const n=ar(t);e.push(n)}this.#ye(e)}}})),this.#V.addEventListener("peer:disconnect",(async e=>{const t=e.detail.string;if(this.#ee.has(t)){let e=this.#ee.get(t);if(e++,this.#ee.set(t,e),e>5){if(d.includes(t))return}else if(e>10&&(this.#z.has(t)&&this.#z.delete(t),!this.#$.includes(t)&&!this.#G.has(t)))return}else this.#ee.set(t,0);let n=[];for(const e of this.#ie.values())n.push(e.id);if(this.#$.includes(t)){let e=[];const n=ar(this.#X.get(t));e.push(n),this.#ye(e)}else if(this.#G.has(t)){const e=this.#X.get(t);if(e.includes("/wss/"))return;let n=[];const r=ar(e);n.push(r),this.#ye(n)}else if(n.includes(t)){let e=[];const n=ar(this.#X.get(t));e.push(n),this.#ye(e)}else{ar(this.#X.get(t))}})),this.#V.addEventListener("self:peer:update",(({detail:{peer:e}})=>{const t=e.id.toString(),n=[];e.addresses.forEach((e=>{const r=e.multiaddr.toString()+"/p2p/"+t;r.includes("webtransport")&&r.includes("certhash")&&n.push(r)})),n.reverse(),this.address=n,this.#pe(),this.#he()})),this.#V.addEventListener("peer:identify",(async e=>{const t=e.detail.peerId.toString();if(d.includes(t)){if(e.detail.connection.remoteAddr.toString().includes("/wss/")){let n=[],r=[];for(const s of e.detail.listenAddrs){if(!s.toString().includes("webtransport"))continue;const e=s.toString()+"/p2p/"+t,i=ar(e);n.push(e),r.push(i)}this.#G.set(t,n),await this.#V.hangUp(Is(t)),this.#ye(r)}}if(e.detail.protocols.includes(n)){const t=e.detail.peerId.toString();let n=[];for(const r of e.detail.listenAddrs){const e=r.toString()+"/p2p/"+t;ar(e),e.includes("webtransport")&&n.push(e)}if(this.#Q.has(t)){const e={addrs:n,last:(new Date).getTime()};this.#Q.set(t,e)}const r="peer-exchange";this.#we(t,r)}})),this.#be(),this.#ve(),this.#Ee(),this.#Se(),this.#_e(),a((e=>{const t=function(e){if(Qr)return{isDialEnabled:rs,isAutoDialEnabled:is};try{const t=e.libp2p_webtransport_dialer_events_total,n=(t.pending??0)-(es.pending??0),r=(t.ready_error??0)-(es.ready_error??0),s=(t.noise_error??0)-(es.noise_error??0),i=(t.upgrade_error??0)-(es.upgrade_error??0),o=(t.close??0)-(es.close??0),a=(t.ready??0)-(es.ready??0),c=(t.abort??0)-(es.abort??0),l=(t.ready_timeout??0)-(es.ready_timeout??0),u=(t.noise_timeout??0)-(es.noise_timeout??0),h=(t.open??0)-(es.open??0),d=(t.remote_close??0)-(es.remote_close??0);Xr.pending+=n,Xr.pending-=l,Xr.pending-=u,Xr.pending-=r,Xr.pending-=s,Xr.pending-=i,Xr.pending-=h,Xr.open+=h,Xr.open-=o,Xr.open-=d,Xr.open-=c,Xr.ready_error=r,Xr.noise_error=s,Xr.upgrade_error=i,Xr.ready_timeout=l,Xr.noise_timeout=u,Xr.close=o,Xr.abort=c,Xr.remote_close=d,Zr.success+=a,Zr.readyErrored+=r,Zr.noiseErrored+=s,Zr.upgradeErrored+=i,Zr.readyTimedout+=l,Zr.noiseTimedout+=u;const p=Zr.readyErrored+Zr.noiseErrored+Zr.upgradeErrored,f=Zr.readyTimedout+Zr.noiseTimedout;if(es=t,ts=p+f,ns>ts&&setTimeout((()=>{is&&(os+=ns-ts),rs&&(ss+=ns-ts)}),3e5),ns=ts,ts-ss>55&&rs&&(rs=!1,console.warn("Peer dial is temporary disabled"),is&&(is=!1,console.warn("Peer autodial is temporary disabled")),setTimeout((()=>{rs||(rs=!0,ss=ts,console.warn("Peer dial is resumed"),is||(is=!0,os=ts,console.warn("Peer autodial is resumed")))}),36e4)),ts-os>45&&is){is=!1,console.warn("Peer autodial is temporary disabled");const e=ts;setTimeout((()=>{!is&&rs&&(is=!0,os=ts,console.warn("Peer autodial is resumed"),rs&&(ss=e))}),36e4)}return{isDialEnabled:rs,isAutoDialEnabled:is}}catch{console.debug("Metrics error")}}(e);this.#ne=t.isDialEnabled,l(t.isAutoDialEnabled)})),setTimeout((()=>{this.#Ie(),setInterval((()=>{this.#Ie()}),5e3)}),1e4),setInterval((()=>{this.#Re()}),5e3),setInterval((()=>{this.#he(),this.#Ae(),this.#Te(),this.#ke()}),1e4)}#De=()=>{};onConnect=e=>this.#De=e;#Pe=()=>{};onDisconnect=e=>this.#Pe=e;joinRoom=e=>{if(this.#Y[e])return[this.#Y[e].sendMessage,this.#Y[e].listenMessage,this.#Y[e].onMembersChange];if(!e)throw Wr("room is required");{let n=[];n=o,this.#Y[e]={onMessage:()=>{},listenMessage:t=>this.#Y[e]={...this.#Y[e],onMessage:t},sendMessage:async r=>{const s=(new Date).getTime();if(s-this.#ue<1e3)throw Wr("can not send more than 1 message/s");this.#ue=s;const i=(new Date).getTime(),o=Gr(JSON.stringify({prefix:t,room:e,message:r,id:this.#V.peerId.toString(),msgId:i}));if(o.byteLength>102400)throw Wr("message too large");const a={publicKey:this.#V.peerId.publicKey,addrs:[o]},c=Gt.encode(a);for(const e of n)await this.#V.services.pubsub.publish(e,c)},members:[this.id],onMembers:()=>{},onMembersChange:t=>{this.#Y[e]={...this.#Y[e],onMembers:t},this.#Y[e].onMembers(this.#Y[e].members),this.#pe()}}}return[this.#Y[e].sendMessage,this.#Y[e].listenMessage,this.#Y[e].onMembersChange]};dial(e){let t=[];const n=ar(e);t.push(n),this.#ye(t)}plugin(e){e(this)}#ke(){for(const e of this.#re)e[1]>6e4&&this.#re.delete(e[0])}#Ae(){let e=!1;for(const t of p)this.#me(t)&&(e=!0);if(!e)for(const e of p)if("connected"!==this.status&&this.#X.has(e)){let t=[];const n=ar(this.#X.get(e));t.push(n),this.#ye(t)}}#Te(){if("connected"===this.status)return;if(this.#q.size<1)return;const e=Array.from(this.#q.keys()),t=e[Math.floor(Math.random()*e.length)],n=this.#q.get(t);let r=[];for(const e of n){const t=ar(e);r.push(t)}this.#ye(r)}#fe(e){this.#ce.includes(e)||(this.#ce.push(e),this.#De(e),setTimeout((()=>{const t=this.#ce.indexOf(e);t>-1&&this.#ce.splice(t,1)}),5e3))}#ge(){this.#J.length=0;for(const e of this.#Q){const t={id:e[0],address:e[1].addrs};this.#J.push(t)}this.#Q.size>0?this.status="connected":this.status="unconnected",this.#pe()}async#_e(){await this.#V.handle(n,(async({connection:e,stream:t})=>{try{const r=await fr(t.source,(e=>$r(e)),(e=>Hr(e,(e=>jr(e.subarray())))),(async function(e){let t="";for await(const n of e)t+=n.toString();return t})),s=e.remotePeer.toString();let i=JSON.parse(r),o={protocol:n,command:null,data:null};if("peer-exchange"===i.command){if(i.protocol==n){const t=[e.remoteAddr.toString()];if(this.#Q.has(s)){const e={addrs:t,last:(new Date).getTime()};this.#Q.set(s,e)}else{this.#$.includes(s)||this.#$.push(s),this.#fe(s);const e={addrs:t,last:(new Date).getTime()};this.#Q.set(s,e),this.#ge()}}if(null!=i.data){this.#ie.set(s,i.data);let e=[];const t=ar(i.data.addr),n=i.data.id;e.push(t),this.#ye(e),this.#z.has(n)}const t=Array.from(this.#z.keys()),r=t[Math.floor(Math.random()*t.length)],a=this.#z.get(r);o.command=i.command,o.data={id:r,addr:a}}fr(JSON.stringify(o),(e=>Hr(e,(e=>Gr(e)))),(e=>Mr(e)),t.sink)}catch(e){}}),{maxInboundStreams:100,maxOutboundStreams:100,runOnTransientConnection:h}),await this.#V.register(n,{})}async#we(e,t){const r=this.#V.getConnections().map((e=>({id:e.remotePeer.toString(),addr:e.remoteAddr.toString()}))).find((t=>t.id==e)).addr,s=ar(r);let i={protocol:n,command:null,data:null};if("peer-exchange"===t){if(this.#ie.has(e))return;const n=Array.from(this.#z.keys()),r=n[Math.floor(Math.random()*n.length)],s=this.#z.get(r);i.command=t,i.data={id:r,addr:s}}const o=JSON.stringify(i);try{const t=await this.#V.dialProtocol(s,n,{runOnTransientConnection:h}),i=await fr(o,(e=>Hr(e,(e=>Gr(e)))),(e=>Mr(e)),t,(e=>$r(e)),(e=>Hr(e,(e=>jr(e.subarray())))),(async function(e){let t="";for await(const n of e)t+=n.toString();return t})),a=JSON.parse(i);if(a.protocol==n){const t=[r];if(this.#Q.has(e)){const n={addrs:t,last:(new Date).getTime()};this.#Q.set(e,n)}else{this.#$.includes(e)||this.#$.push(e),this.#fe(e);const n={addrs:t,last:(new Date).getTime()};this.#Q.set(e,n),this.#ge()}}if("peer-exchange"==a.command&&null!=a.data){this.#ie.set(e,a.data);let t=[];const n=ar(a.data.addr),r=a.data.id;t.push(n),this.#ye(t),this.#z.has(r)}}catch(e){}}async#Ce(){if(navigator.onLine&&this.#ne&&!(this.#Q.size>5))for(const e of p)if(!this.#me(e)&&!this.#X.has(e)){const t=Is(e);for await(const e of this.#V.services.aminoDHT.findPeer(t))if("FINAL_PEER"===e.name){let t=[],n=[];const r=e.peer.id.toString();for(const s of e.peer.multiaddrs){const e=s.toString()+"/p2p/"+r,i=ar(e);n.push(e),t.push(i)}this.#G.set(r,n),this.#me(r)||this.#ye(t)}}}#Re(){const e=(new Date).getTime();for(const t of this.#Q){const n=t[0],r=e-t[1].last;if(r>2e4&&!this.#me(n)||r>6e4){this.#Q.delete(n),this.#ge(),this.#Pe(n);const e=Object.keys(this.#Y);for(const t of e)if(this.#Y[t].members.includes(n)){const e=this.#Y[t].members.indexOf(n);this.#Y[t].members.splice(e,1),this.#Y[t].onMembers(this.#Y[t].members)}}}}#me(e){let t=[];for(const e of this.#V.getPeers())t.push(e.toString());return!!t.includes(e)}async#ye(e){if(e.length>0){const t=e[0].toString().split("/").pop();if(this.#te.map((e=>e[0].toString().split("/").pop())).includes(t))return;if("connected"===this.status&&d.includes(t))return;const n=this.#Q.size,r=this.#V.getPeers().length,s=r-n,i=15;if(this.#$.includes(t)){if(n>i)return}else if(s>i-5||r>25)return;this.#$.includes(t)||p.includes(t)?this.#te.unshift(e):this.#te.push(e)}}#Ie(){if(!this.#ne||!navigator.onLine||"hidden"===document.visibilityState&&"ontouchstart"in document.documentElement)return;let e=[];for(const t of this.#V.getDialQueue()){const n=t.peerId.string;e.push(n)}if(!(e.length>5))for(let t=0;t<5;t++){const t=this.#te.shift();if(!(null!=t&&t.length>0))break;{const n=t[0].toString().split("/").pop();if(this.#me(n))continue;if(e.includes(n))continue;this.#xe(t),this.#j&&this.#Ne(t)}}}async#he(){const e=s,t=JSON.stringify({prefix:"hybrid",id:this.#V.peerId.toString(),address:this.address}),n={publicKey:this.#V.peerId.publicKey,addrs:[Gr(t)]},r=Gt.encode(n);for(const t of e)await this.#V.services.pubsub.publish(t,r)}async#de(){let e=[];e=o;const n=JSON.stringify({prefix:t,signal:"announce",id:this.#V.peerId.toString(),address:this.address,rooms:Object.keys(this.#Y)}),r={publicKey:this.#V.peerId.publicKey,addrs:[Gr(n)]},s=Gt.encode(r);for(const t of e)await this.#V.services.pubsub.publish(t,s)}async#pe(){let e=[];e=o;const n=JSON.stringify({prefix:t,signal:"ping",id:this.#V.peerId.toString(),address:this.address,rooms:Object.keys(this.#Y)}),r={publicKey:this.#V.peerId.publicKey,addrs:[Gr(n)]},s=Gt.encode(r);for(const t of e)await this.#V.services.pubsub.publish(t,s)}#Se(){setInterval((()=>{const e=f,t=Math.floor(Math.random()*e.length);let n=[];n.push(e[t]);for(const e of p)n.push(e);for(const e of n)if(null!=e&&!this.#me(e))if(this.#X.has(e)){let t=[];const n=ar(this.#X.get(e));t.push(n),this.#ye(t)}else if(this.#G.has(e)){let t=[];const n=this.#G.get(e);for(const e of n){const n=ar(e);t.push(n)}this.#ye(t)}else{const t=g,n=t.findIndex((t=>t.Peers[0].ID==e));if(n>-1){const r=t[n].Peers[0].Addrs;let s=[];for(const t of r){const n=ar(t+"/p2p/"+e);s.push(n)}this.#ye(s)}}}),45e3)}async#Me(){const e=this.#V.getConnections();for(const t of e){const e=t.remotePeer,n=t.remoteAddr,r=t.timeline.upgraded,s=3e5,i=(new Date).getTime();if(i-r>s){const t=n.toString(),r=e.toString();this.#$.includes(r)||f.includes(r)||this.#z.has(r)||t.includes("p2p-circuit")||!t.includes("webtransport")||(await this.#H.put(new Xt(r),(new TextEncoder).encode(t)),this.#z.set(r,t))}if(i-r>6e4){const t=e.toString();this.#W.has(t)||this.#W.set(t,0)}}const t=Array.from(this.#z.keys()),n=(e=>{for(let t=e.length-1;t>0;t--){const n=Math.floor(Math.random()*(t+1));[e[t],e[n]]=[e[n],e[t]]}return e})(t).slice(0,10);for(const e of p)n.includes(e)||t.includes(e)&&n.unshift(e);for(const e of n){const t=this.#z.get(e);if(this.#me(e))this.#Z.set(e,0);else{if(this.#Z.has(e)){let t=this.#Z.get(e);if(t++,this.#Z.set(e,t),t>5){this.#X.has(e)||f.includes(e)||!navigator.onLine||setTimeout((async()=>{this.#z.has(e)&&!this.#X.has(e)&&(this.#z.delete(e),await this.#H.delete(new Xt(e)))}),6e4);continue}}else this.#Z.set(e,0);let n=[];const r=ar(t);n.push(r),this.#ye(n)}}const r=Array.from(this.#W.keys());for(const e of r)if(this.#me(e))this.#W.set(e,0);else{let t=this.#W.get(e);if(t<15||t<25&&this.#G.has(e)){let n=[];const r=ar(this.#X.get(e));n.push(r),this.#ye(n),t++,this.#W.set(e,t)}}}async#Ee(){for await(const{key:e,value:t}of this.#H.query({})){const n=e.toString().split("/")[1],r=(new TextDecoder).decode(t);this.#z.set(n,r)}this.#Me(),setInterval((async()=>{this.#Me()}),15e3)}#ve(){setInterval((()=>{0==this.#V.getPeers().length&&this.#be()}),12e4)}#be(){setTimeout((()=>{this.#Oe(),setTimeout((()=>{this.#Le()}),2e4),setTimeout((()=>{this.#Ce()}),3e4),setTimeout((()=>{0==this.#V.getPeers().length&&(this.#Be(),setTimeout((()=>{this.#Ce()}),3e4),setTimeout((()=>{0==this.#V.getPeers().length&&(this.#Ue(),setTimeout((()=>{this.#Ce()}),15e3),setTimeout((()=>{0==this.#V.getPeers().length&&(this.#Fe(),setTimeout((()=>{this.#Ce()}),15e3),setTimeout((()=>{0==this.#V.getPeers().length&&(this.#Ve(),setTimeout((()=>{this.#Ce()}),15e3))}),u))}),u))}),u))}),u)}),5e3)}async#Oe(){if(!navigator.onLine)return;if(!this.#ne)return;let e=!0;for(const t of f)if(this.#z.has(t)){e=!1;let n=[],r=[];const s=t,i=this.#z.get(t),o=ar(i);r.push(i),n.push(o),this.#G.set(s,r),this.#me(s)||this.#ye(n)}if(e)for(const e of f){const t=qh(a),n=await Yr(t.getPeers(Is(e)));if(!n)continue;const r=n.Addrs,s=n.ID;let i=[],o=[];for(const e of r){const t=e.toString()+"/p2p/"+s.toString(),n=ar(t);o.push(t),i.push(n)}this.#G.set(s,o),this.#me(s)||this.#ye(i)}}async#Le(){if(!navigator.onLine)return;if(!this.#ne)return;let e=!0;for(const t of f)if(this.#z.has(t)&&(e=!1),!this.#X.has(t)&&(this.#z.has(t)||e)){const e=qh(a),n=await Yr(e.getPeers(Is(t)));if(!n){navigator.onLine&&await this.#H.delete(new Xt(t));continue}const r=n.Addrs,s=n.ID;let i=[],o=[];for(const e of r){const t=e.toString()+"/p2p/"+s.toString(),n=ar(t);o.push(t),i.push(n)}this.#G.set(s,o),this.#me(s)||this.#ye(i)}}async#Be(){if(!navigator.onLine)return;if(!this.#ne)return;const e=qh(a),t=f,n=await Promise.all(t.map((t=>Yr(e.getPeers(Is(t))))));for(const e of n){if(!e)return;const t=e.Addrs,n=e.ID;let r=[],s=[];for(const e of t){const t=e.toString()+"/p2p/"+n.toString(),i=ar(t);s.push(t),r.push(i)}this.#G.set(n,s),this.#me(n)||this.#ye(r)}}#Ue(){if(!navigator.onLine)return;if(!this.#ne)return;const e=g;for(const t of e){const e=t.Peers[0].Addrs,n=t.Peers[0].ID;let r=[],s=[];for(const t of e){if(!t.includes("wss"))continue;const e=t+"/p2p/"+n,i=ar(e);s.push(e),r.push(i)}this.#G.set(n,s),this.#j=!0,this.#le(!0),this.#me(n)||this.#ye(r)}}async#Fe(){if(!navigator.onLine)return;if(!this.#ne)return;const e=c,t=l,n=await fetch(e+"?name="+t+"&type=txt"),r=(await n.json()).Answer,s=[];for(const e of r){const t=e.data.split("/").pop();s.push(t)}const i=qh(a),o=await Promise.all(s.map((e=>Yr(i.getPeers(Is(e))))));for(const e of o){const t=e.Addrs,n=e.ID;let r=[],s=[];for(const e of t){const t=e.toString()+"/p2p/"+n.toString(),i=ar(t);s.push(t),r.push(i)}this.#G.set(n,s),this.#j=!0,this.#le(!0),this.#me(n)||this.#ye(r)}}async#Ve(){if(console.log("#dialKnownDNSonly()"),!navigator.onLine)return;if(!this.#ne)return;const e=c,t=l,n=await fetch(e+"?name="+t+"&type=txt"),r=(await n.json()).Answer;for(const e of r){const t=e.data.split("/"),n=t.pop(),r="_dnsaddr."+t[2];this.#Ke(n,r)}}async#Ke(e,t){const n=c,r=await fetch(n+"?name="+t+"&type=txt"),s=(await r.json()).Answer;let i=[],o=[];for(const e of s){const t=e.data.split("=")[1],n=ar(t);i.push(n),o.push(t)}this.#j=!0,this.#le(!0),this.#G.set(e,o),this.#G.set(e,o),this.#me(e)||(this.#ye(i),this.#Ne(i))}async#xe(e){const t=e.filter((e=>e.protoNames().includes("webtransport")&&e.protoNames().includes("certhash")));for(const e of t)try{return void await this.#V.dial(e)}catch(e){}}async#Ne(e){const t=e.filter((e=>e.protoNames().includes("wss")));for(const e of t)try{return void await this.#V.dial(e)}catch(e){}}static async createWebpeer(){const e=new _g(r);await e.open();const t=g;for(const e of t){const t=e.Peers[0].Addrs;e.Peers[0].ID;for(const e of t)e.includes("webtransport")&&e.includes("certhash")}let n=()=>{};let s=!1,o=()=>{};o=e=>{s=e};let a=!0,c=()=>{};(e=>{c=e})((e=>{a=e}));let l=[];l.push("/webrtc");const u="stun:stun.l.google.com:19302",d="stun:global.stun.twilio.com:3478",p=atob("dHVybjp0dXJuMDEuYnJpZS5maTo1MzQ5"),f=atob("YnJpZQ=="),m=atob("Zmk="),y=atob("dHVybjpyZWxheTEuZXhwcmVzc3R1cm4uY29tOjM0Nzg="),w=atob("ZWZJSllZNjdDNElRMzFZQUlP"),b=atob("Vk01SmdhODlkYjJaWU9aSA==");async function v(e,t,n,r,s){return new Promise((i=>{let o=!1,a=!1;const c=setTimeout((()=>{let e=[];e.push(o),e.push(a),i(e)}),s);function l(){if(o&&a){let e=[];e.push(o),e.push(a),clearTimeout(c),i(e)}}const u=new RTCPeerConnection({iceServers:[{urls:e},{urls:t,username:n,credential:r}]});u.onicecandidate=s=>{s.candidate&&("srflx"==s.candidate.type&&(o={urls:e},l()),"relay"==s.candidate.type&&(a={urls:t,username:n,credential:r},l()))},u.onicecandidateerror=e=>{console.debug(e)},u.createDataChannel("webpeerjs"),u.createOffer().then((e=>u.setLocalDescription(e)))}))}let E=[],S={};arguments.length>0&&(S=arguments[0]),void 0===S.rtcConfiguration&&(E=await v(u,p,f,m,5e3),E[0]||E[1]?E[0]&&!E[1]?E=await v(u,y,w,b,5e3):!E[0]&&E[1]&&(E=await v(d,p,f,m,5e3)):E=await v(d,y,w,b,5e3),E.forEach((function(e,t){e||this.splice(t,1)}),E),S.rtcConfiguration={iceServers:E});const _=await async function(e={}){const t=await Xf(e);return!1!==e.start&&await t.start(),t}({addresses:{listen:l},transports:[zm(),Jy(),(I={rtcConfiguration:S.rtcConfiguration},e=>new Nw(e,I)),Kb({discoverRelays:1,reservationConcurrency:1,maxReservationQueueLength:3})],connectionManager:{maxConnections:30,minConnections:0,autoDialInterval:6e4,autoDialConcurrency:0,autoDialMaxQueueLength:0,autoDialPriority:1e3,autoDialDiscoveredPeersDebounce:6e4,maxParallelDials:3,dialTimeout:5e3,maxIncomingPendingConnections:5,maxDialQueueLength:10,inboundConnectionThreshold:3,maxPeerAddrsToDial:2,inboundUpgradeTimeout:5e3},connectionEncryption:[Nm()],streamMuxers:[gb({maxInboundStreams:100,maxOutboundStreams:100})],connectionGater:{filterMultiaddrForPeer:async(e,t)=>{const n=t.toString();return!n.includes("/ip4/127.0.0.1")&&!n.includes("/ip6/")&&(n.includes("/ws/")||n.includes("/wss/")?s:a)},denyDialMultiaddr:async e=>{const t=e.toString();return!(!t.includes("/ip4/127.0.0.1")&&!t.includes("/ip6/"))||(t.includes("/ws/")||t.includes("/wss/")?!s:!a)}},peerDiscovery:[bb({interval:5e3,topics:i,listenOnly:!1})],services:{pubsub:Bv({allowPublishToZeroTopicPeers:!0,msgIdFn:Jr,ignoreDuplicatePublishError:!0,runOnTransientConnection:h}),identify:Hv(),identifyPush:zv(),aminoDHT:iS({protocol:"/ipfs/kad/1.0.0",peerInfoMapper:bE,clientMode:!1}),dcutr:$w()},peerStore:{persistence:!0,threshold:1},metrics:uS({onMetrics:e=>{n(e)},intervalMs:1e3})});var I;return await _.services.aminoDHT.setMode("server"),new hS(_,e,(e=>n=e),o,c)}}
85
85
  //! WebPEER.js -- https://github.com/nuzulul/webpeerjs
86
86
  return hS}));