mirror of
https://github.com/logos-messaging/lab.waku.org.git
synced 2026-01-08 16:53:08 +00:00
52 lines
861 KiB
JavaScript
52 lines
861 KiB
JavaScript
|
|
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[948],{4699:function(e,t){"use strict";t.byteLength=function(e){var t=l(e),r=t[0],n=t[1];return(r+n)*3/4-n},t.toByteArray=function(e){var t,r,s=l(e),o=s[0],a=s[1],c=new i((o+a)*3/4-a),u=0,h=a>0?o-4:o;for(r=0;r<h;r+=4)t=n[e.charCodeAt(r)]<<18|n[e.charCodeAt(r+1)]<<12|n[e.charCodeAt(r+2)]<<6|n[e.charCodeAt(r+3)],c[u++]=t>>16&255,c[u++]=t>>8&255,c[u++]=255&t;return 2===a&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,c[u++]=255&t),1===a&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,c[u++]=t>>8&255,c[u++]=255&t),c},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,s=[],o=0,a=n-i;o<a;o+=16383)s.push(function(e,t,n){for(var i,s=[],o=t;o<n;o+=3)s.push(r[(i=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]))>>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return s.join("")}(e,o,o+16383>a?a:o+16383));return 1===i?s.push(r[(t=e[n-1])>>2]+r[t<<4&63]+"=="):2===i&&s.push(r[(t=(e[n-2]<<8)+e[n-1])>>10]+r[t>>4&63]+r[t<<2&63]+"="),s.join("")};for(var r=[],n=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,a=s.length;o<a;++o)r[o]=s[o],n[s.charCodeAt(o)]=o;function l(e){var t=e.length;if(t%4>0)throw Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");-1===r&&(r=t);var n=r===t?0:4-r%4;return[r,n]}n["-".charCodeAt(0)]=62,n["_".charCodeAt(0)]=63},7133:function(e,t,r){"use strict";/*!
|
||
|
|
* The buffer module from node.js, for the browser.
|
||
|
|
*
|
||
|
|
* @author Feross Aboukhadijeh <https://feross.org>
|
||
|
|
* @license MIT
|
||
|
|
*/let n=r(4699),i=r(9087),s="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;function o(e){if(e>2147483647)throw RangeError('The value "'+e+'" is invalid for option "size"');let t=new Uint8Array(e);return Object.setPrototypeOf(t,a.prototype),t}function a(e,t,r){if("number"==typeof e){if("string"==typeof t)throw TypeError('The "string" argument must be of type string. Received type number');return u(e)}return l(e,t,r)}function l(e,t,r){if("string"==typeof e)return function(e,t){if(("string"!=typeof t||""===t)&&(t="utf8"),!a.isEncoding(t))throw TypeError("Unknown encoding: "+t);let r=0|f(e,t),n=o(r),i=n.write(e,t);return i!==r&&(n=n.slice(0,i)),n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(M(e,Uint8Array)){let t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return h(e)}(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(M(e,ArrayBuffer)||e&&M(e.buffer,ArrayBuffer)||"undefined"!=typeof SharedArrayBuffer&&(M(e,SharedArrayBuffer)||e&&M(e.buffer,SharedArrayBuffer)))return d(e,t,r);if("number"==typeof e)throw TypeError('The "value" argument must not be of type number. Received type number');let n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return a.from(n,t,r);let i=function(e){var t;if(a.isBuffer(e)){let t=0|p(e.length),r=o(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||(t=e.length)!=t?o(0):h(e):"Buffer"===e.type&&Array.isArray(e.data)?h(e.data):void 0}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return a.from(e[Symbol.toPrimitive]("string"),t,r);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw TypeError('"size" argument must be of type number');if(e<0)throw RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return c(e),o(e<0?0:0|p(e))}function h(e){let t=e.length<0?0:0|p(e.length),r=o(t);for(let n=0;n<t;n+=1)r[n]=255&e[n];return r}function d(e,t,r){let n;if(t<0||e.byteLength<t)throw RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw RangeError('"length" is outside of buffer bounds');return Object.setPrototypeOf(n=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r),a.prototype),n}function p(e){if(e>=2147483647)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x7fffffff bytes");return 0|e}function f(e,t){if(a.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||M(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);let r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return L(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return x(e).length;default:if(i)return n?-1:L(e).length;t=(""+t).toLowerCase(),i=!0}}function g(e,t,r){let i=!1;if((void 0===t||t<0)&&(t=0),t>this.length||((void 0===r||r>this.length)&&(r=this.length),r<=0||(r>>>=0)<=(t>>>=0)))return"";for(e||(e="utf8");;)switch(e){case"hex":return function(e,t,r){let n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);let i="";for(let n=t;n<r;++n)i+=U[e[n]];return i}(this,t,r);case"utf8":case"utf-8":return w(this,t,r);case"ascii":return function(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;i<r;++i)n+=String.fromCharCode(127&e[i]);return n}(this,t,r);case"latin1":case"binary":return function(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;i<r;++i)n+=String.fromCharCode(e[i]);return n}(this,t,r);case"base64":var s,o;return s=t,o=r,0===s&&o===this.length?n.fromByteArray(this):n.fromByteArray(this.slice(s,o));case"ucs2":case"ucs-2
|
||
|
|
Next ping will be attempted in ${n} seconds.
|
||
|
|
`);return}try{await r.merge(e,{metadata:{ping:(0,tj.iY)(i.toString())}})}catch(e){r_.error("Failed to update ping",e)}}catch(e){r_.error(`Ping failed (${s})`,e)}})()},1e3*n);this.pingKeepAliveTimers.set(s,i)}let o=this.relay;if(o&&0!==i){let t=this.scheduleRelayPings(o,i,e.toString());this.relayKeepAliveTimers.set(e,t)}}stop(e){let t=e.toString();this.pingKeepAliveTimers.has(t)&&(clearInterval(this.pingKeepAliveTimers.get(t)),this.pingKeepAliveTimers.delete(t)),this.relayKeepAliveTimers.has(e)&&(this.relayKeepAliveTimers.get(e)?.map(clearInterval),this.relayKeepAliveTimers.delete(e))}stopAll(){for(let e of[...Object.values(this.pingKeepAliveTimers),...Object.values(this.relayKeepAliveTimers)])clearInterval(e);this.pingKeepAliveTimers.clear(),this.relayKeepAliveTimers.clear()}connectionsExist(){return this.pingKeepAliveTimers.size>0||this.relayKeepAliveTimers.size>0}scheduleRelayPings(e,t,r){let n=[];for(let i of e.pubsubTopics){let s=e.getMeshPeers(i);if(!s.includes(r))continue;let o=(0,tm.Mf)({pubsubTopicShardInfo:(0,tw.Tf)(i),contentTopic:"/relay-ping/1/ping/null",ephemeral:!0}),a=setInterval(()=>{r_.info("Sending Waku Relay ping message"),e.send(o,{payload:new Uint8Array([1])}).catch(e=>r_.error("Failed to send relay ping",e))},1e3*t);n.push(a)}return n}}let rC=new tw.Yd("connection-manager");class rk extends rI{configuredPubsubTopics;static instances=new Map;keepAliveManager;options;libp2p;dialAttemptsForPeer=new Map;dialErrorsForPeer=new Map;currentActiveParallelDialCount=0;pendingPeerDialQueue=[];online=!1;isConnected(){return this.online}toggleOnline(){this.online||(this.online=!0,this.dispatchEvent(new CustomEvent(tb.wh.CONNECTION_STATUS,{detail:this.online})))}toggleOffline(){this.online&&0==this.libp2p.getConnections().length&&(this.online=!1,this.dispatchEvent(new CustomEvent(tb.wh.CONNECTION_STATUS,{detail:this.online})))}static create(e,t,r,n,i,s){let o=rk.instances.get(e);return o||(o=new rk(t,r,n,i,s),rk.instances.set(e,o)),o}stop(){this.keepAliveManager.stopAll(),this.libp2p.removeEventListener("peer:connect",this.onEventHandlers["peer:connect"]),this.libp2p.removeEventListener("peer:disconnect",this.onEventHandlers["peer:disconnect"]),this.libp2p.removeEventListener("peer:discovery",this.onEventHandlers["peer:discovery"])}async dropConnection(e){try{this.keepAliveManager.stop(e),await this.libp2p.hangUp(e),rC.info(`Dropped connection with peer ${e.toString()}`)}catch(t){rC.error(`Error dropping connection with peer ${e.toString()} - ${t}`)}}async getPeersByDiscovery(){let e=await this.libp2p.peerStore.all(),t=this.libp2p.getConnections().map(e=>e.remotePeer),r=[],n=[],i=[],s=[],o=[],a=[];for(let t of e){let e=await this.getTagNamesForPeer(t.id);e.includes(tb.$G.BOOTSTRAP)?r.push(t):e.includes(tb.$G.PEER_EXCHANGE)?n.push(t):e.includes(tb.$G.LOCAL)&&i.push(t)}for(let e of t){let t=await this.libp2p.peerStore.get(e),r=await this.getTagNamesForPeer(e);r.includes(tb.$G.BOOTSTRAP)?s.push(t):r.includes(tb.$G.PEER_EXCHANGE)?o.push(t):r.includes(tb.$G.LOCAL)&&a.push(t)}return{DISCOVERED:{[tb.$G.BOOTSTRAP]:r,[tb.$G.PEER_EXCHANGE]:n,[tb.$G.LOCAL]:i},CONNECTED:{[tb.$G.BOOTSTRAP]:s,[tb.$G.PEER_EXCHANGE]:o,[tb.$G.LOCAL]:a}}}constructor(e,t,r,n,i){super(),this.configuredPubsubTopics=r,this.libp2p=e,this.configuredPubsubTopics=r,this.options={maxDialAttemptsForPeer:3,maxBootstrapPeersAllowed:1,maxParallelDials:3,...i},this.keepAliveManager=new rR(t,n),this.run().then(()=>rC.info("Connection Manager is now running")).catch(e=>rC.error("Unexpected error while running service",e)),this.dialPeerStorePeers().catch(e=>rC.error("Unexpected error while dialing peer store peers",e))}async dialPeerStorePeers(){let e=await this.libp2p.peerStore.all(),t=[];for(let r of e)this.libp2p.getConnections().find(e=>e.remotePeer===r.id)||t.push(this.attemptDial(r.id));try{await Promise.all(t)}catch(e){rC.error("Unexpected error while dialing peer store peers",e)}}async run(){this.startPeerDiscoveryListener(),this.startPeerConnectionListener(),this.startPeerDisconnectionListener()}async dialPeer(e){this.currentActiveParallelDi
|
||
|
|
Not dialing.`),!1}return await this.isPeerDialableBasedOnBootstrapStatus(e)?!this.dialAttemptsForPeer.has(e.toString())||(rC.warn(`Peer ${e.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`),!1):(rC.warn(`Peer ${e.toString()} is not dialable based on bootstrap status. Not dialing.`),!1)}async isPeerDialableBasedOnBootstrapStatus(e){let t=await this.getTagNamesForPeer(e),r=t.some(e=>e===tb.$G.BOOTSTRAP);if(!r)return!0;{let e=this.libp2p.getConnections().filter(e=>e.tags.find(e=>e===tb.$G.BOOTSTRAP)).length;if(e<this.options.maxBootstrapPeersAllowed)return!0}return!1}async dispatchDiscoveryEvent(e){let t=(await this.getTagNamesForPeer(e)).includes(tb.$G.BOOTSTRAP);this.dispatchEvent(new CustomEvent(t?tb.Wq.PEER_DISCOVERY_BOOTSTRAP:tb.Wq.PEER_DISCOVERY_PEER_EXCHANGE,{detail:e}))}async getTagNamesForPeer(e){try{let t=await this.libp2p.peerStore.get(e);return Array.from(t.tags.keys())}catch(t){return rC.error(`Failed to get peer ${e}, error: ${t}`),[]}}async isPeerTopicConfigured(e){let t=await this.getPeerShardInfo(e,this.libp2p.peerStore);if(!t)return!0;let r=(0,tw.yf)(t),n=r.some(e=>this.configuredPubsubTopics.includes(e));return n}async getPeerShardInfo(e,t){let r=await t.get(e),n=r.metadata.get("shardInfo");if(n)return(0,tw.Ix)(n)}}let rB=new tw.Yd("metadata"),rP="/vac/waku/metadata/1.0.0";class rD extends tZ{shardInfo;libp2pComponents;handshakesConfirmed=new Map;constructor(e,t){super(rP,t.components,rB,(0,tw.yf)(e)),this.shardInfo=e,this.libp2pComponents=t,t.registrar.handle(rP,e=>{this.onRequest(e)})}async onRequest(e){try{let{stream:t,connection:r}=e,n=t0.fi._.encode(this.shardInfo),i=await tV([n],tP,t,tL,async e=>await tv(e)),{error:s,shardInfo:o}=this.decodeMetadataResponse(i);if(s)return;await this.savePeerShardInfo(r.remotePeer,o)}catch(e){rB.error("Error handling metadata request",e)}}async query(e){let t;let r=t0.fi.v.encode(this.shardInfo),n=await this.peerStore.get(e);if(!n)return{shardInfo:null,error:tb.K1.NO_PEER_AVAILABLE};try{t=await this.getStream(n)}catch(e){return rB.error("Failed to get stream",e),{shardInfo:null,error:tb.K1.NO_STREAM_AVAILABLE}}let i=await tV([r],tP,t,tL,async e=>await tv(e)),{error:s,shardInfo:o}=this.decodeMetadataResponse(i);return s?{shardInfo:null,error:s}:(await this.savePeerShardInfo(e,o),{shardInfo:o,error:null})}async confirmOrAttemptHandshake(e){let t=this.handshakesConfirmed.get(e.toString());return t?{shardInfo:t,error:null}:await this.query(e)}decodeMetadataResponse(e){let t=new tC;e.forEach(e=>{t.append(e)});let r=t0.fi._.decode(t);return r?{shardInfo:r,error:null}:(rB.error("Error decoding metadata response"),{shardInfo:null,error:tb.K1.DECODE_FAILED})}async savePeerShardInfo(e,t){await this.libp2pComponents.peerStore.merge(e,{metadata:{shardInfo:(0,tw.kL)(t)}}),this.handshakesConfirmed.set(e.toString(),t)}}class rN extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}}async function rL(e,t,r){let n;if(null==t)return e;if(t.aborted)return Promise.reject(new rN(r?.errorMessage,r?.errorCode));let i=new rN(r?.errorMessage,r?.errorCode);try{return await Promise.race([e,new Promise((e,r)=>{n=()=>{r(i)},t.addEventListener("abort",n)})])}finally{null!=n&&t.removeEventListener("abort",n)}}class rx{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=tx(),this.haveNext=tx()}[Symbol.asyncIterator](){return this}async next(){if(null==this.nextResult&&await this.haveNext.promise,null==this.nextResult)throw Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=tx(),e}async throw(e){return this.ended=!0,null!=e&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){return await this._push(void 0),{done:!0,value:void 0}}async push(e,t){await this._push(e,t)}async end(e,t){null!=e?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(null!=e
|
||
|
|
* Copyright (c) 2014, GMO GlobalSign
|
||
|
|
* Copyright (c) 2015-2022, Peculiar Ventures
|
||
|
|
* All rights reserved.
|
||
|
|
*
|
||
|
|
* Author 2014-2019, Yury Strozhevsky
|
||
|
|
*
|
||
|
|
* Redistribution and use in source and binary forms, with or without modification,
|
||
|
|
* are permitted provided that the following conditions are met:
|
||
|
|
*
|
||
|
|
* * Redistributions of source code must retain the above copyright notice, this
|
||
|
|
* list of conditions and the following disclaimer.
|
||
|
|
*
|
||
|
|
* * Redistributions in binary form must reproduce the above copyright notice, this
|
||
|
|
* list of conditions and the following disclaimer in the documentation and/or
|
||
|
|
* other materials provided with the distribution.
|
||
|
|
*
|
||
|
|
* * Neither the name of the copyright holder nor the names of its
|
||
|
|
* contributors may be used to endorse or promote products derived from
|
||
|
|
* this software without specific prior written permission.
|
||
|
|
*
|
||
|
|
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||
|
|
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||
|
|
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||
|
|
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||
|
|
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||
|
|
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||
|
|
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||
|
|
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||
|
|
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||
|
|
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||
|
|
*
|
||
|
|
*/function aq(){if("undefined"==typeof BigInt)throw Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function az(e){let t=0,r=0;for(let r=0;r<e.length;r++){let n=e[r];t+=n.byteLength}let n=new Uint8Array(t);for(let t=0;t<e.length;t++){let i=e[t];n.set(new Uint8Array(i),r),r+=i.byteLength}return n.buffer}function aG(e,t,r,n){return t instanceof Uint8Array?t.byteLength?r<0?(e.error="Wrong parameter: inputOffset less than zero",!1):n<0?(e.error="Wrong parameter: inputLength less than zero",!1):!(t.byteLength-r-n<0)||(e.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):(e.error="Wrong parameter: inputBuffer has zero length",!1):(e.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}class aj{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return az(this.items)}}let aW=[new Uint8Array([1])],aY="0123456789",aQ=new ArrayBuffer(0),aX=new Uint8Array(0),aJ="EndOfContent",aZ="OCTET STRING",a0="BIT STRING";function a1(e){var t;return(t=class extends e{constructor(...e){var t;super(...e);let r=e[0]||{};this.isHexOnly=null!==(t=r.isHexOnly)&&void 0!==t&&t,this.valueHexView=r.valueHex?aU.vJ.toUint8Array(r.valueHex):aX}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(e){this.valueHexView=new Uint8Array(e)}fromBER(e,t,r){let n=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!aG(this,n,t,r))return -1;let i=t+r;return(this.valueHexView=n.subarray(t,i),this.valueHexView.length)?(this.blockLength=r,i):(this.warnings.push("Zero buffer length"),t)}toBER(e=!1){return this.isHexOnly?e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",aQ)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:aU.ep.ToHex(this.valueHexView)}}}).NAME="hexBlock",t}class a2{constructor({blockLength:e=0,error:t="",warnings:r=[],valueBeforeDecode:n=aX}={}){this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=aU.vJ.toUint8Array(n)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:aU.ep.ToHex(this.valueBeforeDecodeView)}}}a2.NAME="baseBlock";class a3 extends a2{fromBER(e,t,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}a3.NAME="valueBlock";class a4 extends a1(a2){constructor({idBlock:e={}}={}){var t,r,n,i;super(),e?(this.isHexOnly=null!==(t=e.isHexOnly)&&void 0!==t&&t,this.valueHexView=e.valueHex?aU.vJ.toUint8Array(e.valueHex):aX,this.tagClass=null!==(r=e.tagClass)&&void 0!==r?r:-1,this.tagNumber=null!==(n=e.tagNumber)&&void 0!==n?n:-1,this.isConstructed=null!==(i=e.isConstructed)&&void 0!==i&&i):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",aQ}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let r=new Uint8Array(1);if(!e){let e=this.tagNumber;e&=31,t|=e,r[0]=t}return r.buffer}if(!this.isHexOnly){let r=aK(this.tagNumber,7),n=new Uint8Array(r),i=r.byteLength,s=new Uint8Array(i+1);if(s[0]=31|t,!e){for(let e=0;e<i-1;e++)s[e+1]=128|n[e];s[i]=n[i-1]}return s.buffer}let r=new Uint8Array(this.valueHexView.byteLength+1);if(r[0]=31|t,!e){let e=this.valueHexView;for(let t=0;t<e.length-1;t++)r[t+1]=128|e[t];r[this.valueHexView.byteLength]=e[e.length-1]}return r.buffer}fromBER(e,t,r){let n=aU.vJ.toUint8Array(e);if(!aG(this,n,t,r))return -1;let i=n.subarray(t,t+r);if(0===i.length)return this.error="Zero buffer length",-1;let s=192&i[0];switch(s){case
|
||
|
|
${e.join("\n")}`:`${t} :`}}a5.Constructed=li,li.NAME="CONSTRUCTED";class ls extends a3{fromBER(e,t,r){return t}toBER(e){return aQ}}ls.override="EndOfContentValueBlock";class lo extends a8{constructor(e={}){super(e,ls),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}a5.EndOfContent=lo,lo.NAME=aJ;class la extends a8{constructor(e={}){super(e,a3),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,r){return(this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=r,t+r>e.byteLength)?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+r}toBER(e,t){let r=new ArrayBuffer(2);if(!e){let e=new Uint8Array(r);e[0]=5,e[1]=0}return t&&t.write(r),r}onAsciiEncoding(){return`${this.constructor.NAME}`}}a5.Null=la,la.NAME="NULL";class ll extends a1(a3){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=aU.vJ.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,r){let n=aU.vJ.toUint8Array(e);return aG(this,n,t,r)?(this.valueHexView=n.subarray(t,t+r),r>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,aH.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}ll.NAME="BooleanValueBlock";class lc extends a8{constructor(e={}){super(e,ll),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}}a5.Boolean=lc,lc.NAME="BOOLEAN";class lu extends a1(ln){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,r){let n=0;if(this.isConstructed){if(this.isHexOnly=!1,-1===(n=ln.prototype.fromBER.call(this,e,t,r)))return n;for(let e=0;e<this.value.length;e++){let t=this.value[e].constructor.NAME;if(t===aJ){if(!this.isIndefiniteForm)return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1;break}if(t!==aZ)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,n=super.fromBER(e,t,r),this.blockLength=r;return n}toBER(e,t){return this.isConstructed?ln.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}lu.NAME="OctetStringValueBlock";class lh extends a8{constructor({idBlock:e={},lenBlock:t={},...r}={}){var n,i;null!==(n=r.isConstructed)&&void 0!==n||(r.isConstructed=!!(null===(i=r.value)||void 0===i?void 0:i.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},lu),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,r){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,0===r)return 0===this.idBlock.error.length&&(this.blockLength+=this.idBlock.blockLength),0===this.lenBlock.error.length&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let n=e instanceof ArrayBuffer?new Uint8Array(e):e,i=n.subarray(t,t+r);try{if(i.byteLength){let e=lt(i,0,i.byteLength);-1!==e.offset&&e.offset===r&&(this.valueBlock.value=[e.result])}}catch(e){}}return super.fromBER(e,t,r)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?li.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${aU.ep.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof lh&&e.push(t.valueBlock.valueHexView);return aU.vJ
|
||
|
|
`),r),r.log.trace('handle: responded with "%s" for "%s"',po,e);continue}if(t.includes(e))return r.log.trace('handle: respond with "%s" for "%s"',e,e),await pl(n,(0,i2.m)(`${e}
|
||
|
|
`),r),r.log.trace('handle: responded with "%s" for "%s"',e,e),{stream:n.unwrap(),protocol:e};if("ls"===e){let i=new tC(...t.map(e=>tP.single((0,i2.m)(`${e}
|
||
|
|
`))),(0,i2.m)("\n"));r.log.trace('handle: respond with "%s" for %s',t,e),await pl(n,i,r),r.log.trace('handle: responded with "%s" for %s',t,e);continue}r.log('handle: respond with "na" for "%s"',e),await pl(n,(0,i2.m)("na\n"),r),r.log('handle: responded with "na" for "%s"',e)}}async function pp(e,t,r){if(1===(t=Array.isArray(t)?[...t]:[t]).length&&!1===r.negotiateFully)return function(e,t,r){let n=e.sink.bind(e),i=e.source,s=!1,o=!1,a=tx(),l=!1,c=!1,u=tx(),h=!1,d=!1,p=tx(),f=rF({sink:n,source:i},{...r,maxDataLength:1024});async function g(){if(o){r.log.trace("optimistic: already negotiating %s stream",t),await a.promise;return}o=!0;try{l||(r.log.trace("optimistic: doing send protocol for %s stream",t),await y()),h||(r.log.trace("optimistic: doing read protocol for %s stream",t),await m())}finally{o=!1,s=!0,a.resolve()}}async function y(){if(c){await u.promise;return}c=!0;try{r.log.trace('optimistic: write ["%s", "%s", data] in source',po,t),await f.writeV([(0,i2.m)(`${po}
|
||
|
|
`),(0,i2.m)(`${t}
|
||
|
|
`)]),r.log.trace('optimistic: wrote ["%s", "%s", data] in source',po,t)}finally{l=!0,c=!1,u.resolve()}}async function m(){if(d){await p.promise;return}d=!0;try{r.log.trace("optimistic: reading multistream select header");let e=await ph(f,r);if(r.log.trace('optimistic: read multistream select header "%s"',e),e===po&&(e=await ph(f,r)),r.log.trace('optimistic: read protocol "%s", expecting "%s"',e,t),e!==t)throw new iJ("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}finally{h=!0,d=!1,p.resolve()}}if(e.sink=async e=>{let{sink:n}=f.unwrap();await n(async function*(){let n=!1;for await(let i of e){if(c&&await u.promise,l)yield i;else{c=!0,r.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',po,t,i.byteLength);let e=`${t}
|
||
|
|
`;yield new tC(Uint8Array.from([19]),(0,i2.m)(`${po}
|
||
|
|
`),tE.cv(e.length),(0,i2.m)(e),i).subarray(),r.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',po,t,i.byteLength),l=!0,c=!1,u.resolve(),g().catch(e=>{r.log.error("could not finish optimistic protocol negotiation of %s",t,e)})}n=!0}n||await g()}())},e.source=async function*(){await g(),r.log.trace('optimistic: reading data from "%s" stream',t),yield*f.unwrap().source}(),null!=e.closeRead){let t=e.closeRead.bind(e);e.closeRead=async e=>{s||await g().catch(e=>{r.log.error("could not negotiate protocol before close read",e)}),await t(e)}}if(null!=e.closeWrite){let t=e.closeWrite.bind(e);e.closeWrite=async e=>{s||await g().catch(e=>{r.log.error("could not negotiate protocol before close write",e)}),await t(e)}}if(null!=e.close){let t=e.close.bind(e);e.close=async e=>{let r=[];c&&r.push(u.promise),d&&r.push(p.promise),r.length>0?await rL(Promise.all(r),e?.signal):(s=!0,o=!1,a.resolve()),await t(e)}}return{stream:e,protocol:t}}(e,t[0],r);let n=rF(e,{...r,maxDataLength:1024}),i=t.shift();if(null==i)throw Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',po,i);let s=(0,i2.m)(`${po}
|
||
|
|
`),o=(0,i2.m)(`${i}
|
||
|
|
`);await pc(n,[s,o],r),r.log.trace("select: reading multistream-select header");let a=await ph(n,r);if(r.log.trace('select: read "%s"',a),a===po&&(r.log.trace("select: reading protocol response"),a=await ph(n,r),r.log.trace('select: read "%s"',a)),a===i)return{stream:n.unwrap(),protocol:i};for(let e of t){r.log.trace('select: write "%s"',e),await pl(n,(0,i2.m)(`${e}
|
||
|
|
`),r),r.log.trace("select: reading protocol response");let t=await ph(n,r);if(r.log.trace('select: read "%s" for "%s"',t,e),t===e)return{stream:n.unwrap(),protocol:e}}throw new iJ("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}let pf=Symbol.for("@libp2p/connection");class pg{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:r,newStream:n,close:i,abort:s,getStreams:o}=e;this.id=`${parseInt(String(1e9*Math.random())).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=r,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),null==this.remoteAddr.getPeerId()&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=n,this._close=i,this._abort=s,this._getStreams=o,this.tags=[]}[Symbol.toStringTag]="Connection";[pf]=!0;get streams(){return this._getStreams()}async newStream(e,t){if("closing"===this.status)throw new iJ("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if("closed"===this.status)throw new iJ("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&t?.runOnTransientConnection!==!0)throw new iJ("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let r=await this._newStream(e,t);return r.direction="outbound",r}async close(e={}){if("closed"!==this.status&&"closing"!==this.status){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",null==e.signal){let t=AbortSignal.timeout(500);rA(1/0,t),e={...e,signal:t}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async t=>t.close(e))),this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(t=>{t.abort(e)}),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}}function py(e,t,r){let n=0;return r.streams.forEach(r=>{r.direction===t&&r.protocol===e&&n++}),n}class pm{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(e=>{this.connectionEncryption.set(e.protocol,e)}),this.muxers=new Map,t.muxers.forEach(e=>{this.muxers.set(e.protocol,e)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??2e3,this.events=e.events}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,t,r){let n=this.components.connectionGater[r];if(void 0!==n&&await n(e,t))throw new iJ(`The multiaddr connection is blocked by gater.${r}`,ts.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){let r,n,i,s,o;let a=await this.components.connectionManager.acceptIncomingConnection(e);if(!a)throw new iJ("connection denied",ts.ERR_CONNECTION_DENIED);let l=AbortSignal.timeout(this.inboundUpgradeTimeout),c=()=>{e.abort(new iJ("inbound upgrade timeout",i0))};l.addEventListener("abort",c,{once:!0}),rA(1/0,l);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new iJ("The multiaddr connection is blocked by gater.acceptConnection",ts.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let a=e;if(t?.skipProtection!==!0){let t=this.components.connectionProtector;null!=t&&(e.log("protecting the inbound connection"),a=await t.protect(e))}try{if(r=a,t?.skipEncryption!==!0){({conn:r,remotePeer:n,protocol:o}=await this._encryptInbound(a));let e={...a,...r};await this.shouldBlock
|