helia 1.1.2 → 1.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +2 -2
- package/src/version.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -81,7 +81,7 @@ a=ice-ufrag:`+e+`
|
|
|
81
81
|
`).replace(/\na=ice-pwd:[^\n]*\n/,`
|
|
82
82
|
a=ice-pwd:`+e+`
|
|
83
83
|
`),r}var hR=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),fR=r=>[...Array(r)].map(()=>hR.at(Math.floor(Math.random()*hR.length))).join("");var z1=D("libp2p:webrtc:transport"),dH=1e4,pH=X("webrtc-direct").code,L8=X("certhash").code,H1=class{metrics;components;init;constructor(e,t={}){this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dial events by type"})})}async dial(e,t){let n=await this._connect(e,t);return z1(`dialing address - ${e.toString()}`),n}createListener(e){throw vS("WebRTCTransport.createListener")}filter(e){return e.filter(mH)}[Symbol.toStringTag]="@libp2p/webrtc-direct";[Pi]=!0;async _connect(e,t){let n=new AbortController,i=n.signal,s=e.getPeerId();if(s===null)throw A1("we need to have the remote's PeerId");let o=oe(s),a=k8(V1(e)),c=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:N8(a.name)}),u=new RTCPeerConnection({certificates:[c]}),l=new Promise((P,M)=>{let W=u.createDataChannel("",{negotiated:!0,id:0}),ue=setTimeout(()=>{let le=`Data channel was never opened: state: ${W.readyState}`;z1.error(le),this.metrics?.dialerEvents.increment({open_error:!0}),M($4("data",le))},dH);W.onopen=le=>{clearTimeout(ue),P(W)},W.onerror=le=>{clearTimeout(ue);let Ve=`Error opening a data channel for handshaking: ${le.target?.toString()??"not specified"}`;z1.error(Ve),this.metrics?.dialerEvents.increment({unknown_error:!0}),M($4("data",Ve))}}),h="libp2p+webrtc+v1/"+fR(32),f=await u.createOffer(),d=lR(f,h);await u.setLocalDescription(d);let p=uR(e,h);await u.setRemoteDescription(p);let m=await l,g=this.components.peerId,y=this.generateNoisePrologue(u,a.code,e),b=O0({prologueBytes:y})(),E=Tc({channel:m,direction:"inbound",dataChannelOptions:this.init.dataChannel}),R={...E,sink:E.sink.bind(E),source:async function*(){for await(let P of E.source)for(let M of P)yield M}()},v=new Qo({peerConnection:u,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),_=kl?"iceconnectionstatechange":"connectionstatechange";u.addEventListener(_,()=>{switch(u.connectionState){case"failed":case"disconnected":case"closed":v.close().catch(P=>{z1.error("error closing connection",P)}).finally(()=>{n.abort()});break;default:break}},{signal:i}),this.metrics?.dialerEvents.increment({peer_connection:!0});let I=new Xo({peerConnection:u,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await b.secureInbound(g,R,o),t.upgrader.upgradeOutbound(v,{skipProtection:!0,skipEncryption:!0,muxerFactory:I})}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw Pl("no local certificate");let i=cR(e);if(i==null)throw Pl("no local fingerprint found");let s=i.trim().toLowerCase().replaceAll(":",""),o=q(s,"hex"),a=dR.encode(o,t),c=P8.decode(V1(n)),u=q("libp2p-webrtc-noise:");return he([u,a,c])}};function mH(r){let e=r.protoCodes();return e.includes(pH)&&e.includes(L8)&&r.getPeerId()!=null&&!e.includes(X("p2p-circuit").code)}function pR(r){return e=>new H1(e,r)}function mR(r){return e=>new P1(e,r)}var gR=WebSocket;var ER=F(wR(),1);function bR(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var vR=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((s,o)=>{if(n){s();return}if(i!=null){o(i);return}let a=l=>{r.removeEventListener("open",c),r.removeEventListener("error",u),l()},c=()=>{a(s)},u=l=>{a(()=>{o(l.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",u)})},t=async function*(){let s=new ER.EventIterator(({push:o,stop:a,fail:c})=>{let u=h=>{let f=null;typeof h.data=="string"&&(f=q(h.data)),bR(h.data)&&(f=new Uint8Array(h.data)),h.data instanceof Uint8Array&&(f=h.data),f!=null&&o(f)},l=h=>{c(h.error??new Error("Socket error"))};return r.addEventListener("message",u),r.addEventListener("error",l),r.addEventListener("close",a),()=>{r.removeEventListener("message",u),r.removeEventListener("error",l),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let o of s)yield bR(o)?new Uint8Array(o):o}(),n=r.readyState===1,i;return r.addEventListener("open",()=>{n=!0,i=null}),r.addEventListener("close",()=>{n=!1,i=null}),r.addEventListener("error",s=>{n||(i=s.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var xR=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",i),r.removeEventListener("error",s)}function i(){n(),e()}function s(o){n(),t(o.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",i),r.addEventListener("error",s)})};var _R=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let i of n){try{await xR(r)}catch(s){if(s.message==="socket closed")break;throw s}r.send(i)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((i,s)=>{r.addEventListener("close",o=>{if(o.wasClean||o.code===1006)i();else{let a=Object.assign(new Error("ws error"),{event:o});s(a)}}),setTimeout(()=>{r.close()})})});var SR=(r,e)=>{e=e??{};let t=vR(r),n=e.remoteAddress,i=e.remotePort;if(r.url!=null)try{let o=new URL(r.url);n=o.hostname,i=parseInt(o.port,10)}catch{}if(n==null||i==null)throw new Error("Remote connection did not have address and/or port");return{sink:_R(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(o=>{r.addEventListener("close",()=>{o()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:i,socket:r}};var kR=F(PR(),1),RH={http:"ws",https:"wss"},IH="ws",NR=(r,e)=>(0,kR.relative)(r,e,RH,IH);function LR(r,e){let t=typeof window>"u"?"":window.location;e=e??{};let n=NR(r,t.toString()),i=new gR(n,e.websocket);return SR(i,e)}function OR(r){let e;try{e=X("sni").code}catch{return null}for(let[t,n]of r)if(t===e&&n!==void 0)return n;return null}function BR(r){return r.some(([e,t])=>e===X("tls").code)}function gn(r,e,t){let n=MR[X(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${X(r).name}`);let i=n(e,t);return r===X("ip6").code?`[${i}]`:i}var MR={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${gn(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${gn(t[0],t[1]??"",e)}:${r}`},dnsaddr:(r,e)=>r,dns4:(r,e)=>r,dns6:(r,e)=>r,dns:(r,e)=>r,ipfs:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${gn(t[0],t[1]??"",e)}/ipfs/${r}`},p2p:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${gn(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=BR(e),n=OR(e);if(t&&n!==null)return`https://${n}`;let i=t?"https://":"http://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let o=gn(s[0],s[1]??"",e);return o=o.replace("tcp://",""),`${i}${o}`},tls:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return gn(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return gn(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=gn(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=BR(e),n=OR(e);if(t&&n!==null)return`wss://${n}`;let i=t?"wss://":"ws://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let o=gn(s[0],s[1]??"",e);return o=o.replace("tcp://",""),`${i}${o}`},wss:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=gn(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${gn(t[0],t[1]??"",e)}/p2p-websocket-star`},"p2p-webrtc-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${gn(t[0],t[1]??"",e)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${gn(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function UR(r,e){let n=re(r).stringTuples(),i=n.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let s=X(i[0]),o=MR[s.name];if(o==null)throw new Error(`No interpreter found for ${s.name}`);let a=o(i[1]??"",n);return e?.assumeHttp!==!1&&i[0]===X("tcp").code&&(a=a.replace("tcp://","http://"),(i[1]==="443"||i[1]==="80")&&(i[1]==="443"&&(a=a.replace("http://","https://")),a=a.substring(0,a.lastIndexOf(":")))),a}var qR=F(KR(),1),F8=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,W1=(0,qR.default)(),Y1=F8&&!W1,VR=W1&&!F8,zR=W1&&F8,HR=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!W1,Q1=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,O2e=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+(()=>"_")()+"ENV"]==="test",$R=typeof navigator<"u"&&navigator.product==="ReactNative";function GR(){throw new Error("WebSocket Servers can not be created in the browser!")}var K8=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},q8=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},WR=r=>globalThis.DOMException===void 0?new q8(r):new DOMException(r),YR=r=>{let e=r.reason===void 0?WR("This operation was aborted."):r.reason;return e instanceof Error?e:WR(e)};function V8(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:s={setTimeout,clearTimeout}}=e,o,a=new Promise((c,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(t===Number.POSITIVE_INFINITY){c(r);return}if(e.signal){let{signal:h}=e;h.aborted&&u(YR(h)),h.addEventListener("abort",()=>{u(YR(h))})}let l=new K8;o=s.setTimeout.call(void 0,()=>{if(n){try{c(n())}catch(h){u(h)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?c():i instanceof Error?u(i):(l.message=i??`Promise timed out after ${t} milliseconds`,u(l))},t),(async()=>{try{c(await r)}catch(h){u(h)}finally{s.clearTimeout.call(void 0,o)}})()});return a.clear=()=>{s.clearTimeout.call(void 0,o),o=void 0},a}var QR=D("libp2p:websockets:socket");function XR(r,e,t){t=t??{};let n={async sink(i){t?.signal!=null&&(i=lt(i,t.signal));try{await r.sink(i)}catch(s){s.type!=="aborted"&&QR.error(s)}},source:t.signal!=null?lt(r.source,t.signal):r.source,remoteAddr:e,timeline:{open:Date.now()},async close(){let i=Date.now();try{await V8(r.close(),{milliseconds:2e3})}catch{let{host:o,port:a}=n.remoteAddr.toOptions();QR("timeout closing stream to %s:%s after %dms, destroying it manually",o,a,Date.now()-i),r.destroy()}finally{n.timeline.close=Date.now()}}};return r.socket.addEventListener("close",()=>{n.timeline.close==null&&(n.timeline.close=Date.now())},{once:!0}),n}function JR(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return zo.matches(t)||Js.matches(t)})}function eI(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Js.matches(t)})}var ao=D("libp2p:websockets"),z8=class{constructor(e){this.init=e}get[Symbol.toStringTag](){return"@libp2p/websockets"}get[Pi](){return!0}async dial(e,t){ao("dialing %s",e),t=t??{};let n=await this._connect(e,t),i=XR(n,e);ao("new outbound connection %s",i.remoteAddr);let s=await t.upgrader.upgradeOutbound(i);return ao("outbound connection %s upgraded",i.remoteAddr),s}async _connect(e,t){if(t?.signal?.aborted===!0)throw new Xr;let n=e.toOptions();ao("dialing %s:%s",n.host,n.port);let i=Me(),s=u=>{ao.error("connection error:",u),i.reject(u)},o=LR(UR(e),this.init);if(o.socket.on!=null?o.socket.on("error",s):o.socket.onerror=s,t.signal==null)return await Promise.race([o.connected(),i.promise]),ao("connected %s",e),o;let a,c=new Promise((u,l)=>{if(a=()=>{l(new Xr),o.close().catch(h=>{ao.error("error closing raw socket",h)})},t?.signal?.aborted===!0){a();return}t?.signal?.addEventListener("abort",a)});try{await Promise.race([c,i.promise,o.connected()])}finally{a!=null&&t?.signal?.removeEventListener("abort",a)}return ao("connected %s",e),o}createListener(e){return GR({...this.init,...e})}filter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):Y1||Q1?eI(e):JR(e)}};function tI(r={}){return()=>new z8(r)}function X1(r){return r[Symbol.asyncIterator]!=null}var j1=r=>{let e=ct.encodingLength(r),t=Tr(e);return ct.encode(r,t),j1.bytes=e,t};j1.bytes=0;function Z1(r,e){e=e??{};let t=e.lengthEncoder??j1;function*n(i){let s=t(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return X1(r)?async function*(){for await(let i of r)yield*n(i)}():function*(){for(let i of r)yield*n(i)}()}Z1.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??j1;return new j(t(r.byteLength),r)};var Uc=F(ms(),1);var PH=8,kH=1024*1024*4,ea;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ea||(ea={}));var $8=r=>{let e=ct.decode(r);return $8.bytes=ct.encodingLength(e),e};$8.bytes=0;function H8(r,e){let t=new j,n=ea.LENGTH,i=-1,s=e?.lengthDecoder??$8,o=e?.maxLengthLength??PH,a=e?.maxDataLength??kH;function*c(){for(;t.byteLength>0;){if(n===ea.LENGTH)try{if(i=s(t),i<0)throw(0,Uc.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,Uc.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(i),n=ea.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>o)throw(0,Uc.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===ea.DATA){if(t.byteLength<i)break;let u=t.sublist(0,i);t.consume(i),e?.onData!=null&&e.onData(u),yield u,n=ea.LENGTH}}}return X1(r)?async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,Uc.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw(0,Uc.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}H8.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:o}=await r.next(t);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return H8(n,{...e??{},onLength:s=>{t=s}})};var J1=F(ms(),1),rI=r=>ct.decode(r);rI.bytes=0;function G8(r,e={}){let t=tt();r.sink(t).catch(o=>{t.end(o)}),r.sink=async o=>{for await(let a of o)t.push(a)};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let i=new j,s={read:async o=>{if(o==null){let{done:c,value:u}=await n.next();return c===!0?new j:u}for(;i.byteLength<o;){let{value:c,done:u}=await n.next();if(u===!0)throw(0,J1.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF");i.append(c)}let a=i.sublist(0,o);return i.consume(o),a},readLP:async()=>{let o=-1,a=new j,c=e?.lengthDecoder??rI;for(;;){a.append(await s.read(1));try{o=c(a)}catch(u){if(u instanceof RangeError)continue;throw u}if(o>-1)break;if(e?.maxLengthLength!=null&&a.byteLength>e.maxLengthLength)throw(0,J1.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG")}if(e?.maxDataLength!=null&&o>e.maxDataLength)throw(0,J1.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");return await s.read(o)},readPB:async o=>{let a=await s.readLP();if(a==null)throw new Error("Value is null");let c=a instanceof Uint8Array?a:a.subarray();return o.decode(c)},write:o=>{o instanceof Uint8Array?t.push(o):t.push(o.subarray())},writeLP:o=>{s.write(Z1.single(o,e))},writePB:(o,a)=>{s.writeLP(a.encode(o))},pb:o=>({read:async()=>await s.readPB(o),write:a=>{s.writePB(a,o)},unwrap:()=>s}),unwrap:()=>{let o=r.source;return r.source=async function*(){yield*i,yield*o}(),r}};return s}async function*W8(...r){let e=tt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async t=>{for await(let n of t)e.push(n)})),e.end()}catch(t){e.end(t)}}),yield*e}var LH=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},nI=r=>r!=null&&(typeof r[Symbol.asyncIterator]=="function"||typeof r[Symbol.iterator]=="function"||typeof r.next=="function"),Y8=r=>r!=null&&typeof r.sink=="function"&&nI(r.source),OH=r=>e=>{let t=r.sink(e);if(t.then!=null){let n=tt({objectMode:!0});return t.then(()=>{n.end()},s=>{n.end(s)}),W8(n,async function*(){yield*r.source,n.end()}())}return r.source};function iI(r,...e){if(Y8(r)){let n=r;r=()=>n.source}else if(nI(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Y8(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)Y8(t[n])&&(t[n]=OH(t[n]));return LH(...t)}function sI(r){return globalThis?.Buffer?.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}var ed=r=>{let e=ct.encodingLength(r),t=sI(e);return ct.encode(r,t),ed.bytes=e,t};ed.bytes=0;function oI(r){r=r??{};let e=r.lengthEncoder??ed;return async function*(n){for await(let i of n){let s=e(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}}}oI.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??ed;return new j(t(r.byteLength),r)};var Vl=F(ms(),1),BH=8,MH=1024*1024*4,ta;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ta||(ta={}));var Q8=r=>{let e=ct.decode(r);return Q8.bytes=ct.encodingLength(e),e};Q8.bytes=0;function zl(r){return async function*(t){let n=new j,i=ta.LENGTH,s=-1,o=r?.lengthDecoder??Q8,a=r?.maxLengthLength??BH,c=r?.maxDataLength??MH;for await(let u of t)for(n.append(u);n.byteLength>0;){if(i===ta.LENGTH)try{if(s=o(n),s<0)throw(0,Vl.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>c)throw(0,Vl.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let l=o.bytes;n.consume(l),r?.onLength!=null&&r.onLength(s),i=ta.DATA}catch(l){if(l instanceof RangeError){if(n.byteLength>a)throw(0,Vl.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw l}if(i===ta.DATA){if(n.byteLength<s)break;let l=n.sublist(0,s);n.consume(s),r?.onData!=null&&r.onData(l),yield l,i=ta.LENGTH}}if(n.byteLength>0)throw(0,Vl.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}}zl.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:o}=await r.next(t);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return zl({...e??{},onLength:s=>{t=s}})(n)};var aI=!!globalThis.process?.env?.DUMP_SESSION_KEYS;var gI=F(dI(),1),Fc=F(Rm(),1),nd=F(mI(),1),J8=F(ul(),1),yI={hashSHA256(r){return(0,nd.hash)(r)},getHKDF(r,e){let i=new gI.HKDF(nd.SHA256,e,r).expand(96),s=i.subarray(0,32),o=i.subarray(32,64),a=i.subarray(64,96);return[s,o,a]},generateX25519KeyPair(){let r=Fc.generateKeyPair();return{publicKey:r.publicKey,privateKey:r.secretKey}},generateX25519KeyPairFromSeed(r){let e=Fc.generateKeyPairFromSeed(r);return{publicKey:e.publicKey,privateKey:e.secretKey}},generateX25519SharedKey(r,e){return Fc.sharedKey(r,e)},chaCha20Poly1305Encrypt(r,e,t,n){return new J8.ChaCha20Poly1305(n).seal(e,r,t)},chaCha20Poly1305Decrypt(r,e,t,n,i){return new J8.ChaCha20Poly1305(n).open(e,r,t,i)}};var e5=F(ul(),1);var $H=r=>globalThis.Buffer?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r),Kc=r=>{let e=$H(2);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(0,r,!1),e};Kc.bytes=2;var $l=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");return r instanceof Uint8Array?new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,!1):r.getUint16(0)};$l.bytes=2;function wI(r){return he([r.ne,r.ciphertext],r.ne.length+r.ciphertext.length)}function bI(r){return he([r.ne,r.ns,r.ciphertext],r.ne.length+r.ns.length+r.ciphertext.length)}function EI(r){return he([r.ns,r.ciphertext],r.ns.length+r.ciphertext.length)}function vI(r){if(r.length<32)throw new Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");return{ne:r.subarray(0,32),ciphertext:r.subarray(32,r.length),ns:new Uint8Array(0)}}function xI(r){if(r.length<80)throw new Error("Cannot decode stage 1 MessageBuffer: length less than 80 bytes.");return{ne:r.subarray(0,32),ns:r.subarray(32,80),ciphertext:r.subarray(80,r.length)}}function _I(r){if(r.length<48)throw new Error("Cannot decode stage 2 MessageBuffer: length less than 48 bytes.");return{ne:new Uint8Array(0),ns:r.subarray(0,48),ciphertext:r.subarray(48,r.length)}}function AI(r,e){return async function*(t){for await(let n of t)for(let i=0;i<n.length;i+=65519){let s=i+65519;s>n.length&&(s=n.length);let o=r.encrypt(n.subarray(i,s),r.session);e?.encryptedPackets.increment(),yield Kc(o.byteLength),yield o}}}function RI(r,e){return async function*(t){for await(let n of t)for(let i=0;i<n.length;i+=65535){let s=i+65535;if(s>n.length&&(s=n.length),s-e5.TAG_LENGTH<i)throw new Error("Invalid chunk");let o=n.subarray(i,s),a=n.subarray(i,s-e5.TAG_LENGTH),{plaintext:c,valid:u}=r.decrypt(o,r.session,a);if(!u)throw e?.decryptErrors.increment(),new Error("Failed to validate decrypted chunk");e?.decryptedPackets.increment(),yield c}}}var ra=class extends Error{constructor(e="Unexpected Peer"){super(e),this.code=ra.code}static get code(){return"ERR_UNEXPECTED_PEER"}},hs=class extends Error{constructor(e="Invalid crypto exchange"){super(e),this.code=hs.code}static get code(){return"ERR_INVALID_CRYPTO_EXCHANGE"}};var id;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let s of t.webtransportCerthashes)n.uint32(10),n.bytes(s);i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={webtransportCerthashes:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.webtransportCerthashes.push(t.bytes());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(id||(id={}));var Wl;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||t.identityKey!=null&&t.identityKey.byteLength>0)&&(n.uint32(10),n.bytes(t.identityKey??new Uint8Array(0))),(i.writeDefaults===!0||t.identitySig!=null&&t.identitySig.byteLength>0)&&(n.uint32(18),n.bytes(t.identitySig??new Uint8Array(0))),t.extensions!=null&&(n.uint32(34),id.codec().encode(t.extensions,n,{writeDefaults:!1})),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={identityKey:new Uint8Array(0),identitySig:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.identityKey=t.bytes();break;case 2:i.identitySig=t.bytes();break;case 4:i.extensions=id.codec().decode(t,t.uint32());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(Wl||(Wl={}));async function II(r,e,t){let n=await WH(r,TI(e));if(r.publicKey==null)throw new Error("PublicKey was missing from local PeerId");return GH(r.publicKey,n,t)}function GH(r,e,t){return Wl.encode({identityKey:r,identitySig:e,extensions:t??{webtransportCerthashes:[]}}).subarray()}async function WH(r,e){if(r.privateKey==null)throw new Error("PrivateKey was missing from PeerId");return await(await cn(r.privateKey)).sign(e)}async function t5(r){return await er(r.identityKey)}function r5(r){return Wl.decode(r)}function TI(r){let e=q("noise-libp2p-static-key:");return he([e,r],e.length+r.length)}async function n5(r,e,t){let n=await er(e.identityKey);if(!n.equals(t))throw new Error(`Payload identity key ${n.toString()} does not match expected remote peer ${t.toString()}`);let i=TI(r);if(n.publicKey==null)throw new Error("PublicKey was missing from PeerId");if(e.identitySig==null)throw new Error("Signature was missing from message");if(!await kr(n.publicKey).verify(i,e.identitySig))throw new Error("Static key doesn't match to peer that signed payload!");return n}function Yl(r){return!(!(r instanceof Uint8Array)||r.length!==32)}var ar=D("libp2p:noise");var Bn;aI?Bn=ar:Bn=Object.assign(()=>{},{enabled:!1,trace:()=>{},error:()=>{}});function DI(r){Bn(`LOCAL_STATIC_PUBLIC_KEY ${B(r.publicKey,"hex")}`),Bn(`LOCAL_STATIC_PRIVATE_KEY ${B(r.privateKey,"hex")}`)}function i5(r){r?(Bn(`LOCAL_PUBLIC_EPHEMERAL_KEY ${B(r.publicKey,"hex")}`),Bn(`LOCAL_PRIVATE_EPHEMERAL_KEY ${B(r.privateKey,"hex")}`)):Bn("Missing local ephemeral keys.")}function CI(r){Bn(`REMOTE_STATIC_PUBLIC_KEY ${B(r,"hex")}`)}function s5(r){Bn(`REMOTE_EPHEMERAL_PUBLIC_KEY ${B(r,"hex")}`)}function PI(r){r.cs1&&r.cs2?(Bn(`CIPHER_STATE_1 ${r.cs1.n.getUint64()} ${B(r.cs1.k,"hex")}`),Bn(`CIPHER_STATE_2 ${r.cs2.n.getUint64()} ${B(r.cs2.k,"hex")}`)):Bn("Missing cipher state.")}var YH="Cipherstate has reached maximum n, a new handshake must be performed",sd=class{constructor(e=0){this.n=e,this.bytes=new Uint8Array(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw new Error(YH)}};var od=class{constructor(e){this.crypto=e}encryptWithAd(e,t,n){let i=this.encrypt(e.k,e.n,t,n);return e.n.increment(),i}decryptWithAd(e,t,n,i){let{plaintext:s,valid:o}=this.decrypt(e.k,e.n,t,n,i);return o&&e.n.increment(),{plaintext:s,valid:o}}hasKey(e){return!this.isEmptyKey(e.k)}createEmptyKey(){return new Uint8Array(32)}isEmptyKey(e){let t=this.createEmptyKey();return pe(t,e)}encrypt(e,t,n,i){return t.assertValue(),this.crypto.chaCha20Poly1305Encrypt(i,t.getBytes(),n,e)}encryptAndHash(e,t){let n;return this.hasKey(e.cs)?n=this.encryptWithAd(e.cs,e.h,t):n=t,this.mixHash(e,n),n}decrypt(e,t,n,i,s){t.assertValue();let o=this.crypto.chaCha20Poly1305Decrypt(i,t.getBytes(),n,e,s);return o?{plaintext:o,valid:!0}:{plaintext:new Uint8Array(0),valid:!1}}decryptAndHash(e,t){let n,i=!0;return this.hasKey(e.cs)?{plaintext:n,valid:i}=this.decryptWithAd(e.cs,e.h,t):n=t,this.mixHash(e,t),{plaintext:n,valid:i}}dh(e,t){try{let n=this.crypto.generateX25519SharedKey(e,t);return n.length===32?n:n.subarray(0,32)}catch(n){let i=n;return ar.error(i),new Uint8Array(32)}}mixHash(e,t){e.h=this.getHash(e.h,t)}getHash(e,t){return this.crypto.hashSHA256(he([e,t],e.length+t.length))}mixKey(e,t){let[n,i]=this.crypto.getHKDF(e.ck,t);e.cs=this.initializeKey(i),e.ck=n}initializeKey(e){return{k:e,n:new sd}}initializeSymmetric(e){let t=q(e,"utf-8"),n=this.hashProtocolName(t),i=n,s=this.createEmptyKey();return{cs:this.initializeKey(s),ck:i,h:n}}hashProtocolName(e){if(e.length<=32){let t=new Uint8Array(32);return t.set(e),t}else return this.getHash(e,new Uint8Array(0))}split(e){let[t,n]=this.crypto.getHKDF(e.ck,new Uint8Array(0)),i=this.initializeKey(t),s=this.initializeKey(n);return{cs1:i,cs2:s}}writeMessageRegular(e,t){let n=this.encryptWithAd(e,new Uint8Array(0),t),i=this.createEmptyKey(),s=new Uint8Array(0);return{ne:i,ns:s,ciphertext:n}}readMessageRegular(e,t){return this.decryptWithAd(e,new Uint8Array(0),t.ciphertext)}};var ad=class extends od{initializeInitiator(e,t,n,i){let s="Noise_XX_25519_ChaChaPoly_SHA256",o=this.initializeSymmetric(s);this.mixHash(o,e);let a=new Uint8Array(32);return{ss:o,s:t,rs:n,psk:i,re:a}}initializeResponder(e,t,n,i){let s="Noise_XX_25519_ChaChaPoly_SHA256",o=this.initializeSymmetric(s);this.mixHash(o,e);let a=new Uint8Array(32);return{ss:o,s:t,rs:n,psk:i,re:a}}writeMessageA(e,t,n){let i=new Uint8Array(0);n!==void 0?e.e=n:e.e=this.crypto.generateX25519KeyPair();let s=e.e.publicKey;this.mixHash(e.ss,s);let o=this.encryptAndHash(e.ss,t);return{ne:s,ns:i,ciphertext:o}}writeMessageB(e,t){e.e=this.crypto.generateX25519KeyPair();let n=e.e.publicKey;this.mixHash(e.ss,n),this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let i=e.s.publicKey,s=this.encryptAndHash(e.ss,i);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let o=this.encryptAndHash(e.ss,t);return{ne:n,ns:s,ciphertext:o}}writeMessageC(e,t){let n=e.s.publicKey,i=this.encryptAndHash(e.ss,n);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let s=this.encryptAndHash(e.ss,t),a={ne:this.createEmptyKey(),ns:i,ciphertext:s},{cs1:c,cs2:u}=this.split(e.ss);return{h:e.ss.h,messageBuffer:a,cs1:c,cs2:u}}readMessageA(e,t){return Yl(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),this.decryptAndHash(e.ss,t.ciphertext)}readMessageB(e,t){if(Yl(t.ne)&&(e.re=t.ne),this.mixHash(e.ss,e.re),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let{plaintext:n,valid:i}=this.decryptAndHash(e.ss,t.ns);i&&Yl(n)&&(e.rs=n),this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:s,valid:o}=this.decryptAndHash(e.ss,t.ciphertext);return{plaintext:s,valid:i&&o}}readMessageC(e,t){let{plaintext:n,valid:i}=this.decryptAndHash(e.ss,t.ns);if(i&&Yl(n)&&(e.rs=n),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:s,valid:o}=this.decryptAndHash(e.ss,t.ciphertext),{cs1:a,cs2:c}=this.split(e.ss);return{h:e.ss.h,plaintext:s,valid:i&&o,cs1:a,cs2:c}}initSession(e,t,n){let i=this.createEmptyKey(),s=new Uint8Array(32),o;return e?o=this.initializeInitiator(t,n,s,i):o=this.initializeResponder(t,n,s,i),{hs:o,i:e,mc:0}}sendMessage(e,t,n){let i;if(e.mc===0)i=this.writeMessageA(e.hs,t,n);else if(e.mc===1)i=this.writeMessageB(e.hs,t);else if(e.mc===2){let{h:s,messageBuffer:o,cs1:a,cs2:c}=this.writeMessageC(e.hs,t);i=o,e.h=s,e.cs1=a,e.cs2=c}else if(e.mc>2)if(e.i){if(!e.cs1)throw new Error("CS1 (cipher state) is not defined");i=this.writeMessageRegular(e.cs1,t)}else{if(!e.cs2)throw new Error("CS2 (cipher state) is not defined");i=this.writeMessageRegular(e.cs2,t)}else throw new Error("Session invalid.");return e.mc++,i}recvMessage(e,t){let n=new Uint8Array(0),i=!1;if(e.mc===0)({plaintext:n,valid:i}=this.readMessageA(e.hs,t));else if(e.mc===1)({plaintext:n,valid:i}=this.readMessageB(e.hs,t));else if(e.mc===2){let{h:s,plaintext:o,valid:a,cs1:c,cs2:u}=this.readMessageC(e.hs,t);n=o,i=a,e.h=s,e.cs1=c,e.cs2=u}return e.mc++,{plaintext:n,valid:i}}};var cd=class{constructor(e,t,n,i,s,o,a,c){this.remoteExtensions={webtransportCerthashes:[]},this.isInitiator=e,this.payload=t,this.prologue=n,this.staticKeypair=s,this.connection=o,a&&(this.remotePeer=a),this.xx=c??new ad(i),this.session=this.xx.initSession(this.isInitiator,this.prologue,this.staticKeypair)}async propose(){if(DI(this.session.hs.s),this.isInitiator){ar.trace("Stage 0 - Initiator starting to send first message.");let e=this.xx.sendMessage(this.session,new Uint8Array(0));this.connection.writeLP(wI(e)),ar.trace("Stage 0 - Initiator finished sending first message."),i5(this.session.hs.e)}else{ar.trace("Stage 0 - Responder waiting to receive first message...");let e=vI((await this.connection.readLP()).subarray()),{valid:t}=this.xx.recvMessage(this.session,e);if(!t)throw new hs("xx handshake stage 0 validation fail");ar.trace("Stage 0 - Responder received first message."),s5(this.session.hs.re)}}async exchange(){if(this.isInitiator){ar.trace("Stage 1 - Initiator waiting to receive first message from responder...");let e=xI((await this.connection.readLP()).subarray()),{plaintext:t,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new hs("xx handshake stage 1 validation fail");ar.trace("Stage 1 - Initiator received the message."),s5(this.session.hs.re),CI(this.session.hs.rs),ar.trace("Initiator going to check remote's signature...");try{let i=r5(t);this.remotePeer=this.remotePeer||await t5(i),await n5(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let s=i;throw new ra(`Error occurred while verifying signed payload: ${s.message}`)}ar.trace("All good with the signature!")}else{ar.trace("Stage 1 - Responder sending out first message with signed payload and static key.");let e=this.xx.sendMessage(this.session,this.payload);this.connection.writeLP(bI(e)),ar.trace("Stage 1 - Responder sent the second handshake message with signed payload."),i5(this.session.hs.e)}}async finish(){if(this.isInitiator){ar.trace("Stage 2 - Initiator sending third handshake message.");let e=this.xx.sendMessage(this.session,this.payload);this.connection.writeLP(EI(e)),ar.trace("Stage 2 - Initiator sent message with signed payload.")}else{ar.trace("Stage 2 - Responder waiting for third handshake message...");let e=_I((await this.connection.readLP()).subarray()),{plaintext:t,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new hs("xx handshake stage 2 validation fail");ar.trace("Stage 2 - Responder received the message, finished handshake.");try{let i=r5(t);this.remotePeer=this.remotePeer||await t5(i),await n5(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let s=i;throw new ra(`Error occurred while verifying signed payload: ${s.message}`)}}PI(this.session)}encrypt(e,t){let n=this.getCS(t);return this.xx.encryptWithAd(n,new Uint8Array(0),e)}decrypt(e,t,n){let i=this.getCS(t,!1);return this.xx.decryptWithAd(i,new Uint8Array(0),e,n)}getRemoteStaticKey(){return this.session.hs.rs}getCS(e,t=!0){if(!e.cs1||!e.cs2)throw new hs("Handshake not completed properly, cipher state does not exist.");return this.isInitiator?t?e.cs1:e.cs2:t?e.cs2:e.cs1}setRemoteNoiseExtension(e){e&&(this.remoteExtensions=e)}};function kI(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}var ud=class{constructor(e={}){this.protocol="/noise";let{staticNoiseKey:t,extensions:n,crypto:i,prologueBytes:s,metrics:o}=e;this.crypto=i??yI,this.extensions=n,this.metrics=o?kI(o):void 0,t?this.staticKeys=this.crypto.generateX25519KeyPairFromSeed(t):this.staticKeys=this.crypto.generateX25519KeyPair(),this.prologue=s??new Uint8Array(0)}async secureOutbound(e,t,n){let i=G8(t,{lengthEncoder:Kc,lengthDecoder:$l,maxDataLength:65535}),s=await this.performHandshake({connection:i,isInitiator:!0,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,s),remoteExtensions:s.remoteExtensions,remotePeer:s.remotePeer}}async secureInbound(e,t,n){let i=G8(t,{lengthEncoder:Kc,lengthDecoder:$l,maxDataLength:65535}),s=await this.performHandshake({connection:i,isInitiator:!1,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,s),remotePeer:s.remotePeer,remoteExtensions:s.remoteExtensions}}async performHandshake(e){let t=await II(e.localPeer,this.staticKeys.publicKey,this.extensions);return await this.performXXHandshake(e,t)}async performXXHandshake(e,t){let{isInitiator:n,remotePeer:i,connection:s}=e,o=new cd(n,t,this.prologue,this.crypto,this.staticKeys,s,i);try{await o.propose(),await o.exchange(),await o.finish(),this.metrics?.xxHandshakeSuccesses.increment()}catch(a){if(this.metrics?.xxHandshakeErrors.increment(),a instanceof Error)throw a.message=`Error occurred during XX handshake: ${a.message}`,a}return o}async createSecureConnection(e,t){let[n,i]=l0(),s=e.unwrap();return await iI(n,AI(t,this.metrics),s,zl({lengthDecoder:$l}),RI(t,this.metrics),n),i}};function NI(r={}){return()=>new ud(r)}var $r=D("libp2p:webtransport"),QH=Object.values(vn).map(r=>r.decoder).reduce((r,e)=>r.or(e));function XH(r){return Fn.decode(QH.decode(r))}function LI(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}async function OI(r,e,t,n,i){let s=r.writable.getWriter(),o=r.readable.getReader();await s.ready;function a(){let f=n.findIndex(d=>d===h);f!==-1&&(n.splice(f,1),h.stat.timeline.close=Date.now(),i?.(h))}let c=!1,u=!1;(async function(){let f=await s.closed.catch(d=>d);if(f!=null){let d=f.message;d.includes("aborted by the remote server")||d.includes("STOP_SENDING")||$r.error(`WebTransport writer closed unexpectedly: streamId=${e} err=${f.message}`)}c=!0,c&&u&&a()})().catch(()=>{$r.error("WebTransport failed to cleanup closed stream")}),async function(){let f=await o.closed.catch(d=>d);f!=null&&$r.error(`WebTransport reader closed unexpectedly: streamId=${e} err=${f.message}`),u=!0,c&&u&&a()}().catch(()=>{$r.error("WebTransport failed to cleanup closed stream")});let l=!1,h={id:e,abort(f){c||(s.abort(),c=!0),h.closeRead(),u=!0,a()},close(){h.closeRead(),h.closeWrite(),a()},closeRead(){u||(o.cancel().catch(f=>{f.toString().includes("RESET_STREAM")===!0&&(c=!0)}),u=!0),c&&a()},closeWrite(){c||(c=!0,s.close().catch(f=>{f.toString().includes("RESET_STREAM")===!0&&(u=!0)})),u&&a()},reset(){h.close()},stat:{direction:t,timeline:{open:Date.now()}},metadata:{},source:async function*(){for(;;){let f=await o.read();if(f.done===!0){u=!0,c&&a();return}yield new j(f.value)}}(),sink:async function(f){if(l)throw new Error("sink already called on stream");l=!0;try{for await(let d of f)if(d instanceof Uint8Array)await s.write(d);else for(let p of d)await s.write(p)}finally{h.closeWrite()}}};return h}function jH(r){let e=r.stringTuples(),{url:t,certhashes:n,remotePeer:i}=e.reduce((s,[o,a])=>{switch(o){case X("ip6").code:case X("dns6").code:a?.includes(":")===!0&&(a=`[${a}]`);case X("ip4").code:case X("dns4").code:if(s.seenHost||s.seenPort)throw new Error("Invalid multiaddr, saw host and already saw the host or port");return{...s,url:`${s.url}${a??""}`,seenHost:!0};case X("quic").code:case X("quic-v1").code:case X("webtransport").code:if(!s.seenHost||!s.seenPort)throw new Error("Invalid multiaddr, Didn't see host and port, but saw quic/webtransport");return s;case X("udp").code:if(s.seenPort)throw new Error("Invalid multiaddr, saw port but already saw the port");return{...s,url:`${s.url}:${a??""}`,seenPort:!0};case X("certhash").code:if(!s.seenHost||!s.seenPort)throw new Error("Invalid multiaddr, saw the certhash before seeing the host and port");return{...s,certhashes:s.certhashes.concat([XH(a??"")])};case X("p2p").code:return{...s,remotePeer:oe(a??"")};default:throw new Error(`unexpected component in multiaddr: ${o} ${X(o).name} ${a??""} `)}},{url:"https://",seenHost:!1,seenPort:!1,certhashes:[]});return{url:t,certhashes:n,remotePeer:i}}function ZH(r,e){return e.filter(n=>!!r.find(i=>{if(n.length!==i.length)return!1;for(let s=0;s<n.length;s++)if(i[s]!==n[s])return!1;return!0})).length===e.length}var o5=class{components;config;constructor(e,t={}){this.components=e,this.config={maxInboundStreams:t.maxInboundStreams??1e3}}[Symbol.toStringTag]="@libp2p/webtransport";[Pi]=!0;async dial(e,t){$r("dialing %s",e);let n=this.components.peerId;if(n===void 0)throw new Error("Need a local peerid");t=t??{};let{url:i,certhashes:s,remotePeer:o}=jH(e);if(s.length===0)throw new Error("Expected multiaddr to contain certhashes");let a=new WebTransport(`${i}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:s.map(u=>({algorithm:"sha-256",value:u.digest}))});if(a.closed.catch(u=>{$r.error("WebTransport transport closed due to:",u)}),await a.ready,o==null)throw new Error("Need a target peerid");if(!await this.authenticateWebTransport(a,n,o,s))throw new Error("Failed to authenticate webtransport");let c={close:async u=>{u!=null&&$r("Closing webtransport with err:",u),a.close()},remoteAddr:e,timeline:{open:Date.now()},...LI()};a.closed.catch(u=>{$r.error("WebTransport connection closed:",u),c.timeline.close=Date.now()});try{t?.signal?.throwIfAborted()}catch(u){throw a.close(),u}return t.upgrader.upgradeOutbound(c,{skipEncryption:!0,muxerFactory:this.webtransportMuxer(a),skipProtection:!0})}async authenticateWebTransport(e,t,n,i){let s=await e.createBidirectionalStream(),o=s.writable.getWriter(),a=s.readable.getReader();await o.ready;let c={source:async function*(){for(;;){let h=await a.read();if(h.value!=null&&(yield h.value),h.done===!0)break}}(),sink:async function(h){for await(let f of h)await o.write(f)}},u=NI()(),{remoteExtensions:l}=await u.secureOutbound(t,c,n);if(o.close().catch(h=>{$r.error(`Failed to close authentication stream writer: ${h.message}`)}),a.cancel().catch(h=>{$r.error(`Failed to close authentication stream reader: ${h.message}`)}),!ZH(l?.webtransportCerthashes??[],i.map(h=>h.bytes)))throw new Error("Our certhashes are not a subset of the remote's reported certhashes");return!0}webtransportMuxer(e){let t=0,n=this.config;return{protocol:"webtransport",createStreamMuxer:i=>{typeof i=="function"&&(i={onIncomingStream:i});let s=[];(async function(){let a=e.incomingBidirectionalStreams.getReader();for(;;){let{done:c,value:u}=await a.read();if(c===!0)break;if(s.length>=n.maxInboundStreams)u.writable.close().catch(l=>{$r.error(`Failed to close inbound stream that crossed our maxInboundStream limit: ${l.message}`)}),u.readable.cancel().catch(l=>{$r.error(`Failed to close inbound stream that crossed our maxInboundStream limit: ${l.message}`)});else{let l=await OI(u,String(t++),"inbound",s,i?.onStreamEnd);s.push(l),i?.onIncomingStream?.(l)}}})().catch(()=>{$r.error("WebTransport failed to receive incoming stream")});let o={protocol:"webtransport",streams:s,newStream:async a=>{let c=await e.createBidirectionalStream(),u=await OI(c,String(t++),i?.direction??"outbound",s,i?.onStreamEnd);return s.push(u),u},close:a=>{a!=null&&$r("Closing webtransport muxer with err:",a),e.close()},...LI()};try{i?.signal?.throwIfAborted()}catch(a){throw e.close(),a}return o}}}createListener(e){throw new Error("Webtransport servers are not supported in Node or the browser")}filter(e){return e.filter(t=>t.protoNames().includes("webtransport"))}};function BI(r={}){return e=>new o5(e,r)}var UT=F(Zr(),1);var tT=F($I(),1);var eT=F(JI(),1),uo=eT.default;var Oe;(function(r){r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH"})(Oe||(Oe={}));var fd=D("libp2p:keychain"),g$="/pkcs8/",rT="/info/",na=new WeakMap,ia={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3},c5={dek:{keyLength:512/8,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function fs(r){return r==null||typeof r!="string"?!1:r===(0,tT.default)(r.trim())&&r.length>0}async function at(){let t=Math.random()*800+200;await new Promise(n=>setTimeout(n,t))}function Li(r){return new ve(g$+r)}function lo(r){return new ve(rT+r)}var sa=class{constructor(e,t){if(this.components=e,this.init=uo(c5,t),this.init.pass!=null&&this.init.pass?.length<20)throw new Error("pass must be least 20 characters");if(this.init.dek?.keyLength!=null&&this.init.dek.keyLength<ia.minKeyLength)throw new Error(`dek.keyLength must be least ${ia.minKeyLength} bytes`);if(this.init.dek?.salt?.length!=null&&this.init.dek.salt.length<ia.minSaltLength)throw new Error(`dek.saltLength must be least ${ia.minSaltLength} bytes`);if(this.init.dek?.iterationCount!=null&&this.init.dek.iterationCount<ia.minIterationCount)throw new Error(`dek.iterationCount must be least ${ia.minIterationCount}`);let n=this.init.pass!=null&&this.init.dek?.salt!=null?sl(this.init.pass,this.init.dek?.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";na.set(this,{dek:n})}static generateOptions(){let e=Object.assign({},c5),t=Math.ceil(ia.minSaltLength/3)*3;return e.dek.salt=B(Cn(t),"base64"),e}static get options(){return c5}async createKey(e,t,n=2048){if(!fs(e)||e==="self")throw await at(),new w("Invalid key name",Oe.ERR_INVALID_KEY_NAME);if(typeof t!="string")throw await at(),new w("Invalid key type",Oe.ERR_INVALID_KEY_TYPE);let i=Li(e);if(await this.components.datastore.has(i))throw await at(),new w("Key name already exists",Oe.ERR_KEY_ALREADY_EXISTS);switch(t.toLowerCase()){case"rsa":if(!Number.isSafeInteger(n)||n<2048)throw await at(),new w("Invalid RSA key size",Oe.ERR_INVALID_KEY_SIZE);break;default:break}let o;try{let a=await il(t,n),c=await a.id(),u=na.get(this);if(u==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let l=u.dek,h=await a.export(l);o={name:e,id:c};let f=this.components.datastore.batch();f.put(i,q(h)),f.put(lo(e),q(JSON.stringify(o))),await f.commit()}catch(a){throw await at(),a}return o}async listKeys(){let e={prefix:rT},t=[];for await(let n of this.components.datastore.query(e))t.push(JSON.parse(B(n.value)));return t}async findKeyById(e){try{let n=(await this.listKeys()).find(i=>i.id===e);if(n==null)throw new w(`Key with id '${e}' does not exist.`,Oe.ERR_KEY_NOT_FOUND);return n}catch(t){throw await at(),t}}async findKeyByName(e){if(!fs(e))throw await at(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);let t=lo(e);try{let n=await this.components.datastore.get(t);return JSON.parse(B(n))}catch(n){throw await at(),fd.error(n),new w(`Key '${e}' does not exist.`,Oe.ERR_KEY_NOT_FOUND)}}async removeKey(e){if(!fs(e)||e==="self")throw await at(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);let t=Li(e),n=await this.findKeyByName(e),i=this.components.datastore.batch();return i.delete(t),i.delete(lo(e)),await i.commit(),n}async renameKey(e,t){if(!fs(e)||e==="self")throw await at(),new w(`Invalid old key name '${e}'`,Oe.ERR_OLD_KEY_NAME_INVALID);if(!fs(t)||t==="self")throw await at(),new w(`Invalid new key name '${t}'`,Oe.ERR_NEW_KEY_NAME_INVALID);let n=Li(e),i=Li(t),s=lo(e),o=lo(t);if(await this.components.datastore.has(i))throw await at(),new w(`Key '${t}' already exists`,Oe.ERR_KEY_ALREADY_EXISTS);try{let c=await this.components.datastore.get(n),u=await this.components.datastore.get(s),l=JSON.parse(B(u));l.name=t;let h=this.components.datastore.batch();return h.put(i,c),h.put(o,q(JSON.stringify(l))),h.delete(n),h.delete(s),await h.commit(),l}catch(c){throw await at(),c}}async exportKey(e,t){if(!fs(e))throw await at(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);if(t==null)throw await at(),new w("Password is required",Oe.ERR_PASSWORD_REQUIRED);let n=Li(e);try{let i=await this.components.datastore.get(n),s=B(i),o=na.get(this);if(o==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let a=o.dek;return await(await Xa(s,a)).export(t)}catch(i){throw await at(),i}}async exportPeerId(e){let t="temporary-password",n=await this.exportKey(e,t),i=await Xa(n,t);return await er(i.public.bytes,i.bytes)}async importKey(e,t,n){if(!fs(e)||e==="self")throw await at(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);if(t==null)throw await at(),new w("PEM encoded key is required",Oe.ERR_PEM_REQUIRED);let i=Li(e);if(await this.components.datastore.has(i))throw await at(),new w(`Key '${e}' already exists`,Oe.ERR_KEY_ALREADY_EXISTS);let o;try{o=await Xa(t,n)}catch{throw await at(),new w("Cannot read the key, most likely the password is wrong",Oe.ERR_CANNOT_READ_KEY)}let a;try{a=await o.id();let l=na.get(this);if(l==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let h=l.dek;t=await o.export(h)}catch(l){throw await at(),l}let c={name:e,id:a},u=this.components.datastore.batch();return u.put(i,q(t)),u.put(lo(e),q(JSON.stringify(c))),await u.commit(),c}async importPeer(e,t){try{if(!fs(e))throw new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);if(t==null)throw new w("PeerId is required",Oe.ERR_MISSING_PRIVATE_KEY);if(t.privateKey==null)throw new w("PeerId.privKey is required",Oe.ERR_MISSING_PRIVATE_KEY);let n=await cn(t.privateKey),i=Li(e);if(await this.components.datastore.has(i))throw await at(),new w(`Key '${e}' already exists`,Oe.ERR_KEY_ALREADY_EXISTS);let o=na.get(this);if(o==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let a=o.dek,c=await n.export(a),u={name:e,id:t.toString()},l=this.components.datastore.batch();return l.put(i,q(c)),l.put(lo(e),q(JSON.stringify(u))),await l.commit(),u}catch(n){throw await at(),n}}async getPrivateKey(e){if(!fs(e))throw await at(),new w(`Invalid key name '${e}'`,Oe.ERR_INVALID_KEY_NAME);try{let t=Li(e),n=await this.components.datastore.get(t);return B(n)}catch(t){throw await at(),fd.error(t),new w(`Key '${e}' does not exist.`,Oe.ERR_KEY_NOT_FOUND)}}async rotateKeychainPass(e,t){if(typeof e!="string")throw await at(),new w(`Invalid old pass type '${typeof e}'`,Oe.ERR_INVALID_OLD_PASS_TYPE);if(typeof t!="string")throw await at(),new w(`Invalid new pass type '${typeof t}'`,Oe.ERR_INVALID_NEW_PASS_TYPE);if(t.length<20)throw await at(),new w(`Invalid pass length ${t.length}`,Oe.ERR_INVALID_PASS_LENGTH);fd("recreating keychain");let n=na.get(this);if(n==null)throw new w("dek missing",Oe.ERR_INVALID_PARAMETERS);let i=n.dek;this.init.pass=t;let s=t!=null&&this.init.dek?.salt!=null?sl(t,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";na.set(this,{dek:s});let o=await this.listKeys();for(let a of o){let c=await this.components.datastore.get(Li(a.name)),u=B(c),l=await Xa(u,i),h=s.toString(),f=await l.export(h),d=this.components.datastore.batch(),p={name:a.name,id:a.id};d.put(Li(a.name),q(f)),d.put(lo(a.name),q(JSON.stringify(p))),await d.commit()}fd("keychain reconstructed")}};var u5;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.id!=null&&(n.uint32(10),n.bytes(t.id)),t.pubKey!=null&&(n.uint32(18),n.bytes(t.pubKey)),t.privKey!=null&&(n.uint32(26),n.bytes(t.privKey)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.id=t.bytes();break;case 2:i.pubKey=t.bytes();break;case 3:i.privKey=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(u5||(u5={}));var dd=async()=>{let r=await il("Ed25519"),e=await y$(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function nT(r){return await er(Qa(r))}async function y$(r){return await er(Qa(r.public),J3(r))}var iT={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var Ql;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.publicKey=t.bytes();break;case 2:i.payloadType=t.bytes();break;case 3:i.payload=t.bytes();break;case 5:i.signature=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(Ql||(Ql={}));var w$,Wt=class{constructor(e){let{peerId:t,payloadType:n,payload:i,signature:s}=e;this.peerId=t,this.payloadType=n,this.payload=i,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=Ql.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return pe(this.marshal(),e.marshal())}async validate(e){let t=sT(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return await kr(this.peerId.publicKey).verify(t.subarray(),this.signature)}};w$=Wt;Wt.createFromProtobuf=async r=>{let e=Ql.decode(r),t=await er(e.publicKey);return new Wt({peerId:t,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};Wt.seal=async(r,e)=>{if(e.privateKey==null)throw new Error("Missing private key");let t=r.domain,n=r.codec,i=r.marshal(),s=sT(t,n,i),a=await(await cn(e.privateKey)).sign(s.subarray());return new Wt({peerId:e,payloadType:n,payload:i,signature:a})};Wt.openAndCertify=async(r,e)=>{let t=await Wt.createFromProtobuf(r);if(!await t.validate(e))throw new w("envelope signature is not valid for the given domain",iT.ERR_SIGNATURE_NOT_VALID);return t};var sT=(r,e,t)=>{let n=q(r),i=ct.encode(n.byteLength),s=ct.encode(e.length),o=ct.encode(t.length);return new j(i,n,s,e,o,t)};function oT(r,e){let t=(n,i)=>n.toString().localeCompare(i.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,i)=>e[i].equals(n)))}var Xl;(function(r){let e;(function(n){let i;n.codec=()=>(i==null&&(i=se((s,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(o.uint32(10),o.bytes(s.multiaddr)),a.lengthDelimited!==!1&&o.ldelim()},(s,o)=>{let a={multiaddr:new Uint8Array(0)},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let u=s.uint32();switch(u>>>3){case 1:a.multiaddr=s.bytes();break;default:s.skipType(u&7);break}}return a})),i),n.encode=s=>ie(s,n.codec()),n.decode=s=>ne(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=se((n,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(i.uint32(10),i.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(i.uint32(16),i.uint64(n.seq)),n.addresses!=null)for(let o of n.addresses)i.uint32(26),r.AddressInfo.codec().encode(o,i);s.lengthDelimited!==!1&&i.ldelim()},(n,i)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},o=i==null?n.len:n.pos+i;for(;n.pos<o;){let a=n.uint32();switch(a>>>3){case 1:s.peerId=n.bytes();break;case 2:s.seq=n.uint64();break;case 3:s.addresses.push(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return s})),t),r.encode=n=>ie(n,r.codec()),r.decode=n=>ne(n,r.codec())})(Xl||(Xl={}));var aT="libp2p-peer-record",cT=Uint8Array.from([3,1]);var zt=class{constructor(e){this.domain=zt.DOMAIN,this.codec=zt.CODEC;let{peerId:t,multiaddrs:n,seqNumber:i}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=i??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Xl.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof zt)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!oT(this.multiaddrs,e.multiaddrs))}};zt.createFromProtobuf=r=>{let e=Xl.decode(r),t=It(e.peerId),n=(e.addresses??[]).map(s=>re(s.multiaddr)),i=e.seq;return new zt({peerId:t,multiaddrs:n,seqNumber:i})};zt.DOMAIN=aT;zt.CODEC=cT;var lr={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var zc;(function(r){let e;(function(i){let s;i.codec=()=>(s==null&&(s=se((o,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),o.key!=null&&o.key!==""&&(a.uint32(10),a.string(o.key)),o.value!=null&&o.value.byteLength>0&&(a.uint32(18),a.bytes(o.value)),c.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{let c={key:"",value:new Uint8Array(0)},u=a==null?o.len:o.pos+a;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:c.key=o.string();break;case 2:c.value=o.bytes();break;default:o.skipType(l&7);break}}return c})),s),i.encode=o=>ie(o,i.codec()),i.decode=o=>ne(o,i.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(i){let s;i.codec=()=>(s==null&&(s=se((o,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),o.key!=null&&o.key!==""&&(a.uint32(10),a.string(o.key)),o.value!=null&&(a.uint32(18),md.codec().encode(o.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(o,a)=>{let c={key:""},u=a==null?o.len:o.pos+a;for(;o.pos<u;){let l=o.uint32();switch(l>>>3){case 1:c.key=o.string();break;case 2:c.value=md.codec().decode(o,o.uint32());break;default:o.skipType(l&7);break}}return c})),s),i.encode=o=>ie(o,i.codec()),i.decode=o=>ne(o,i.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=se((i,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),i.addresses!=null)for(let a of i.addresses)s.uint32(10),pd.codec().encode(a,s);if(i.protocols!=null)for(let a of i.protocols)s.uint32(18),s.string(a);if(i.publicKey!=null&&(s.uint32(34),s.bytes(i.publicKey)),i.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(i.peerRecordEnvelope)),i.metadata!=null&&i.metadata.size!==0)for(let[a,c]of i.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(i.tags!=null&&i.tags.size!==0)for(let[a,c]of i.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.addresses.push(pd.codec().decode(i,i.uint32()));break;case 2:o.protocols.push(i.string());break;case 4:o.publicKey=i.bytes();break;case 5:o.peerRecordEnvelope=i.bytes();break;case 6:{let u=r.Peer$metadataEntry.codec().decode(i,i.uint32());o.metadata.set(u.key,u.value);break}case 7:{let u=r.Peer$tagsEntry.codec().decode(i,i.uint32());o.tags.set(u.key,u.value);break}default:i.skipType(c&7);break}}return o})),n),r.encode=i=>ie(i,r.codec()),r.decode=i=>ne(i,r.codec())})(zc||(zc={}));var pd;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.multiaddr=t.bytes();break;case 2:i.isCertified=t.bool();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(pd||(pd={}));var md;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.value=t.uint32();break;case 2:i.expiry=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(md||(md={}));async function Hc(r,e){let t=zc.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=await nT(kr(t.publicKey)));let n=new Map,i=BigInt(Date.now());for(let[s,o]of t.tags.entries())o.expiry!=null&&o.expiry<i||n.set(s,o);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:o})=>({multiaddr:re(s),isCertified:o??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var l5="/peers/";function $c(r){if(!pf(r)||r.type==null)throw new w("Invalid PeerId",lr.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new ve(`${l5}${e}`)}async function uT(r,e,t){let n=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=re(i.multiaddr)),!Vo(i.multiaddr))throw new w("Multiaddr was invalid",lr.ERR_INVALID_PARAMETERS);if(!await e(r,i.multiaddr))continue;let s=i.isCertified??!1,o=i.multiaddr.toString(),a=n.get(o);a!=null?i.isCertified=a.isCertified||s:n.set(o,{multiaddr:i.multiaddr,isCertified:s})}return[...n.values()].sort((i,s)=>i.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:i,multiaddr:s})=>({isCertified:i,multiaddr:s.bytes}))}async function yd(r,e,t,n){if(e==null)throw new w("Invalid PeerData",lr.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!pe(e.publicKey,r.publicKey))throw new w("publicKey bytes do not match peer id publicKey bytes",lr.ERR_INVALID_PARAMETERS);let i=n.existingPeer;if(i!=null&&!r.equals(i.id))throw new w("peer id did not match existing peer id",lr.ERR_INVALID_PARAMETERS);let s=i?.addresses??[],o=new Set(i?.protocols??[]),a=i?.metadata??new Map,c=i?.tags??new Map,u=i?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(h=>({isCertified:!1,multiaddr:h}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(o=new Set(e.protocols)),e.metadata!=null){let h=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=gd(h,{validate:lT})}if(e.tags!=null){let h=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=gd(h,{validate:hT,map:fT})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(h=>({isCertified:!1,multiaddr:h}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(o=new Set([...o,...e.protocols])),e.metadata!=null){let h=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[f,d]of h)d==null?a.delete(f):a.set(f,d);a=gd([...a.entries()],{validate:lT})}if(e.tags!=null){let h=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),f=new Map(c);for(let[d,p]of h)p==null?f.delete(d):f.set(d,p);c=gd([...f.entries()],{validate:hT,map:fT})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let l={addresses:await uT(r,n.addressFilter??(async()=>!0),s),protocols:[...o.values()].sort((h,f)=>h.localeCompare(f)),metadata:a,tags:c,publicKey:i?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:u};return r.type!=="RSA"&&delete l.publicKey,l}function gd(r,e){let t=new Map;for(let[n,i]of r)i!=null&&e.validate(n,i);for(let[n,i]of r.sort(([s],[o])=>s.localeCompare(o)))i!=null&&t.set(n,e.map?.(n,i)??i);return t}function lT(r,e){if(typeof r!="string")throw new w("Metadata key must be a string",lr.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new w("Metadata value must be a Uint8Array",lr.ERR_INVALID_PARAMETERS)}function hT(r,e){if(typeof r!="string")throw new w("Tag name must be a string",lr.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new w("Tag value must be an integer",lr.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new w("Tag value must be between 0-100",lr.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new w("Tag ttl must be an integer",lr.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new w("Tag ttl must be between greater than 0",lr.ERR_INVALID_PARAMETERS)}}function fT(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}var wd=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Pu({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has($c(e))}async delete(e){if(this.peerId.equals(e))throw new w("Cannot delete self peer",lr.ERR_INVALID_PARAMETERS);await this.datastore.delete($c(e))}async load(e){let t=await this.datastore.get($c(e));return Hc(e,t)}async save(e,t){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await yd(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,i)}async patch(e,t){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await yd(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,s,n,i)}async merge(e,t){let{existingBuf:n,existingPeer:i}=await this.#e(e),s=await yd(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,s,n,i)}async*all(){for await(let{key:e,value:t}of this.datastore.query({prefix:l5})){let n=e.toString().split("/")[2],i=Yt.decode(n),s=It(i);s.equals(this.peerId)||(yield Hc(s,t))}}async#e(e){try{let t=await this.datastore.get($c(e)),n=await Hc(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,i){let s=zc.encode(t);return n!=null&&pe(s,n)?{peer:await Hc(e,s),previous:i,updated:!1}:(await this.datastore.put($c(e),s),{peer:await Hc(e,s),previous:i,updated:!0})}};var ft=D("libp2p:peer-store"),bd=class{store;events;peerId;constructor(e,t={}){this.events=e.events,this.peerId=e.peerId,this.store=new wd(e,t)}async forEach(e){ft.trace("forEach await read lock");let t=await this.store.lock.readLock();ft.trace("forEach got read lock");try{for await(let n of this.store.all())e(n)}finally{ft.trace("forEach release read lock"),t()}}async all(){ft.trace("all await read lock");let e=await this.store.lock.readLock();ft.trace("all got read lock");try{let t=[];for await(let n of this.store.all())t.push(n);return t}finally{ft.trace("all release read lock"),e()}}async delete(e){ft.trace("delete await write lock");let t=await this.store.lock.writeLock();ft.trace("delete got write lock");try{await this.store.delete(e)}finally{ft.trace("delete release write lock"),t()}}async has(e){ft.trace("has await read lock");let t=await this.store.lock.readLock();ft.trace("has got read lock");try{return await this.store.has(e)}finally{ft.trace("has release read lock"),t()}}async get(e){ft.trace("get await read lock");let t=await this.store.lock.readLock();ft.trace("get got read lock");try{return await this.store.load(e)}finally{ft.trace("get release read lock"),t()}}async save(e,t){ft.trace("save await write lock");let n=await this.store.lock.writeLock();ft.trace("save got write lock");try{let i=await this.store.save(e,t);return this.#e(e,i),i.peer}finally{ft.trace("save release write lock"),n()}}async patch(e,t){ft.trace("patch await write lock");let n=await this.store.lock.writeLock();ft.trace("patch got write lock");try{let i=await this.store.patch(e,t);return this.#e(e,i),i.peer}finally{ft.trace("patch release write lock"),n()}}async merge(e,t){ft.trace("merge await write lock");let n=await this.store.lock.writeLock();ft.trace("merge got write lock");try{let i=await this.store.merge(e,t);return this.#e(e,i),i.peer}finally{ft.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await Wt.openAndCertify(e,zt.DOMAIN);if(t?.equals(n.peerId)===!1)return ft("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let i=zt.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(o){if(o.code!=="ERR_NOT_FOUND")throw o}if(s?.peerRecordEnvelope!=null){let o=await Wt.createFromProtobuf(s.peerRecordEnvelope),a=zt.createFromProtobuf(o.payload);if(a.seqNumber>=i.seqNumber)return ft("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,i.seqNumber),!1}return await this.patch(i.peerId,{peerRecordEnvelope:e,addresses:i.multiaddrs.map(o=>({isCertified:!0,multiaddr:o}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function dT(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var b$=D("libp2p:address-manager"),E$=r=>r;function h5(r,e){let t=r.getPeerId();return t!=null&&oe(t).equals(e)&&(r=r.decapsulate(re(`/p2p/${e.toString()}`))),r}var Ed=class{components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:i=[]}=t;this.components=e,this.listen=n.map(s=>s.toString()),this.announce=new Set(i.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??E$,this._updatePeerStoreAddresses=dT(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>re(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{b$.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>re(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>re(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>re(e))}addObservedAddr(e){e=h5(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=h5(e,this.components.peerId);let t=e.toString(),i=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),i||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=h5(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,i])=>i.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>re(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};function pT(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}var f5=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>pT(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},v$=["metrics","connectionProtector"],x$=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function mT(r={}){let e=new f5(r);return new Proxy(e,{get(n,i,s){if(typeof i=="string"&&!x$.includes(i)){let o=e.components[i];if(o==null&&!v$.includes(i))throw new w(`${i} not set`,"ERR_SERVICE_MISSING");return o}return Reflect.get(n,i,s)},set(n,i,s){return typeof i=="string"?e.components[i]=s:Reflect.set(n,i,s),!0}})}function gT(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!Nn(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}function d5(r){try{let{address:e}=r.nodeAddress();return!!Nn(e)}catch{return!0}}function Gc(r,e){let t=d5(r.multiaddr),n=d5(e.multiaddr);return t&&!n?1:!t&&n||r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}var m5=F(Xd(),1),g5=F(bT(),1);var ET=globalThis.fetch,vT=globalThis.Headers,$8e=globalThis.Request,G8e=globalThis.Response;function vd(r,e,t){return`${r}?name=${e}&type=${t}`}async function xT(r,e){return await(await ET(r,{headers:new vT({accept:"application/dns-json"}),signal:e})).json()}function oa(r,e){return`${e}_${r}`}var p5=Object.assign((0,m5.default)("dns-over-http-resolver"),{error:(0,m5.default)("dns-over-http-resolver:error")}),y5=class{constructor(e={}){this._cache=new g5.default({max:e?.maxCache??100}),this._TXTcache=new g5.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??xT,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>e.abort())}getServers(){return this._servers}_getShuffledServers(){let e=[...this._servers];for(let t=e.length-1;t>0;t--){let n=Math.floor(Math.random()*t),i=e[t];e[t]=e[n],e[n]=i}return e}setServers(e){this._servers=e}async resolve(e,t="A"){switch(t){case"A":return await this.resolve4(e);case"AAAA":return await this.resolve6(e);case"TXT":return await this.resolveTxt(e);default:throw new Error(`${t} is not supported`)}}async resolve4(e){let t="A",n=this._cache.get(oa(e,t));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(vd(s,e,t),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(oa(e,t),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),p5.error(`${s} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}async resolve6(e){let t="AAAA",n=this._cache.get(oa(e,t));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(vd(s,e,t),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(oa(e,t),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),p5.error(`${s} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}async resolveTxt(e){let t="TXT",n=this._TXTcache.get(oa(e,t));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(vd(s,e,t),o.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(oa(e,t),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),p5.error(`${s} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${t}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},_T=y5;var ST=_T;var{code:I$}=X("dnsaddr");async function Wc(r,e={}){let t=new ST;e.signal!=null&&e.signal.addEventListener("abort",()=>{t.cancel()});let n=r.getPeerId(),[,i]=r.stringTuples().find(([a])=>a===I$)??[];if(i==null)throw new Error("No hostname found in multiaddr");let o=(await t.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(o=o.filter(a=>a.includes(n))),o}var Oi;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.DHT_DISABLED="DHT is not available",r.PUBSUB_DISABLED="PubSub is not available",r.CONN_ENCRYPTION_REQUIRED="At least one connection encryption module is required",r.ERR_TRANSPORTS_REQUIRED="At least one transport module is required",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Oi||(Oi={}));var V;(function(r){r.DHT_DISABLED="ERR_DHT_DISABLED",r.ERR_PUBSUB_DISABLED="ERR_PUBSUB_DISABLED",r.PUBSUB_NOT_STARTED="ERR_PUBSUB_NOT_STARTED",r.DHT_NOT_STARTED="ERR_DHT_NOT_STARTED",r.CONN_ENCRYPTION_REQUIRED="ERR_CONN_ENCRYPTION_REQUIRED",r.ERR_TRANSPORTS_REQUIRED="ERR_TRANSPORTS_REQUIRED",r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TIMEOUT="ERR_TIMEOUT",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_KEYCHAIN_REQUIRED="ERR_KEYCHAIN_REQUIRED",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(V||(V={}));var T$={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Wc},addressSorter:Gc},transportManager:{faultTolerance:no.FATAL_ALL}};function AT(r){let e=uo(T$,r);if(e.transports==null||e.transports.length<1)throw new w(Oi.ERR_TRANSPORTS_REQUIRED,V.ERR_TRANSPORTS_REQUIRED);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new w(Oi.ERR_PROTECTOR_REQUIRED,V.ERR_PROTECTOR_REQUIRED);return e}var RT="keep-alive";var CT=F(C4(),1);var D$=D("libp2p:get-peer");function xd(r){if(pf(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:oe(t),r.forEach(n=>{if(!Vo(n))throw D$.error("multiaddr %s was invalid",n),new w("Invalid Multiaddr",V.ERR_INVALID_MULTIADDR);let i=n.getPeerId();if(i==null){if(e!=null)throw new w("Multiaddrs must all have the same peer id or have no peer id",V.ERR_INVALID_PARAMETERS)}else{let s=oe(i);if(e==null||!e.equals(s))throw new w("Multiaddrs must all have the same peer id or have no peer id",V.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}var Bi=D("libp2p:connection-manager:auto-dial"),_d={minConnections:50,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3},Sd=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialInterval;started;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??_d.minConnections,this.autoDialPriority=t.autoDialPriority??_d.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??_d.autoDialInterval,this.started=!1,this.queue=new vt({concurrency:t.autoDialConcurrency??_d.autoDialConcurrency}),this.queue.addListener("error",n=>{Bi.error("error during auto-dial",n)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(n=>{Bi.error(n)})})}isStarted(){return this.started}start(){this.autoDialInterval=setInterval(()=>{this.autoDial().catch(e=>{Bi.error("error while autodialing",e)})},this.autoDialIntervalMs),this.started=!0}afterStart(){this.autoDial().catch(e=>{Bi.error("error while autodialing",e)})}stop(){this.queue.clear(),clearInterval(this.autoDialInterval),this.started=!1}async autoDial(){if(!this.started)return;let e=this.connectionManager.getConnectionsMap(),t=e.size,n=new Rr(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean));if(t>=this.minConnections){Bi.trace("have enough connections %d/%d",t,this.minConnections);return}Bi("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let i=await this.peerStore.all(),o=i.filter(u=>!(u.addresses.length===0||e.has(u.id)||n.has(u.id))).sort(()=>Math.random()>.5?1:-1),a=new Mr;for(let u of o)a.has(u.id)||a.set(u.id,[...u.tags.values()].reduce((l,h)=>l+h.value,0));let c=o.sort((u,l)=>{let h=a.get(u.id)??0,f=a.get(l.id)??0;return h>f?-1:h<f?1:0});Bi("selected %d/%d peers to dial",c.length,i.length);for(let u of c)this.queue.add(async()=>{let l=this.connectionManager.getConnectionsMap().size;if(l>=this.minConnections){Bi("got enough connections now %d/%d",l,this.minConnections),this.queue.clear();return}Bi("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})}).catch(l=>{Bi.error("could not connect to peerStore stored peer",l)})}};var Yc=D("libp2p:connection-manager:connection-pruner"),IT={maxConnections:300,allow:[]},Ad=class{maxConnections;connectionManager;peerStore;allow;events;constructor(e,t={}){this.maxConnections=t.maxConnections??IT.maxConnections,this.allow=t.allow??IT.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{Yc.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=Math.max(t-this.maxConnections,0);if(Yc("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;Yc("max connections limit exceeded %d/%d, pruning %d connection(s)",t,this.maxConnections,n);let i=new Mr;for(let a of e){let c=a.remotePeer;if(!i.has(c)){i.set(c,0);try{let u=await this.peerStore.get(c);i.set(c,[...u.tags.values()].reduce((l,h)=>l+h.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&Yc.error("error loading peer tags",u)}}}let s=e.sort((a,c)=>{let u=i.get(a.remotePeer)??0,l=i.get(c.remotePeer)??0;if(u>l)return 1;if(u<l)return-1;let h=a.stat.timeline.open,f=c.stat.timeline.open;return h<f?1:h>f?-1:0}),o=[];for(let a of s)if(Yc("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||o.push(a),o.length===n)break;await Promise.all(o.map(async a=>{try{await a.close()}catch(c){Yc.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:o})}};var S5=F(Zr(),1);var x5=F(Zr(),1);var TT=D("libp2p:connection-manager:utils");async function _5(r,e){if(!r.protoNames().includes("dnsaddr"))return[r];let n=await P$(r,e),o=(await Promise.all(n.map(async a=>_5(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return TT("resolved %s to",r,o.map(a=>a.toString())),o}async function P$(r,e){try{return r=re(r.toString()),await r.resolve(e)}catch(t){return TT.error(`multiaddr ${r.toString()} could not be resolved`,t),[]}}function DT(...r){let e=[];for(let n of r)if(n!=null){try{(0,x5.setMaxListeners)?.(1/0,n)}catch{}e.push(n)}let t=it(e);try{(0,x5.setMaxListeners)?.(1/0,t)}catch{}return t}var Ir=D("libp2p:connection-manager:dial-queue"),jl={addressSorter:Gc,maxParallelDials:100,maxPeerAddrsToDial:25,maxParallelDialsPerPeer:10,dialTimeout:3e4,resolvers:{dnsaddr:Wc}},Rd=class{pendingDials;queue;peerId;peerStore;connectionGater;transportManager;addressSorter;maxPeerAddrsToDial;maxParallelDialsPerPeer;dialTimeout;inProgressDialCount;pendingDialCount;shutDownController;constructor(e,t={}){this.addressSorter=t.addressSorter??jl.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??jl.maxPeerAddrsToDial,this.maxParallelDialsPerPeer=t.maxParallelDialsPerPeer??jl.maxParallelDialsPerPeer,this.dialTimeout=t.dialTimeout??jl.dialTimeout,this.peerId=e.peerId,this.peerStore=e.peerStore,this.connectionGater=e.connectionGater,this.transportManager=e.transportManager,this.shutDownController=new AbortController;try{(0,S5.setMaxListeners)?.(1/0,this.shutDownController.signal)}catch{}this.pendingDialCount=e.metrics?.registerMetric("libp2p_dialler_pending_dials"),this.inProgressDialCount=e.metrics?.registerMetric("libp2p_dialler_in_progress_dials"),this.pendingDials=[];for(let[n,i]of Object.entries(t.resolvers??{}))Jm.set(n,i);this.queue=new vt({concurrency:t.maxParallelDials??jl.maxParallelDials}),this.queue.on("add",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("active",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("completed",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("error",n=>{Ir.error("error in dial queue",n),this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("empty",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("idle",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)})}stop(){this.shutDownController.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:i}=xd(e),s=i.map(l=>({multiaddr:l,isCertified:!1})),o=this.createDialAbortControllers(t.signal),a;try{a=await this.calculateMultiaddrs(n,s,{...t,signal:o})}catch(l){throw o.clear(),l}let c=this.pendingDials.find(l=>!!(l.peerId!=null&&n!=null&&l.peerId.equals(n)||a.map(({multiaddr:h})=>h.toString()).join()===l.multiaddrs.map(h=>h.toString()).join()));if(c!=null)return Ir("joining existing dial target for %p",n),o.clear(),c.promise;Ir("creating dial target for",a.map(({multiaddr:l})=>l.toString()));let u={id:N$(),status:"queued",peerId:n,multiaddrs:a.map(({multiaddr:l})=>l)};return u.promise=this.performDial(u,{...t,signal:o}).finally(()=>{this.pendingDials=this.pendingDials.filter(l=>l.id!==u.id),o.clear()}).catch(l=>{throw Ir.error("dial failed to %s",u.multiaddrs.map(h=>h.toString()).join(", "),l),o.aborted?new w(l.message,V.ERR_TIMEOUT):l}),this.pendingDials.push(u),u.promise}createDialAbortControllers(e){let t=it([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);try{(0,S5.setMaxListeners)?.(1/0,t)}catch{}return t}async calculateMultiaddrs(e,t=[],n={}){if(e!=null){if(this.peerId.equals(e))throw new w("Tried to dial self",V.ERR_DIALED_SELF);if(await this.connectionGater.denyDialPeer?.(e)===!0)throw new w("The dial request is blocked by gater.allowDialPeer",V.ERR_PEER_DIAL_INTERCEPTED);if(t.length===0){Ir("loading multiaddrs for %p",e);try{let l=await this.peerStore.get(e);t.push(...l.addresses),Ir("loaded multiaddrs for %p",e,t.map(({multiaddr:h})=>h.toString()))}catch(l){if(l.code!==V.ERR_NOT_FOUND)throw l}}}let i=(await Promise.all(t.map(async l=>{let h=await _5(l.multiaddr,n);return h.length===1&&h[0].equals(l.multiaddr)?l:h.map(f=>({multiaddr:f,isCertified:!1}))}))).flat(),s=i.filter(l=>!!this.transportManager.transportForMultiaddr(l.multiaddr)),o=new Map;for(let l of s){let h=l.multiaddr.toString(),f=o.get(h);if(f!=null){f.isCertified=f.isCertified||l.isCertified||!1;continue}o.set(h,l)}let a=[...o.values()];if((a.length===0||a.length>this.maxPeerAddrsToDial)&&(Ir("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:l})=>l.toString())),Ir("addresses for %p after filtering",e??"unknown peer",a.map(({multiaddr:l})=>l.toString()))),a.length===0)throw new w("The dial request has no valid addresses",V.ERR_NO_VALID_ADDRESSES);if(a.length>this.maxPeerAddrsToDial)throw new w("dial with more addresses than allowed",V.ERR_TOO_MANY_ADDRESSES);if(e!=null){let l=`/p2p/${e.toString()}`;a=a.map(h=>{let f=h.multiaddr.getPeerId();return h.multiaddr.protos().pop()?.path===!0?h:f!==e.toString()?{multiaddr:h.multiaddr.encapsulate(l),isCertified:h.isCertified}:h})}let c=[];for(let l of a)this.connectionGater.denyDialMultiaddr!=null&&await this.connectionGater.denyDialMultiaddr(l.multiaddr)||c.push(l);let u=c.sort(this.addressSorter);if(u.length===0)throw new w("The connection gater denied all addresses in the dial request",V.ERR_NO_VALID_ADDRESSES);return u}async performDial(e,t={}){let n=e.multiaddrs.map(()=>new AbortController);try{let i=new vt({concurrency:this.maxParallelDialsPerPeer});i.on("error",o=>{Ir.error("error dialling",o)});let s=await Promise.any(e.multiaddrs.map(async(o,a)=>{let c=n[a];if(c==null)throw new w("dialAction did not come with an AbortController",V.ERR_INVALID_PARAMETERS);let u=DT(c.signal,t.signal);u.addEventListener("abort",()=>{Ir("dial to %s aborted",o)});let l=Me();return await i.add(async()=>{if(u.aborted){Ir("dial to %s was aborted before reaching the head of the peer dial queue",o),l.reject(new Xr);return}await this.queue.add(async()=>{try{if(u.aborted){Ir("dial to %s was aborted before reaching the head of the dial queue",o),l.reject(new Xr);return}e.status="active";let h=await this.transportManager.dial(o,{...t,signal:u});if(c.signal.aborted){Ir("multiple dials succeeded, closing superfluous connection"),h.close().catch(f=>{Ir.error("error closing superfluous connection",f)}),l.reject(new Xr);return}n[a]=void 0,n.forEach(f=>{f!==void 0&&f.abort()}),Ir("dial to %s succeeded",o),l.resolve(h)}catch(h){Ir.error("error during dial of %s",o,h),l.reject(h)}},{...t,signal:u}).catch(h=>{l.reject(h)})},{signal:u}).catch(h=>{l.reject(h)}).finally(()=>{u.clear()}),l.promise}));if(s==null)throw new w("successful dial led to empty object returned from peer dial queue",V.ERR_TRANSPORT_DIAL_FAILED);return e.status="success",s}catch(i){throw e.status="error",e.multiaddrs.length===1&&i.name==="AggregateError"?i.errors[0]:i}}};function N$(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var yn=D("libp2p:connection-manager"),B$=50,Qc={minConnections:50,maxConnections:300,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0},Id=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;constructor(e,t={}){this.maxConnections=t.maxConnections??Qc.maxConnections;let n=t.minConnections??Qc.minConnections;if(this.maxConnections<n)throw new w("Connection Manager maxConnections must be greater than minConnections",V.ERR_INVALID_PARAMETERS);this.connections=new Mr,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map(i=>re(i)),this.deny=(t.deny??[]).map(i=>re(i)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Qc.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new CT.RateLimiterMemory({points:t.inboundConnectionThreshold??Qc.inboundConnectionThreshold,duration:1}),this.autoDial=new Sd({connectionManager:this,peerStore:e.peerStore,events:e.events},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??Qc.autoDialConcurrency,autoDialPriority:t.autoDialPriority??Qc.autoDialPriority}),this.connectionPruner=new Ad({connectionManager:this,peerStore:e.peerStore,events:e.events},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Rd({peerId:e.peerId,metrics:e.metrics,peerStore:e.peerStore,transportManager:e.transportManager,connectionGater:e.connectionGater},{addressSorter:t.addressSorter??Gc,maxParallelDials:t.maxParallelDials??100,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??3e4,resolvers:t.resolvers??{dnsaddr:Wc}})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.stat.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let i of n.streams){let s=`${i.stat.direction} ${i.stat.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let i of n){let s={};for(let o of i.streams){let a=`${o.stat.direction} ${o.stat.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[o,a]of Object.entries(s))e[o]=e[o]??[],e[o].push(a)}let t={};for(let[n,i]of Object.entries(e)){i=i.sort((o,a)=>o-a);let s=Math.floor(i.length*.9);t[n]=i[s]}return t}}),this.autoDial.start(),this.started=!0,yn("started")}async afterStart(){Promise.resolve().then(async()=>{let e=[];for(let t of await this.peerStore.all())t.tags.has(RT)&&e.push(t.id);await Promise.all(e.map(async t=>{await this.openConnection(t).catch(n=>{yn.error(n)})}))}).catch(e=>{yn.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(i){yn.error(i)}})());yn("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),yn("stopped")}onConnect(e){this._onConnect(e).catch(t=>{yn.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,i=this.connections.get(n),s=!1;i!=null?i.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,i=this.connections.get(n);i!=null&&i.length>1?(i=i.filter(s=>s.id!==t.id),this.connections.set(n,i)):i!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new w("Not started",V.ERR_NODE_NOT_STARTED);let{peerId:n}=xd(e);if(n!=null){yn("dial %p",n);let a=this.getConnections(n);if(a.length>0)return yn("had an existing connection to %p",n),a[0]}let i=await this.dialQueue.dial(e,{...t,priority:t.priority??B$}),s=this.connections.get(i.remotePeer);s==null&&(s=[],this.connections.set(i.remotePeer,s));let o=!1;for(let a of s)a.id===i.id&&(o=!0);return o||s.push(i),i}async closeConnections(e){let t=this.connections.get(e)??[];await Promise.all(t.map(async n=>{await n.close()}))}async acceptIncomingConnection(e){if(this.deny.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return yn("connection from %s refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return yn("connection from %s refused - incomingPendingConnections exceeded by peer %s",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let i=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(i,1)}catch{return yn("connection from %s refused - inboundConnectionThreshold exceeded by host %s",i,e.remoteAddr),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(yn("connection from %s refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){return this.dialQueue.pendingDials}};async function*Zl(r,e){yield*Kn(r,async t=>(await e.merge(t.id,{multiaddrs:t.multiaddrs}),t))}function Td(r){let e=new Set;return Fr(r,t=>e.has(t.id.toString())?!1:(e.add(t.id.toString()),!0))}async function*Dd(r,e=1){let t=0;for await(let n of r)t++,yield n;if(t<e)throw new w(`more peers required, seen: ${t} min: ${e}`,"NOT_FOUND")}var Cd=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new w("No content routers available",V.ERR_NO_ROUTERS_AVAILABLE);yield*be(jt(...this.routers.map(n=>n.findProviders(e,t))),n=>Zl(n,this.components.peerStore),n=>Td(n),n=>Dd(n))}async provide(e,t={}){if(this.routers.length===0)throw new w("No content routers available",V.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new w(Oi.NOT_STARTED_YET,V.DHT_NOT_STARTED);await Promise.all(this.routers.map(async i=>{await i.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new w(Oi.NOT_STARTED_YET,V.DHT_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var M$=D("libp2p:peer-routing"),Pd=class{components;routers;constructor(e,t){this.components=e,this.routers=t.routers??[]}async findPeer(e,t){if(this.routers.length===0)throw new w("No peer routers available",V.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.components.peerId.toString())throw new w("Should not try to find self",V.ERR_FIND_SELF);let n=await be(jt(...this.routers.map(i=>async function*(){try{yield await i.findPeer(e,t)}catch(s){M$.error(s)}}())),i=>Fr(i,Boolean),i=>Zl(i,this.components.peerStore),async i=>si(i));if(n!=null)return n;throw new w(Oi.NOT_FOUND,V.ERR_NOT_FOUND)}async*getClosestPeers(e,t){if(this.routers.length===0)throw new w("No peer routers available",V.ERR_NO_ROUTERS_AVAILABLE);yield*be(jt(...this.routers.map(n=>n.getClosestPeers(e,t))),n=>Zl(n,this.components.peerStore),n=>Td(n),n=>Dd(n))}};var T5=D("libp2p:registrar"),D5=32,C5=64,kd=class{topologies;handlers;components;constructor(e){this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onConnect=this._onConnect.bind(this),this.components.events.addEventListener("connection:close",this._onDisconnect),this.components.events.addEventListener("connection:open",this._onConnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new w(`No handler registered for protocol ${e}`,V.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new w(`Handler already registered for protocol ${e}`,V.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=uo.bind({ignoreUndefined:!0})({maxInboundStreams:D5,maxOutboundStreams:C5},n);this.handlers.set(e,{handler:t,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){let t=Array.isArray(e)?e:[e];t.forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:t})}async register(e,t){if(!Gg(t))throw T5.error("topology must be an instance of interfaces/topology"),new w("topology must be an instance of interfaces/topology",V.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,i=this.topologies.get(e);return i==null&&(i=new Map,this.topologies.set(e,i)),i.set(n,t),await t.setRegistrar(this),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t.remotePeer).then(n=>{for(let i of n.protocols){let s=this.topologies.get(i);if(s!=null)for(let o of s.values())o.onDisconnect(t.remotePeer)}}).catch(n=>{T5.error("could not inform topologies of disconnecting peer %p",t.remotePeer,n)})}_onConnect(e){let t=e.detail;this.components.peerStore.get(t.remotePeer).then(n=>{for(let i of n.protocols){let s=this.topologies.get(i);if(s!=null)for(let o of s.values())o.onConnect(t.remotePeer,t)}}).catch(n=>{T5.error("could not inform topologies of connecting peer %p",t.remotePeer,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,i=(n?.protocols??[]).filter(o=>!t.protocols.includes(o)),s=t.protocols.filter(o=>!(n?.protocols??[]).includes(o));for(let o of i){let a=this.topologies.get(o);if(a!=null)for(let c of a.values())c.onDisconnect(t.id)}for(let o of s){let a=this.topologies.get(o);if(a!=null)for(let c of a.values()){let u=this.components.connectionManager.getConnections(t.id)[0];u!=null&&c.onConnect(t.id,u)}}}};var aa=D("libp2p:transports"),Nd=class{components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.components=e,this.started=!1,this.transports=new Map,this.listeners=hi({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??no.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(t==null)throw new w("Transport must have a valid tag",V.ERR_INVALID_KEY);if(this.transports.has(t))throw new w(`There is already a transport with the tag ${t}`,V.ERR_DUPLICATE_TRANSPORT);aa("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(aa("closing listeners for %s",t);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),aa("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.transportForMultiaddr(e);if(n==null)throw new w(`No transport available for address ${String(e)}`,V.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=V.ERR_TRANSPORT_DIAL_FAILED),i}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}transportForMultiaddr(e){for(let t of this.transports.values())if(t.filter([e]).length>0)return t}async listen(e){if(e==null||e.length===0){aa("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,i]of this.transports.entries()){let s=i.filter(e),o=[];for(let u of s){aa("creating listener for %s on %s",n,u);let l=i.createListener({upgrader:this.components.upgrader}),h=this.listeners.get(n)??[];h==null&&(h=[],this.listeners.set(n,h)),h.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let f=h.findIndex(d=>d===l);h.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),o.push(l.listen(u))}if(o.length===0){t.push(n);continue}if((await Promise.allSettled(o)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==no.NO_FATAL)throw new w(`Transport (${n}) could not listen on any available address`,V.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===no.FATAL_ALL)throw new w(n,V.ERR_NO_VALID_ADDRESSES);aa(`libp2p in dial mode only: ${n}`)}}async remove(e){aa("removing %s",e);for(let t of this.listeners.get(e)??[])await t.close();this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var L5=F(Zr(),1);var ds="/multistream/1.0.0";var F$=D("libp2p:mss"),PT=q(`
|
|
84
|
-
`);function Jl(r){let e=new j(r,PT);return Et.single(e)}function ca(r,e,t={}){let n=Jl(e);t.writeBytes===!0?r.push(n.subarray()):r.push(n)}function kT(r,e,t={}){let n=new j;for(let i of e)n.append(Jl(i));t.writeBytes===!0?r.push(n.subarray()):r.push(n)}async function K$(r,e){let t=1,n={[Symbol.asyncIterator]:()=>n,next:async()=>await r.next(t)},i=n;e?.signal!=null&&(i=lt(n,e.signal));let s=a=>{t=a},o=await be(i,a=>Ct(a,{onLength:s,maxDataLength:1024}),async a=>await si(a));if(o==null||o.length===0)throw new w("no buffer returned","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");if(o.get(o.byteLength-1)!==PT[0])throw F$.error("Invalid mss message - missing newline - %s",o.subarray()),new w("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return o.sublist(0,-1)}async function Xc(r,e){let t=await K$(r,e);return B(t.subarray())}function P5(r){let e=async function*(){let t=yield,n=new j;for await(let i of r){if(t==null){n.append(i),t=yield n,n=new j;continue}for(n.append(i);n.length>=t;){let s=n.sublist(0,t);if(n.consume(t),t=yield s,t==null){n.length>0&&(t=yield n,n=new j);break}}}if(t!=null)throw Object.assign(new Error(`stream ended before ${t} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return e.next(),e}function Ld(r){let e=tt(),t=P5(r.source),n=Me(),i,s=r.sink(async function*(){yield*e,yield*await n.promise}());return s.catch(a=>{i=a}),{reader:t,writer:e,stream:{sink:async a=>{if(i!=null){await Promise.reject(i);return}n.resolve(a),await s},source:t},rest:()=>e.end(),write:e.push,read:async()=>{let a=await t.next();if(a.value!=null)return a.value}}}var eh=D("libp2p:mss:select");async function th(r,e,t={}){e=Array.isArray(e)?[...e]:[e];let{reader:n,writer:i,rest:s,stream:o}=Ld(r),a=e.shift();if(a==null)throw new Error("At least one protocol must be specified");eh.trace('select: write ["%s", "%s"]',ds,a);let c=q(ds),u=q(a);kT(i,[c,u],t);let l=await Xc(n,t);if(eh.trace('select: read "%s"',l),l===ds&&(l=await Xc(n,t),eh.trace('select: read "%s"',l)),l===a)return s(),{stream:o,protocol:a};for(let h of e){eh.trace('select: write "%s"',h),ca(i,q(h),t);let f=await Xc(n,t);if(eh.trace('select: read "%s" for "%s"',f,h),f===h)return s(),{stream:o,protocol:h}}throw s(),new w("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}var rh=D("libp2p:mss:handle");async function nh(r,e,t){e=Array.isArray(e)?e:[e];let{writer:n,reader:i,rest:s,stream:o}=Ld(r);for(;;){let a=await Xc(i,t);if(rh.trace('read "%s"',a),a===ds){rh.trace('respond with "%s" for "%s"',ds,a),ca(n,q(ds),t);continue}if(e.includes(a))return ca(n,q(a),t),rh.trace('respond with "%s" for "%s"',a,a),s(),{stream:o,protocol:a};if(a==="ls"){ca(n,new j(...e.map(c=>Jl(q(c)))),t),rh.trace('respond with "%s" for %s',e,a);continue}ca(n,q("na"),t),rh('respond with "na" for "%s"',a)}}var LT=Symbol.for("@libp2p/connection");var OT="OPEN",k5="CLOSING",Od="CLOSED";var V$=D("libp2p:connection"),N5=class{id;remoteAddr;remotePeer;stat;tags;_newStream;_close;_getStreams;_closing;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:i,close:s,getStreams:o,stat:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.stat={...a,status:OT},this._newStream=i,this._close=s,this._getStreams=o,this.tags=[],this._closing=!1}[Symbol.toStringTag]="Connection";[LT]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.stat.status===k5)throw new w("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.stat.status===Od)throw new w("the connection is closed","ERR_CONNECTION_CLOSED");Array.isArray(e)||(e=[e]);let n=await this._newStream(e,t);return n.stat.direction="outbound",n}addStream(e){e.stat.direction="inbound"}removeStream(e){}async close(){if(!(this.stat.status===Od||this._closing)){this.stat.status=k5;try{this.streams.forEach(e=>{e.close()})}catch(e){V$.error(e)}this._closing=!0,await this._close(),this._closing=!1,this.stat.timeline.close=Date.now(),this.stat.status=Od}}};function BT(r){return new N5(r)}var At=D("libp2p:upgrader");function H$(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==V.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return D5}function $$(r,e){try{let{options:t}=e.getHandler(r);return t.maxOutboundStreams}catch(t){if(t.code!==V.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return C5}function MT(r,e,t){let n=0;return t.streams.forEach(i=>{i.stat.direction===e&&i.stat.protocol===r&&n++}),n}var Bd=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,t.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??3e4,this.events=e.events}async shouldBlockConnection(e,t,n){let i=this.components.connectionGater[n];if(i!==void 0&&await i(e,t))throw new w(`The multiaddr connection is blocked by gater.${n}`,V.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new w("connection denied",V.ERR_CONNECTION_DENIED);let i,s,o,a,c,u=it([AbortSignal.timeout(this.inboundUpgradeTimeout)]);try{(0,L5.setMaxListeners)?.(1/0,u)}catch{}try{let l=Er(e,u);if(e.source=l.source,e.sink=l.sink,await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new w("The multiaddr connection is blocked by gater.acceptConnection",V.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),At("starting the inbound connection upgrade");let h=e;if(t?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(At("protecting the inbound connection"),h=await f.protect(e))}try{if(i=h,t?.skipEncryption!==!0){({conn:i,remotePeer:s,protocol:c}=await this._encryptInbound(h));let f={...h,...i};await this.shouldBlockConnection(s,f,"denyInboundEncryptedConnection")}else{let f=e.remoteAddr.getPeerId();if(f==null)throw new w("inbound connection that skipped encryption must have a peer id",V.ERR_INVALID_MULTIADDR);let d=oe(f);c="native",s=d}if(o=i,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){let f=await this._multiplexInbound({...h,...i},this.muxers);a=f.muxerFactory,o=f.stream}}catch(f){throw At.error("Failed to upgrade inbound connection",f),f}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),At("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:o,muxerFactory:a,remotePeer:s})}finally{this.components.connectionManager.afterUpgradeInbound(),u.clear()}}async upgradeOutbound(e,t){let n=e.remoteAddr.getPeerId(),i;n!=null&&(i=oe(n),await this.shouldBlockConnection(i,e,"denyOutboundConnection"));let s,o,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),At("Starting the outbound connection upgrade");let l=e;if(t?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(l=await h.protect(e))}try{if(s=l,t?.skipEncryption!==!0){({conn:s,remotePeer:o,protocol:c}=await this._encryptOutbound(l,i));let h={...l,...s};await this.shouldBlockConnection(o,h,"denyOutboundEncryptedConnection")}else{if(i==null)throw new w("Encryption was skipped but no peer id was passed",V.ERR_INVALID_PEER);c="native",o=i}if(a=s,t?.muxerFactory!=null)u=t.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexOutbound({...l,...s},this.muxers);u=h.muxerFactory,a=h.stream}}catch(h){throw At.error("Failed to upgrade outbound connection",h),await e.close(h),h}return await this.shouldBlockConnection(o,e,"denyOutboundUpgradedConnection"),At("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:o})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:i,upgradedConn:s,remotePeer:o,muxerFactory:a}=e,c,u,l;a!=null&&(c=a.createStreamMuxer({direction:n,onIncomingStream:d=>{l!=null&&Promise.resolve().then(async()=>{let p=this.components.registrar.getProtocols(),{stream:m,protocol:g}=await nh(d,p);if(At("%s: incoming stream opened on %s",n,g),l==null)return;let y=H$(g,this.components.registrar);if(MT(g,"inbound",l)===y){let E=new w(`Too many inbound protocol streams for protocol "${g}" - limit ${y}`,V.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(E),E}d.source=m.source,d.sink=m.sink,d.stat.protocol=g,await this.components.peerStore.merge(o,{protocols:[g]}),l.addStream(d),this.components.metrics?.trackProtocolStream(d,l),this._onStream({connection:l,stream:d,protocol:g})}).catch(p=>{At.error(p),d.stat.timeline.close==null&&d.close()})},onStreamEnd:d=>{l?.removeStream(d.id)}}),u=async(d,p={})=>{if(c==null)throw new w("Stream is not multiplexed",V.ERR_MUXER_UNAVAILABLE);At("%s: starting new stream on %s",n,d);let m=await c.newStream();try{if(p.signal==null){At("No abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d),p.signal=AbortSignal.timeout(3e4);try{(0,L5.setMaxListeners)?.(1/0,p.signal)}catch{}}let{stream:g,protocol:y}=await th(m,d,p),b=$$(y,this.components.registrar);if(MT(y,"outbound",l)===b){let R=new w(`Too many outbound protocol streams for protocol "${y}" - limit ${b}`,V.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw m.abort(R),R}return await this.components.peerStore.merge(o,{protocols:[y]}),m.source=g.source,m.sink=g.sink,m.stat.protocol=y,this.components.metrics?.trackProtocolStream(m,l),m}catch(g){throw At.error("could not create new stream",g),m.stat.timeline.close==null&&m.close(),g.code!=null?g:new w(String(g),V.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([c.sink(s.source),s.sink(c.source)]).catch(d=>{At.error(d)}));let h=i.timeline;i.timeline=new Proxy(h,{set:(...d)=>(l!=null&&d[1]==="close"&&d[2]!=null&&h.close==null&&(async()=>{try{l.stat.status==="OPEN"&&await l.close()}catch(p){At.error(p)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(p=>{At.error(p)}),Reflect.set(...d))}),i.timeline.upgraded=Date.now();let f=()=>{throw new w("connection is not multiplexed",V.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=BT({remoteAddr:i.remoteAddr,remotePeer:o,stat:{status:"OPEN",direction:n,timeline:i.timeline,multiplexer:c?.protocol,encryption:t},newStream:u??f,getStreams:()=>c!=null?c.streams:f(),close:async()=>{await i.close(),c?.close()}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:t,stream:n,protocol:i}=e,{handler:s}=this.components.registrar.getHandler(i);s({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());At("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:i}=await nh(e,t,{writeBytes:!0}),s=this.connectionEncryption.get(i);if(s==null)throw new Error(`no crypto module found for ${i}`);return At("encrypting inbound connection..."),{...await s.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw new w(String(n),V.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());At("selecting outbound crypto protocol",n);try{let{stream:i,protocol:s}=await th(e,n,{writeBytes:!0}),o=this.connectionEncryption.get(s);if(o==null)throw new Error(`no crypto module found for ${s}`);return At("encrypting outbound connection to %p",t),{...await o.secureOutbound(this.components.peerId,i,t),protocol:s}}catch(i){throw new w(String(i),V.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());At("outbound selecting muxer %s",n);try{let{stream:i,protocol:s}=await th(e,n,{writeBytes:!0});At("%s selected as muxer protocol",s);let o=t.get(s);return{stream:i,muxerFactory:o}}catch(i){throw At.error("error multiplexing outbound stream",i),new w(String(i),V.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let n=Array.from(t.keys());At("inbound handling muxers %s",n);try{let{stream:i,protocol:s}=await nh(e,n,{writeBytes:!0}),o=t.get(s);return{stream:i,muxerFactory:o}}catch(i){throw At.error("error multiplexing inbound stream",i),new w(String(i),V.ERR_MUXER_UNAVAILABLE)}}};var Gr=D("libp2p"),O5=class extends Ue{peerId;peerStore;contentRouting;peerRouting;keychain;metrics;services;components;#e;constructor(e){super();let t=new Ue,n=t.dispatchEvent.bind(t);t.dispatchEvent=c=>{let u=n(c),l=this.dispatchEvent(new Je(c.type,{detail:c.detail}));return u||l};try{(0,UT.setMaxListeners)?.(1/0,t)}catch{}this.#e=!1,this.peerId=e.peerId,this.services={};let i=this.components=mT({peerId:e.peerId,events:t,datastore:e.datastore??new yo,connectionGater:gT(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new bd(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),i.events.addEventListener("peer:update",c=>{c.detail.previous==null&&this.safeDispatchEvent("peer:discovery",{detail:c.detail.peer})}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Bd(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((c,u)=>this.configureComponent(`connection-encryption-${u}`,c(this.components))),muxers:(e.streamMuxers??[]).map((c,u)=>this.configureComponent(`stream-muxers-${u}`,c(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Nd(this.components,e.transportManager)),this.configureComponent("connectionManager",new Id(this.components,e.connectionManager)),this.configureComponent("registrar",new kd(this.components)),this.configureComponent("addressManager",new Ed(this.components,e.addresses));let s=sa.generateOptions();this.keychain=this.configureComponent("keyChain",new sa(this.components,{...s,...e.keychain}));let o=(e.peerRouters??[]).map((c,u)=>this.configureComponent(`peer-router-${u}`,c(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Pd(this.components,{routers:o}));let a=(e.contentRouters??[]).map((c,u)=>this.configureComponent(`content-router-${u}`,c(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Cd(this.components,{routers:a})),(e.peerDiscovery??[]).forEach((c,u)=>{this.configureComponent(`peer-discovery-${u}`,c(this.components)).addEventListener("peer",h=>{this.#t(h)})}),e.transports.forEach((c,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,c(this.components)))}),e.services!=null)for(let c of Object.keys(e.services)){let u=e.services[c],l=u(this.components);if(l==null){Gr.error("service factory %s returned null or undefined instance",c);continue}this.services[c]=l,this.configureComponent(c,l),l[wl]!=null&&(Gr("registering service %s for content routing",c),a.push(l[wl])),l[bl]!=null&&(Gr("registering service %s for peer routing",c),o.push(l[bl])),l[qo]!=null&&(Gr("registering service %s for peer discovery",c),l[qo].addEventListener("peer",h=>{this.#t(h)}))}}configureComponent(e,t){return t==null&&Gr.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.#e)return;this.#e=!0,Gr("libp2p is starting"),(await this.keychain.listKeys()).find(t=>t.name==="self")==null&&(Gr("importing self key into keychain"),await this.keychain.importPeer("self",this.components.peerId));try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.safeDispatchEvent("start",{detail:this}),Gr("libp2p has started")}catch(t){throw Gr.error("An error occurred starting libp2p",t),await this.stop(),t}}async stop(){this.#e&&(Gr("libp2p is stopping"),this.#e=!1,await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.safeDispatchEvent("stop",{detail:this}),Gr("libp2p has stopped"))}isStarted(){return this.#e}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Rr;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,t)}async dialProtocol(e,t,n={}){if(t==null)throw new w("no protocols were provided to open a stream",V.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw new w("no protocols were provided to open a stream",V.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e){Vo(e)&&(e=oe(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e)}async getPublicKey(e,t={}){if(Gr("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;let n=await this.peerStore.get(e);if(n.id.publicKey!=null)return n.id.publicKey;let i=he([q("/pk/"),e.multihash.digest]),s=await this.contentRouting.get(i,t);return kr(s),await this.peerStore.patch(e,{publicKey:s}),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async i=>{await this.components.registrar.handle(i,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}#t(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){Gr.error(new Error(V.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs,protocols:t.protocols}).catch(n=>{Gr.error(n)})}};async function FT(r){if(r.peerId==null){let e=r.datastore;if(e!=null)try{let t=new sa({datastore:e},uo(sa.generateOptions(),r.keychain));r.peerId=await t.exportPeerId("self")}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}}return r.peerId==null&&(r.peerId=await dd()),new O5(AT(r))}async function KT(r){let e=await FT(r);return r.start!==!1&&await e.start(),e}var M5=F(Zr(),1);var qT="libp2p",VT="autonat",zT="1.0.0";var we;(function(r){let e;(function(u){u.DIAL="DIAL",u.DIAL_RESPONSE="DIAL_RESPONSE"})(e=r.MessageType||(r.MessageType={}));let t;(function(u){u[u.DIAL=0]="DIAL",u[u.DIAL_RESPONSE=1]="DIAL_RESPONSE"})(t||(t={})),function(u){u.codec=()=>Ht(t)}(e=r.MessageType||(r.MessageType={}));let n;(function(u){u.OK="OK",u.E_DIAL_ERROR="E_DIAL_ERROR",u.E_DIAL_REFUSED="E_DIAL_REFUSED",u.E_BAD_REQUEST="E_BAD_REQUEST",u.E_INTERNAL_ERROR="E_INTERNAL_ERROR"})(n=r.ResponseStatus||(r.ResponseStatus={}));let i;(function(u){u[u.OK=0]="OK",u[u.E_DIAL_ERROR=100]="E_DIAL_ERROR",u[u.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",u[u.E_BAD_REQUEST=200]="E_BAD_REQUEST",u[u.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"})(i||(i={})),function(u){u.codec=()=>Ht(i)}(n=r.ResponseStatus||(r.ResponseStatus={}));let s;(function(u){let l;u.codec=()=>(l==null&&(l=se((h,f,d={})=>{if(d.lengthDelimited!==!1&&f.fork(),h.id!=null&&(f.uint32(10),f.bytes(h.id)),h.addrs!=null)for(let p of h.addrs)f.uint32(18),f.bytes(p);d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={addrs:[]},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.id=h.bytes();break;case 2:d.addrs.push(h.bytes());break;default:h.skipType(m&7);break}}return d})),l),u.encode=h=>ie(h,u.codec()),u.decode=h=>ne(h,u.codec())})(s=r.PeerInfo||(r.PeerInfo={}));let o;(function(u){let l;u.codec=()=>(l==null&&(l=se((h,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),h.peer!=null&&(f.uint32(10),r.PeerInfo.codec().encode(h.peer,f)),d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.peer=r.PeerInfo.codec().decode(h,h.uint32());break;default:h.skipType(m&7);break}}return d})),l),u.encode=h=>ie(h,u.codec()),u.decode=h=>ne(h,u.codec())})(o=r.Dial||(r.Dial={}));let a;(function(u){let l;u.codec=()=>(l==null&&(l=se((h,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),h.status!=null&&(f.uint32(8),r.ResponseStatus.codec().encode(h.status,f)),h.statusText!=null&&(f.uint32(18),f.string(h.statusText)),h.addr!=null&&(f.uint32(26),f.bytes(h.addr)),d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.status=r.ResponseStatus.codec().decode(h);break;case 2:d.statusText=h.string();break;case 3:d.addr=h.bytes();break;default:h.skipType(m&7);break}}return d})),l),u.encode=h=>ie(h,u.codec()),u.decode=h=>ne(h,u.codec())})(a=r.DialResponse||(r.DialResponse={}));let c;r.codec=()=>(c==null&&(c=se((u,l,h={})=>{h.lengthDelimited!==!1&&l.fork(),u.type!=null&&(l.uint32(8),r.MessageType.codec().encode(u.type,l)),u.dial!=null&&(l.uint32(18),r.Dial.codec().encode(u.dial,l)),u.dialResponse!=null&&(l.uint32(26),r.DialResponse.codec().encode(u.dialResponse,l)),h.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let h={},f=l==null?u.len:u.pos+l;for(;u.pos<f;){let d=u.uint32();switch(d>>>3){case 1:h.type=r.MessageType.codec().decode(u);break;case 2:h.dial=r.Dial.codec().decode(u,u.uint32());break;case 3:h.dialResponse=r.DialResponse.codec().decode(u,u.uint32());break;default:u.skipType(d&7);break}}return h})),c),r.encode=u=>ie(u,r.codec()),r.decode=u=>ne(u,r.codec())})(we||(we={}));var Qe=D("libp2p:autonat"),B5=4,U5=class{components;startupDelay;refreshInterval;protocol;timeout;maxInboundStreams;maxOutboundStreams;verifyAddressTimeout;started;constructor(e,t){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??qT}/${VT}/${zT}`,this.timeout=t.timeout??3e4,this.maxInboundStreams=t.maxInboundStreams??1,this.maxOutboundStreams=t.maxOutboundStreams??1,this.startupDelay=t.startupDelay??5e3,this.refreshInterval=t.refreshInterval??6e4,this._verifyExternalAddresses=this._verifyExternalAddresses.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(this.protocol,e=>{this.handleIncomingAutonatStream(e).catch(t=>{Qe.error("error handling incoming autonat stream",t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.startupDelay),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),clearTimeout(this.verifyAddressTimeout),this.started=!1}async handleIncomingAutonatStream(e){let t=it([AbortSignal.timeout(this.timeout)]);try{(0,M5.setMaxListeners)?.(1/0,t)}catch{}let n=this.components.addressManager.getAddresses().map(i=>i.toOptions().host);try{let i=Er(e.stream,t),s=this;await be(i,o=>Ct(o),async function*(o){let a=await si(o);if(a==null){Qe("no message received"),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"No message was sent"}});return}let c;try{c=we.decode(a)}catch(m){Qe.error("could not decode message",m),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"Could not decode message"}});return}let u=c.dial;if(u==null){Qe.error("dial was missing from message"),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}});return}let l,h=u.peer;if(h==null||h.id==null){Qe.error("PeerId missing from message"),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}});return}try{l=It(h.id)}catch(m){Qe.error("invalid PeerId",m),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}});return}if(Qe("incoming request from %p",l),!e.connection.remotePeer.equals(l)){Qe("target peer %p did not equal sending peer %p",l,e.connection.remotePeer),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}});return}let f=h.addrs.map(m=>re(m)).filter(m=>{let g=m.toOptions().host===e.connection.remoteAddr.toOptions().host;return Qe.trace("request to dial %s was sent from %s is same host %s",m,e.connection.remoteAddr,g),g}).filter(m=>{let g=m.toOptions().host,y=!(Nn(g)??!1);return Qe.trace("host %s was public %s",g,y),y}).filter(m=>{let g=m.toOptions().host,y=!n.includes(g);return Qe.trace("host %s was not our host %s",g,y),y}).filter(m=>{let g=!!s.components.transportManager.transportForMultiaddr(m);return Qe.trace("transport for %s is supported %s",m,g),g}).map(m=>(m.getPeerId()==null&&(m=m.encapsulate(`/p2p/${l.toString()}`)),m));if(f.length===0){Qe("no valid multiaddrs for %p in message",l),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}});return}Qe("dial multiaddrs %s for peer %p",f.map(m=>m.toString()).join(", "),l);let d="",p=f[0];for await(let m of f){let g;p=m;try{if(g=await s.components.connectionManager.openConnection(m,{signal:t}),!g.remoteAddr.equals(m))throw Qe.error("tried to dial %s but dialed %s",m,g.remoteAddr),new Error("Unexpected remote address");Qe("Success %p",l),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.OK,addr:g.remoteAddr.decapsulateCode(X("p2p").code).bytes}});return}catch(y){Qe("could not dial %p",l,y),d=y.message}finally{g!=null&&await g.close()}}yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_DIAL_ERROR,statusText:d,addr:p.bytes}})},o=>Et(o),e.stream)}catch(i){Qe.error("error handling incoming autonat stream",i)}finally{t.clear()}}_verifyExternalAddresses(){this.verifyExternalAddresses().catch(e=>{Qe.error("error verifying external address",e)})}async verifyExternalAddresses(){if(clearTimeout(this.verifyAddressTimeout),!this.isStarted())return;let e=this.components.addressManager,t=e.getObservedAddrs().filter(s=>{let o=s.toOptions();return!(Nn(o.host)??!1)});if(t.length===0){Qe("no public addresses found, not requesting verification"),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval);return}let n=AbortSignal.timeout(this.timeout);try{(0,M5.setMaxListeners)?.(1/0,n)}catch{}let i=this;try{Qe("verify multiaddrs %s",t.map(h=>h.toString()).join(", "));let s=we.encode({type:we.MessageType.DIAL,dial:{peer:{id:this.components.peerId.toBytes(),addrs:t.map(h=>h.bytes)}}}),a=(await dd()).toBytes(),c={},u=[],l=async h=>{try{Qe("asking %p to verify multiaddr",h.id);let f=await i.components.connectionManager.openConnection(h.id,{signal:n}),d=await f.newStream(this.protocol,{signal:n}),p=Er(d,n),m=await be([s],y=>Et(y),p,y=>Ct(y),async y=>si(y));if(m==null){Qe("no response received from %p",f.remotePeer);return}let g=we.decode(m);if(g.type!==we.MessageType.DIAL_RESPONSE||g.dialResponse==null){Qe("invalid autonat response from %p",f.remotePeer);return}if(g.dialResponse.status===we.ResponseStatus.OK){let y=f.remoteAddr.toOptions(),b;if(y.family===4)b=y.host.split(".")[0];else if(y.family===6)b=y.host.split(":")[0];else{Qe('remote address "%s" was not IP4 or IP6?',y.host);return}if(u.includes(b)){Qe("already have response from network segment %d - %s",b,y.host);return}u.push(b)}return g.dialResponse}catch(f){Qe.error("error asking remote to verify multiaddr",f)}};for await(let h of $o(Kn(this.components.peerRouting.getClosestPeers(a,{signal:n}),f=>async()=>l(f)),{concurrency:B5}))try{if(h==null)continue;let f=h.addr==null?t[0]:re(h.addr);if(Qe("autonat response for %s is %s",f,h.status),h.status===we.ResponseStatus.E_BAD_REQUEST||h.status===we.ResponseStatus.E_DIAL_REFUSED||h.addr==null&&t.length>1)continue;if(!t.some(p=>p.equals(f))){Qe("peer reported %s as %s but it was not in our observed address list",f,h.status);continue}let d=f.toString();if(c[d]==null&&(c[d]={success:0,failure:0}),h.status===we.ResponseStatus.OK?c[d].success++:h.status===we.ResponseStatus.E_DIAL_ERROR&&c[d].failure++,c[d].success===B5){Qe("%s is externally dialable",f),e.confirmObservedAddr(f);return}if(c[d].failure===B5){Qe("%s is not externally dialable",f),e.removeObservedAddr(f);return}}catch(f){Qe.error("could not verify external address",f)}}finally{this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval)}}};function HT(r={}){return e=>new U5(e,r)}var sD=F(Zr(),1);var Md="/libp2p/relay";var $T="circuit-relay-source",GT="circuit-relay-relay";var Ud=BigInt(131072),Mi="/libp2p/circuit/relay/0.2.0/hop",ih="/libp2p/circuit/relay/0.2.0/stop",WT=30*1e3,YT=30*1e3;var nt;(function(r){let e;(function(i){i.RESERVE="RESERVE",i.CONNECT="CONNECT",i.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.RESERVE=0]="RESERVE",i[i.CONNECT=1]="CONNECT",i[i.STATUS=2]="STATUS"})(t||(t={})),function(i){i.codec=()=>Ht(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=se((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.peer!=null&&(s.uint32(18),jc.codec().encode(i.peer,s)),i.reservation!=null&&(s.uint32(26),Fd.codec().encode(i.reservation,s)),i.limit!=null&&(s.uint32(34),Zc.codec().encode(i.limit,s)),i.status!=null&&(s.uint32(40),De.codec().encode(i.status,s)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.peer=jc.codec().decode(i,i.uint32());break;case 3:o.reservation=Fd.codec().decode(i,i.uint32());break;case 4:o.limit=Zc.codec().decode(i,i.uint32());break;case 5:o.status=De.codec().decode(i);break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>ie(i,r.codec()),r.decode=i=>ne(i,r.codec())})(nt||(nt={}));var wn;(function(r){let e;(function(i){i.CONNECT="CONNECT",i.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.CONNECT=0]="CONNECT",i[i.STATUS=1]="STATUS"})(t||(t={})),function(i){i.codec=()=>Ht(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=se((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.peer!=null&&(s.uint32(18),jc.codec().encode(i.peer,s)),i.limit!=null&&(s.uint32(26),Zc.codec().encode(i.limit,s)),i.status!=null&&(s.uint32(32),De.codec().encode(i.status,s)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.peer=jc.codec().decode(i,i.uint32());break;case 3:o.limit=Zc.codec().decode(i,i.uint32());break;case 4:o.status=De.codec().decode(i);break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>ie(i,r.codec()),r.decode=i=>ne(i,r.codec())})(wn||(wn={}));var jc;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={id:new Uint8Array(0),addrs:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.id=t.bytes();break;case 2:i.addrs.push(t.bytes());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(jc||(jc={}));var Fd;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);t.voucher!=null&&(n.uint32(26),n.bytes(t.voucher)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={expire:0n,addrs:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.expire=t.uint64();break;case 2:i.addrs.push(t.bytes());break;case 3:i.voucher=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(Fd||(Fd={}));var Zc;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.duration=t.uint32();break;case 2:i.data=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(Zc||(Zc={}));var De;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(De||(De={}));var F5;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(F5||(F5={}));(function(r){r.codec=()=>Ht(F5)})(De||(De={}));var Kd;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={relay:new Uint8Array(0),peer:new Uint8Array(0),expiration:0n},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.relay=t.bytes();break;case 2:i.peer=t.bytes();break;case 3:i.expiration=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(Kd||(Kd={}));var K5=D("libp2p:circuit-relay:utils");async function*QT(r,e){for await(let t of r){let n=BigInt(t.byteLength);if(e.remaining-n<0){let i=Number(e.remaining);e.remaining=0n;try{i!==0&&(yield t.subarray(0,i))}catch(s){K5.error(s)}throw new Error("data limit exceeded")}e.remaining-=n,yield t}}var j$=(r,e,t,n)=>{function i(h){r.abort(h),e.abort(h),clearTimeout(a)}let s=new AbortController,o=it([t,s.signal]),a=setTimeout(()=>{s.abort()},n.duration),c=!1,u=!1,l={remaining:n.data};queueMicrotask(()=>{e.sink(QT(lt(r.source,o,{abortMessage:"duration limit exceeded"}),l)).catch(h=>{K5.error("error while relaying streams src -> dst",h),i(h)}).finally(()=>{c=!0,u&&(o.clear(),clearTimeout(a))})}),queueMicrotask(()=>{r.sink(QT(lt(e.source,o,{abortMessage:"duration limit exceeded"}),l)).catch(h=>{K5.error("error while relaying streams dst -> src",h),i(h)}).finally(()=>{u=!0,c&&(o.clear(),clearTimeout(a))})})};function XT(r,e,t,n){let i=n?.data??BigInt(Ud),s=n?.duration??12e4;j$(r,e,t,{data:i,duration:s})}async function qd(r){let e=new TextEncoder().encode(r),t=await Pe.digest(e);return ee.createV0(t)}function V5(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var nD=F(tD(),1),J$=new Set(["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed"]),z5=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},eG=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r},tG=r=>J$.has(r),rD=r=>globalThis.DOMException===void 0?new Error(r):new DOMException(r);async function H5(r,e){return new Promise((t,n)=>{e={onFailedAttempt(){},retries:10,...e};let i=nD.default.operation(e);i.attempt(async s=>{try{t(await r(s))}catch(o){if(!(o instanceof Error)){n(new TypeError(`Non-error was thrown: "${o}". You should only throw errors.`));return}if(o instanceof z5)i.stop(),n(o.originalError);else if(o instanceof TypeError&&!tG(o.message))i.stop(),n(o);else{eG(o,s,e);try{await e.onFailedAttempt(o)}catch(a){n(a);return}i.retry(o)||n(i.mainError())}}}),e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",()=>{i.stop();let s=e.signal.reason===void 0?rD("The operation was aborted."):e.signal.reason;n(s instanceof Error?s:rD(s))},{once:!0})})}var $5=D("libp2p:circuit-relay:advert-service"),Vd=class extends Ue{contentRouting;timeout;started;bootDelay;constructor(e,t){super(),this.contentRouting=e.contentRouting,this.bootDelay=t?.bootDelay??YT,this.started=!1}isStarted(){return this.started}start(){this.started||(this.timeout=setTimeout(()=>{this._advertiseService().catch(e=>{$5.error("could not advertise service",e)})},this.bootDelay),this.started=!0)}stop(){try{clearTimeout(this.timeout)}catch{}this.started=!1}async _advertiseService(){await H5(async()=>{try{let e=await qd(Md);await this.contentRouting.provide(e),this.safeDispatchEvent("advert:success",{detail:void 0})}catch(e){if(this.safeDispatchEvent("advert:error",{detail:e}),e.code===V.ERR_NO_ROUTERS_AVAILABLE){$5.error("a content router, such as a DHT, must be provided in order to advertise the relay service",e),this.stop();return}throw $5.error("could not advertise service",e),e}})}};var zd=class{reservations=new Mr;_started=!1;interval;maxReservations;reservationClearInterval;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;constructor(e={}){this.maxReservations=e.maxReservations??15,this.reservationClearInterval=e.reservationClearInterval??3e5,this.applyDefaultLimit=e.applyDefaultLimit!==!1,this.reservationTtl=e.reservationTtl??72e5,this.defaultDurationLimit=e.defaultDurationLimit??12e4,this.defaultDataLimit=e.defaultDataLimit??Ud}isStarted(){return this._started}start(){this._started||(this._started=!0,this.interval=setInterval(()=>{let e=new Date().getTime();this.reservations.forEach((t,n)=>{t.expire.getTime()<e&&this.reservations.delete(n)})},this.reservationClearInterval))}stop(){clearInterval(this.interval)}reserve(e,t,n){if(this.reservations.size>=this.maxReservations&&!this.reservations.has(e))return{status:De.RESERVATION_REFUSED};let i=new Date(Date.now()+this.reservationTtl),s;return this.applyDefaultLimit&&(s=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),this.reservations.set(e,{addr:t,expire:i,limit:s}),{status:De.OK,expire:Math.round(i.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}hasReservation(e){return this.reservations.has(e)}get(e){return this.reservations.get(e)}};var Jc=class{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:e,peer:t,expiration:n}){this.relay=e,this.peer=t,this.expiration=n}marshal(){return Kd.encode({relay:this.relay.toBytes(),peer:this.peer.toBytes(),expiration:BigInt(this.expiration)})}equals(e){return!(!(e instanceof Jc)||!this.peer.equals(e.peer)||!this.relay.equals(e.relay)||this.expiration!==e.expiration)}};var bt=D("libp2p:circuit-relay:server"),iD=r=>r.protoCodes().includes(290),G5=class extends Ue{registrar;peerStore;addressManager;peerId;connectionManager;connectionGater;reservationStore;advertService;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;constructor(e,t={}){super(),this.registrar=e.registrar,this.peerStore=e.peerStore,this.addressManager=e.addressManager,this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.connectionGater=e.connectionGater,this.started=!1,this.hopTimeout=t?.hopTimeout??WT,this.shutdownController=new AbortController,this.maxInboundHopStreams=t.maxInboundHopStreams,this.maxOutboundHopStreams=t.maxOutboundHopStreams;try{(0,sD.setMaxListeners)?.(1/0,this.shutdownController.signal)}catch{}t.advertise!=null&&t.advertise!==!1&&(this.advertService=new Vd(e,t.advertise===!0?void 0:t.advertise),this.advertService.addEventListener("advert:success",()=>{this.safeDispatchEvent("relay:advert:success",{})}),this.advertService.addEventListener("advert:error",n=>{this.safeDispatchEvent("relay:advert:error",{detail:n.detail})})),this.reservationStore=new zd(t.reservations)}isStarted(){return this.started}async start(){this.started||(this.advertService?.start(),await this.registrar.handle(Mi,e=>{this.onHop(e).catch(t=>{bt.error(t)})},{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams}),this.reservationStore.start(),this.started=!0)}async stop(){this.advertService?.stop(),this.reservationStore.stop(),this.shutdownController.abort(),await this.registrar.unhandle(Mi),this.started=!1}async onHop({connection:e,stream:t}){bt("received circuit v2 hop protocol stream from %s",e.remotePeer);let n=Me(),i=setTimeout(()=>{n.reject("timed out")},this.hopTimeout),s=_r(t);try{let o=await Promise.race([s.pb(nt).read(),n.promise]);if(o?.type==null)throw new Error("request was invalid, could not read from stream");bt("received",o.type),await Promise.race([this.handleHopProtocol({connection:e,stream:s,request:o}),n.promise])}catch(o){bt.error("error while handling hop",o),s.pb(nt).write({type:nt.Type.STATUS,status:De.MALFORMED_MESSAGE}),t.abort(o)}finally{clearTimeout(i)}}async handleHopProtocol({stream:e,request:t,connection:n}){switch(bt("received hop message"),t.type){case nt.Type.RESERVE:await this.handleReserve({stream:e,request:t,connection:n});break;case nt.Type.CONNECT:await this.handleConnect({stream:e,request:t,connection:n});break;default:bt.error("invalid hop request type %s via peer %s",t.type,n.remotePeer),e.pb(nt).write({type:nt.Type.STATUS,status:De.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,request:t,connection:n}){let i=e.pb(nt);if(bt("hop reserve request from %s",n.remotePeer),iD(n.remoteAddr)){bt.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),i.write({type:nt.Type.STATUS,status:De.PERMISSION_DENIED});return}if(await this.connectionGater.denyInboundRelayReservation?.(n.remotePeer)===!0){bt.error("reservation for %p denied by connection gater",n.remotePeer),i.write({type:nt.Type.STATUS,status:De.PERMISSION_DENIED});return}let s=this.reservationStore.reserve(n.remotePeer,n.remoteAddr);if(s.status!==De.OK){i.write({type:nt.Type.STATUS,status:s.status});return}try{if(s.expire!=null){let o=s.expire*1e3-Date.now();await this.peerStore.merge(n.remotePeer,{tags:{[$T]:{value:1,ttl:o}}})}i.write({type:nt.Type.STATUS,status:De.OK,reservation:await this.makeReservation(n.remotePeer,BigInt(s.expire??0)),limit:this.reservationStore.get(n.remotePeer)?.limit}),bt("sent confirmation response to %s",n.remotePeer)}catch(o){bt.error("failed to send confirmation response to %p",n.remotePeer,o),this.reservationStore.removeReservation(n.remotePeer)}}async makeReservation(e,t){let n=[];for(let s of this.addressManager.getAddresses())s.toString().includes("/p2p-circuit")||n.push(s.bytes);let i=await Wt.seal(new Jc({peer:e,relay:this.peerId,expiration:Number(t)}),this.peerId);return{addrs:n,expire:t,voucher:i.marshal()}}async handleConnect({stream:e,request:t,connection:n}){let i=e.pb(nt);if(iD(n.remoteAddr)){bt.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),i.write({type:nt.Type.STATUS,status:De.PERMISSION_DENIED});return}bt("hop connect request from %s",n.remotePeer);let s;try{if(t.peer==null)throw bt.error("no peer info in hop connect request"),new Error("no peer info in request");t.peer.addrs.forEach(re),s=It(t.peer.id)}catch(h){bt.error("invalid hop connect request via peer %p %s",n.remotePeer,h),i.write({type:nt.Type.STATUS,status:De.MALFORMED_MESSAGE});return}if(!this.reservationStore.hasReservation(s)){bt.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",s,n.remotePeer,De.NO_RESERVATION),i.write({type:nt.Type.STATUS,status:De.NO_RESERVATION});return}if(await this.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,s)===!0){bt.error("hop connect for %p to %p denied by connection gater",n.remotePeer,s),i.write({type:nt.Type.STATUS,status:De.PERMISSION_DENIED});return}let o=this.connectionManager.getConnections(s);if(o.length===0){bt("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",s,n.remotePeer),i.write({type:nt.Type.STATUS,status:De.NO_RESERVATION});return}let a=o[0],c=await this.stopHop({connection:a,request:{type:wn.Type.CONNECT,peer:{id:n.remotePeer.toBytes(),addrs:[]}}});if(c==null){bt.error("failed to open stream to destination peer %s",a?.remotePeer),i.write({type:nt.Type.STATUS,status:De.CONNECTION_FAILED});return}i.write({type:nt.Type.STATUS,status:De.OK});let u=e.unwrap();bt("connection from %p to %p established - merging streans",n.remotePeer,s);let l=this.reservationStore.get(s)?.limit;XT(u,c,this.shutdownController.signal,l)}async stopHop({connection:e,request:t}){bt("starting circuit relay v2 stop request to %s",e.remotePeer);let n=await e.newStream([ih]),i=_r(n),s=i.pb(wn);s.write(t);let o;try{o=await s.read()}catch{bt.error("error parsing stop message response from %s",e.remotePeer)}if(o==null){bt.error("could not read response from %s",e.remotePeer),n.close();return}if(o.status===De.OK)return bt("stop request to %s was successful",e.remotePeer),i.unwrap();bt("stop request failed with code %d",o.status),n.close()}get reservations(){return this.reservationStore.reservations}};function Y5(r={}){return e=>new G5(e,r)}var sG=D("libp2p:stream:converter");function Q5(r,e={}){let{stream:t,remoteAddr:n}=r,{sink:i,source:s}=t,o=async function*(){for await(let u of s)u instanceof Uint8Array?yield u:yield*u}(),a={async sink(u){e.signal!=null&&(u=lt(u,e.signal));try{await i(u),await c()}catch(l){l.type!=="aborted"&&sG(l)}},source:e.signal!=null?lt(o,e.signal):o,remoteAddr:n,timeline:{open:Date.now(),close:void 0},async close(){await i(async function*(){yield new Uint8Array(0)}()),await c()}};async function c(){a.timeline.close==null&&(a.timeline.close=Date.now()),await Promise.resolve()}return a}var fo=D("libp2p:circuit-relay:discover-relays"),Hd=class extends Ue{peerId;peerStore;contentRouting;registrar;started;topologyId;constructor(e){super(),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(Mi,Es({onConnect:e=>{this.safeDispatchEvent("relay:discover",{detail:e})}})),this.discover().catch(e=>{fo.error("error listening on relays",e)}),this.started=!0}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async discover(){fo("searching peer store for relays");let e=(await this.peerStore.all()).filter(({protocols:t})=>t.includes(Mi)).sort(()=>Math.random()-.5);for(let t of e)fo("found relay peer %p in content peer store",t.id),this.safeDispatchEvent("relay:discover",{detail:t.id});fo("found %d relay peers in peer store",e.length);try{fo("searching content routing for relays");let t=await qd(Md),n=0;for await(let i of this.contentRouting.findProviders(t))if(i.multiaddrs.length>0&&!i.id.equals(this.peerId)){let s=i.id;n++,await this.peerStore.merge(s,{multiaddrs:i.multiaddrs}),fo("found relay peer %p in content routing",s),this.safeDispatchEvent("relay:discover",{detail:s})}fo("found %d relay peers in content routing",n)}catch(t){fo.error("failed when finding relays on the network",t)}}};var oD=D("libp2p:circuit-relay:transport:listener"),X5=class extends Ue{connectionManager;relayStore;listeningAddrs;constructor(e){super(),this.connectionManager=e.connectionManager,this.relayStore=e.relayStore,this.listeningAddrs=new Mr,this.relayStore.addEventListener("relay:removed",t=>{this.#e(t.detail)})}async listen(e){oD("listen on %s",e);let t=e.getPeerId(),n;if(t!=null){let s=oe(t),o=this.connectionManager.getConnectionsMap().get(s)??[];o.length>0&&(n=o[0])}if(n==null){let s=e.toString().split("/p2p-circuit").find(a=>a!==""),o=re(s);n=await this.connectionManager.openConnection(o)}if(!this.relayStore.hasReservation(n.remotePeer)){await this.relayStore.addRelay(n.remotePeer,"configured");return}let i=this.relayStore.getReservation(n.remotePeer);if(i==null)throw new w("Did not have reservation after making reservation","ERR_NO_RESERVATION");if(this.listeningAddrs.has(n.remotePeer)){oD("already listening on relay %p",n.remotePeer);return}this.listeningAddrs.set(n.remotePeer,i.addrs.map(s=>re(s).encapsulate("/p2p-circuit"))),this.safeDispatchEvent("listening",{})}getAddrs(){return[...this.listeningAddrs.values()].flat()}async close(){}#e(e){let t=this.listeningAddrs.has(e);this.listeningAddrs.delete(e),t&&this.safeDispatchEvent("close",{})}};function aD(r){return new X5(r)}var bn=D("libp2p:circuit-relay:transport:reservation-store"),aG=60*1e3*10,cG=60*1e3*5,uG=30*1e3,$d=class extends Ue{peerId;connectionManager;transportManager;peerStore;events;reserveQueue;reservations;maxDiscoveredRelays;started;constructor(e,t){super(),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Mr,this.maxDiscoveredRelays=t?.discoverRelays??0,this.started=!1,this.reserveQueue=new vt({concurrency:t?.reservationConcurrency??1}),this.events.addEventListener("peer:disconnect",n=>{this.#t(n.detail)})}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!0}async addRelay(e,t){if(this.peerId.equals(e)){bn("not trying to use self as relay");return}bn("add relay %p",e),await this.reserveQueue.add(async()=>{try{let n=this.reservations.get(e);if(n!=null){if(V5(n.reservation.expire)>aG){bn("already have reservation on relay peer %p and it expires in more than 10 minutes",e);return}clearTimeout(n.timeout),this.reservations.delete(e)}if(t==="discovered"&&[...this.reservations.values()].reduce((u,l)=>(l.type==="discovered"&&u++,u),0)>=this.maxDiscoveredRelays){bn("already have enough discovered relays");return}let i=await this.connectionManager.openConnection(e);if(i.remoteAddr.protoNames().includes("p2p-circuit")){bn("not creating reservation over relayed connection");return}let s=await this.#e(i);bn("created reservation on relay peer %p",e);let o=V5(s.expire),a=Math.min(Math.max(o-cG,uG),Math.pow(2,31)-1),c=setTimeout(()=>{this.addRelay(e,t).catch(u=>{bn.error("could not refresh reservation to relay %p",e,u)})},a);this.reservations.set(e,{timeout:c,reservation:s,type:t}),await this.peerStore.merge(e,{tags:{[GT]:{value:1,ttl:o}}}),await this.transportManager.listen([re(`/p2p/${e.toString()}/p2p-circuit`)])}catch(n){bn.error("could not reserve slot on %p",e,n),this.reservations.delete(e)}})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}async#e(e){bn("requesting reservation from %s",e.remotePeer);let t=await e.newStream(Mi),i=_r(t).pb(nt);i.write({type:nt.Type.RESERVE});let s;try{s=await i.read()}catch(a){throw bn.error("error parsing reserve message response from %p because",e.remotePeer,a),a}finally{t.close()}if(s.status===De.OK&&s.reservation!=null)return s.reservation;let o=`reservation failed with status ${s.status??"undefined"}`;throw bn.error(o),new Error(o)}#t(e){let t=this.reservations.get(e);t!=null&&(bn("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&&(bn("not enough relays %d/%d",this.reservations.size,this.maxDiscoveredRelays),this.safeDispatchEvent("relay:not-enough-relays",{})))}};var Wr=D("libp2p:circuit-relay:transport"),lG=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(re)}catch{return!1}return!0},j5=class{discovery;registrar;peerStore;connectionManager;peerId;upgrader;addressManager;connectionGater;reservationStore;started;constructor(e,t){this.registrar=e.registrar,this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.peerId=e.peerId,this.upgrader=e.upgrader,this.addressManager=e.addressManager,this.connectionGater=e.connectionGater,t.discoverRelays!=null&&t.discoverRelays>0&&(this.discovery=new Hd(e),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(i=>{Wr.error("could not add discovered relay %p",n.detail,i)})})),this.reservationStore=new $d(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.discover().catch(n=>{Wr.error("could not discover relays",n)})}),this.started=!1}isStarted(){return this.started}async start(){await this.reservationStore.start(),await this.discovery?.start(),await this.registrar.handle(ih,e=>{this.onStop(e).catch(t=>{Wr.error(t)})}),this.started=!0}async stop(){this.discovery?.stop(),await this.reservationStore.stop(),await this.registrar.unhandle(ih),this.started=!1}[Pi]=!0;[Symbol.toStringTag]="libp2p/circuit-relay-v2";async dial(e,t={}){if(e.protoCodes().filter(p=>p===290).length!==1){let p="Invalid circuit relay address";throw Wr.error(p,e),new w(p,V.ERR_RELAYED_DIAL)}let n=e.toString().split("/p2p-circuit"),i=re(n[0]),s=re(n[n.length-1]),o=i.getPeerId(),a=s.getPeerId();if(o==null||a==null){let p=`Circuit relay dial to ${e.toString()} failed as address did not have peer ids`;throw Wr.error(p),new w(p,V.ERR_RELAYED_DIAL)}let c=oe(o),u=oe(a),l=!1,f=this.connectionManager.getConnections(c)[0];f==null&&(await this.peerStore.merge(c,{multiaddrs:[i]}),f=await this.connectionManager.openConnection(c,t),l=!0);let d;try{return d=await f.newStream([Mi]),await this.connectV2({stream:d,connection:f,destinationPeer:u,destinationAddr:s,relayAddr:i,ma:e,disconnectOnFailure:l})}catch(p){throw Wr.error(`Circuit relay dial to destination ${u.toString()} via relay ${c.toString()} failed`,p),d?.abort(p),l&&await f.close(),p}}async connectV2({stream:e,connection:t,destinationPeer:n,destinationAddr:i,relayAddr:s,ma:o,disconnectOnFailure:a}){try{let c=_r(e),u=c.pb(nt);u.write({type:nt.Type.CONNECT,peer:{id:n.toBytes(),addrs:[re(i).bytes]}});let l=await u.read();if(l.status!==De.OK)throw new w(`failed to connect via relay with status ${l?.status?.toString()??"undefined"}`,V.ERR_HOP_REQUEST_FAILED);let h=Q5({stream:c.unwrap(),remoteAddr:o,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`)});return Wr("new outbound connection %s",h.remoteAddr),await this.upgrader.upgradeOutbound(h)}catch(c){throw Wr.error(`Circuit relay dial to destination ${n.toString()} via relay ${t.remotePeer.toString()} failed`,c),a&&await t.close(),c}}createListener(e){return aD({connectionManager:this.connectionManager,relayStore:this.reservationStore})}filter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>ri.matches(t))}async onStop({connection:e,stream:t}){let n=_r(t),i=await n.readPB(wn);if(Wr("received circuit v2 stop protocol request from %s",e.remotePeer),i?.type===void 0)return;let s=n.pb(wn);if(Wr("new circuit relay v2 stop stream from %s",e.remotePeer),i.type!==wn.Type.CONNECT){Wr.error("invalid stop connect request via peer %s",e.remotePeer),s.write({type:wn.Type.STATUS,status:De.UNEXPECTED_MESSAGE});return}if(!lG(i)){Wr.error("invalid stop connect request via peer %s",e.remotePeer),s.write({type:wn.Type.STATUS,status:De.MALFORMED_MESSAGE});return}let o=It(i.peer.id);if(await this.connectionGater.denyInboundRelayedConnection?.(e.remotePeer,o)===!0){s.write({type:wn.Type.STATUS,status:De.PERMISSION_DENIED});return}s.write({type:wn.Type.STATUS,status:De.OK});let a=e.remoteAddr.encapsulate(`/p2p-circuit/p2p/${o.toString()}`),c=this.addressManager.getAddresses()[0],u=Q5({stream:n.unwrap(),remoteAddr:a,localAddr:c});Wr("new inbound connection %s",u.remoteAddr),await this.upgrader.upgradeInbound(u),Wr("%s connection %s upgraded","inbound",u.remoteAddr)}};function Z5(r={}){return e=>new j5(e,r)}var cD="0.45.2";var J5=`js-libp2p/${cD}`;var uD="0.1.0",lD="id",hD="id/push",fD="1.0.0",dD="1.0.0";var Gd=F(Zr(),1);var po;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let s of t.listenAddrs)n.uint32(18),n.bytes(s);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let s of t.protocols)n.uint32(26),n.string(s);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={listenAddrs:[],protocols:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 5:i.protocolVersion=t.string();break;case 6:i.agentVersion=t.string();break;case 1:i.publicKey=t.bytes();break;case 2:i.listenAddrs.push(t.bytes());break;case 4:i.observedAddr=t.bytes();break;case 3:i.protocols.push(t.string());break;case 8:i.signedPeerRecord=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(po||(po={}));var Ur=D("libp2p:identify"),pD=1024*8,ci={protocolPrefix:"ipfs",agentVersion:J5,timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1,maxObservedAddresses:10,maxIdentifyMessageSize:8192},Wd=class{identifyProtocolStr;identifyPushProtocolStr;host;started;timeout;peerId;peerStore;registrar;connectionManager;addressManager;maxInboundStreams;maxOutboundStreams;maxPushIncomingStreams;maxPushOutgoingStreams;maxIdentifyMessageSize;maxObservedAddresses;events;constructor(e,t){this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.events=e.events,this.identifyProtocolStr=`/${t.protocolPrefix??ci.protocolPrefix}/${lD}/${fD}`,this.identifyPushProtocolStr=`/${t.protocolPrefix??ci.protocolPrefix}/${hD}/${dD}`,this.timeout=t.timeout??ci.timeout,this.maxInboundStreams=t.maxInboundStreams??ci.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??ci.maxOutboundStreams,this.maxPushIncomingStreams=t.maxPushIncomingStreams??ci.maxPushIncomingStreams,this.maxPushOutgoingStreams=t.maxPushOutgoingStreams??ci.maxPushOutgoingStreams,this.maxIdentifyMessageSize=t.maxIdentifyMessageSize??ci.maxIdentifyMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??ci.maxObservedAddresses,this.host={protocolVersion:`${t.protocolPrefix??ci.protocolPrefix}/${uD}`,agentVersion:t.agentVersion??ci.agentVersion},e.events.addEventListener("connection:open",n=>{let i=n.detail;this.identify(i).catch(s=>{Ur.error("error during identify trigged by connection:open",s)})}),e.events.addEventListener("self:peer:update",n=>{this.push().catch(i=>{Ur.error(i)})}),this.host.agentVersion===J5&&(HR||VR?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(Y1||Q1||zR||$R)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:q(this.host.agentVersion),ProtocolVersion:q(this.host.protocolVersion)}}),await this.registrar.handle(this.identifyProtocolStr,e=>{this._handleIdentify(e).catch(t=>{Ur.error(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),await this.registrar.handle(this.identifyPushProtocolStr,e=>{this._handlePush(e).catch(t=>{Ur.error(t)})},{maxInboundStreams:this.maxPushIncomingStreams,maxOutboundStreams:this.maxPushOutgoingStreams}),this.started=!0)}async stop(){await this.registrar.unhandle(this.identifyProtocolStr),await this.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async pushToConnections(e){let t=this.addressManager.getAddresses().map(l=>l.decapsulateCode(X("p2p").code)),n=new zt({peerId:this.peerId,multiaddrs:t}),i=await Wt.seal(n,this.peerId),s=this.registrar.getProtocols(),o=await this.peerStore.get(this.peerId),a=B(o.metadata.get("AgentVersion")??q(this.host.agentVersion)),c=B(o.metadata.get("ProtocolVersion")??q(this.host.protocolVersion)),u=e.map(async l=>{let h,f=AbortSignal.timeout(this.timeout);try{(0,Gd.setMaxListeners)?.(1/0,f)}catch{}try{h=await l.newStream([this.identifyPushProtocolStr],{signal:f}),await Er(h,f).sink(be([po.encode({listenAddrs:t.map(p=>p.bytes),signedPeerRecord:i.marshal(),protocols:s,agentVersion:a,protocolVersion:c})],p=>Et(p)))}catch(d){Ur.error("could not push identify update to peer",d)}finally{h?.close()}});await Promise.all(u)}async push(){if(!this.isStarted())return;let e=[];await Promise.all(this.connectionManager.getConnections().map(async t=>{try{if(!(await this.peerStore.get(t.remotePeer)).protocols.includes(this.identifyPushProtocolStr))return;e.push(t)}catch(n){if(n.code!==V.ERR_NOT_FOUND)throw n}})),await this.pushToConnections(e)}async _identify(e,t={}){let n,i=it([AbortSignal.timeout(this.timeout),t?.signal]);try{(0,Gd.setMaxListeners)?.(1/0,i)}catch{}try{n=await e.newStream([this.identifyProtocolStr],{signal:i});let s=Er(n,i),o=await be([],s,a=>Ct(a,{maxDataLength:this.maxIdentifyMessageSize??pD}),async a=>si(a));if(o==null)throw new w("No data could be retrieved",V.ERR_CONNECTION_ENDED);try{return po.decode(o)}catch(a){throw new w(String(a),V.ERR_INVALID_MESSAGE)}}finally{n?.close(),i.clear()}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:i,protocols:s,observedAddr:o}=n;if(i==null)throw new w("public key was missing from identify message",V.ERR_MISSING_PUBLIC_KEY);let a=await er(i);if(!e.remotePeer.equals(a))throw new w("identified peer does not match the expected peer",V.ERR_INVALID_PEER);if(this.peerId.equals(a))throw new w("identified peer is our own peer id?",V.ERR_INVALID_PEER);let c=hG(o);Ur("identify completed for peer %p and protocols %o",a,s),Ur("our observed address is %s",c),c!=null&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(Ur("storing our observed address %s",c?.toString()),this.addressManager.addObservedAddr(c));let u=await this.#e(e.remotePeer,n),l={peerId:a,protocolVersion:n.protocolVersion,agentVersion:n.agentVersion,publicKey:n.publicKey,listenAddrs:n.listenAddrs.map(h=>re(h)),observedAddr:n.observedAddr==null?void 0:re(n.observedAddr),protocols:n.protocols,signedPeerRecord:u};this.events.safeDispatchEvent("peer:identify",{detail:l})}async _handleIdentify(e){let{connection:t,stream:n}=e,i=AbortSignal.timeout(this.timeout);try{(0,Gd.setMaxListeners)?.(1/0,i)}catch{}try{let s=this.peerId.publicKey??new Uint8Array(0),o=await this.peerStore.get(this.peerId),a=this.addressManager.getAddresses().map(f=>f.decapsulateCode(X("p2p").code)),c=o.peerRecordEnvelope;if(a.length>0&&c==null){let f=new zt({peerId:this.peerId,multiaddrs:a});c=(await Wt.seal(f,this.peerId)).marshal().subarray()}let u=po.encode({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:s,listenAddrs:a.map(f=>f.bytes),signedPeerRecord:c,observedAddr:t.remoteAddr.bytes,protocols:o.protocols}),l=Er(n,i),h=be([u],f=>Et(f));await l.sink(h)}catch(s){Ur.error("could not respond to identify request",s)}finally{n.close()}}async _handlePush(e){let{connection:t,stream:n}=e;try{if(this.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");let i=Er(n,AbortSignal.timeout(this.timeout)),o=await _r(i,{maxDataLength:this.maxIdentifyMessageSize??pD}).readPB(po);await this.#e(t.remotePeer,o)}catch(i){Ur.error("received invalid message",i);return}finally{n.close()}Ur("handled push from %p",t.remotePeer)}async#e(e,t){if(t==null)throw new Error("Message was null or undefined");if(Ur("received identify from %p",e),t.signedPeerRecord==null)return;let n=t.signedPeerRecord,i=await Wt.openAndCertify(n,zt.DOMAIN),s=zt.createFromProtobuf(i.payload);if(!s.peerId.equals(i.peerId))throw new Error("signing key does not match PeerId in the PeerRecord");if(!e.equals(s.peerId))throw new Error("signing key does not match remote PeerId");let o;try{o=await this.peerStore.get(s.peerId)}catch(c){if(c.code!=="ERR_NOT_FOUND")throw c}Ur("received signedPeerRecord in push from %p",e);let a=o?.metadata??new Map;if(o?.peerRecordEnvelope!=null){let c=await Wt.createFromProtobuf(o.peerRecordEnvelope),u=zt.createFromProtobuf(c.payload);u.seqNumber>=s.seqNumber&&(Ur("sequence number was lower or equal to existing sequence number - stored: %d received: %d",u.seqNumber,s.seqNumber),s=u,n=o.peerRecordEnvelope)}return t.agentVersion!=null&&a.set("AgentVersion",q(t.agentVersion)),t.protocolVersion!=null&&a.set("ProtocolVersion",q(t.protocolVersion)),await this.peerStore.patch(s.peerId,{peerRecordEnvelope:n,protocols:t.protocols,addresses:s.multiaddrs.map(c=>({isCertified:!0,multiaddr:c})),metadata:a}),Ur("consumed signedPeerRecord sent in push from %p",e),{seq:s.seqNumber,addresses:s.multiaddrs}}};function hG(r){if(r!=null&&r.length>0)try{return re(r)}catch{}}function mD(r={}){return e=>new Wd(e,r)}var gD={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};async function yD(r){return KT({...r,addresses:{listen:["/webrtc"]},transports:[mR(),pR(),BI(),tI(),Z5({discoverRelays:1})],connectionEncryption:[O0()],streamMuxers:[ax(),ES()],peerDiscovery:[xx(gD)],contentRouters:[Dx("https://cid.contact")],services:{identify:mD(),autoNAT:HT(),pubsub:ov(),dht:m_({clientMode:!0}),relay:Y5({advertise:!0})}})}var e6="1.1.2",Yd="helia";var fG=D("helia");async function dG(r={}){let e=r.datastore??new yo,t=r.blockstore??new su,n=r.libp2p??await yD({datastore:e,start:!1}),i=new df({...r,datastore:e,blockstore:t,libp2p:n});return r.start!==!1&&await i.start(),i.libp2p.isStarted()?await wD(i):i.libp2p.addEventListener("start",()=>{wD(i).catch(s=>{fG.error("could not add Helia to agent version",s)})}),i}async function wD(r){let t=(await r.libp2p.peerStore.get(r.libp2p.peerId)).metadata.get("AgentVersion");if(t==null)return;let n=new TextDecoder().decode(t);n.match(/js-libp2p\/\d+\.\d+\.\d+\sUserAgent=/)!=null&&(n.includes(Yd)?n=`${Yd}/${e6} ${n.split(" ").slice(1).join(" ")}`:n=`${Yd}/${e6} ${n}`,await r.libp2p.peerStore.merge(r.libp2p.peerId,{metadata:{AgentVersion:new TextEncoder().encode(n)}}))}return oh(pG);})();
|
|
84
|
+
`);function Jl(r){let e=new j(r,PT);return Et.single(e)}function ca(r,e,t={}){let n=Jl(e);t.writeBytes===!0?r.push(n.subarray()):r.push(n)}function kT(r,e,t={}){let n=new j;for(let i of e)n.append(Jl(i));t.writeBytes===!0?r.push(n.subarray()):r.push(n)}async function K$(r,e){let t=1,n={[Symbol.asyncIterator]:()=>n,next:async()=>await r.next(t)},i=n;e?.signal!=null&&(i=lt(n,e.signal));let s=a=>{t=a},o=await be(i,a=>Ct(a,{onLength:s,maxDataLength:1024}),async a=>await si(a));if(o==null||o.length===0)throw new w("no buffer returned","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");if(o.get(o.byteLength-1)!==PT[0])throw F$.error("Invalid mss message - missing newline - %s",o.subarray()),new w("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return o.sublist(0,-1)}async function Xc(r,e){let t=await K$(r,e);return B(t.subarray())}function P5(r){let e=async function*(){let t=yield,n=new j;for await(let i of r){if(t==null){n.append(i),t=yield n,n=new j;continue}for(n.append(i);n.length>=t;){let s=n.sublist(0,t);if(n.consume(t),t=yield s,t==null){n.length>0&&(t=yield n,n=new j);break}}}if(t!=null)throw Object.assign(new Error(`stream ended before ${t} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return e.next(),e}function Ld(r){let e=tt(),t=P5(r.source),n=Me(),i,s=r.sink(async function*(){yield*e,yield*await n.promise}());return s.catch(a=>{i=a}),{reader:t,writer:e,stream:{sink:async a=>{if(i!=null){await Promise.reject(i);return}n.resolve(a),await s},source:t},rest:()=>e.end(),write:e.push,read:async()=>{let a=await t.next();if(a.value!=null)return a.value}}}var eh=D("libp2p:mss:select");async function th(r,e,t={}){e=Array.isArray(e)?[...e]:[e];let{reader:n,writer:i,rest:s,stream:o}=Ld(r),a=e.shift();if(a==null)throw new Error("At least one protocol must be specified");eh.trace('select: write ["%s", "%s"]',ds,a);let c=q(ds),u=q(a);kT(i,[c,u],t);let l=await Xc(n,t);if(eh.trace('select: read "%s"',l),l===ds&&(l=await Xc(n,t),eh.trace('select: read "%s"',l)),l===a)return s(),{stream:o,protocol:a};for(let h of e){eh.trace('select: write "%s"',h),ca(i,q(h),t);let f=await Xc(n,t);if(eh.trace('select: read "%s" for "%s"',f,h),f===h)return s(),{stream:o,protocol:h}}throw s(),new w("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}var rh=D("libp2p:mss:handle");async function nh(r,e,t){e=Array.isArray(e)?e:[e];let{writer:n,reader:i,rest:s,stream:o}=Ld(r);for(;;){let a=await Xc(i,t);if(rh.trace('read "%s"',a),a===ds){rh.trace('respond with "%s" for "%s"',ds,a),ca(n,q(ds),t);continue}if(e.includes(a))return ca(n,q(a),t),rh.trace('respond with "%s" for "%s"',a,a),s(),{stream:o,protocol:a};if(a==="ls"){ca(n,new j(...e.map(c=>Jl(q(c)))),t),rh.trace('respond with "%s" for %s',e,a);continue}ca(n,q("na"),t),rh('respond with "na" for "%s"',a)}}var LT=Symbol.for("@libp2p/connection");var OT="OPEN",k5="CLOSING",Od="CLOSED";var V$=D("libp2p:connection"),N5=class{id;remoteAddr;remotePeer;stat;tags;_newStream;_close;_getStreams;_closing;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:i,close:s,getStreams:o,stat:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.stat={...a,status:OT},this._newStream=i,this._close=s,this._getStreams=o,this.tags=[],this._closing=!1}[Symbol.toStringTag]="Connection";[LT]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.stat.status===k5)throw new w("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.stat.status===Od)throw new w("the connection is closed","ERR_CONNECTION_CLOSED");Array.isArray(e)||(e=[e]);let n=await this._newStream(e,t);return n.stat.direction="outbound",n}addStream(e){e.stat.direction="inbound"}removeStream(e){}async close(){if(!(this.stat.status===Od||this._closing)){this.stat.status=k5;try{this.streams.forEach(e=>{e.close()})}catch(e){V$.error(e)}this._closing=!0,await this._close(),this._closing=!1,this.stat.timeline.close=Date.now(),this.stat.status=Od}}};function BT(r){return new N5(r)}var At=D("libp2p:upgrader");function H$(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==V.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return D5}function $$(r,e){try{let{options:t}=e.getHandler(r);return t.maxOutboundStreams}catch(t){if(t.code!==V.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return C5}function MT(r,e,t){let n=0;return t.streams.forEach(i=>{i.stat.direction===e&&i.stat.protocol===r&&n++}),n}var Bd=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,t.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??3e4,this.events=e.events}async shouldBlockConnection(e,t,n){let i=this.components.connectionGater[n];if(i!==void 0&&await i(e,t))throw new w(`The multiaddr connection is blocked by gater.${n}`,V.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new w("connection denied",V.ERR_CONNECTION_DENIED);let i,s,o,a,c,u=it([AbortSignal.timeout(this.inboundUpgradeTimeout)]);try{(0,L5.setMaxListeners)?.(1/0,u)}catch{}try{let l=Er(e,u);if(e.source=l.source,e.sink=l.sink,await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new w("The multiaddr connection is blocked by gater.acceptConnection",V.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),At("starting the inbound connection upgrade");let h=e;if(t?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(At("protecting the inbound connection"),h=await f.protect(e))}try{if(i=h,t?.skipEncryption!==!0){({conn:i,remotePeer:s,protocol:c}=await this._encryptInbound(h));let f={...h,...i};await this.shouldBlockConnection(s,f,"denyInboundEncryptedConnection")}else{let f=e.remoteAddr.getPeerId();if(f==null)throw new w("inbound connection that skipped encryption must have a peer id",V.ERR_INVALID_MULTIADDR);let d=oe(f);c="native",s=d}if(o=i,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){let f=await this._multiplexInbound({...h,...i},this.muxers);a=f.muxerFactory,o=f.stream}}catch(f){throw At.error("Failed to upgrade inbound connection",f),f}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),At("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:o,muxerFactory:a,remotePeer:s})}finally{this.components.connectionManager.afterUpgradeInbound(),u.clear()}}async upgradeOutbound(e,t){let n=e.remoteAddr.getPeerId(),i;n!=null&&(i=oe(n),await this.shouldBlockConnection(i,e,"denyOutboundConnection"));let s,o,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),At("Starting the outbound connection upgrade");let l=e;if(t?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(l=await h.protect(e))}try{if(s=l,t?.skipEncryption!==!0){({conn:s,remotePeer:o,protocol:c}=await this._encryptOutbound(l,i));let h={...l,...s};await this.shouldBlockConnection(o,h,"denyOutboundEncryptedConnection")}else{if(i==null)throw new w("Encryption was skipped but no peer id was passed",V.ERR_INVALID_PEER);c="native",o=i}if(a=s,t?.muxerFactory!=null)u=t.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexOutbound({...l,...s},this.muxers);u=h.muxerFactory,a=h.stream}}catch(h){throw At.error("Failed to upgrade outbound connection",h),await e.close(h),h}return await this.shouldBlockConnection(o,e,"denyOutboundUpgradedConnection"),At("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:o})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:i,upgradedConn:s,remotePeer:o,muxerFactory:a}=e,c,u,l;a!=null&&(c=a.createStreamMuxer({direction:n,onIncomingStream:d=>{l!=null&&Promise.resolve().then(async()=>{let p=this.components.registrar.getProtocols(),{stream:m,protocol:g}=await nh(d,p);if(At("%s: incoming stream opened on %s",n,g),l==null)return;let y=H$(g,this.components.registrar);if(MT(g,"inbound",l)===y){let E=new w(`Too many inbound protocol streams for protocol "${g}" - limit ${y}`,V.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(E),E}d.source=m.source,d.sink=m.sink,d.stat.protocol=g,await this.components.peerStore.merge(o,{protocols:[g]}),l.addStream(d),this.components.metrics?.trackProtocolStream(d,l),this._onStream({connection:l,stream:d,protocol:g})}).catch(p=>{At.error(p),d.stat.timeline.close==null&&d.close()})},onStreamEnd:d=>{l?.removeStream(d.id)}}),u=async(d,p={})=>{if(c==null)throw new w("Stream is not multiplexed",V.ERR_MUXER_UNAVAILABLE);At("%s: starting new stream on %s",n,d);let m=await c.newStream();try{if(p.signal==null){At("No abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d),p.signal=AbortSignal.timeout(3e4);try{(0,L5.setMaxListeners)?.(1/0,p.signal)}catch{}}let{stream:g,protocol:y}=await th(m,d,p),b=$$(y,this.components.registrar);if(MT(y,"outbound",l)===b){let R=new w(`Too many outbound protocol streams for protocol "${y}" - limit ${b}`,V.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw m.abort(R),R}return await this.components.peerStore.merge(o,{protocols:[y]}),m.source=g.source,m.sink=g.sink,m.stat.protocol=y,this.components.metrics?.trackProtocolStream(m,l),m}catch(g){throw At.error("could not create new stream",g),m.stat.timeline.close==null&&m.close(),g.code!=null?g:new w(String(g),V.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([c.sink(s.source),s.sink(c.source)]).catch(d=>{At.error(d)}));let h=i.timeline;i.timeline=new Proxy(h,{set:(...d)=>(l!=null&&d[1]==="close"&&d[2]!=null&&h.close==null&&(async()=>{try{l.stat.status==="OPEN"&&await l.close()}catch(p){At.error(p)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(p=>{At.error(p)}),Reflect.set(...d))}),i.timeline.upgraded=Date.now();let f=()=>{throw new w("connection is not multiplexed",V.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=BT({remoteAddr:i.remoteAddr,remotePeer:o,stat:{status:"OPEN",direction:n,timeline:i.timeline,multiplexer:c?.protocol,encryption:t},newStream:u??f,getStreams:()=>c!=null?c.streams:f(),close:async()=>{await i.close(),c?.close()}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:t,stream:n,protocol:i}=e,{handler:s}=this.components.registrar.getHandler(i);s({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());At("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:i}=await nh(e,t,{writeBytes:!0}),s=this.connectionEncryption.get(i);if(s==null)throw new Error(`no crypto module found for ${i}`);return At("encrypting inbound connection..."),{...await s.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw new w(String(n),V.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());At("selecting outbound crypto protocol",n);try{let{stream:i,protocol:s}=await th(e,n,{writeBytes:!0}),o=this.connectionEncryption.get(s);if(o==null)throw new Error(`no crypto module found for ${s}`);return At("encrypting outbound connection to %p",t),{...await o.secureOutbound(this.components.peerId,i,t),protocol:s}}catch(i){throw new w(String(i),V.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());At("outbound selecting muxer %s",n);try{let{stream:i,protocol:s}=await th(e,n,{writeBytes:!0});At("%s selected as muxer protocol",s);let o=t.get(s);return{stream:i,muxerFactory:o}}catch(i){throw At.error("error multiplexing outbound stream",i),new w(String(i),V.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let n=Array.from(t.keys());At("inbound handling muxers %s",n);try{let{stream:i,protocol:s}=await nh(e,n,{writeBytes:!0}),o=t.get(s);return{stream:i,muxerFactory:o}}catch(i){throw At.error("error multiplexing inbound stream",i),new w(String(i),V.ERR_MUXER_UNAVAILABLE)}}};var Gr=D("libp2p"),O5=class extends Ue{peerId;peerStore;contentRouting;peerRouting;keychain;metrics;services;components;#e;constructor(e){super();let t=new Ue,n=t.dispatchEvent.bind(t);t.dispatchEvent=c=>{let u=n(c),l=this.dispatchEvent(new Je(c.type,{detail:c.detail}));return u||l};try{(0,UT.setMaxListeners)?.(1/0,t)}catch{}this.#e=!1,this.peerId=e.peerId,this.services={};let i=this.components=mT({peerId:e.peerId,events:t,datastore:e.datastore??new yo,connectionGater:gT(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new bd(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),i.events.addEventListener("peer:update",c=>{c.detail.previous==null&&this.safeDispatchEvent("peer:discovery",{detail:c.detail.peer})}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Bd(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((c,u)=>this.configureComponent(`connection-encryption-${u}`,c(this.components))),muxers:(e.streamMuxers??[]).map((c,u)=>this.configureComponent(`stream-muxers-${u}`,c(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Nd(this.components,e.transportManager)),this.configureComponent("connectionManager",new Id(this.components,e.connectionManager)),this.configureComponent("registrar",new kd(this.components)),this.configureComponent("addressManager",new Ed(this.components,e.addresses));let s=sa.generateOptions();this.keychain=this.configureComponent("keyChain",new sa(this.components,{...s,...e.keychain}));let o=(e.peerRouters??[]).map((c,u)=>this.configureComponent(`peer-router-${u}`,c(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Pd(this.components,{routers:o}));let a=(e.contentRouters??[]).map((c,u)=>this.configureComponent(`content-router-${u}`,c(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Cd(this.components,{routers:a})),(e.peerDiscovery??[]).forEach((c,u)=>{this.configureComponent(`peer-discovery-${u}`,c(this.components)).addEventListener("peer",h=>{this.#t(h)})}),e.transports.forEach((c,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,c(this.components)))}),e.services!=null)for(let c of Object.keys(e.services)){let u=e.services[c],l=u(this.components);if(l==null){Gr.error("service factory %s returned null or undefined instance",c);continue}this.services[c]=l,this.configureComponent(c,l),l[wl]!=null&&(Gr("registering service %s for content routing",c),a.push(l[wl])),l[bl]!=null&&(Gr("registering service %s for peer routing",c),o.push(l[bl])),l[qo]!=null&&(Gr("registering service %s for peer discovery",c),l[qo].addEventListener("peer",h=>{this.#t(h)}))}}configureComponent(e,t){return t==null&&Gr.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.#e)return;this.#e=!0,Gr("libp2p is starting"),(await this.keychain.listKeys()).find(t=>t.name==="self")==null&&(Gr("importing self key into keychain"),await this.keychain.importPeer("self",this.components.peerId));try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.safeDispatchEvent("start",{detail:this}),Gr("libp2p has started")}catch(t){throw Gr.error("An error occurred starting libp2p",t),await this.stop(),t}}async stop(){this.#e&&(Gr("libp2p is stopping"),this.#e=!1,await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.safeDispatchEvent("stop",{detail:this}),Gr("libp2p has stopped"))}isStarted(){return this.#e}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Rr;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,t)}async dialProtocol(e,t,n={}){if(t==null)throw new w("no protocols were provided to open a stream",V.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw new w("no protocols were provided to open a stream",V.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e){Vo(e)&&(e=oe(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e)}async getPublicKey(e,t={}){if(Gr("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;let n=await this.peerStore.get(e);if(n.id.publicKey!=null)return n.id.publicKey;let i=he([q("/pk/"),e.multihash.digest]),s=await this.contentRouting.get(i,t);return kr(s),await this.peerStore.patch(e,{publicKey:s}),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async i=>{await this.components.registrar.handle(i,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}#t(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){Gr.error(new Error(V.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs,protocols:t.protocols}).catch(n=>{Gr.error(n)})}};async function FT(r){if(r.peerId==null){let e=r.datastore;if(e!=null)try{let t=new sa({datastore:e},uo(sa.generateOptions(),r.keychain));r.peerId=await t.exportPeerId("self")}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}}return r.peerId==null&&(r.peerId=await dd()),new O5(AT(r))}async function KT(r){let e=await FT(r);return r.start!==!1&&await e.start(),e}var M5=F(Zr(),1);var qT="libp2p",VT="autonat",zT="1.0.0";var we;(function(r){let e;(function(u){u.DIAL="DIAL",u.DIAL_RESPONSE="DIAL_RESPONSE"})(e=r.MessageType||(r.MessageType={}));let t;(function(u){u[u.DIAL=0]="DIAL",u[u.DIAL_RESPONSE=1]="DIAL_RESPONSE"})(t||(t={})),function(u){u.codec=()=>Ht(t)}(e=r.MessageType||(r.MessageType={}));let n;(function(u){u.OK="OK",u.E_DIAL_ERROR="E_DIAL_ERROR",u.E_DIAL_REFUSED="E_DIAL_REFUSED",u.E_BAD_REQUEST="E_BAD_REQUEST",u.E_INTERNAL_ERROR="E_INTERNAL_ERROR"})(n=r.ResponseStatus||(r.ResponseStatus={}));let i;(function(u){u[u.OK=0]="OK",u[u.E_DIAL_ERROR=100]="E_DIAL_ERROR",u[u.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",u[u.E_BAD_REQUEST=200]="E_BAD_REQUEST",u[u.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"})(i||(i={})),function(u){u.codec=()=>Ht(i)}(n=r.ResponseStatus||(r.ResponseStatus={}));let s;(function(u){let l;u.codec=()=>(l==null&&(l=se((h,f,d={})=>{if(d.lengthDelimited!==!1&&f.fork(),h.id!=null&&(f.uint32(10),f.bytes(h.id)),h.addrs!=null)for(let p of h.addrs)f.uint32(18),f.bytes(p);d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={addrs:[]},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.id=h.bytes();break;case 2:d.addrs.push(h.bytes());break;default:h.skipType(m&7);break}}return d})),l),u.encode=h=>ie(h,u.codec()),u.decode=h=>ne(h,u.codec())})(s=r.PeerInfo||(r.PeerInfo={}));let o;(function(u){let l;u.codec=()=>(l==null&&(l=se((h,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),h.peer!=null&&(f.uint32(10),r.PeerInfo.codec().encode(h.peer,f)),d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.peer=r.PeerInfo.codec().decode(h,h.uint32());break;default:h.skipType(m&7);break}}return d})),l),u.encode=h=>ie(h,u.codec()),u.decode=h=>ne(h,u.codec())})(o=r.Dial||(r.Dial={}));let a;(function(u){let l;u.codec=()=>(l==null&&(l=se((h,f,d={})=>{d.lengthDelimited!==!1&&f.fork(),h.status!=null&&(f.uint32(8),r.ResponseStatus.codec().encode(h.status,f)),h.statusText!=null&&(f.uint32(18),f.string(h.statusText)),h.addr!=null&&(f.uint32(26),f.bytes(h.addr)),d.lengthDelimited!==!1&&f.ldelim()},(h,f)=>{let d={},p=f==null?h.len:h.pos+f;for(;h.pos<p;){let m=h.uint32();switch(m>>>3){case 1:d.status=r.ResponseStatus.codec().decode(h);break;case 2:d.statusText=h.string();break;case 3:d.addr=h.bytes();break;default:h.skipType(m&7);break}}return d})),l),u.encode=h=>ie(h,u.codec()),u.decode=h=>ne(h,u.codec())})(a=r.DialResponse||(r.DialResponse={}));let c;r.codec=()=>(c==null&&(c=se((u,l,h={})=>{h.lengthDelimited!==!1&&l.fork(),u.type!=null&&(l.uint32(8),r.MessageType.codec().encode(u.type,l)),u.dial!=null&&(l.uint32(18),r.Dial.codec().encode(u.dial,l)),u.dialResponse!=null&&(l.uint32(26),r.DialResponse.codec().encode(u.dialResponse,l)),h.lengthDelimited!==!1&&l.ldelim()},(u,l)=>{let h={},f=l==null?u.len:u.pos+l;for(;u.pos<f;){let d=u.uint32();switch(d>>>3){case 1:h.type=r.MessageType.codec().decode(u);break;case 2:h.dial=r.Dial.codec().decode(u,u.uint32());break;case 3:h.dialResponse=r.DialResponse.codec().decode(u,u.uint32());break;default:u.skipType(d&7);break}}return h})),c),r.encode=u=>ie(u,r.codec()),r.decode=u=>ne(u,r.codec())})(we||(we={}));var Qe=D("libp2p:autonat"),B5=4,U5=class{components;startupDelay;refreshInterval;protocol;timeout;maxInboundStreams;maxOutboundStreams;verifyAddressTimeout;started;constructor(e,t){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??qT}/${VT}/${zT}`,this.timeout=t.timeout??3e4,this.maxInboundStreams=t.maxInboundStreams??1,this.maxOutboundStreams=t.maxOutboundStreams??1,this.startupDelay=t.startupDelay??5e3,this.refreshInterval=t.refreshInterval??6e4,this._verifyExternalAddresses=this._verifyExternalAddresses.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(this.protocol,e=>{this.handleIncomingAutonatStream(e).catch(t=>{Qe.error("error handling incoming autonat stream",t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.startupDelay),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),clearTimeout(this.verifyAddressTimeout),this.started=!1}async handleIncomingAutonatStream(e){let t=it([AbortSignal.timeout(this.timeout)]);try{(0,M5.setMaxListeners)?.(1/0,t)}catch{}let n=this.components.addressManager.getAddresses().map(i=>i.toOptions().host);try{let i=Er(e.stream,t),s=this;await be(i,o=>Ct(o),async function*(o){let a=await si(o);if(a==null){Qe("no message received"),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"No message was sent"}});return}let c;try{c=we.decode(a)}catch(m){Qe.error("could not decode message",m),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"Could not decode message"}});return}let u=c.dial;if(u==null){Qe.error("dial was missing from message"),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}});return}let l,h=u.peer;if(h==null||h.id==null){Qe.error("PeerId missing from message"),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}});return}try{l=It(h.id)}catch(m){Qe.error("invalid PeerId",m),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}});return}if(Qe("incoming request from %p",l),!e.connection.remotePeer.equals(l)){Qe("target peer %p did not equal sending peer %p",l,e.connection.remotePeer),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}});return}let f=h.addrs.map(m=>re(m)).filter(m=>{let g=m.toOptions().host===e.connection.remoteAddr.toOptions().host;return Qe.trace("request to dial %s was sent from %s is same host %s",m,e.connection.remoteAddr,g),g}).filter(m=>{let g=m.toOptions().host,y=!(Nn(g)??!1);return Qe.trace("host %s was public %s",g,y),y}).filter(m=>{let g=m.toOptions().host,y=!n.includes(g);return Qe.trace("host %s was not our host %s",g,y),y}).filter(m=>{let g=!!s.components.transportManager.transportForMultiaddr(m);return Qe.trace("transport for %s is supported %s",m,g),g}).map(m=>(m.getPeerId()==null&&(m=m.encapsulate(`/p2p/${l.toString()}`)),m));if(f.length===0){Qe("no valid multiaddrs for %p in message",l),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}});return}Qe("dial multiaddrs %s for peer %p",f.map(m=>m.toString()).join(", "),l);let d="",p=f[0];for await(let m of f){let g;p=m;try{if(g=await s.components.connectionManager.openConnection(m,{signal:t}),!g.remoteAddr.equals(m))throw Qe.error("tried to dial %s but dialed %s",m,g.remoteAddr),new Error("Unexpected remote address");Qe("Success %p",l),yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.OK,addr:g.remoteAddr.decapsulateCode(X("p2p").code).bytes}});return}catch(y){Qe("could not dial %p",l,y),d=y.message}finally{g!=null&&await g.close()}}yield we.encode({type:we.MessageType.DIAL_RESPONSE,dialResponse:{status:we.ResponseStatus.E_DIAL_ERROR,statusText:d,addr:p.bytes}})},o=>Et(o),e.stream)}catch(i){Qe.error("error handling incoming autonat stream",i)}finally{t.clear()}}_verifyExternalAddresses(){this.verifyExternalAddresses().catch(e=>{Qe.error("error verifying external address",e)})}async verifyExternalAddresses(){if(clearTimeout(this.verifyAddressTimeout),!this.isStarted())return;let e=this.components.addressManager,t=e.getObservedAddrs().filter(s=>{let o=s.toOptions();return!(Nn(o.host)??!1)});if(t.length===0){Qe("no public addresses found, not requesting verification"),this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval);return}let n=AbortSignal.timeout(this.timeout);try{(0,M5.setMaxListeners)?.(1/0,n)}catch{}let i=this;try{Qe("verify multiaddrs %s",t.map(h=>h.toString()).join(", "));let s=we.encode({type:we.MessageType.DIAL,dial:{peer:{id:this.components.peerId.toBytes(),addrs:t.map(h=>h.bytes)}}}),a=(await dd()).toBytes(),c={},u=[],l=async h=>{try{Qe("asking %p to verify multiaddr",h.id);let f=await i.components.connectionManager.openConnection(h.id,{signal:n}),d=await f.newStream(this.protocol,{signal:n}),p=Er(d,n),m=await be([s],y=>Et(y),p,y=>Ct(y),async y=>si(y));if(m==null){Qe("no response received from %p",f.remotePeer);return}let g=we.decode(m);if(g.type!==we.MessageType.DIAL_RESPONSE||g.dialResponse==null){Qe("invalid autonat response from %p",f.remotePeer);return}if(g.dialResponse.status===we.ResponseStatus.OK){let y=f.remoteAddr.toOptions(),b;if(y.family===4)b=y.host.split(".")[0];else if(y.family===6)b=y.host.split(":")[0];else{Qe('remote address "%s" was not IP4 or IP6?',y.host);return}if(u.includes(b)){Qe("already have response from network segment %d - %s",b,y.host);return}u.push(b)}return g.dialResponse}catch(f){Qe.error("error asking remote to verify multiaddr",f)}};for await(let h of $o(Kn(this.components.peerRouting.getClosestPeers(a,{signal:n}),f=>async()=>l(f)),{concurrency:B5}))try{if(h==null)continue;let f=h.addr==null?t[0]:re(h.addr);if(Qe("autonat response for %s is %s",f,h.status),h.status===we.ResponseStatus.E_BAD_REQUEST||h.status===we.ResponseStatus.E_DIAL_REFUSED||h.addr==null&&t.length>1)continue;if(!t.some(p=>p.equals(f))){Qe("peer reported %s as %s but it was not in our observed address list",f,h.status);continue}let d=f.toString();if(c[d]==null&&(c[d]={success:0,failure:0}),h.status===we.ResponseStatus.OK?c[d].success++:h.status===we.ResponseStatus.E_DIAL_ERROR&&c[d].failure++,c[d].success===B5){Qe("%s is externally dialable",f),e.confirmObservedAddr(f);return}if(c[d].failure===B5){Qe("%s is not externally dialable",f),e.removeObservedAddr(f);return}}catch(f){Qe.error("could not verify external address",f)}}finally{this.verifyAddressTimeout=setTimeout(this._verifyExternalAddresses,this.refreshInterval)}}};function HT(r={}){return e=>new U5(e,r)}var sD=F(Zr(),1);var Md="/libp2p/relay";var $T="circuit-relay-source",GT="circuit-relay-relay";var Ud=BigInt(131072),Mi="/libp2p/circuit/relay/0.2.0/hop",ih="/libp2p/circuit/relay/0.2.0/stop",WT=30*1e3,YT=30*1e3;var nt;(function(r){let e;(function(i){i.RESERVE="RESERVE",i.CONNECT="CONNECT",i.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.RESERVE=0]="RESERVE",i[i.CONNECT=1]="CONNECT",i[i.STATUS=2]="STATUS"})(t||(t={})),function(i){i.codec=()=>Ht(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=se((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.peer!=null&&(s.uint32(18),jc.codec().encode(i.peer,s)),i.reservation!=null&&(s.uint32(26),Fd.codec().encode(i.reservation,s)),i.limit!=null&&(s.uint32(34),Zc.codec().encode(i.limit,s)),i.status!=null&&(s.uint32(40),De.codec().encode(i.status,s)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.peer=jc.codec().decode(i,i.uint32());break;case 3:o.reservation=Fd.codec().decode(i,i.uint32());break;case 4:o.limit=Zc.codec().decode(i,i.uint32());break;case 5:o.status=De.codec().decode(i);break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>ie(i,r.codec()),r.decode=i=>ne(i,r.codec())})(nt||(nt={}));var wn;(function(r){let e;(function(i){i.CONNECT="CONNECT",i.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(i){i[i.CONNECT=0]="CONNECT",i[i.STATUS=1]="STATUS"})(t||(t={})),function(i){i.codec=()=>Ht(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=se((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),r.Type.codec().encode(i.type,s)),i.peer!=null&&(s.uint32(18),jc.codec().encode(i.peer,s)),i.limit!=null&&(s.uint32(26),Zc.codec().encode(i.limit,s)),i.status!=null&&(s.uint32(32),De.codec().encode(i.status,s)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(i);break;case 2:o.peer=jc.codec().decode(i,i.uint32());break;case 3:o.limit=Zc.codec().decode(i,i.uint32());break;case 4:o.status=De.codec().decode(i);break;default:i.skipType(c&7);break}}return o})),n),r.encode=i=>ie(i,r.codec()),r.decode=i=>ne(i,r.codec())})(wn||(wn={}));var jc;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={id:new Uint8Array(0),addrs:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.id=t.bytes();break;case 2:i.addrs.push(t.bytes());break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(jc||(jc={}));var Fd;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);t.voucher!=null&&(n.uint32(26),n.bytes(t.voucher)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={expire:0n,addrs:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.expire=t.uint64();break;case 2:i.addrs.push(t.bytes());break;case 3:i.voucher=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(Fd||(Fd={}));var Zc;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.duration=t.uint32();break;case 2:i.data=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(Zc||(Zc={}));var De;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(De||(De={}));var F5;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(F5||(F5={}));(function(r){r.codec=()=>Ht(F5)})(De||(De={}));var Kd;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={relay:new Uint8Array(0),peer:new Uint8Array(0),expiration:0n},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 1:i.relay=t.bytes();break;case 2:i.peer=t.bytes();break;case 3:i.expiration=t.uint64();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(Kd||(Kd={}));var K5=D("libp2p:circuit-relay:utils");async function*QT(r,e){for await(let t of r){let n=BigInt(t.byteLength);if(e.remaining-n<0){let i=Number(e.remaining);e.remaining=0n;try{i!==0&&(yield t.subarray(0,i))}catch(s){K5.error(s)}throw new Error("data limit exceeded")}e.remaining-=n,yield t}}var j$=(r,e,t,n)=>{function i(h){r.abort(h),e.abort(h),clearTimeout(a)}let s=new AbortController,o=it([t,s.signal]),a=setTimeout(()=>{s.abort()},n.duration),c=!1,u=!1,l={remaining:n.data};queueMicrotask(()=>{e.sink(QT(lt(r.source,o,{abortMessage:"duration limit exceeded"}),l)).catch(h=>{K5.error("error while relaying streams src -> dst",h),i(h)}).finally(()=>{c=!0,u&&(o.clear(),clearTimeout(a))})}),queueMicrotask(()=>{r.sink(QT(lt(e.source,o,{abortMessage:"duration limit exceeded"}),l)).catch(h=>{K5.error("error while relaying streams dst -> src",h),i(h)}).finally(()=>{u=!0,c&&(o.clear(),clearTimeout(a))})})};function XT(r,e,t,n){let i=n?.data??BigInt(Ud),s=n?.duration??12e4;j$(r,e,t,{data:i,duration:s})}async function qd(r){let e=new TextEncoder().encode(r),t=await Pe.digest(e);return ee.createV0(t)}function V5(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var nD=F(tD(),1),J$=new Set(["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed"]),z5=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},eG=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r},tG=r=>J$.has(r),rD=r=>globalThis.DOMException===void 0?new Error(r):new DOMException(r);async function H5(r,e){return new Promise((t,n)=>{e={onFailedAttempt(){},retries:10,...e};let i=nD.default.operation(e);i.attempt(async s=>{try{t(await r(s))}catch(o){if(!(o instanceof Error)){n(new TypeError(`Non-error was thrown: "${o}". You should only throw errors.`));return}if(o instanceof z5)i.stop(),n(o.originalError);else if(o instanceof TypeError&&!tG(o.message))i.stop(),n(o);else{eG(o,s,e);try{await e.onFailedAttempt(o)}catch(a){n(a);return}i.retry(o)||n(i.mainError())}}}),e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",()=>{i.stop();let s=e.signal.reason===void 0?rD("The operation was aborted."):e.signal.reason;n(s instanceof Error?s:rD(s))},{once:!0})})}var $5=D("libp2p:circuit-relay:advert-service"),Vd=class extends Ue{contentRouting;timeout;started;bootDelay;constructor(e,t){super(),this.contentRouting=e.contentRouting,this.bootDelay=t?.bootDelay??YT,this.started=!1}isStarted(){return this.started}start(){this.started||(this.timeout=setTimeout(()=>{this._advertiseService().catch(e=>{$5.error("could not advertise service",e)})},this.bootDelay),this.started=!0)}stop(){try{clearTimeout(this.timeout)}catch{}this.started=!1}async _advertiseService(){await H5(async()=>{try{let e=await qd(Md);await this.contentRouting.provide(e),this.safeDispatchEvent("advert:success",{detail:void 0})}catch(e){if(this.safeDispatchEvent("advert:error",{detail:e}),e.code===V.ERR_NO_ROUTERS_AVAILABLE){$5.error("a content router, such as a DHT, must be provided in order to advertise the relay service",e),this.stop();return}throw $5.error("could not advertise service",e),e}})}};var zd=class{reservations=new Mr;_started=!1;interval;maxReservations;reservationClearInterval;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;constructor(e={}){this.maxReservations=e.maxReservations??15,this.reservationClearInterval=e.reservationClearInterval??3e5,this.applyDefaultLimit=e.applyDefaultLimit!==!1,this.reservationTtl=e.reservationTtl??72e5,this.defaultDurationLimit=e.defaultDurationLimit??12e4,this.defaultDataLimit=e.defaultDataLimit??Ud}isStarted(){return this._started}start(){this._started||(this._started=!0,this.interval=setInterval(()=>{let e=new Date().getTime();this.reservations.forEach((t,n)=>{t.expire.getTime()<e&&this.reservations.delete(n)})},this.reservationClearInterval))}stop(){clearInterval(this.interval)}reserve(e,t,n){if(this.reservations.size>=this.maxReservations&&!this.reservations.has(e))return{status:De.RESERVATION_REFUSED};let i=new Date(Date.now()+this.reservationTtl),s;return this.applyDefaultLimit&&(s=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),this.reservations.set(e,{addr:t,expire:i,limit:s}),{status:De.OK,expire:Math.round(i.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}hasReservation(e){return this.reservations.has(e)}get(e){return this.reservations.get(e)}};var Jc=class{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:e,peer:t,expiration:n}){this.relay=e,this.peer=t,this.expiration=n}marshal(){return Kd.encode({relay:this.relay.toBytes(),peer:this.peer.toBytes(),expiration:BigInt(this.expiration)})}equals(e){return!(!(e instanceof Jc)||!this.peer.equals(e.peer)||!this.relay.equals(e.relay)||this.expiration!==e.expiration)}};var bt=D("libp2p:circuit-relay:server"),iD=r=>r.protoCodes().includes(290),G5=class extends Ue{registrar;peerStore;addressManager;peerId;connectionManager;connectionGater;reservationStore;advertService;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;constructor(e,t={}){super(),this.registrar=e.registrar,this.peerStore=e.peerStore,this.addressManager=e.addressManager,this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.connectionGater=e.connectionGater,this.started=!1,this.hopTimeout=t?.hopTimeout??WT,this.shutdownController=new AbortController,this.maxInboundHopStreams=t.maxInboundHopStreams,this.maxOutboundHopStreams=t.maxOutboundHopStreams;try{(0,sD.setMaxListeners)?.(1/0,this.shutdownController.signal)}catch{}t.advertise!=null&&t.advertise!==!1&&(this.advertService=new Vd(e,t.advertise===!0?void 0:t.advertise),this.advertService.addEventListener("advert:success",()=>{this.safeDispatchEvent("relay:advert:success",{})}),this.advertService.addEventListener("advert:error",n=>{this.safeDispatchEvent("relay:advert:error",{detail:n.detail})})),this.reservationStore=new zd(t.reservations)}isStarted(){return this.started}async start(){this.started||(this.advertService?.start(),await this.registrar.handle(Mi,e=>{this.onHop(e).catch(t=>{bt.error(t)})},{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams}),this.reservationStore.start(),this.started=!0)}async stop(){this.advertService?.stop(),this.reservationStore.stop(),this.shutdownController.abort(),await this.registrar.unhandle(Mi),this.started=!1}async onHop({connection:e,stream:t}){bt("received circuit v2 hop protocol stream from %s",e.remotePeer);let n=Me(),i=setTimeout(()=>{n.reject("timed out")},this.hopTimeout),s=_r(t);try{let o=await Promise.race([s.pb(nt).read(),n.promise]);if(o?.type==null)throw new Error("request was invalid, could not read from stream");bt("received",o.type),await Promise.race([this.handleHopProtocol({connection:e,stream:s,request:o}),n.promise])}catch(o){bt.error("error while handling hop",o),s.pb(nt).write({type:nt.Type.STATUS,status:De.MALFORMED_MESSAGE}),t.abort(o)}finally{clearTimeout(i)}}async handleHopProtocol({stream:e,request:t,connection:n}){switch(bt("received hop message"),t.type){case nt.Type.RESERVE:await this.handleReserve({stream:e,request:t,connection:n});break;case nt.Type.CONNECT:await this.handleConnect({stream:e,request:t,connection:n});break;default:bt.error("invalid hop request type %s via peer %s",t.type,n.remotePeer),e.pb(nt).write({type:nt.Type.STATUS,status:De.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,request:t,connection:n}){let i=e.pb(nt);if(bt("hop reserve request from %s",n.remotePeer),iD(n.remoteAddr)){bt.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),i.write({type:nt.Type.STATUS,status:De.PERMISSION_DENIED});return}if(await this.connectionGater.denyInboundRelayReservation?.(n.remotePeer)===!0){bt.error("reservation for %p denied by connection gater",n.remotePeer),i.write({type:nt.Type.STATUS,status:De.PERMISSION_DENIED});return}let s=this.reservationStore.reserve(n.remotePeer,n.remoteAddr);if(s.status!==De.OK){i.write({type:nt.Type.STATUS,status:s.status});return}try{if(s.expire!=null){let o=s.expire*1e3-Date.now();await this.peerStore.merge(n.remotePeer,{tags:{[$T]:{value:1,ttl:o}}})}i.write({type:nt.Type.STATUS,status:De.OK,reservation:await this.makeReservation(n.remotePeer,BigInt(s.expire??0)),limit:this.reservationStore.get(n.remotePeer)?.limit}),bt("sent confirmation response to %s",n.remotePeer)}catch(o){bt.error("failed to send confirmation response to %p",n.remotePeer,o),this.reservationStore.removeReservation(n.remotePeer)}}async makeReservation(e,t){let n=[];for(let s of this.addressManager.getAddresses())s.toString().includes("/p2p-circuit")||n.push(s.bytes);let i=await Wt.seal(new Jc({peer:e,relay:this.peerId,expiration:Number(t)}),this.peerId);return{addrs:n,expire:t,voucher:i.marshal()}}async handleConnect({stream:e,request:t,connection:n}){let i=e.pb(nt);if(iD(n.remoteAddr)){bt.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),i.write({type:nt.Type.STATUS,status:De.PERMISSION_DENIED});return}bt("hop connect request from %s",n.remotePeer);let s;try{if(t.peer==null)throw bt.error("no peer info in hop connect request"),new Error("no peer info in request");t.peer.addrs.forEach(re),s=It(t.peer.id)}catch(h){bt.error("invalid hop connect request via peer %p %s",n.remotePeer,h),i.write({type:nt.Type.STATUS,status:De.MALFORMED_MESSAGE});return}if(!this.reservationStore.hasReservation(s)){bt.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",s,n.remotePeer,De.NO_RESERVATION),i.write({type:nt.Type.STATUS,status:De.NO_RESERVATION});return}if(await this.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,s)===!0){bt.error("hop connect for %p to %p denied by connection gater",n.remotePeer,s),i.write({type:nt.Type.STATUS,status:De.PERMISSION_DENIED});return}let o=this.connectionManager.getConnections(s);if(o.length===0){bt("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",s,n.remotePeer),i.write({type:nt.Type.STATUS,status:De.NO_RESERVATION});return}let a=o[0],c=await this.stopHop({connection:a,request:{type:wn.Type.CONNECT,peer:{id:n.remotePeer.toBytes(),addrs:[]}}});if(c==null){bt.error("failed to open stream to destination peer %s",a?.remotePeer),i.write({type:nt.Type.STATUS,status:De.CONNECTION_FAILED});return}i.write({type:nt.Type.STATUS,status:De.OK});let u=e.unwrap();bt("connection from %p to %p established - merging streans",n.remotePeer,s);let l=this.reservationStore.get(s)?.limit;XT(u,c,this.shutdownController.signal,l)}async stopHop({connection:e,request:t}){bt("starting circuit relay v2 stop request to %s",e.remotePeer);let n=await e.newStream([ih]),i=_r(n),s=i.pb(wn);s.write(t);let o;try{o=await s.read()}catch{bt.error("error parsing stop message response from %s",e.remotePeer)}if(o==null){bt.error("could not read response from %s",e.remotePeer),n.close();return}if(o.status===De.OK)return bt("stop request to %s was successful",e.remotePeer),i.unwrap();bt("stop request failed with code %d",o.status),n.close()}get reservations(){return this.reservationStore.reservations}};function Y5(r={}){return e=>new G5(e,r)}var sG=D("libp2p:stream:converter");function Q5(r,e={}){let{stream:t,remoteAddr:n}=r,{sink:i,source:s}=t,o=async function*(){for await(let u of s)u instanceof Uint8Array?yield u:yield*u}(),a={async sink(u){e.signal!=null&&(u=lt(u,e.signal));try{await i(u),await c()}catch(l){l.type!=="aborted"&&sG(l)}},source:e.signal!=null?lt(o,e.signal):o,remoteAddr:n,timeline:{open:Date.now(),close:void 0},async close(){await i(async function*(){yield new Uint8Array(0)}()),await c()}};async function c(){a.timeline.close==null&&(a.timeline.close=Date.now()),await Promise.resolve()}return a}var fo=D("libp2p:circuit-relay:discover-relays"),Hd=class extends Ue{peerId;peerStore;contentRouting;registrar;started;topologyId;constructor(e){super(),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(Mi,Es({onConnect:e=>{this.safeDispatchEvent("relay:discover",{detail:e})}})),this.discover().catch(e=>{fo.error("error listening on relays",e)}),this.started=!0}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async discover(){fo("searching peer store for relays");let e=(await this.peerStore.all()).filter(({protocols:t})=>t.includes(Mi)).sort(()=>Math.random()-.5);for(let t of e)fo("found relay peer %p in content peer store",t.id),this.safeDispatchEvent("relay:discover",{detail:t.id});fo("found %d relay peers in peer store",e.length);try{fo("searching content routing for relays");let t=await qd(Md),n=0;for await(let i of this.contentRouting.findProviders(t))if(i.multiaddrs.length>0&&!i.id.equals(this.peerId)){let s=i.id;n++,await this.peerStore.merge(s,{multiaddrs:i.multiaddrs}),fo("found relay peer %p in content routing",s),this.safeDispatchEvent("relay:discover",{detail:s})}fo("found %d relay peers in content routing",n)}catch(t){fo.error("failed when finding relays on the network",t)}}};var oD=D("libp2p:circuit-relay:transport:listener"),X5=class extends Ue{connectionManager;relayStore;listeningAddrs;constructor(e){super(),this.connectionManager=e.connectionManager,this.relayStore=e.relayStore,this.listeningAddrs=new Mr,this.relayStore.addEventListener("relay:removed",t=>{this.#e(t.detail)})}async listen(e){oD("listen on %s",e);let t=e.getPeerId(),n;if(t!=null){let s=oe(t),o=this.connectionManager.getConnectionsMap().get(s)??[];o.length>0&&(n=o[0])}if(n==null){let s=e.toString().split("/p2p-circuit").find(a=>a!==""),o=re(s);n=await this.connectionManager.openConnection(o)}if(!this.relayStore.hasReservation(n.remotePeer)){await this.relayStore.addRelay(n.remotePeer,"configured");return}let i=this.relayStore.getReservation(n.remotePeer);if(i==null)throw new w("Did not have reservation after making reservation","ERR_NO_RESERVATION");if(this.listeningAddrs.has(n.remotePeer)){oD("already listening on relay %p",n.remotePeer);return}this.listeningAddrs.set(n.remotePeer,i.addrs.map(s=>re(s).encapsulate("/p2p-circuit"))),this.safeDispatchEvent("listening",{})}getAddrs(){return[...this.listeningAddrs.values()].flat()}async close(){}#e(e){let t=this.listeningAddrs.has(e);this.listeningAddrs.delete(e),t&&this.safeDispatchEvent("close",{})}};function aD(r){return new X5(r)}var bn=D("libp2p:circuit-relay:transport:reservation-store"),aG=60*1e3*10,cG=60*1e3*5,uG=30*1e3,$d=class extends Ue{peerId;connectionManager;transportManager;peerStore;events;reserveQueue;reservations;maxDiscoveredRelays;started;constructor(e,t){super(),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Mr,this.maxDiscoveredRelays=t?.discoverRelays??0,this.started=!1,this.reserveQueue=new vt({concurrency:t?.reservationConcurrency??1}),this.events.addEventListener("peer:disconnect",n=>{this.#t(n.detail)})}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!0}async addRelay(e,t){if(this.peerId.equals(e)){bn("not trying to use self as relay");return}bn("add relay %p",e),await this.reserveQueue.add(async()=>{try{let n=this.reservations.get(e);if(n!=null){if(V5(n.reservation.expire)>aG){bn("already have reservation on relay peer %p and it expires in more than 10 minutes",e);return}clearTimeout(n.timeout),this.reservations.delete(e)}if(t==="discovered"&&[...this.reservations.values()].reduce((u,l)=>(l.type==="discovered"&&u++,u),0)>=this.maxDiscoveredRelays){bn("already have enough discovered relays");return}let i=await this.connectionManager.openConnection(e);if(i.remoteAddr.protoNames().includes("p2p-circuit")){bn("not creating reservation over relayed connection");return}let s=await this.#e(i);bn("created reservation on relay peer %p",e);let o=V5(s.expire),a=Math.min(Math.max(o-cG,uG),Math.pow(2,31)-1),c=setTimeout(()=>{this.addRelay(e,t).catch(u=>{bn.error("could not refresh reservation to relay %p",e,u)})},a);this.reservations.set(e,{timeout:c,reservation:s,type:t}),await this.peerStore.merge(e,{tags:{[GT]:{value:1,ttl:o}}}),await this.transportManager.listen([re(`/p2p/${e.toString()}/p2p-circuit`)])}catch(n){bn.error("could not reserve slot on %p",e,n),this.reservations.delete(e)}})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}async#e(e){bn("requesting reservation from %s",e.remotePeer);let t=await e.newStream(Mi),i=_r(t).pb(nt);i.write({type:nt.Type.RESERVE});let s;try{s=await i.read()}catch(a){throw bn.error("error parsing reserve message response from %p because",e.remotePeer,a),a}finally{t.close()}if(s.status===De.OK&&s.reservation!=null)return s.reservation;let o=`reservation failed with status ${s.status??"undefined"}`;throw bn.error(o),new Error(o)}#t(e){let t=this.reservations.get(e);t!=null&&(bn("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&&(bn("not enough relays %d/%d",this.reservations.size,this.maxDiscoveredRelays),this.safeDispatchEvent("relay:not-enough-relays",{})))}};var Wr=D("libp2p:circuit-relay:transport"),lG=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(re)}catch{return!1}return!0},j5=class{discovery;registrar;peerStore;connectionManager;peerId;upgrader;addressManager;connectionGater;reservationStore;started;constructor(e,t){this.registrar=e.registrar,this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.peerId=e.peerId,this.upgrader=e.upgrader,this.addressManager=e.addressManager,this.connectionGater=e.connectionGater,t.discoverRelays!=null&&t.discoverRelays>0&&(this.discovery=new Hd(e),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(i=>{Wr.error("could not add discovered relay %p",n.detail,i)})})),this.reservationStore=new $d(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.discover().catch(n=>{Wr.error("could not discover relays",n)})}),this.started=!1}isStarted(){return this.started}async start(){await this.reservationStore.start(),await this.discovery?.start(),await this.registrar.handle(ih,e=>{this.onStop(e).catch(t=>{Wr.error(t)})}),this.started=!0}async stop(){this.discovery?.stop(),await this.reservationStore.stop(),await this.registrar.unhandle(ih),this.started=!1}[Pi]=!0;[Symbol.toStringTag]="libp2p/circuit-relay-v2";async dial(e,t={}){if(e.protoCodes().filter(p=>p===290).length!==1){let p="Invalid circuit relay address";throw Wr.error(p,e),new w(p,V.ERR_RELAYED_DIAL)}let n=e.toString().split("/p2p-circuit"),i=re(n[0]),s=re(n[n.length-1]),o=i.getPeerId(),a=s.getPeerId();if(o==null||a==null){let p=`Circuit relay dial to ${e.toString()} failed as address did not have peer ids`;throw Wr.error(p),new w(p,V.ERR_RELAYED_DIAL)}let c=oe(o),u=oe(a),l=!1,f=this.connectionManager.getConnections(c)[0];f==null&&(await this.peerStore.merge(c,{multiaddrs:[i]}),f=await this.connectionManager.openConnection(c,t),l=!0);let d;try{return d=await f.newStream([Mi]),await this.connectV2({stream:d,connection:f,destinationPeer:u,destinationAddr:s,relayAddr:i,ma:e,disconnectOnFailure:l})}catch(p){throw Wr.error(`Circuit relay dial to destination ${u.toString()} via relay ${c.toString()} failed`,p),d?.abort(p),l&&await f.close(),p}}async connectV2({stream:e,connection:t,destinationPeer:n,destinationAddr:i,relayAddr:s,ma:o,disconnectOnFailure:a}){try{let c=_r(e),u=c.pb(nt);u.write({type:nt.Type.CONNECT,peer:{id:n.toBytes(),addrs:[re(i).bytes]}});let l=await u.read();if(l.status!==De.OK)throw new w(`failed to connect via relay with status ${l?.status?.toString()??"undefined"}`,V.ERR_HOP_REQUEST_FAILED);let h=Q5({stream:c.unwrap(),remoteAddr:o,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`)});return Wr("new outbound connection %s",h.remoteAddr),await this.upgrader.upgradeOutbound(h)}catch(c){throw Wr.error(`Circuit relay dial to destination ${n.toString()} via relay ${t.remotePeer.toString()} failed`,c),a&&await t.close(),c}}createListener(e){return aD({connectionManager:this.connectionManager,relayStore:this.reservationStore})}filter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>ri.matches(t))}async onStop({connection:e,stream:t}){let n=_r(t),i=await n.readPB(wn);if(Wr("received circuit v2 stop protocol request from %s",e.remotePeer),i?.type===void 0)return;let s=n.pb(wn);if(Wr("new circuit relay v2 stop stream from %s",e.remotePeer),i.type!==wn.Type.CONNECT){Wr.error("invalid stop connect request via peer %s",e.remotePeer),s.write({type:wn.Type.STATUS,status:De.UNEXPECTED_MESSAGE});return}if(!lG(i)){Wr.error("invalid stop connect request via peer %s",e.remotePeer),s.write({type:wn.Type.STATUS,status:De.MALFORMED_MESSAGE});return}let o=It(i.peer.id);if(await this.connectionGater.denyInboundRelayedConnection?.(e.remotePeer,o)===!0){s.write({type:wn.Type.STATUS,status:De.PERMISSION_DENIED});return}s.write({type:wn.Type.STATUS,status:De.OK});let a=e.remoteAddr.encapsulate(`/p2p-circuit/p2p/${o.toString()}`),c=this.addressManager.getAddresses()[0],u=Q5({stream:n.unwrap(),remoteAddr:a,localAddr:c});Wr("new inbound connection %s",u.remoteAddr),await this.upgrader.upgradeInbound(u),Wr("%s connection %s upgraded","inbound",u.remoteAddr)}};function Z5(r={}){return e=>new j5(e,r)}var cD="0.45.3";var J5=`js-libp2p/${cD}`;var uD="0.1.0",lD="id",hD="id/push",fD="1.0.0",dD="1.0.0";var Gd=F(Zr(),1);var po;(function(r){let e;r.codec=()=>(e==null&&(e=se((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let s of t.listenAddrs)n.uint32(18),n.bytes(s);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let s of t.protocols)n.uint32(26),n.string(s);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={listenAddrs:[],protocols:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let o=t.uint32();switch(o>>>3){case 5:i.protocolVersion=t.string();break;case 6:i.agentVersion=t.string();break;case 1:i.publicKey=t.bytes();break;case 2:i.listenAddrs.push(t.bytes());break;case 4:i.observedAddr=t.bytes();break;case 3:i.protocols.push(t.string());break;case 8:i.signedPeerRecord=t.bytes();break;default:t.skipType(o&7);break}}return i})),e),r.encode=t=>ie(t,r.codec()),r.decode=t=>ne(t,r.codec())})(po||(po={}));var Ur=D("libp2p:identify"),pD=1024*8,ci={protocolPrefix:"ipfs",agentVersion:J5,timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1,maxObservedAddresses:10,maxIdentifyMessageSize:8192},Wd=class{identifyProtocolStr;identifyPushProtocolStr;host;started;timeout;peerId;peerStore;registrar;connectionManager;addressManager;maxInboundStreams;maxOutboundStreams;maxPushIncomingStreams;maxPushOutgoingStreams;maxIdentifyMessageSize;maxObservedAddresses;events;constructor(e,t){this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.events=e.events,this.identifyProtocolStr=`/${t.protocolPrefix??ci.protocolPrefix}/${lD}/${fD}`,this.identifyPushProtocolStr=`/${t.protocolPrefix??ci.protocolPrefix}/${hD}/${dD}`,this.timeout=t.timeout??ci.timeout,this.maxInboundStreams=t.maxInboundStreams??ci.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??ci.maxOutboundStreams,this.maxPushIncomingStreams=t.maxPushIncomingStreams??ci.maxPushIncomingStreams,this.maxPushOutgoingStreams=t.maxPushOutgoingStreams??ci.maxPushOutgoingStreams,this.maxIdentifyMessageSize=t.maxIdentifyMessageSize??ci.maxIdentifyMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??ci.maxObservedAddresses,this.host={protocolVersion:`${t.protocolPrefix??ci.protocolPrefix}/${uD}`,agentVersion:t.agentVersion??ci.agentVersion},e.events.addEventListener("connection:open",n=>{let i=n.detail;this.identify(i).catch(s=>{Ur.error("error during identify trigged by connection:open",s)})}),e.events.addEventListener("self:peer:update",n=>{this.push().catch(i=>{Ur.error(i)})}),this.host.agentVersion===J5&&(HR||VR?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(Y1||Q1||zR||$R)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:q(this.host.agentVersion),ProtocolVersion:q(this.host.protocolVersion)}}),await this.registrar.handle(this.identifyProtocolStr,e=>{this._handleIdentify(e).catch(t=>{Ur.error(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),await this.registrar.handle(this.identifyPushProtocolStr,e=>{this._handlePush(e).catch(t=>{Ur.error(t)})},{maxInboundStreams:this.maxPushIncomingStreams,maxOutboundStreams:this.maxPushOutgoingStreams}),this.started=!0)}async stop(){await this.registrar.unhandle(this.identifyProtocolStr),await this.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async pushToConnections(e){let t=this.addressManager.getAddresses().map(l=>l.decapsulateCode(X("p2p").code)),n=new zt({peerId:this.peerId,multiaddrs:t}),i=await Wt.seal(n,this.peerId),s=this.registrar.getProtocols(),o=await this.peerStore.get(this.peerId),a=B(o.metadata.get("AgentVersion")??q(this.host.agentVersion)),c=B(o.metadata.get("ProtocolVersion")??q(this.host.protocolVersion)),u=e.map(async l=>{let h,f=AbortSignal.timeout(this.timeout);try{(0,Gd.setMaxListeners)?.(1/0,f)}catch{}try{h=await l.newStream([this.identifyPushProtocolStr],{signal:f}),await Er(h,f).sink(be([po.encode({listenAddrs:t.map(p=>p.bytes),signedPeerRecord:i.marshal(),protocols:s,agentVersion:a,protocolVersion:c})],p=>Et(p)))}catch(d){Ur.error("could not push identify update to peer",d)}finally{h?.close()}});await Promise.all(u)}async push(){if(!this.isStarted())return;let e=[];await Promise.all(this.connectionManager.getConnections().map(async t=>{try{if(!(await this.peerStore.get(t.remotePeer)).protocols.includes(this.identifyPushProtocolStr))return;e.push(t)}catch(n){if(n.code!==V.ERR_NOT_FOUND)throw n}})),await this.pushToConnections(e)}async _identify(e,t={}){let n,i=it([AbortSignal.timeout(this.timeout),t?.signal]);try{(0,Gd.setMaxListeners)?.(1/0,i)}catch{}try{n=await e.newStream([this.identifyProtocolStr],{signal:i});let s=Er(n,i),o=await be([],s,a=>Ct(a,{maxDataLength:this.maxIdentifyMessageSize??pD}),async a=>si(a));if(o==null)throw new w("No data could be retrieved",V.ERR_CONNECTION_ENDED);try{return po.decode(o)}catch(a){throw new w(String(a),V.ERR_INVALID_MESSAGE)}}finally{n?.close(),i.clear()}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:i,protocols:s,observedAddr:o}=n;if(i==null)throw new w("public key was missing from identify message",V.ERR_MISSING_PUBLIC_KEY);let a=await er(i);if(!e.remotePeer.equals(a))throw new w("identified peer does not match the expected peer",V.ERR_INVALID_PEER);if(this.peerId.equals(a))throw new w("identified peer is our own peer id?",V.ERR_INVALID_PEER);let c=hG(o);Ur("identify completed for peer %p and protocols %o",a,s),Ur("our observed address is %s",c),c!=null&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(Ur("storing our observed address %s",c?.toString()),this.addressManager.addObservedAddr(c));let u=await this.#e(e.remotePeer,n),l={peerId:a,protocolVersion:n.protocolVersion,agentVersion:n.agentVersion,publicKey:n.publicKey,listenAddrs:n.listenAddrs.map(h=>re(h)),observedAddr:n.observedAddr==null?void 0:re(n.observedAddr),protocols:n.protocols,signedPeerRecord:u};this.events.safeDispatchEvent("peer:identify",{detail:l})}async _handleIdentify(e){let{connection:t,stream:n}=e,i=AbortSignal.timeout(this.timeout);try{(0,Gd.setMaxListeners)?.(1/0,i)}catch{}try{let s=this.peerId.publicKey??new Uint8Array(0),o=await this.peerStore.get(this.peerId),a=this.addressManager.getAddresses().map(f=>f.decapsulateCode(X("p2p").code)),c=o.peerRecordEnvelope;if(a.length>0&&c==null){let f=new zt({peerId:this.peerId,multiaddrs:a});c=(await Wt.seal(f,this.peerId)).marshal().subarray()}let u=po.encode({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:s,listenAddrs:a.map(f=>f.bytes),signedPeerRecord:c,observedAddr:t.remoteAddr.bytes,protocols:o.protocols}),l=Er(n,i),h=be([u],f=>Et(f));await l.sink(h)}catch(s){Ur.error("could not respond to identify request",s)}finally{n.close()}}async _handlePush(e){let{connection:t,stream:n}=e;try{if(this.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");let i=Er(n,AbortSignal.timeout(this.timeout)),o=await _r(i,{maxDataLength:this.maxIdentifyMessageSize??pD}).readPB(po);await this.#e(t.remotePeer,o)}catch(i){Ur.error("received invalid message",i);return}finally{n.close()}Ur("handled push from %p",t.remotePeer)}async#e(e,t){if(t==null)throw new Error("Message was null or undefined");if(Ur("received identify from %p",e),t.signedPeerRecord==null)return;let n=t.signedPeerRecord,i=await Wt.openAndCertify(n,zt.DOMAIN),s=zt.createFromProtobuf(i.payload);if(!s.peerId.equals(i.peerId))throw new Error("signing key does not match PeerId in the PeerRecord");if(!e.equals(s.peerId))throw new Error("signing key does not match remote PeerId");let o;try{o=await this.peerStore.get(s.peerId)}catch(c){if(c.code!=="ERR_NOT_FOUND")throw c}Ur("received signedPeerRecord in push from %p",e);let a=o?.metadata??new Map;if(o?.peerRecordEnvelope!=null){let c=await Wt.createFromProtobuf(o.peerRecordEnvelope),u=zt.createFromProtobuf(c.payload);u.seqNumber>=s.seqNumber&&(Ur("sequence number was lower or equal to existing sequence number - stored: %d received: %d",u.seqNumber,s.seqNumber),s=u,n=o.peerRecordEnvelope)}return t.agentVersion!=null&&a.set("AgentVersion",q(t.agentVersion)),t.protocolVersion!=null&&a.set("ProtocolVersion",q(t.protocolVersion)),await this.peerStore.patch(s.peerId,{peerRecordEnvelope:n,protocols:t.protocols,addresses:s.multiaddrs.map(c=>({isCertified:!0,multiaddr:c})),metadata:a}),Ur("consumed signedPeerRecord sent in push from %p",e),{seq:s.seqNumber,addresses:s.multiaddrs}}};function hG(r){if(r!=null&&r.length>0)try{return re(r)}catch{}}function mD(r={}){return e=>new Wd(e,r)}var gD={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};async function yD(r){return KT({...r,addresses:{listen:["/webrtc"]},transports:[mR(),pR(),BI(),tI(),Z5({discoverRelays:1})],connectionEncryption:[O0()],streamMuxers:[ax(),ES()],peerDiscovery:[xx(gD)],contentRouters:[Dx("https://cid.contact")],services:{identify:mD(),autoNAT:HT(),pubsub:ov(),dht:m_({clientMode:!0}),relay:Y5({advertise:!0})}})}var e6="1.1.3",Yd="helia";var fG=D("helia");async function dG(r={}){let e=r.datastore??new yo,t=r.blockstore??new su,n=r.libp2p??await yD({datastore:e,start:!1}),i=new df({...r,datastore:e,blockstore:t,libp2p:n});return r.start!==!1&&await i.start(),i.libp2p.isStarted()?await wD(i):i.libp2p.addEventListener("start",()=>{wD(i).catch(s=>{fG.error("could not add Helia to agent version",s)})}),i}async function wD(r){let t=(await r.libp2p.peerStore.get(r.libp2p.peerId)).metadata.get("AgentVersion");if(t==null)return;let n=new TextDecoder().decode(t);n.match(/js-libp2p\/\d+\.\d+\.\d+\sUserAgent=/)!=null&&(n.includes(Yd)?n=`${Yd}/${e6} ${n.split(" ").slice(1).join(" ")}`:n=`${Yd}/${e6} ${n}`,await r.libp2p.peerStore.merge(r.libp2p.peerId,{metadata:{AgentVersion:new TextEncoder().encode(n)}}))}return oh(pG);})();
|
|
85
85
|
/*! Bundled license information:
|
|
86
86
|
|
|
87
87
|
@noble/ed25519/lib/esm/index.js:
|
package/dist/src/version.d.ts
CHANGED
package/dist/src/version.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "helia",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.3",
|
|
4
4
|
"description": "An implementation of IPFS in JavaScript",
|
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
|
6
6
|
"homepage": "https://github.com/ipfs/helia/tree/master/packages/helia#readme",
|
|
@@ -181,7 +181,7 @@
|
|
|
181
181
|
"@ipld/dag-json": "^10.0.1",
|
|
182
182
|
"@types/sinon": "^10.0.14",
|
|
183
183
|
"aegir": "^39.0.4",
|
|
184
|
-
"delay": "^
|
|
184
|
+
"delay": "^6.0.0",
|
|
185
185
|
"sinon": "^15.0.2",
|
|
186
186
|
"sinon-ts": "^1.0.0"
|
|
187
187
|
},
|
package/src/version.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export const version = '1.1.
|
|
1
|
+
export const version = '1.1.3'
|
|
2
2
|
export const name = 'helia'
|