@libp2p/ping 2.0.36 → 2.0.37
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/index.min.js.map +3 -3
- package/dist/src/index.d.ts +1 -2
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js.map +1 -1
- package/dist/src/ping.d.ts +0 -1
- package/dist/src/ping.d.ts.map +1 -1
- package/dist/src/ping.js +8 -9
- package/dist/src/ping.js.map +1 -1
- package/package.json +6 -6
- package/src/index.ts +1 -2
- package/src/ping.ts +10 -11
package/dist/index.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PPing = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2PPing=(()=>{var S=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var W=(o,t)=>{for(var e in t)S(o,e,{get:t[e],enumerable:!0})},$=(o,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of q(t))!G.call(o,n)&&n!==e&&S(o,n,{get:()=>t[n],enumerable:!(r=X(t,n))||r.enumerable});return o};var K=o=>$(S({},"__esModule",{value:!0}),o);var Q={};W(Q,{PING_PROTOCOL:()=>k,ping:()=>Z});var y=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};var g=class extends Error{static name="ProtocolError";constructor(t="Protocol error"){super(t),this.name="ProtocolError"}},x=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}};var R=Symbol.for("@libp2p/service-capabilities"),rt=Symbol.for("@libp2p/service-dependencies");function E(o,t){if(o===t)return!0;if(o.byteLength!==t.byteLength)return!1;for(let e=0;e<o.byteLength;e++)if(o[e]!==t[e])return!1;return!0}function l(o=0){return new Uint8Array(o)}function b(o=0){return new Uint8Array(o)}function T(o,t){t==null&&(t=o.reduce((n,i)=>n+i.length,0));let e=b(t),r=0;for(let n of o)e.set(n,r),r+=n.length;return e}var M=Symbol.for("@achingbrain/uint8arraylist");function B(o,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let r of o){let n=e+r.byteLength;if(t<n)return{buf:r,index:t-e};e=n}throw new RangeError("index is out of bounds")}function L(o){return!!o?.[M]}var O=class o{bufs;length;[M]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let r of t)if(r instanceof Uint8Array)e+=r.byteLength,this.bufs.push(r);else if(L(r))e+=r.byteLength,this.bufs.push(...r.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let r of t.reverse())if(r instanceof Uint8Array)e+=r.byteLength,this.bufs.unshift(r);else if(L(r))e+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=B(this.bufs,t);return e.buf[e.index]}set(t,e){let r=B(this.bufs,t);r.buf[r.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let r=0;r<t.length;r++)this.set(e+r,t[r]);else if(L(t))for(let r=0;r<t.length;r++)this.set(e+r,t.get(r));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:r,length:n}=this._subList(t,e);return T(r,n)}subarray(t,e){let{bufs:r,length:n}=this._subList(t,e);return r.length===1?r[0]:T(r,n)}sublist(t,e){let{bufs:r,length:n}=this._subList(t,e),i=new o;return i.length=n,i.bufs=[...r],i}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let r=[],n=0;for(let i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=n,u=a+s.byteLength;if(n=u,t>=u)continue;let f=t>=a&&t<u,h=e>a&&e<=u;if(f&&h){if(t===a&&e===u){r.push(s);break}let c=t-a;r.push(s.subarray(c,c+(e-t)));break}if(f){if(t===0){r.push(s);continue}r.push(s.subarray(t-a));continue}if(h){if(e===u){r.push(s);break}r.push(s.subarray(0,e-a));break}r.push(s)}return{bufs:r,length:e-t}}indexOf(t,e=0){if(!L(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let r=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let n=r.byteLength;if(n===0)throw new TypeError("search must be at least 1 byte long");let i=256,s=new Int32Array(i);for(let c=0;c<i;c++)s[c]=-1;for(let c=0;c<n;c++)s[r[c]]=c;let a=s,u=this.byteLength-r.byteLength,f=r.byteLength-1,h;for(let c=e;c<=u;c+=h){h=0;for(let d=f;d>=0;d--){let D=this.get(c+d);if(r[d]!==D){h=Math.max(1,d-a[D]);break}}if(h===0)return c}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let r=b(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,e),this.write(r,t)}getInt16(t,e){let r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,e)}setInt16(t,e,r){let n=l(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,e,r),this.write(n,t)}getInt32(t,e){let r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,e)}setInt32(t,e,r){let n=l(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,e,r),this.write(n,t)}getBigInt64(t,e){let r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,e)}setBigInt64(t,e,r){let n=l(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,e,r),this.write(n,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let r=b(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,e),this.write(r,t)}getUint16(t,e){let r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,e)}setUint16(t,e,r){let n=l(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,e,r),this.write(n,t)}getUint32(t,e){let r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,e)}setUint32(t,e,r){let n=l(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,e,r),this.write(n,t)}getBigUint64(t,e){let r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,e)}setBigUint64(t,e,r){let n=l(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,e,r),this.write(n,t)}getFloat32(t,e){let r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,e)}setFloat32(t,e,r){let n=l(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,e,r),this.write(n,t)}getFloat64(t,e){let r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,e)}setFloat64(t,e,r){let n=l(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,e,r),this.write(n,t)}equals(t){if(t==null||!(t instanceof o)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!E(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let r=new o;return r.bufs=t,e==null&&(e=t.reduce((n,i)=>n+i.byteLength,0)),r.length=e,r}};var p=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function _(o=32){if(p&&typeof p.getRandomValues=="function")return p.getRandomValues(new Uint8Array(o));if(p&&typeof p.randomBytes=="function")return Uint8Array.from(p.randomBytes(o));throw new Error("crypto.getRandomValues must be defined")}function U(o){if(isNaN(o)||o<=0)throw new y("random bytes length must be a Number bigger than 0");return _(o)}function m(){let o={};return o.promise=new Promise((t,e)=>{o.resolve=t,o.reject=e}),o}var A=class extends Error{type;code;constructor(t,e,r){super(t??"The operation was aborted"),this.type="aborted",this.name=r??"AbortError",this.code=e??"ABORT_ERR"}};async function w(o,t,e){if(t==null)return o;if(t.aborted)return o.catch(()=>{}),Promise.reject(new A(e?.errorMessage,e?.errorCode,e?.errorName));let r,n=new A(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([o,new Promise((i,s)=>{r=()=>{s(n)},t.addEventListener("abort",r)})])}finally{r!=null&&t.removeEventListener("abort",r)}}var N=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=m(),this.haveNext=m()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=m(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=m(),await w(this.readNext.promise,e?.signal,e)}};function V(){return new N}var v=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function P(o,t){let e=V();o.sink(e).catch(async s=>{await e.end(s)}),o.sink=async s=>{for await(let a of s)await e.push(a);await e.end()};let r=o.source;o.source[Symbol.iterator]!=null?r=o.source[Symbol.iterator]():o.source[Symbol.asyncIterator]!=null&&(r=o.source[Symbol.asyncIterator]());let n=new O;return{read:async s=>{if(s?.signal?.throwIfAborted(),s?.bytes==null){let{done:u,value:f}=await w(r.next(),s?.signal);return u===!0?null:f}for(;n.byteLength<s.bytes;){let{value:u,done:f}=await w(r.next(),s?.signal);if(f===!0)throw new v("unexpected end of input");n.append(u)}let a=n.sublist(0,s.bytes);return n.consume(s.bytes),a},write:async(s,a)=>{a?.signal?.throwIfAborted(),s instanceof Uint8Array?await e.push(s,a):await e.push(s.subarray(),a)},unwrap:()=>{if(n.byteLength>0){let s=o.source;o.source=async function*(){t?.yieldBytes===!1?yield n:yield*n,yield*s}()}return o}}}var k="/ipfs/ping/1.0.0";var F="1.0.0",H="ping",j="ipfs";var I=class{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;log;constructor(t,e={}){this.components=t,this.log=t.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol=`/${e.protocolPrefix??j}/${H}/${F}`,this.timeout=e.timeout??1e4,this.maxInboundStreams=e.maxInboundStreams??2,this.maxOutboundStreams=e.maxOutboundStreams??1,this.runOnLimitedConnection=e.runOnLimitedConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[R]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(t){this.log("incoming ping from %p",t.connection.remotePeer);let{stream:e}=t,r=Date.now(),n=P(e),i=!1;Promise.resolve().then(async()=>{for(;;){let s=AbortSignal.timeout(this.timeout);s.addEventListener("abort",()=>{e?.abort(new x("ping timeout"))});let a=await n.read({bytes:32,signal:s});await n.write(a,{signal:s}),i=!0}}).catch(s=>{i&&s.name==="UnexpectedEOFError"&&e.readStatus!=="ready"||(this.log.error("incoming ping from %p failed with error - %e",t.connection.remotePeer,s),e?.abort(s))}).finally(()=>{let s=Date.now()-r;this.log("incoming ping from %p complete in %dms",t.connection.remotePeer,s);let a=AbortSignal.timeout(this.timeout);e.close({signal:a}).catch(u=>{this.log.error("error closing ping stream from %p - %e",t.connection.remotePeer,u),e?.abort(u)})})}async ping(t,e={}){this.log("pinging %p",t);let r=Date.now(),n=U(32),i=await this.components.connectionManager.openConnection(t,e),s;if(e.signal==null){let a=AbortSignal.timeout(this.timeout);e={...e,signal:a}}try{s=await i.newStream(this.protocol,{...e,runOnLimitedConnection:this.runOnLimitedConnection});let a=P(s),[,u]=await Promise.all([a.write(n,e),a.read({...e,bytes:32})]),f=Date.now()-r;if(!E(n,u.subarray()))throw new g(`Received wrong ping ack after ${f}ms`);return this.log("ping %p complete in %dms",i.remotePeer,f),f}catch(a){throw this.log.error("error while pinging %p",i.remotePeer,a),s?.abort(a),a}finally{s!=null&&await s.close(e)}}};function Z(o={}){return t=>new I(t,o)}return K(Q);})();
|
|
2
|
+
"use strict";var Libp2PPing=(()=>{var I=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var W=(o,t)=>{for(var e in t)I(o,e,{get:t[e],enumerable:!0})},$=(o,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of q(t))!G.call(o,n)&&n!==e&&I(o,n,{get:()=>t[n],enumerable:!(r=X(t,n))||r.enumerable});return o};var K=o=>$(I({},"__esModule",{value:!0}),o);var Q={};W(Q,{PING_PROTOCOL:()=>k,ping:()=>Z});var y=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};var x=class extends Error{static name="ProtocolError";constructor(t="Protocol error"){super(t),this.name="ProtocolError"}},g=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}};var B=Symbol.for("@libp2p/service-capabilities"),rt=Symbol.for("@libp2p/service-dependencies");function E(o,t){if(o===t)return!0;if(o.byteLength!==t.byteLength)return!1;for(let e=0;e<o.byteLength;e++)if(o[e]!==t[e])return!1;return!0}function h(o=0){return new Uint8Array(o)}function b(o=0){return new Uint8Array(o)}function T(o,t){t==null&&(t=o.reduce((n,a)=>n+a.length,0));let e=b(t),r=0;for(let n of o)e.set(n,r),r+=n.length;return e}var M=Symbol.for("@achingbrain/uint8arraylist");function C(o,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let r of o){let n=e+r.byteLength;if(t<n)return{buf:r,index:t-e};e=n}throw new RangeError("index is out of bounds")}function L(o){return!!o?.[M]}var O=class o{bufs;length;[M]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let r of t)if(r instanceof Uint8Array)e+=r.byteLength,this.bufs.push(r);else if(L(r))e+=r.byteLength,this.bufs.push(...r.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let r of t.reverse())if(r instanceof Uint8Array)e+=r.byteLength,this.bufs.unshift(r);else if(L(r))e+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=C(this.bufs,t);return e.buf[e.index]}set(t,e){let r=C(this.bufs,t);r.buf[r.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let r=0;r<t.length;r++)this.set(e+r,t[r]);else if(L(t))for(let r=0;r<t.length;r++)this.set(e+r,t.get(r));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:r,length:n}=this._subList(t,e);return T(r,n)}subarray(t,e){let{bufs:r,length:n}=this._subList(t,e);return r.length===1?r[0]:T(r,n)}sublist(t,e){let{bufs:r,length:n}=this._subList(t,e),a=new o;return a.length=n,a.bufs=[...r],a}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let r=[],n=0;for(let a=0;a<this.bufs.length;a++){let s=this.bufs[a],i=n,u=i+s.byteLength;if(n=u,t>=u)continue;let f=t>=i&&t<u,l=e>i&&e<=u;if(f&&l){if(t===i&&e===u){r.push(s);break}let c=t-i;r.push(s.subarray(c,c+(e-t)));break}if(f){if(t===0){r.push(s);continue}r.push(s.subarray(t-i));continue}if(l){if(e===u){r.push(s);break}r.push(s.subarray(0,e-i));break}r.push(s)}return{bufs:r,length:e-t}}indexOf(t,e=0){if(!L(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let r=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let n=r.byteLength;if(n===0)throw new TypeError("search must be at least 1 byte long");let a=256,s=new Int32Array(a);for(let c=0;c<a;c++)s[c]=-1;for(let c=0;c<n;c++)s[r[c]]=c;let i=s,u=this.byteLength-r.byteLength,f=r.byteLength-1,l;for(let c=e;c<=u;c+=l){l=0;for(let d=f;d>=0;d--){let R=this.get(c+d);if(r[d]!==R){l=Math.max(1,d-i[R]);break}}if(l===0)return c}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let r=b(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,e),this.write(r,t)}getInt16(t,e){let r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,e)}setInt16(t,e,r){let n=h(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,e,r),this.write(n,t)}getInt32(t,e){let r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,e)}setInt32(t,e,r){let n=h(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,e,r),this.write(n,t)}getBigInt64(t,e){let r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,e)}setBigInt64(t,e,r){let n=h(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,e,r),this.write(n,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let r=b(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,e),this.write(r,t)}getUint16(t,e){let r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,e)}setUint16(t,e,r){let n=h(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,e,r),this.write(n,t)}getUint32(t,e){let r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,e)}setUint32(t,e,r){let n=h(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,e,r),this.write(n,t)}getBigUint64(t,e){let r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,e)}setBigUint64(t,e,r){let n=h(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,e,r),this.write(n,t)}getFloat32(t,e){let r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,e)}setFloat32(t,e,r){let n=h(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,e,r),this.write(n,t)}getFloat64(t,e){let r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,e)}setFloat64(t,e,r){let n=h(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,e,r),this.write(n,t)}equals(t){if(t==null||!(t instanceof o)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!E(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let r=new o;return r.bufs=t,e==null&&(e=t.reduce((n,a)=>n+a.byteLength,0)),r.length=e,r}};var p=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function _(o=32){if(p&&typeof p.getRandomValues=="function")return p.getRandomValues(new Uint8Array(o));if(p&&typeof p.randomBytes=="function")return Uint8Array.from(p.randomBytes(o));throw new Error("crypto.getRandomValues must be defined")}function U(o){if(isNaN(o)||o<=0)throw new y("random bytes length must be a Number bigger than 0");return _(o)}function m(){let o={};return o.promise=new Promise((t,e)=>{o.resolve=t,o.reject=e}),o}var A=class extends Error{type;code;constructor(t,e,r){super(t??"The operation was aborted"),this.type="aborted",this.name=r??"AbortError",this.code=e??"ABORT_ERR"}};async function w(o,t,e){if(t==null)return o;if(t.aborted)return o.catch(()=>{}),Promise.reject(new A(e?.errorMessage,e?.errorCode,e?.errorName));let r,n=new A(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([o,new Promise((a,s)=>{r=()=>{s(n)},t.addEventListener("abort",r)})])}finally{r!=null&&t.removeEventListener("abort",r)}}var N=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=m(),this.haveNext=m()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=m(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=m(),await w(this.readNext.promise,e?.signal,e)}};function V(){return new N}var v=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function P(o,t){let e=V();o.sink(e).catch(async s=>{await e.end(s)}),o.sink=async s=>{for await(let i of s)await e.push(i);await e.end()};let r=o.source;o.source[Symbol.iterator]!=null?r=o.source[Symbol.iterator]():o.source[Symbol.asyncIterator]!=null&&(r=o.source[Symbol.asyncIterator]());let n=new O;return{read:async s=>{if(s?.signal?.throwIfAborted(),s?.bytes==null){let{done:u,value:f}=await w(r.next(),s?.signal);return u===!0?null:f}for(;n.byteLength<s.bytes;){let{value:u,done:f}=await w(r.next(),s?.signal);if(f===!0)throw new v("unexpected end of input");n.append(u)}let i=n.sublist(0,s.bytes);return n.consume(s.bytes),i},write:async(s,i)=>{i?.signal?.throwIfAborted(),s instanceof Uint8Array?await e.push(s,i):await e.push(s.subarray(),i)},unwrap:()=>{if(n.byteLength>0){let s=o.source;o.source=(async function*(){t?.yieldBytes===!1?yield n:yield*n,yield*s})()}return o}}}var k="/ipfs/ping/1.0.0";var F="1.0.0",H="ping",j="ipfs";var S=class{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;constructor(t,e={}){this.components=t,this.started=!1,this.protocol=`/${e.protocolPrefix??j}/${H}/${F}`,this.timeout=e.timeout??1e4,this.maxInboundStreams=e.maxInboundStreams??2,this.maxOutboundStreams=e.maxOutboundStreams??1,this.runOnLimitedConnection=e.runOnLimitedConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[B]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(t){let e=t.connection.log.newScope("ping");e.trace("ping from %p",t.connection.remotePeer);let{stream:r}=t,n=Date.now(),a=P(r),s=!1;Promise.resolve().then(async()=>{for(;;){let i=AbortSignal.timeout(this.timeout);i.addEventListener("abort",()=>{r?.abort(new g("ping timeout"))});let u=await a.read({bytes:32,signal:i});await a.write(u,{signal:i}),s=!0}}).catch(i=>{s&&i.name==="UnexpectedEOFError"&&r.readStatus!=="ready"||(e.error("ping from %p failed with error - %e",t.connection.remotePeer,i),r?.abort(i))}).finally(()=>{let i=Date.now()-n;e("ping from %p complete in %dms",t.connection.remotePeer,i);let u=AbortSignal.timeout(this.timeout);r.close({signal:u}).catch(f=>{e.error("error closing ping stream from %p - %e",t.connection.remotePeer,f),r?.abort(f)})})}async ping(t,e={}){let r=Date.now(),n=U(32),a=await this.components.connectionManager.openConnection(t,e),s=a.log.newScope("ping"),i;if(e.signal==null){let u=AbortSignal.timeout(this.timeout);e={...e,signal:u}}try{i=await a.newStream(this.protocol,{...e,runOnLimitedConnection:this.runOnLimitedConnection});let u=P(i),[,f]=await Promise.all([u.write(n,e),u.read({...e,bytes:32})]),l=Date.now()-r;if(!E(n,f.subarray()))throw new x(`Received wrong ping ack after ${l}ms`);return s("ping %p complete in %dms",a.remotePeer,l),l}catch(u){throw s.error("error while pinging %p",a.remotePeer,u),i?.abort(u),u}finally{i!=null&&await i.close(e)}}};function Z(o={}){return t=>new S(t,o)}return K(Q);})();
|
|
3
3
|
/*! Bundled license information:
|
|
4
4
|
|
|
5
5
|
@noble/hashes/esm/utils.js:
|
package/dist/index.min.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/index.ts", "../../interface/src/errors.ts", "../../interface/src/index.ts", "../../../node_modules/uint8arrays/src/equals.ts", "../../../node_modules/uint8arrays/src/alloc.ts", "../../../node_modules/uint8arrays/src/concat.ts", "../../../node_modules/uint8arraylist/src/index.ts", "../../../node_modules/@noble/hashes/src/crypto.ts", "../../../node_modules/@noble/hashes/src/utils.ts", "../../crypto/src/random-bytes.ts", "../../../node_modules/p-defer/index.js", "../../../node_modules/race-signal/src/index.ts", "../../../node_modules/it-queueless-pushable/src/index.ts", "../../../node_modules/it-byte-stream/src/errors.ts", "../../../node_modules/it-byte-stream/src/index.ts", "../src/constants.ts", "../src/ping.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @packageDocumentation\n *\n * The ping service implements the [libp2p ping spec](https://github.com/libp2p/specs/blob/master/ping/ping.md) allowing you to make a latency measurement to a remote peer.\n *\n * @example\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n * import { ping } from '@libp2p/ping'\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const node = await createLibp2p({\n * services: {\n * ping: ping()\n * }\n * })\n *\n * const rtt = await node.services.ping.ping(multiaddr('/ip4/...'))\n *\n * console.info(rtt)\n * ```\n */\n\nimport { Ping as PingClass } from './ping.js'\nimport type { AbortOptions, ComponentLogger, PeerId } from '@libp2p/interface'\nimport type { ConnectionManager, Registrar } from '@libp2p/interface-internal'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface Ping {\n ping(peer: PeerId | Multiaddr | Multiaddr[], options?: AbortOptions): Promise<number>\n}\n\n/**\n * @deprecated Use the `Ping` export instead\n */\nexport type PingService = Ping\n\nexport interface PingInit {\n protocolPrefix?: string\n maxInboundStreams?: number\n maxOutboundStreams?: number\n runOnLimitedConnection?: boolean\n\n /**\n * How long we should wait for a ping response\n */\n timeout?: number\n}\n\n/**\n * @deprecated Use the `PingInit` export instead\n */\nexport type PingServiceInit = PingInit\n\nexport interface PingComponents {\n registrar: Registrar\n connectionManager: ConnectionManager\n logger: ComponentLogger\n}\n\nexport function ping (init: PingInit = {}): (components: PingComponents) => Ping {\n return (components) => new PingClass(components, init)\n}\n\nexport { PING_PROTOCOL } from './constants.js'\n", "/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nexport class AbortError extends Error {\n static name = 'AbortError'\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.name = 'AbortError'\n }\n}\n\n/**\n * Thrown when a remote Peer ID does not match the expected one\n */\nexport class UnexpectedPeerError extends Error {\n static name = 'UnexpectedPeerError'\n\n constructor (message = 'Unexpected Peer') {\n super(message)\n this.name = 'UnexpectedPeerError'\n }\n}\n\n/**\n * Thrown when a crypto exchange fails\n */\nexport class InvalidCryptoExchangeError extends Error {\n static name = 'InvalidCryptoExchangeError'\n\n constructor (message = 'Invalid crypto exchange') {\n super(message)\n this.name = 'InvalidCryptoExchangeError'\n }\n}\n\n/**\n * Thrown when invalid parameters are passed to a function or method call\n */\nexport class InvalidParametersError extends Error {\n static name = 'InvalidParametersError'\n\n constructor (message = 'Invalid parameters') {\n super(message)\n this.name = 'InvalidParametersError'\n }\n}\n\n/**\n * Thrown when a public key is invalid\n */\nexport class InvalidPublicKeyError extends Error {\n static name = 'InvalidPublicKeyError'\n\n constructor (message = 'Invalid public key') {\n super(message)\n this.name = 'InvalidPublicKeyError'\n }\n}\n\n/**\n * Thrown when a private key is invalid\n */\nexport class InvalidPrivateKeyError extends Error {\n static name = 'InvalidPrivateKeyError'\n\n constructor (message = 'Invalid private key') {\n super(message)\n this.name = 'InvalidPrivateKeyError'\n }\n}\n\n/**\n * Thrown when a operation is unsupported\n */\nexport class UnsupportedOperationError extends Error {\n static name = 'UnsupportedOperationError'\n\n constructor (message = 'Unsupported operation') {\n super(message)\n this.name = 'UnsupportedOperationError'\n }\n}\n\n/**\n * Thrown when a connection is closing\n */\nexport class ConnectionClosingError extends Error {\n static name = 'ConnectionClosingError'\n\n constructor (message = 'The connection is closing') {\n super(message)\n this.name = 'ConnectionClosingError'\n }\n}\n\n/**\n * Thrown when a connection is closed\n */\nexport class ConnectionClosedError extends Error {\n static name = 'ConnectionClosedError'\n\n constructor (message = 'The connection is closed') {\n super(message)\n this.name = 'ConnectionClosedError'\n }\n}\n\n/**\n * Thrown when a connection fails\n */\nexport class ConnectionFailedError extends Error {\n static name = 'ConnectionFailedError'\n\n constructor (message = 'Connection failed') {\n super(message)\n this.name = 'ConnectionFailedError'\n }\n}\n\n/**\n * Thrown when the muxer is closed and an attempt to open a stream occurs\n */\nexport class MuxerClosedError extends Error {\n static name = 'MuxerClosedError'\n\n constructor (message = 'The muxer is closed') {\n super(message)\n this.name = 'MuxerClosedError'\n }\n}\n\n/**\n * Thrown when a protocol stream is reset by the remote muxer\n */\nexport class StreamResetError extends Error {\n static name = 'StreamResetError'\n\n constructor (message = 'The stream has been reset') {\n super(message)\n this.name = 'StreamResetError'\n }\n}\n\n/**\n * Thrown when a stream is in an invalid state\n */\nexport class StreamStateError extends Error {\n static name = 'StreamStateError'\n\n constructor (message = 'The stream is in an invalid state') {\n super(message)\n this.name = 'StreamStateError'\n }\n}\n\n/**\n * Thrown when a value could not be found\n */\nexport class NotFoundError extends Error {\n static name = 'NotFoundError'\n\n constructor (message = 'Not found') {\n super(message)\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Thrown when an invalid peer ID is encountered\n */\nexport class InvalidPeerIdError extends Error {\n static name = 'InvalidPeerIdError'\n\n constructor (message = 'Invalid PeerID') {\n super(message)\n this.name = 'InvalidPeerIdError'\n }\n}\n\n/**\n * Thrown when an invalid multiaddr is encountered\n */\nexport class InvalidMultiaddrError extends Error {\n static name = 'InvalidMultiaddrError'\n\n constructor (message = 'Invalid multiaddr') {\n super(message)\n this.name = 'InvalidMultiaddrError'\n }\n}\n\n/**\n * Thrown when an invalid CID is encountered\n */\nexport class InvalidCIDError extends Error {\n static name = 'InvalidCIDError'\n\n constructor (message = 'Invalid CID') {\n super(message)\n this.name = 'InvalidCIDError'\n }\n}\n\n/**\n * Thrown when an invalid multihash is encountered\n */\nexport class InvalidMultihashError extends Error {\n static name = 'InvalidMultihashError'\n\n constructor (message = 'Invalid Multihash') {\n super(message)\n this.name = 'InvalidMultihashError'\n }\n}\n\n/**\n * Thrown when a protocol is not supported\n */\nexport class UnsupportedProtocolError extends Error {\n static name = 'UnsupportedProtocolError'\n\n constructor (message = 'Unsupported protocol error') {\n super(message)\n this.name = 'UnsupportedProtocolError'\n }\n}\n\n/**\n * An invalid or malformed message was encountered during a protocol exchange\n */\nexport class InvalidMessageError extends Error {\n static name = 'InvalidMessageError'\n\n constructor (message = 'Invalid message') {\n super(message)\n this.name = 'InvalidMessageError'\n }\n}\n\n/**\n * Thrown when a remote peer sends a structurally valid message that does not\n * comply with the protocol\n */\nexport class ProtocolError extends Error {\n static name = 'ProtocolError'\n\n constructor (message = 'Protocol error') {\n super(message)\n this.name = 'ProtocolError'\n }\n}\n\n/**\n * Throw when an operation times out\n */\nexport class TimeoutError extends Error {\n static name = 'TimeoutError'\n\n constructor (message = 'Timed out') {\n super(message)\n this.name = 'TimeoutError'\n }\n}\n\n/**\n * Thrown when a startable component is interacted with but it has not been\n * started yet\n */\nexport class NotStartedError extends Error {\n static name = 'NotStartedError'\n\n constructor (message = 'Not started') {\n super(message)\n this.name = 'NotStartedError'\n }\n}\n\n/**\n * Thrown when a component is started that has already been started\n */\nexport class AlreadyStartedError extends Error {\n static name = 'AlreadyStartedError'\n\n constructor (message = 'Already started') {\n super(message)\n this.name = 'AlreadyStartedError'\n }\n}\n\n/**\n * Thrown when dialing an address failed\n */\nexport class DialError extends Error {\n static name = 'DialError'\n\n constructor (message = 'Dial error') {\n super(message)\n this.name = 'DialError'\n }\n}\n\n/**\n * Thrown when listening on an address failed\n */\nexport class ListenError extends Error {\n static name = 'ListenError'\n\n constructor (message = 'Listen error') {\n super(message)\n this.name = 'ListenError'\n }\n}\n\n/**\n * This error is thrown when a limited connection is encountered, i.e. if the\n * user tried to open a stream on a connection for a protocol that is not\n * configured to run over limited connections.\n */\nexport class LimitedConnectionError extends Error {\n static name = 'LimitedConnectionError'\n\n constructor (message = 'Limited connection') {\n super(message)\n this.name = 'LimitedConnectionError'\n }\n}\n\n/**\n * This error is thrown where there are too many inbound protocols streams open\n */\nexport class TooManyInboundProtocolStreamsError extends Error {\n static name = 'TooManyInboundProtocolStreamsError'\n\n constructor (message = 'Too many inbound protocol streams') {\n super(message)\n this.name = 'TooManyInboundProtocolStreamsError'\n }\n}\n\n/**\n * This error is thrown where there are too many outbound protocols streams open\n */\nexport class TooManyOutboundProtocolStreamsError extends Error {\n static name = 'TooManyOutboundProtocolStreamsError'\n\n constructor (message = 'Too many outbound protocol streams') {\n super(message)\n this.name = 'TooManyOutboundProtocolStreamsError'\n }\n}\n\n/**\n * Thrown when an attempt to operate on an unsupported key was made\n */\nexport class UnsupportedKeyTypeError extends Error {\n static name = 'UnsupportedKeyTypeError'\n\n constructor (message = 'Unsupported key type') {\n super(message)\n this.name = 'UnsupportedKeyTypeError'\n }\n}\n\n/**\n * Thrown when an operation has not been implemented\n */\nexport class NotImplementedError extends Error {\n static name = 'NotImplementedError'\n\n constructor (message = 'Not implemented') {\n super(message)\n this.name = 'NotImplementedError'\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Exports a `Libp2p` type for modules to use as a type argument.\n *\n * @example\n *\n * ```typescript\n * import type { Libp2p } from '@libp2p/interface'\n *\n * function doSomethingWithLibp2p (node: Libp2p) {\n * // ...\n * }\n * ```\n */\n\nimport type { Connection, NewStreamOptions, Stream } from './connection.js'\nimport type { ContentRouting } from './content-routing.js'\nimport type { Ed25519PublicKey, PublicKey, RSAPublicKey, Secp256k1PublicKey } from './keys.js'\nimport type { Metrics } from './metrics.js'\nimport type { Ed25519PeerId, PeerId, RSAPeerId, Secp256k1PeerId, URLPeerId } from './peer-id.js'\nimport type { PeerInfo } from './peer-info.js'\nimport type { PeerRouting } from './peer-routing.js'\nimport type { Address, Peer, PeerStore } from './peer-store.js'\nimport type { Startable } from './startable.js'\nimport type { StreamHandler, StreamHandlerOptions } from './stream-handler.js'\nimport type { Topology } from './topology.js'\nimport type { Listener, OutboundConnectionUpgradeEvents } from './transport.js'\nimport type { DNS } from '@multiformats/dns'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { TypedEventTarget } from 'main-event'\nimport type { ProgressOptions, ProgressEvent } from 'progress-events'\n\n/**\n * Used by the connection manager to sort addresses into order before dialling\n */\nexport interface AddressSorter {\n (a: Address, b: Address): -1 | 0 | 1\n}\n\n/**\n * Event detail emitted when peer data changes\n */\nexport interface PeerUpdate {\n peer: Peer\n previous?: Peer\n}\n\n/**\n * Peer data signed by the remote Peer's public key\n */\nexport interface SignedPeerRecord {\n addresses: Multiaddr[]\n seq: bigint\n}\n\n/**\n * A certificate that can be used to secure connections\n */\nexport interface TLSCertificate {\n /**\n * The private key that corresponds to the certificate in PEM format\n */\n key: string\n\n /**\n * The certificate chain in PEM format\n */\n cert: string\n}\n\n/**\n * Data returned from a successful identify response\n */\nexport interface IdentifyResult {\n /**\n * The remote Peer's PeerId\n */\n peerId: PeerId\n\n /**\n * The unsigned addresses they are listening on. Note - any multiaddrs present\n * in the signed peer record should be preferred to the value here.\n */\n listenAddrs: Multiaddr[]\n\n /**\n * The protocols the remote peer supports\n */\n protocols: string[]\n\n /**\n * The remote protocol version\n */\n protocolVersion?: string\n\n /**\n * The remote agent version\n */\n agentVersion?: string\n\n /**\n * The public key part of the remote PeerId - this is only useful for older\n * RSA-based PeerIds, the more modern Ed25519 and secp256k1 types have the\n * public key embedded in them\n */\n publicKey?: Uint8Array\n\n /**\n * If set this is the address that the remote peer saw the identify request\n * originate from\n */\n observedAddr?: Multiaddr\n\n /**\n * If sent by the remote peer this is the deserialized signed peer record\n */\n signedPeerRecord?: SignedPeerRecord\n\n /**\n * The connection that the identify protocol ran over\n */\n connection: Connection\n}\n\n/**\n * Logger component for libp2p\n */\nexport interface Logger {\n (formatter: any, ...args: any[]): void\n error(formatter: any, ...args: any[]): void\n trace(formatter: any, ...args: any[]): void\n enabled: boolean\n}\n\n/**\n * Peer logger component for libp2p. This can be used to create loggers that are\n * scoped to individual system components or services.\n *\n * To see logs, run your app with `DEBUG` set as an env var or for browsers, in\n * `localStorage`:\n *\n * ```console\n * $ DEBUG=libp2p* node index.js\n * libp2p:my-service hello +0ms\n * ```\n */\nexport interface ComponentLogger {\n /**\n * Returns a logger for the specified component.\n *\n * @example\n *\n * ```TypeScript\n * import { ComponentLogger, Logger } from '@libp2p/interface'\n *\n * interface MyServiceComponents {\n * logger: ComponentLogger\n * }\n *\n * class MyService {\n * private readonly log: Logger\n *\n * constructor (components) {\n * this.log = components.logger.forComponent('libp2p:my-service')\n *\n * this.log('hello')\n * // logs:\n * // libp2p:my-service hello +0ms\n * }\n * }\n * ```\n */\n forComponent(name: string): Logger\n}\n\nexport interface MultiaddrResolveOptions extends AbortOptions, LoggerOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n}\n\n/**\n * `MultiaddrResolver`s perform resolution of multiaddr components that require\n * translation by external systems (for example DNSADDR to TXT records).\n */\nexport interface MultiaddrResolver {\n /**\n * Returns true if this resolver can resolve components of this multiaddr\n */\n canResolve (address: Multiaddr): boolean\n\n /**\n * Returns one or more multiaddrs with components resolved to other values\n */\n resolve (address: Multiaddr, options: MultiaddrResolveOptions): Promise<Multiaddr[]>\n}\n\n/**\n * Once you have a libp2p instance, you can listen to several events it emits,\n * so that you can be notified of relevant network events.\n *\n * Event names are `noun:verb` so the first part is the name of the object\n * being acted on and the second is the action.\n */\nexport interface Libp2pEvents<T extends ServiceMap = ServiceMap> {\n /**\n * This event is dispatched when a new network peer is discovered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:discovery', (event) => {\n * const peerInfo = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:discovery': CustomEvent<PeerInfo>\n\n /**\n * This event will be triggered any time a new peer connects.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:connect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:connect': CustomEvent<PeerId>\n\n /**\n * This event will be triggered any time we are disconnected from another\n * peer, regardless of the circumstances of that disconnection. If we happen\n * to have multiple connections to a peer, this event will **only** be\n * triggered when the last connection is closed.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:disconnect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:disconnect': CustomEvent<PeerId>\n\n /**\n * When a peer tagged with `keep-alive` disconnects, we will make multiple\n * attempts to reconnect to it with a backoff factor (see the connection\n * manager settings for details). If these all fail, the `keep-alive` tag will\n * be removed and this event will be emitted.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:reconnect-failure', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:reconnect-failure': CustomEvent<PeerId>\n\n /**\n * This event is dispatched after a remote peer has successfully responded to\n * the identify protocol. Note that for this to be emitted, both peers must\n * have an identify service configured.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:identify', (event) => {\n * const identifyResult = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:identify': CustomEvent<IdentifyResult>\n\n /**\n * This event is dispatched when the peer store data for a peer has been\n * updated - e.g. their multiaddrs, protocols etc have changed.\n *\n * If they were previously known to this node, the old peer data will be\n * set in the `previous` field.\n *\n * This may be in response to the identify protocol running, a manual\n * update or some other event.\n */\n 'peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when the current node's peer record changes -\n * for example a transport started listening on a new address or a new\n * protocol handler was registered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('self:peer:update', (event) => {\n * const { peer } = event.detail\n * // ...\n * })\n * ```\n */\n 'self:peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when a transport begins listening on a new address\n */\n 'transport:listening': CustomEvent<Listener>\n\n /**\n * This event is dispatched when a transport stops listening on an address\n */\n 'transport:close': CustomEvent<Listener>\n\n /**\n * This event is dispatched when the connection manager has more than the\n * configured allowable max connections and has closed some connections to\n * bring the node back under the limit.\n */\n 'connection:prune': CustomEvent<Connection[]>\n\n /**\n * This event notifies listeners when new incoming or outgoing connections\n * are opened.\n */\n 'connection:open': CustomEvent<Connection>\n\n /**\n * This event notifies listeners when incoming or outgoing connections are\n * closed.\n */\n 'connection:close': CustomEvent<Connection>\n\n /**\n * This event notifies listeners that a TLS certificate is available for use\n */\n 'certificate:provision': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that a new TLS certificate is available for\n * use. Any previous certificate may no longer be valid.\n */\n 'certificate:renew': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that the node has started\n *\n * ```TypeScript\n * libp2p.addEventListener('start', (event) => {\n * console.info(libp2p.isStarted()) // true\n * })\n * ```\n */\n start: CustomEvent<Libp2p<T>>\n\n /**\n * This event notifies listeners that the node has stopped\n *\n * ```TypeScript\n * libp2p.addEventListener('stop', (event) => {\n * console.info(libp2p.isStarted()) // false\n * })\n * ```\n */\n stop: CustomEvent<Libp2p<T>>\n}\n\n/**\n * A map of user defined services available on the libp2p node via the\n * `services` key\n *\n * @example\n *\n * ```TypeScript\n * const node = await createLibp2p({\n * // ...other options\n * services: {\n * myService: myService({\n * // ...service options\n * })\n * }\n * })\n *\n * // invoke methods on the service\n * node.services.myService.anOperation()\n * ```\n */\nexport type ServiceMap = Record<string, unknown>\n\nexport type PendingDialStatus = 'queued' | 'active' | 'error' | 'success'\n\n/**\n * An item in the dial queue\n */\nexport interface PendingDial {\n /**\n * A unique identifier for this dial\n */\n id: string\n\n /**\n * The current status of the dial\n */\n status: PendingDialStatus\n\n /**\n * If known, this is the peer id that libp2p expects to be dialling\n */\n peerId?: PeerId\n\n /**\n * The list of multiaddrs that will be dialled. The returned connection will\n * use the first address that succeeds, all other dials part of this pending\n * dial will be cancelled.\n */\n multiaddrs: Multiaddr[]\n}\n\nexport type Libp2pStatus = 'starting' | 'started' | 'stopping' | 'stopped'\n\nexport interface IsDialableOptions extends AbortOptions {\n /**\n * If the dial attempt would open a protocol, and the multiaddr being dialed\n * is a circuit relay address, passing true here would cause the test to fail\n * because that protocol would not be allowed to run over a data/time limited\n * connection.\n */\n runOnLimitedConnection?: boolean\n}\n\nexport type TransportManagerDialProgressEvents =\n ProgressEvent<'transport-manager:selected-transport', string>\n\nexport type OpenConnectionProgressEvents =\n TransportManagerDialProgressEvents |\n ProgressEvent<'dial-queue:already-connected'> |\n ProgressEvent<'dial-queue:already-in-dial-queue'> |\n ProgressEvent<'dial-queue:add-to-dial-queue'> |\n ProgressEvent<'dial-queue:start-dial'> |\n ProgressEvent<'dial-queue:calculated-addresses', Address[]> |\n OutboundConnectionUpgradeEvents\n\nexport interface DialOptions extends AbortOptions, ProgressOptions {\n /**\n * If true, open a new connection to the remote even if one already exists\n */\n force?: boolean\n}\n\nexport interface DialProtocolOptions extends NewStreamOptions {\n\n}\n\n/**\n * Libp2p nodes implement this interface.\n */\nexport interface Libp2p<T extends ServiceMap = ServiceMap> extends Startable, TypedEventTarget<Libp2pEvents<T>> {\n /**\n * The PeerId is a unique identifier for a node on the network.\n *\n * It is the hash of an RSA public key or, for Ed25519 or secp256k1 keys,\n * the key itself.\n *\n * @example\n *\n * ```TypeScript\n * console.info(libp2p.peerId)\n * // PeerId(12D3Foo...)\n * ````\n */\n peerId: PeerId\n\n /**\n * The peer store holds information we know about other peers on the network.\n * - multiaddrs, supported protocols, etc.\n *\n * @example\n *\n * ```TypeScript\n * const peer = await libp2p.peerStore.get(peerId)\n * console.info(peer)\n * // { id: PeerId(12D3Foo...), addresses: [] ... }\n * ```\n */\n peerStore: PeerStore\n\n /**\n * The peer routing subsystem allows the user to find peers on the network\n * or to find peers close to binary keys.\n *\n * @example\n *\n * ```TypeScript\n * const peerInfo = await libp2p.peerRouting.findPeer(peerId)\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * ```\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.peerRouting.getClosestPeers(key)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n peerRouting: PeerRouting\n\n /**\n * The content routing subsystem allows the user to find providers for content,\n * let the network know they are providers for content, and get/put values to\n * the DHT.\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.contentRouting.findProviders(cid)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n contentRouting: ContentRouting\n\n /**\n * The metrics subsystem allows recording values to assess the health/performance\n * of the running node.\n *\n * @example\n *\n * ```TypeScript\n * const metric = libp2p.metrics.registerMetric({\n * 'my-metric'\n * })\n *\n * // later\n * metric.update(5)\n * ```\n */\n metrics?: Metrics\n\n /**\n * The logger used by this libp2p node\n */\n logger: ComponentLogger\n\n /**\n * The current status of the libp2p node\n */\n status: Libp2pStatus\n\n /**\n * Get a deduplicated list of peer advertising multiaddrs by concatenating\n * the listen addresses used by transports with any configured\n * announce addresses as well as observed addresses reported by peers.\n *\n * If Announce addrs are specified, configured listen addresses will be\n * ignored though observed addresses will still be included.\n *\n * @example\n *\n * ```TypeScript\n * const listenMa = libp2p.getMultiaddrs()\n * // [ <Multiaddr 047f00000106f9ba - /ip4/127.0.0.1/tcp/63930> ]\n * ```\n */\n getMultiaddrs(): Multiaddr[]\n\n /**\n * Returns a list of supported protocols\n *\n * @example\n *\n * ```TypeScript\n * const protocols = libp2p.getProtocols()\n * // [ '/ipfs/ping/1.0.0', '/ipfs/id/1.0.0' ]\n * ```\n */\n getProtocols(): string[]\n\n /**\n * Return a list of all connections this node has open, optionally filtering\n * by a PeerId\n *\n * @example\n *\n * ```TypeScript\n * for (const connection of libp2p.getConnections()) {\n * console.log(peerId, connection.remoteAddr.toString())\n * // Logs the PeerId string and the observed remote multiaddr of each Connection\n * }\n * ```\n */\n getConnections(peerId?: PeerId): Connection[]\n\n /**\n * Return the list of dials currently in progress or queued to start\n *\n * @example\n *\n * ```TypeScript\n * for (const pendingDial of libp2p.getDialQueue()) {\n * console.log(pendingDial)\n * }\n * ```\n */\n getDialQueue(): PendingDial[]\n\n /**\n * Return a list of all peers we currently have a connection open to\n */\n getPeers(): PeerId[]\n\n /**\n * Dials to the provided peer. If successful, the known metadata of the\n * peer will be added to the nodes `peerStore`.\n *\n * If a PeerId is passed as the first argument, the peer will need to have known multiaddrs for it in the PeerStore.\n *\n * @example\n *\n * ```TypeScript\n * const conn = await libp2p.dial(remotePeerId)\n *\n * // create a new stream within the connection\n * const stream = await conn.newStream(['/echo/1.1.0', '/echo/1.0.0'])\n *\n * // protocol negotiated: 'echo/1.0.0' means that the other party only supports the older version\n *\n * // ...\n * await conn.close()\n * ```\n */\n dial(peer: PeerId | Multiaddr | Multiaddr[], options?: DialOptions): Promise<Connection>\n\n /**\n * Dials to the provided peer and tries to handshake with the given protocols in order.\n * If successful, the known metadata of the peer will be added to the nodes `peerStore`,\n * and the `MuxedStream` will be returned together with the successful negotiated protocol.\n *\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n *\n * const { stream, protocol } = await libp2p.dialProtocol(remotePeerId, protocols)\n *\n * // Use this new stream like any other duplex stream\n * pipe([1, 2, 3], stream, consume)\n * ```\n */\n dialProtocol(peer: PeerId | Multiaddr | Multiaddr[], protocols: string | string[], options?: DialProtocolOptions): Promise<Stream>\n\n /**\n * Attempts to gracefully close an open connection to the given peer. If the\n * connection is not closed in the grace period, it will be forcefully closed.\n *\n * An AbortSignal can optionally be passed to control when the connection is\n * forcefully closed.\n *\n * @example\n *\n * ```TypeScript\n * await libp2p.hangUp(remotePeerId)\n * ```\n */\n hangUp(peer: PeerId | Multiaddr, options?: AbortOptions): Promise<void>\n\n /**\n * Sets up [multistream-select routing](https://github.com/multiformats/multistream-select) of protocols to their application handlers. Whenever a stream is opened on one of the provided protocols, the handler will be called. `handle` must be called in order to register a handler and support for a given protocol. This also informs other peers of the protocols you support.\n *\n * `libp2p.handle(protocols, handler, options)`\n *\n * In the event of a new handler for the same protocol being added and error\n * will be thrown. Pass `force: true` to override this.\n *\n * @example\n *\n * ```TypeScript\n * const handler = ({ connection, stream, protocol }) => {\n * // use stream or connection according to the needs\n * }\n *\n * libp2p.handle('/echo/1.0.0', handler, {\n * maxInboundStreams: 5,\n * maxOutboundStreams: 5\n * })\n * ```\n */\n handle(protocol: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise<void>\n\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.unhandle(['/echo/1.0.0'])\n * ```\n */\n unhandle(protocols: string[] | string, options?: AbortOptions): Promise<void>\n\n /**\n * Register a topology to be informed when peers are encountered that\n * support the specified protocol\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register('/echo/1.0.0', {\n * onConnect: (peer, connection) => {\n * // handle connect\n * },\n * onDisconnect: (peer, connection) => {\n * // handle disconnect\n * }\n * })\n * ```\n */\n register(protocol: string, topology: Topology, options?: AbortOptions): Promise<string>\n\n /**\n * Unregister topology to no longer be informed when peers connect or\n * disconnect.\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register(...)\n *\n * libp2p.unregister(id)\n * ```\n */\n unregister(id: string): void\n\n /**\n * Returns the public key for the passed PeerId. If the PeerId is of the 'RSA'\n * type this may mean searching the routing if the peer's key is not present\n * in the peer store.\n */\n getPublicKey(peer: Ed25519PeerId, options?: AbortOptions): Promise<Ed25519PublicKey>\n getPublicKey(peer: Secp256k1PeerId, options?: AbortOptions): Promise<Secp256k1PublicKey>\n getPublicKey(peer: RSAPeerId, options?: AbortOptions): Promise<RSAPublicKey>\n getPublicKey(peer: URLPeerId, options?: AbortOptions): Promise<never>\n getPublicKey(peer: PeerId, options?: AbortOptions): Promise<PublicKey>\n\n /**\n * Given the current node configuration, returns a promise of `true` or\n * `false` if the node would attempt to dial the passed multiaddr.\n *\n * This means a relevant transport is configured, and the connection gater\n * would not block the dial attempt.\n *\n * This may involve resolving DNS addresses so you should pass an AbortSignal.\n */\n isDialable(multiaddr: Multiaddr | Multiaddr[], options?: IsDialableOptions): Promise<boolean>\n\n /**\n * A set of user defined services\n */\n services: T\n}\n\n/**\n * Metadata about the current node\n */\nexport interface NodeInfo {\n /**\n * The implementation name\n */\n name: string\n\n /**\n * The implementation version\n */\n version: string\n\n /**\n * A string that contains information about the implementation and runtime\n */\n userAgent: string\n}\n\n/**\n * An object that contains an AbortSignal as\n * the optional `signal` property.\n *\n * @example\n *\n * ```TypeScript\n * const controller = new AbortController()\n *\n * aLongRunningOperation({\n * signal: controller.signal\n * })\n *\n * // later\n *\n * controller.abort()\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * An object that contains a Logger as the `log` property.\n */\nexport interface LoggerOptions {\n log: Logger\n}\n\n/**\n * An object that includes a trace object that is passed onwards.\n *\n * This is used by metrics method tracing to link function calls together.\n */\nexport interface TraceOptions {\n trace?: any\n}\n\n/**\n * A signal that needs to be cleared when no longer in use\n */\nexport interface ClearableSignal extends AbortSignal {\n clear(): void\n}\n\n/**\n * When a routing operation involves reading values, these options allow\n * controlling where the values are read from. By default libp2p will check\n * local caches but may not use the network if a valid local value is found,\n * these options allow tuning that behavior.\n */\nexport interface RoutingOptions extends AbortOptions, ProgressOptions, TraceOptions {\n /**\n * Pass `false` to not use the network\n *\n * @default true\n */\n useNetwork?: boolean\n\n /**\n * Pass `false` to not use cached values\n *\n * @default true\n */\n useCache?: boolean\n}\n\n/**\n * This symbol is used by libp2p services to define the capabilities they can\n * provide to other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of provided capabilities.\n */\nexport const serviceCapabilities = Symbol.for('@libp2p/service-capabilities')\n\n/**\n * This symbol is used by libp2p services to define the capabilities they\n * require from other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of required capabilities.\n */\nexport const serviceDependencies = Symbol.for('@libp2p/service-dependencies')\n\nexport * from './connection.js'\nexport * from './connection-encrypter.js'\nexport * from './connection-gater.js'\nexport * from './content-routing.js'\nexport * from './keys.js'\nexport * from './metrics.js'\nexport * from './peer-discovery.js'\nexport * from './peer-id.js'\nexport * from './peer-info.js'\nexport * from './peer-routing.js'\nexport * from './peer-store.js'\nexport * from './pubsub.js'\nexport * from './record.js'\nexport * from './stream-handler.js'\nexport * from './stream-muxer.js'\nexport * from './topology.js'\nexport * from './transport.js'\nexport * from './errors.js'\nexport * from 'main-event'\nexport * from './startable.js'\n", "/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n", "/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n", "import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n", "/**\n * @packageDocumentation\n *\n * A class that lets you do operations over a list of Uint8Arrays without\n * copying them.\n *\n * ```js\n * import { Uint8ArrayList } from 'uint8arraylist'\n *\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray()\n * // -> Uint8Array([0, 1, 2, 3, 4, 5])\n *\n * list.consume(3)\n * list.subarray()\n * // -> Uint8Array([3, 4, 5])\n *\n * // you can also iterate over the list\n * for (const buf of list) {\n * // ..do something with `buf`\n * }\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ## Converting Uint8ArrayLists to Uint8Arrays\n *\n * There are two ways to turn a `Uint8ArrayList` into a `Uint8Array` - `.slice` and `.subarray` and one way to turn a `Uint8ArrayList` into a `Uint8ArrayList` with different contents - `.sublist`.\n *\n * ### slice\n *\n * Slice follows the same semantics as [Uint8Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice) in that it creates a new `Uint8Array` and copies bytes into it using an optional offset & length.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.slice(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ### subarray\n *\n * Subarray attempts to follow the same semantics as [Uint8Array.subarray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray) with one important different - this is a no-copy operation, unless the requested bytes span two internal buffers in which case it is a copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0]) - no-copy\n *\n * list.subarray(2, 5)\n * // -> Uint8Array([2, 3, 4]) - copy\n * ```\n *\n * ### sublist\n *\n * Sublist creates and returns a new `Uint8ArrayList` that shares the underlying buffers with the original so is always a no-copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.sublist(0, 1)\n * // -> Uint8ArrayList([0]) - no-copy\n *\n * list.sublist(2, 5)\n * // -> Uint8ArrayList([2], [3, 4]) - no-copy\n * ```\n *\n * ## Inspiration\n *\n * Borrows liberally from [bl](https://www.npmjs.com/package/bl) but only uses native JS types.\n */\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc'\nimport { concat } from 'uint8arrays/concat'\nimport { equals } from 'uint8arrays/equals'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\nexport type Appendable = Uint8ArrayList | Uint8Array\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number): { buf: Uint8Array, index: number } {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\n\n/**\n * Check if object is a CID instance\n *\n * @example\n *\n * ```js\n * import { isUint8ArrayList, Uint8ArrayList } from 'uint8arraylist'\n *\n * isUint8ArrayList(true) // false\n * isUint8ArrayList([]) // false\n * isUint8ArrayList(new Uint8ArrayList()) // true\n * ```\n */\nexport function isUint8ArrayList (value: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList implements Iterable<Uint8Array> {\n private bufs: Uint8Array[]\n public length: number\n public readonly [symbol] = true\n\n constructor (...data: Appendable[]) {\n this.bufs = []\n this.length = 0\n\n if (data.length > 0) {\n this.appendAll(data)\n }\n }\n\n * [Symbol.iterator] (): Iterator<Uint8Array> {\n yield * this.bufs\n }\n\n get byteLength (): number {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append (...bufs: Appendable[]): void {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.push(...buf.bufs)\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend (...bufs: Appendable[]): void {\n this.prependAll(bufs)\n }\n\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.unshift(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.unshift(...buf.bufs)\n } else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number): number {\n const res = findBufAndOffset(this.bufs, index)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number): void {\n const res = findBufAndOffset(this.bufs, index)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable, offset: number = 0): void {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\n }\n } else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i))\n }\n } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number): void {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = []\n this.length = 0\n return\n }\n\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength\n this.length -= this.bufs[0].byteLength\n this.bufs.shift()\n } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\n }\n }\n\n /**\n * Extracts a section of an array and returns a new array.\n *\n * This is a copy operation as it is with Uint8Arrays and Arrays\n * - note this is different to the behaviour of Node Buffers.\n */\n slice (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a alloc from the given start and end element index.\n *\n * In the best case where the data extracted comes from a single Uint8Array\n * internally this is a no-copy operation otherwise it is a copy operation.\n */\n subarray (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a allocList from the given start and end element index.\n *\n * This is a no-copy operation.\n */\n sublist (beginInclusive?: number, endExclusive?: number): Uint8ArrayList {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList()\n list.length = length\n // don't loop, just set the bufs\n list.bufs = [...bufs]\n\n return list\n }\n\n private _subList (beginInclusive?: number, endExclusive?: number): { bufs: Uint8Array[], length: number } {\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? this.length\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: this.bufs, length: this.length }\n }\n\n const bufs: Uint8Array[] = []\n let offset = 0\n\n for (let i = 0; i < this.bufs.length; i++) {\n const buf = this.bufs[i]\n const bufStart = offset\n const bufEnd = bufStart + buf.byteLength\n\n // for next loop\n offset = bufEnd\n\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue\n }\n\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n\n if (sliceStartInBuf && sliceEndsInBuf) {\n // slice is wholly contained within this buffer\n if (beginInclusive === bufStart && endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n const start = beginInclusive - bufStart\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)))\n break\n }\n\n if (sliceStartInBuf) {\n // slice starts in this buffer\n if (beginInclusive === 0) {\n // requested whole buffer\n bufs.push(buf)\n continue\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart))\n continue\n }\n\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart))\n break\n }\n\n // slice started before this buffer and ends after it\n bufs.push(buf)\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n indexOf (search: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array')\n }\n\n const needle = search instanceof Uint8Array ? search : search.subarray()\n\n offset = Number(offset ?? 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M: number = needle.byteLength\n\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long')\n }\n\n // radix\n const radix: number = 256\n const rightmostPositions: Int32Array = new Int32Array(radix)\n\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c: number = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1\n }\n\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j\n }\n\n // Return offset of first match, -1 if no match\n const right = rightmostPositions\n const lastIndex = this.byteLength - needle.byteLength\n const lastPatIndex = needle.byteLength - 1\n let skip: number\n\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0\n\n for (let j = lastPatIndex; j >= 0; j--) {\n const char: number = this.get(i + j)\n\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char])\n break\n }\n }\n\n if (skip === 0) {\n return i\n }\n }\n\n return -1\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n equals (other: any): other is Uint8ArrayList {\n if (other == null) {\n return false\n }\n\n if (!(other instanceof Uint8ArrayList)) {\n return false\n }\n\n if (other.bufs.length !== this.bufs.length) {\n return false\n }\n\n for (let i = 0; i < this.bufs.length; i++) {\n if (!equals(this.bufs[i], other.bufs[i])) {\n return false\n }\n }\n\n return true\n }\n\n /**\n * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this\n * method if you know the total size of all the Uint8Arrays ahead of time.\n */\n static fromUint8Arrays (bufs: Uint8Array[], length?: number): Uint8ArrayList {\n const list = new Uint8ArrayList()\n list.bufs = bufs\n\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0)\n }\n\n list.length = length\n\n return list\n }\n}\n\n/*\nfunction indexOf (needle: Uint8Array, haystack: Uint8Array, offset = 0) {\n for (let i = offset; i < haystack.byteLength; i++) {\n for (let j = 0; j < needle.length; j++) {\n if (haystack[i + j] !== needle[j]) {\n break\n }\n\n if (j === needle.byteLength -1) {\n return i\n }\n }\n\n if (haystack.byteLength - i < needle.byteLength) {\n break\n }\n }\n\n return -1\n}\n*/\n", "/**\n * Internal webcrypto alias.\n * We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n * See utils.ts for details.\n * @module\n */\ndeclare const globalThis: Record<string, any> | undefined;\nexport const crypto: any =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n abstract clone(): T;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash function */\nexport type CHash = ReturnType<typeof createHasher>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof createOptHasher>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof createXOFer>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function createOptHasher<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): Hash<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\n\nexport function createXOFer<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): HashXOF<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport { randomBytes as randB } from '@noble/hashes/utils'\n\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes (length: number): Uint8Array {\n if (isNaN(length) || length <= 0) {\n throw new InvalidParametersError('random bytes length must be a Number bigger than 0')\n }\n return randB(length)\n}\n", "export default function pDefer() {\n\tconst deferred = {};\n\n\tdeferred.promise = new Promise((resolve, reject) => {\n\t\tdeferred.resolve = resolve;\n\t\tdeferred.reject = reject;\n\t});\n\n\treturn deferred;\n}\n", "/**\n * An abort error class that extends error\n */\nexport class AbortError extends Error {\n public type: string\n public code: string | string\n\n constructor (message?: string, code?: string, name?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.name = name ?? 'AbortError'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n\nexport interface RaceSignalOptions {\n /**\n * The message for the error thrown if the signal aborts\n */\n errorMessage?: string\n\n /**\n * The code for the error thrown if the signal aborts\n */\n errorCode?: string\n\n /**\n * The name for the error thrown if the signal aborts\n */\n errorName?: string\n}\n\n/**\n * Race a promise against an abort signal\n */\nexport async function raceSignal <T> (promise: Promise<T>, signal?: AbortSignal, opts?: RaceSignalOptions): Promise<T> {\n if (signal == null) {\n return promise\n }\n\n if (signal.aborted) {\n // the passed promise may yet resolve or reject but the use has signalled\n // they are no longer interested so smother the error\n promise.catch(() => {})\n return Promise.reject(new AbortError(opts?.errorMessage, opts?.errorCode, opts?.errorName))\n }\n\n let listener\n\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage, opts?.errorCode, opts?.errorName)\n\n try {\n return await Promise.race([\n promise,\n new Promise<T>((resolve, reject) => {\n listener = () => {\n reject(error)\n }\n signal.addEventListener('abort', listener)\n })\n ])\n } finally {\n if (listener != null) {\n signal.removeEventListener('abort', listener)\n }\n }\n}\n", "/**\n * @packageDocumentation\n *\n * A pushable async generator that waits until the current value is consumed\n * before allowing a new value to be pushed.\n *\n * Useful for when you don't want to keep memory usage under control and/or\n * allow a downstream consumer to dictate how fast data flows through a pipe,\n * but you want to be able to apply a transform to that data.\n *\n * @example\n *\n * ```typescript\n * import { queuelessPushable } from 'it-queueless-pushable'\n *\n * const pushable = queuelessPushable<string>()\n *\n * // run asynchronously\n * Promise.resolve().then(async () => {\n * // push a value - the returned promise will not resolve until the value is\n * // read from the pushable\n * await pushable.push('hello')\n * })\n *\n * // read a value\n * const result = await pushable.next()\n * console.info(result) // { done: false, value: 'hello' }\n * ```\n */\n\nimport deferred from 'p-defer'\nimport { raceSignal } from 'race-signal'\nimport type { AbortOptions } from 'abort-error'\nimport type { RaceSignalOptions } from 'race-signal'\n\nexport interface Pushable<T> extends AsyncGenerator<T, void, unknown> {\n /**\n * End the iterable after all values in the buffer (if any) have been yielded. If an\n * error is passed the buffer is cleared immediately and the next iteration will\n * throw the passed error\n */\n end(err?: Error, options?: AbortOptions & RaceSignalOptions): Promise<void>\n\n /**\n * Push a value into the iterable. Values are yielded from the iterable in the order\n * they are pushed. Values not yet consumed from the iterable are buffered.\n */\n push(value: T, options?: AbortOptions & RaceSignalOptions): Promise<void>\n}\n\nclass QueuelessPushable <T> implements Pushable<T> {\n private readNext: PromiseWithResolvers<void>\n private haveNext: PromiseWithResolvers<void>\n private ended: boolean\n private nextResult: IteratorResult<T> | undefined\n private error?: Error\n\n constructor () {\n this.ended = false\n\n this.readNext = deferred()\n this.haveNext = deferred()\n }\n\n [Symbol.asyncIterator] (): AsyncGenerator<T, void, unknown> {\n return this\n }\n\n async next (): Promise<IteratorResult<T, void>> {\n if (this.nextResult == null) {\n // wait for the supplier to push a value\n await this.haveNext.promise\n }\n\n if (this.nextResult == null) {\n throw new Error('HaveNext promise resolved but nextResult was undefined')\n }\n\n const nextResult = this.nextResult\n this.nextResult = undefined\n\n // signal to the supplier that we read the value\n this.readNext.resolve()\n this.readNext = deferred()\n\n return nextResult\n }\n\n async throw (err?: Error): Promise<IteratorReturnResult<undefined>> {\n this.ended = true\n this.error = err\n\n if (err != null) {\n // this can cause unhandled promise rejections if nothing is awaiting the\n // next value so attach a dummy catch listener to the promise\n this.haveNext.promise.catch(() => {})\n this.haveNext.reject(err)\n }\n\n const result: IteratorReturnResult<undefined> = {\n done: true,\n value: undefined\n }\n\n return result\n }\n\n async return (): Promise<IteratorResult<T>> {\n const result: IteratorReturnResult<undefined> = {\n done: true,\n value: undefined\n }\n\n this.ended = true\n this.nextResult = result\n\n // let the consumer know we have a new value\n this.haveNext.resolve()\n\n return result\n }\n\n async push (value: T, options?: AbortOptions & RaceSignalOptions): Promise<void> {\n await this._push(value, options)\n }\n\n async end (err?: Error, options?: AbortOptions & RaceSignalOptions): Promise<void> {\n if (err != null) {\n await this.throw(err)\n } else {\n // abortable return\n await this._push(undefined, options)\n }\n }\n\n private async _push (value?: T, options?: AbortOptions & RaceSignalOptions): Promise<void> {\n if (value != null && this.ended) {\n throw this.error ?? new Error('Cannot push value onto an ended pushable')\n }\n\n // wait for all values to be read\n while (this.nextResult != null) {\n await this.readNext.promise\n }\n\n if (value != null) {\n this.nextResult = { done: false, value }\n } else {\n this.ended = true\n this.nextResult = { done: true, value: undefined }\n }\n\n // let the consumer know we have a new value\n this.haveNext.resolve()\n this.haveNext = deferred()\n\n // wait for the consumer to have finished processing the value and requested\n // the next one or for the passed signal to abort the waiting\n await raceSignal(\n this.readNext.promise,\n options?.signal,\n options\n )\n }\n}\n\nexport function queuelessPushable <T> (): Pushable<T> {\n return new QueuelessPushable<T>()\n}\n", "/**\n * The incoming stream ended before the expected number of bytes were read\n */\nexport class UnexpectedEOFError extends Error {\n name = 'UnexpectedEOFError'\n code = 'ERR_UNEXPECTED_EOF'\n}\n", "/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive bytes over streams.\n *\n * @example\n *\n * ```typescript\n * import { byteStream } from 'it-byte-stream'\n *\n * const stream = byteStream(duplex)\n *\n * // read the next chunk\n * const bytes = await stream.read()\n *\n * // read the next five bytes\n * const fiveBytes = await stream.read(5)\n *\n * // write bytes into the stream\n * await stream.write(Uint8Array.from([0, 1, 2, 3, 4]))\n * ```\n */\n\nimport { queuelessPushable } from 'it-queueless-pushable'\nimport { raceSignal } from 'race-signal'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { UnexpectedEOFError } from './errors.js'\nimport type { AbortOptions } from 'abort-error'\nimport type { Duplex } from 'it-stream-types'\n\nexport interface ReadOptions extends AbortOptions {\n bytes: number\n}\n\nexport interface ByteStream <Stream = unknown> {\n /**\n * Read bytes from the stream.\n *\n * If a required number of bytes is passed as an option, this will wait for\n * the underlying stream to supply that number of bytes, throwing an\n * `UnexpectedEOFError` if the stream closes before this happens.\n *\n * If no required number of bytes is passed, this will return `null` if the\n * underlying stream closes before supplying any bytes.\n */\n read(options: ReadOptions): Promise<Uint8ArrayList>\n read(options?: AbortOptions): Promise<Uint8ArrayList | null>\n\n /**\n * Write the passed bytes to the stream\n */\n write(input: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise<void>\n\n /**\n * Returns the underlying stream\n */\n unwrap(): Stream\n}\n\nexport interface ByteStreamOpts {\n /**\n * After the stream is unwrapped, any bytes that have been read from the\n * incoming stream will be yielded in-order as `Uint8Array`(s).\n *\n * To yield a single `Uint8ArrayList` with all unread bytes instead, pass\n * `false` here.\n */\n yieldBytes?: boolean\n}\n\nexport function byteStream <Stream extends Duplex<any, any, any>> (duplex: Stream, opts?: ByteStreamOpts): ByteStream<Stream> {\n const write = queuelessPushable()\n\n duplex.sink(write).catch(async (err: Error) => {\n await write.end(err)\n })\n\n duplex.sink = async (source: any) => {\n for await (const buf of source) {\n await write.push(buf)\n }\n\n await write.end()\n }\n\n let source: AsyncGenerator<any> = duplex.source\n\n if (duplex.source[Symbol.iterator] != null) {\n source = duplex.source[Symbol.iterator]()\n } else if (duplex.source[Symbol.asyncIterator] != null) {\n source = duplex.source[Symbol.asyncIterator]()\n }\n\n const readBuffer = new Uint8ArrayList()\n\n const W: ByteStream<Stream> = {\n read: async (options?: ReadOptions) => {\n options?.signal?.throwIfAborted()\n\n if (options?.bytes == null) {\n // just read whatever arrives\n const { done, value } = await raceSignal(source.next(), options?.signal)\n\n if (done === true) {\n return null\n }\n\n return value\n }\n\n while (readBuffer.byteLength < options.bytes) {\n const { value, done } = await raceSignal(source.next(), options?.signal)\n\n if (done === true) {\n throw new UnexpectedEOFError('unexpected end of input')\n }\n\n readBuffer.append(value)\n }\n\n const buf = readBuffer.sublist(0, options.bytes)\n readBuffer.consume(options.bytes)\n\n return buf\n },\n write: async (data, options?: AbortOptions) => {\n options?.signal?.throwIfAborted()\n\n // just write\n if (data instanceof Uint8Array) {\n await write.push(data, options)\n } else {\n await write.push(data.subarray(), options)\n }\n },\n unwrap: () => {\n if (readBuffer.byteLength > 0) {\n const originalStream = duplex.source\n duplex.source = (async function * () {\n if (opts?.yieldBytes === false) {\n yield readBuffer\n } else {\n yield * readBuffer\n }\n\n yield * originalStream\n }())\n }\n\n return duplex\n }\n }\n\n return W\n}\n", "export const PING_PROTOCOL = '/ipfs/ping/1.0.0'\nexport const PING_LENGTH = 32\nexport const PROTOCOL_VERSION = '1.0.0'\nexport const PROTOCOL_NAME = 'ping'\nexport const PROTOCOL_PREFIX = 'ipfs'\nexport const TIMEOUT = 10000\n\n// See https://github.com/libp2p/specs/blob/d4b5fb0152a6bb86cfd9ea/ping/ping.md?plain=1#L38-L43\n// The dialing peer MUST NOT keep more than one outbound stream for the ping protocol per peer.\n// The listening peer SHOULD accept at most two streams per peer since cross-stream behavior is\n// non-linear and stream writes occur asynchronously. The listening peer may perceive the\n// dialing peer closing and opening the wrong streams (for instance, closing stream B and\n// opening stream A even though the dialing peer is opening stream B and closing stream A).\nexport const MAX_INBOUND_STREAMS = 2\nexport const MAX_OUTBOUND_STREAMS = 1\n", "import { randomBytes } from '@libp2p/crypto'\nimport { ProtocolError, TimeoutError, serviceCapabilities } from '@libp2p/interface'\nimport { byteStream } from 'it-byte-stream'\nimport { setMaxListeners } from 'main-event'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { PROTOCOL_PREFIX, PROTOCOL_NAME, PING_LENGTH, PROTOCOL_VERSION, TIMEOUT, MAX_INBOUND_STREAMS, MAX_OUTBOUND_STREAMS } from './constants.js'\nimport type { PingComponents, PingInit, Ping as PingInterface } from './index.js'\nimport type { AbortOptions, Logger, Stream, PeerId, Startable, IncomingStreamData } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport class Ping implements Startable, PingInterface {\n public readonly protocol: string\n private readonly components: PingComponents\n private started: boolean\n private readonly timeout: number\n private readonly maxInboundStreams: number\n private readonly maxOutboundStreams: number\n private readonly runOnLimitedConnection: boolean\n private readonly log: Logger\n\n constructor (components: PingComponents, init: PingInit = {}) {\n this.components = components\n this.log = components.logger.forComponent('libp2p:ping')\n this.started = false\n this.protocol = `/${init.protocolPrefix ?? PROTOCOL_PREFIX}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`\n this.timeout = init.timeout ?? TIMEOUT\n this.maxInboundStreams = init.maxInboundStreams ?? MAX_INBOUND_STREAMS\n this.maxOutboundStreams = init.maxOutboundStreams ?? MAX_OUTBOUND_STREAMS\n this.runOnLimitedConnection = init.runOnLimitedConnection ?? true\n\n this.handleMessage = this.handleMessage.bind(this)\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/ping'\n\n readonly [serviceCapabilities]: string[] = [\n '@libp2p/ping'\n ]\n\n async start (): Promise<void> {\n await this.components.registrar.handle(this.protocol, this.handleMessage, {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams,\n runOnLimitedConnection: this.runOnLimitedConnection\n })\n this.started = true\n }\n\n async stop (): Promise<void> {\n await this.components.registrar.unhandle(this.protocol)\n this.started = false\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n /**\n * A handler to register with Libp2p to process ping messages\n */\n handleMessage (data: IncomingStreamData): void {\n this.log('incoming ping from %p', data.connection.remotePeer)\n\n const { stream } = data\n const start = Date.now()\n const bytes = byteStream(stream)\n let pinged = false\n\n Promise.resolve().then(async () => {\n while (true) {\n const signal = AbortSignal.timeout(this.timeout)\n setMaxListeners(Infinity, signal)\n signal.addEventListener('abort', () => {\n stream?.abort(new TimeoutError('ping timeout'))\n })\n\n const buf = await bytes.read({\n bytes: PING_LENGTH,\n signal\n })\n await bytes.write(buf, {\n signal\n })\n\n pinged = true\n }\n })\n .catch(err => {\n // ignore the error if we've processed at least one ping, the remote\n // closed the stream and we handled or are handling the close cleanly\n if (pinged && err.name === 'UnexpectedEOFError' && stream.readStatus !== 'ready') {\n return\n }\n\n this.log.error('incoming ping from %p failed with error - %e', data.connection.remotePeer, err)\n stream?.abort(err)\n })\n .finally(() => {\n const ms = Date.now() - start\n this.log('incoming ping from %p complete in %dms', data.connection.remotePeer, ms)\n\n const signal = AbortSignal.timeout(this.timeout)\n setMaxListeners(Infinity, signal)\n\n stream.close({\n signal\n })\n .catch(err => {\n this.log.error('error closing ping stream from %p - %e', data.connection.remotePeer, err)\n stream?.abort(err)\n })\n })\n }\n\n /**\n * Ping a given peer and wait for its response, getting the operation latency.\n */\n async ping (peer: PeerId | Multiaddr | Multiaddr[], options: AbortOptions = {}): Promise<number> {\n this.log('pinging %p', peer)\n\n const start = Date.now()\n const data = randomBytes(PING_LENGTH)\n const connection = await this.components.connectionManager.openConnection(peer, options)\n let stream: Stream | undefined\n\n if (options.signal == null) {\n const signal = AbortSignal.timeout(this.timeout)\n\n options = {\n ...options,\n signal\n }\n }\n\n try {\n stream = await connection.newStream(this.protocol, {\n ...options,\n runOnLimitedConnection: this.runOnLimitedConnection\n })\n\n const bytes = byteStream(stream)\n\n const [, result] = await Promise.all([\n bytes.write(data, options),\n bytes.read({\n ...options,\n bytes: PING_LENGTH\n })\n ])\n\n const ms = Date.now() - start\n\n if (!uint8ArrayEquals(data, result.subarray())) {\n throw new ProtocolError(`Received wrong ping ack after ${ms}ms`)\n }\n\n this.log('ping %p complete in %dms', connection.remotePeer, ms)\n\n return ms\n } catch (err: any) {\n this.log.error('error while pinging %p', connection.remotePeer, err)\n\n stream?.abort(err)\n\n throw err\n } finally {\n if (stream != null) {\n await stream.close(options)\n }\n }\n }\n}\n"],
|
|
5
|
-
"mappings": ";8bAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,EAAA,SAAAC,ICyCM,IAAOC,EAAP,cAAsC,KAAK,CAC/C,OAAO,KAAO,yBAEd,YAAaC,EAAU,qBAAoB,CACzC,MAAMA,CAAO,EACb,KAAK,KAAO,wBACd,GAuMI,IAAOC,EAAP,cAA6B,KAAK,CACtC,OAAO,KAAO,gBAEd,YAAaC,EAAU,iBAAgB,CACrC,MAAMA,CAAO,EACb,KAAK,KAAO,eACd,GAMWC,EAAP,cAA4B,KAAK,CACrC,OAAO,KAAO,eAEd,YAAaD,EAAU,YAAW,CAChC,MAAMA,CAAO,EACb,KAAK,KAAO,cACd,GC2lBK,IAAME,EAAsB,OAAO,IAAI,8BAA8B,EAS/DC,GAAsB,OAAO,IAAI,8BAA8B,ECz2BtE,SAAUC,EAAQC,EAAeC,EAAa,CAClD,GAAID,IAAMC,EACR,MAAO,GAGT,GAAID,EAAE,aAAeC,EAAE,WACrB,MAAO,GAGT,QAASC,EAAI,EAAGA,EAAIF,EAAE,WAAYE,IAChC,GAAIF,EAAEE,CAAC,IAAMD,EAAEC,CAAC,EACd,MAAO,GAIX,MAAO,EACT,CCfM,SAAUC,EAAOC,EAAe,EAAC,CACrC,OAAO,IAAI,WAAWA,CAAI,CAC5B,CAOM,SAAUC,EAAaD,EAAe,EAAC,CAC3C,OAAO,IAAI,WAAWA,CAAI,CAC5B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,EAAK,WAAW,WAAYS,CAAG,EACxFR,GAAQ,MAAMQ,CAAG,CACnB,CAAC,CACL,CAAC,CACL,CAKA,MAAM,KAAME,EAAwCC,EAAwB,CAAA,EAAE,CAC5E,KAAK,IAAI,aAAcD,CAAI,EAE3B,IAAMT,EAAQ,KAAK,IAAG,EAChBF,EAAOa,EAAY,EAAW,EAC9BC,EAAa,MAAM,KAAK,WAAW,kBAAkB,eAAeH,EAAMC,CAAO,EACnFX,EAEJ,GAAIW,EAAQ,QAAU,KAAM,CAC1B,IAAMN,EAAS,YAAY,QAAQ,KAAK,OAAO,EAE/CM,EAAU,CACR,GAAGA,EACH,OAAAN,EAEJ,CAEA,GAAI,CACFL,EAAS,MAAMa,EAAW,UAAU,KAAK,SAAU,CACjD,GAAGF,EACH,uBAAwB,KAAK,uBAC9B,EAED,IAAMT,EAAQC,EAAWH,CAAM,EAEzB,CAAC,CAAEc,CAAM,EAAI,MAAM,QAAQ,IAAI,CACnCZ,EAAM,MAAMH,EAAMY,CAAO,EACzBT,EAAM,KAAK,CACT,GAAGS,EACH,MAAO,GACR,EACF,EAEKF,EAAK,KAAK,IAAG,EAAKR,EAExB,GAAI,CAACc,EAAiBhB,EAAMe,EAAO,SAAQ,CAAE,EAC3C,MAAM,IAAIE,EAAc,iCAAiCP,CAAE,IAAI,EAGjE,YAAK,IAAI,2BAA4BI,EAAW,WAAYJ,CAAE,EAEvDA,CACT,OAASD,EAAU,CACjB,WAAK,IAAI,MAAM,yBAA0BK,EAAW,WAAYL,CAAG,EAEnER,GAAQ,MAAMQ,CAAG,EAEXA,CACR,SACMR,GAAU,MACZ,MAAMA,EAAO,MAAMW,CAAO,CAE9B,CACF,GhB7GI,SAAUM,EAAMC,EAAiB,CAAA,EAAE,CACvC,OAAQC,GAAe,IAAIC,EAAUD,EAAYD,CAAI,CACvD",
|
|
6
|
-
"names": ["index_exports", "__export", "PING_PROTOCOL", "ping", "InvalidParametersError", "message", "ProtocolError", "message", "TimeoutError", "serviceCapabilities", "serviceDependencies", "equals", "a", "b", "i", "alloc", "size", "allocUnsafe", "concat", "arrays", "length", "acc", "curr", "output", "allocUnsafe", "offset", "arr", "symbol", "findBufAndOffset", "bufs", "index", "offset", "buf", "bufEnd", "isUint8ArrayList", "value", "Uint8ArrayList", "_Uint8ArrayList", "data", "length", "res", "i", "bytes", "beginInclusive", "endExclusive", "concat", "list", "bufStart", "sliceStartInBuf", "sliceEndsInBuf", "start", "search", "needle", "M", "radix", "rightmostPositions", "j", "right", "lastIndex", "lastPatIndex", "skip", "char", "byteOffset", "allocUnsafe", "littleEndian", "alloc", "other", "equals", "acc", "curr", "crypto", "randomBytes", "bytesLength", "crypto", "randomBytes", "length", "InvalidParametersError", "pDefer", "deferred", "resolve", "reject", "AbortError", "message", "code", "name", "raceSignal", "promise", "signal", "opts", "listener", "error", "resolve", "reject", "QueuelessPushable", "pDefer", "nextResult", "err", "result", "value", "options", "raceSignal", "queuelessPushable", "UnexpectedEOFError", "byteStream", "duplex", "opts", "write", "queuelessPushable", "err", "source", "buf", "readBuffer", "Uint8ArrayList", "options", "done", "value", "raceSignal", "UnexpectedEOFError", "data", "originalStream", "PING_PROTOCOL", "PROTOCOL_VERSION", "PROTOCOL_NAME", "PROTOCOL_PREFIX", "Ping", "components", "init", "PROTOCOL_PREFIX", "PROTOCOL_NAME", "PROTOCOL_VERSION", "serviceCapabilities", "data", "stream", "start", "bytes", "byteStream", "pinged", "signal", "TimeoutError", "buf", "err", "ms", "peer", "options", "randomBytes", "connection", "result", "equals", "ProtocolError", "ping", "init", "components", "Ping"]
|
|
4
|
+
"sourcesContent": ["/**\n * @packageDocumentation\n *\n * The ping service implements the [libp2p ping spec](https://github.com/libp2p/specs/blob/master/ping/ping.md) allowing you to make a latency measurement to a remote peer.\n *\n * @example\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n * import { ping } from '@libp2p/ping'\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const node = await createLibp2p({\n * services: {\n * ping: ping()\n * }\n * })\n *\n * const rtt = await node.services.ping.ping(multiaddr('/ip4/...'))\n *\n * console.info(rtt)\n * ```\n */\n\nimport { Ping as PingClass } from './ping.js'\nimport type { AbortOptions, PeerId } from '@libp2p/interface'\nimport type { ConnectionManager, Registrar } from '@libp2p/interface-internal'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport interface Ping {\n ping(peer: PeerId | Multiaddr | Multiaddr[], options?: AbortOptions): Promise<number>\n}\n\n/**\n * @deprecated Use the `Ping` export instead\n */\nexport type PingService = Ping\n\nexport interface PingInit {\n protocolPrefix?: string\n maxInboundStreams?: number\n maxOutboundStreams?: number\n runOnLimitedConnection?: boolean\n\n /**\n * How long we should wait for a ping response\n */\n timeout?: number\n}\n\n/**\n * @deprecated Use the `PingInit` export instead\n */\nexport type PingServiceInit = PingInit\n\nexport interface PingComponents {\n registrar: Registrar\n connectionManager: ConnectionManager\n}\n\nexport function ping (init: PingInit = {}): (components: PingComponents) => Ping {\n return (components) => new PingClass(components, init)\n}\n\nexport { PING_PROTOCOL } from './constants.js'\n", "/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nexport class AbortError extends Error {\n static name = 'AbortError'\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.name = 'AbortError'\n }\n}\n\n/**\n * Thrown when a remote Peer ID does not match the expected one\n */\nexport class UnexpectedPeerError extends Error {\n static name = 'UnexpectedPeerError'\n\n constructor (message = 'Unexpected Peer') {\n super(message)\n this.name = 'UnexpectedPeerError'\n }\n}\n\n/**\n * Thrown when a crypto exchange fails\n */\nexport class InvalidCryptoExchangeError extends Error {\n static name = 'InvalidCryptoExchangeError'\n\n constructor (message = 'Invalid crypto exchange') {\n super(message)\n this.name = 'InvalidCryptoExchangeError'\n }\n}\n\n/**\n * Thrown when invalid parameters are passed to a function or method call\n */\nexport class InvalidParametersError extends Error {\n static name = 'InvalidParametersError'\n\n constructor (message = 'Invalid parameters') {\n super(message)\n this.name = 'InvalidParametersError'\n }\n}\n\n/**\n * Thrown when a public key is invalid\n */\nexport class InvalidPublicKeyError extends Error {\n static name = 'InvalidPublicKeyError'\n\n constructor (message = 'Invalid public key') {\n super(message)\n this.name = 'InvalidPublicKeyError'\n }\n}\n\n/**\n * Thrown when a private key is invalid\n */\nexport class InvalidPrivateKeyError extends Error {\n static name = 'InvalidPrivateKeyError'\n\n constructor (message = 'Invalid private key') {\n super(message)\n this.name = 'InvalidPrivateKeyError'\n }\n}\n\n/**\n * Thrown when a operation is unsupported\n */\nexport class UnsupportedOperationError extends Error {\n static name = 'UnsupportedOperationError'\n\n constructor (message = 'Unsupported operation') {\n super(message)\n this.name = 'UnsupportedOperationError'\n }\n}\n\n/**\n * Thrown when a connection is closing\n */\nexport class ConnectionClosingError extends Error {\n static name = 'ConnectionClosingError'\n\n constructor (message = 'The connection is closing') {\n super(message)\n this.name = 'ConnectionClosingError'\n }\n}\n\n/**\n * Thrown when a connection is closed\n */\nexport class ConnectionClosedError extends Error {\n static name = 'ConnectionClosedError'\n\n constructor (message = 'The connection is closed') {\n super(message)\n this.name = 'ConnectionClosedError'\n }\n}\n\n/**\n * Thrown when a connection fails\n */\nexport class ConnectionFailedError extends Error {\n static name = 'ConnectionFailedError'\n\n constructor (message = 'Connection failed') {\n super(message)\n this.name = 'ConnectionFailedError'\n }\n}\n\n/**\n * Thrown when the muxer is closed and an attempt to open a stream occurs\n */\nexport class MuxerClosedError extends Error {\n static name = 'MuxerClosedError'\n\n constructor (message = 'The muxer is closed') {\n super(message)\n this.name = 'MuxerClosedError'\n }\n}\n\n/**\n * Thrown when a protocol stream is reset by the remote muxer\n */\nexport class StreamResetError extends Error {\n static name = 'StreamResetError'\n\n constructor (message = 'The stream has been reset') {\n super(message)\n this.name = 'StreamResetError'\n }\n}\n\n/**\n * Thrown when a stream is in an invalid state\n */\nexport class StreamStateError extends Error {\n static name = 'StreamStateError'\n\n constructor (message = 'The stream is in an invalid state') {\n super(message)\n this.name = 'StreamStateError'\n }\n}\n\n/**\n * Thrown when a value could not be found\n */\nexport class NotFoundError extends Error {\n static name = 'NotFoundError'\n\n constructor (message = 'Not found') {\n super(message)\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Thrown when an invalid peer ID is encountered\n */\nexport class InvalidPeerIdError extends Error {\n static name = 'InvalidPeerIdError'\n\n constructor (message = 'Invalid PeerID') {\n super(message)\n this.name = 'InvalidPeerIdError'\n }\n}\n\n/**\n * Thrown when an invalid multiaddr is encountered\n */\nexport class InvalidMultiaddrError extends Error {\n static name = 'InvalidMultiaddrError'\n\n constructor (message = 'Invalid multiaddr') {\n super(message)\n this.name = 'InvalidMultiaddrError'\n }\n}\n\n/**\n * Thrown when an invalid CID is encountered\n */\nexport class InvalidCIDError extends Error {\n static name = 'InvalidCIDError'\n\n constructor (message = 'Invalid CID') {\n super(message)\n this.name = 'InvalidCIDError'\n }\n}\n\n/**\n * Thrown when an invalid multihash is encountered\n */\nexport class InvalidMultihashError extends Error {\n static name = 'InvalidMultihashError'\n\n constructor (message = 'Invalid Multihash') {\n super(message)\n this.name = 'InvalidMultihashError'\n }\n}\n\n/**\n * Thrown when a protocol is not supported\n */\nexport class UnsupportedProtocolError extends Error {\n static name = 'UnsupportedProtocolError'\n\n constructor (message = 'Unsupported protocol error') {\n super(message)\n this.name = 'UnsupportedProtocolError'\n }\n}\n\n/**\n * An invalid or malformed message was encountered during a protocol exchange\n */\nexport class InvalidMessageError extends Error {\n static name = 'InvalidMessageError'\n\n constructor (message = 'Invalid message') {\n super(message)\n this.name = 'InvalidMessageError'\n }\n}\n\n/**\n * Thrown when a remote peer sends a structurally valid message that does not\n * comply with the protocol\n */\nexport class ProtocolError extends Error {\n static name = 'ProtocolError'\n\n constructor (message = 'Protocol error') {\n super(message)\n this.name = 'ProtocolError'\n }\n}\n\n/**\n * Throw when an operation times out\n */\nexport class TimeoutError extends Error {\n static name = 'TimeoutError'\n\n constructor (message = 'Timed out') {\n super(message)\n this.name = 'TimeoutError'\n }\n}\n\n/**\n * Thrown when a startable component is interacted with but it has not been\n * started yet\n */\nexport class NotStartedError extends Error {\n static name = 'NotStartedError'\n\n constructor (message = 'Not started') {\n super(message)\n this.name = 'NotStartedError'\n }\n}\n\n/**\n * Thrown when a component is started that has already been started\n */\nexport class AlreadyStartedError extends Error {\n static name = 'AlreadyStartedError'\n\n constructor (message = 'Already started') {\n super(message)\n this.name = 'AlreadyStartedError'\n }\n}\n\n/**\n * Thrown when dialing an address failed\n */\nexport class DialError extends Error {\n static name = 'DialError'\n\n constructor (message = 'Dial error') {\n super(message)\n this.name = 'DialError'\n }\n}\n\n/**\n * Thrown when listening on an address failed\n */\nexport class ListenError extends Error {\n static name = 'ListenError'\n\n constructor (message = 'Listen error') {\n super(message)\n this.name = 'ListenError'\n }\n}\n\n/**\n * This error is thrown when a limited connection is encountered, i.e. if the\n * user tried to open a stream on a connection for a protocol that is not\n * configured to run over limited connections.\n */\nexport class LimitedConnectionError extends Error {\n static name = 'LimitedConnectionError'\n\n constructor (message = 'Limited connection') {\n super(message)\n this.name = 'LimitedConnectionError'\n }\n}\n\n/**\n * This error is thrown where there are too many inbound protocols streams open\n */\nexport class TooManyInboundProtocolStreamsError extends Error {\n static name = 'TooManyInboundProtocolStreamsError'\n\n constructor (message = 'Too many inbound protocol streams') {\n super(message)\n this.name = 'TooManyInboundProtocolStreamsError'\n }\n}\n\n/**\n * This error is thrown where there are too many outbound protocols streams open\n */\nexport class TooManyOutboundProtocolStreamsError extends Error {\n static name = 'TooManyOutboundProtocolStreamsError'\n\n constructor (message = 'Too many outbound protocol streams') {\n super(message)\n this.name = 'TooManyOutboundProtocolStreamsError'\n }\n}\n\n/**\n * Thrown when an attempt to operate on an unsupported key was made\n */\nexport class UnsupportedKeyTypeError extends Error {\n static name = 'UnsupportedKeyTypeError'\n\n constructor (message = 'Unsupported key type') {\n super(message)\n this.name = 'UnsupportedKeyTypeError'\n }\n}\n\n/**\n * Thrown when an operation has not been implemented\n */\nexport class NotImplementedError extends Error {\n static name = 'NotImplementedError'\n\n constructor (message = 'Not implemented') {\n super(message)\n this.name = 'NotImplementedError'\n }\n}\n", "/**\n * @packageDocumentation\n *\n * Exports a `Libp2p` type for modules to use as a type argument.\n *\n * @example\n *\n * ```typescript\n * import type { Libp2p } from '@libp2p/interface'\n *\n * function doSomethingWithLibp2p (node: Libp2p) {\n * // ...\n * }\n * ```\n */\n\nimport type { Connection, NewStreamOptions, Stream } from './connection.js'\nimport type { ContentRouting } from './content-routing.js'\nimport type { Ed25519PublicKey, PublicKey, RSAPublicKey, Secp256k1PublicKey } from './keys.js'\nimport type { Metrics } from './metrics.js'\nimport type { Ed25519PeerId, PeerId, RSAPeerId, Secp256k1PeerId, URLPeerId } from './peer-id.js'\nimport type { PeerInfo } from './peer-info.js'\nimport type { PeerRouting } from './peer-routing.js'\nimport type { Address, Peer, PeerStore } from './peer-store.js'\nimport type { Startable } from './startable.js'\nimport type { StreamHandler, StreamHandlerOptions } from './stream-handler.js'\nimport type { Topology } from './topology.js'\nimport type { Listener, OutboundConnectionUpgradeEvents } from './transport.js'\nimport type { DNS } from '@multiformats/dns'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { TypedEventTarget } from 'main-event'\nimport type { ProgressOptions, ProgressEvent } from 'progress-events'\n\n/**\n * Used by the connection manager to sort addresses into order before dialling\n */\nexport interface AddressSorter {\n (a: Address, b: Address): -1 | 0 | 1\n}\n\n/**\n * Event detail emitted when peer data changes\n */\nexport interface PeerUpdate {\n peer: Peer\n previous?: Peer\n}\n\n/**\n * Peer data signed by the remote Peer's public key\n */\nexport interface SignedPeerRecord {\n addresses: Multiaddr[]\n seq: bigint\n}\n\n/**\n * A certificate that can be used to secure connections\n */\nexport interface TLSCertificate {\n /**\n * The private key that corresponds to the certificate in PEM format\n */\n key: string\n\n /**\n * The certificate chain in PEM format\n */\n cert: string\n}\n\n/**\n * Data returned from a successful identify response\n */\nexport interface IdentifyResult {\n /**\n * The remote Peer's PeerId\n */\n peerId: PeerId\n\n /**\n * The unsigned addresses they are listening on. Note - any multiaddrs present\n * in the signed peer record should be preferred to the value here.\n */\n listenAddrs: Multiaddr[]\n\n /**\n * The protocols the remote peer supports\n */\n protocols: string[]\n\n /**\n * The remote protocol version\n */\n protocolVersion?: string\n\n /**\n * The remote agent version\n */\n agentVersion?: string\n\n /**\n * The public key part of the remote PeerId - this is only useful for older\n * RSA-based PeerIds, the more modern Ed25519 and secp256k1 types have the\n * public key embedded in them\n */\n publicKey?: Uint8Array\n\n /**\n * If set this is the address that the remote peer saw the identify request\n * originate from\n */\n observedAddr?: Multiaddr\n\n /**\n * If sent by the remote peer this is the deserialized signed peer record\n */\n signedPeerRecord?: SignedPeerRecord\n\n /**\n * The connection that the identify protocol ran over\n */\n connection: Connection\n}\n\n/**\n * Logger component for libp2p\n */\nexport interface Logger {\n /**\n * Log a message\n */\n (formatter: any, ...args: any[]): void\n\n /**\n * Log an error message\n */\n error(formatter: any, ...args: any[]): void\n\n /**\n * Log a trace message\n */\n trace(formatter: any, ...args: any[]): void\n\n /**\n * `true` if this logger is enabled\n */\n enabled: boolean\n\n /**\n * Create a logger scoped below this one\n *\n * @example\n *\n * ```ts\n * import { defaultLogger } from '@libp2p/logger'\n *\n * const log = defaultLogger().forComponent('foo')\n *\n * log('hello')\n * // foo hello\n *\n * const subLog = log.newScope('bar')\n *\n * subLog('hello')\n * // foo:bar hello\n * ```\n */\n newScope(name: string): Logger\n}\n\n/**\n * Peer logger component for libp2p. This can be used to create loggers that are\n * scoped to individual system components or services.\n *\n * To see logs, run your app with `DEBUG` set as an env var or for browsers, in\n * `localStorage`:\n *\n * ```console\n * $ DEBUG=libp2p* node index.js\n * libp2p:my-service hello +0ms\n * ```\n */\nexport interface ComponentLogger {\n /**\n * Returns a logger for the specified component.\n *\n * @example\n *\n * ```TypeScript\n * import { ComponentLogger, Logger } from '@libp2p/interface'\n *\n * interface MyServiceComponents {\n * logger: ComponentLogger\n * }\n *\n * class MyService {\n * private readonly log: Logger\n *\n * constructor (components) {\n * this.log = components.logger.forComponent('libp2p:my-service')\n *\n * this.log('hello')\n * // logs:\n * // libp2p:my-service hello +0ms\n * }\n * }\n * ```\n */\n forComponent(name: string): Logger\n}\n\nexport interface MultiaddrResolveOptions extends AbortOptions, LoggerOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n}\n\n/**\n * `MultiaddrResolver`s perform resolution of multiaddr components that require\n * translation by external systems (for example DNSADDR to TXT records).\n */\nexport interface MultiaddrResolver {\n /**\n * Returns true if this resolver can resolve components of this multiaddr\n */\n canResolve (address: Multiaddr): boolean\n\n /**\n * Returns one or more multiaddrs with components resolved to other values\n */\n resolve (address: Multiaddr, options: MultiaddrResolveOptions): Promise<Multiaddr[]>\n}\n\n/**\n * Once you have a libp2p instance, you can listen to several events it emits,\n * so that you can be notified of relevant network events.\n *\n * Event names are `noun:verb` so the first part is the name of the object\n * being acted on and the second is the action.\n */\nexport interface Libp2pEvents<T extends ServiceMap = ServiceMap> {\n /**\n * This event is dispatched when a new network peer is discovered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:discovery', (event) => {\n * const peerInfo = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:discovery': CustomEvent<PeerInfo>\n\n /**\n * This event will be triggered any time a new peer connects.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:connect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:connect': CustomEvent<PeerId>\n\n /**\n * This event will be triggered any time we are disconnected from another\n * peer, regardless of the circumstances of that disconnection. If we happen\n * to have multiple connections to a peer, this event will **only** be\n * triggered when the last connection is closed.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:disconnect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:disconnect': CustomEvent<PeerId>\n\n /**\n * When a peer tagged with `keep-alive` disconnects, we will make multiple\n * attempts to reconnect to it with a backoff factor (see the connection\n * manager settings for details). If these all fail, the `keep-alive` tag will\n * be removed and this event will be emitted.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:reconnect-failure', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:reconnect-failure': CustomEvent<PeerId>\n\n /**\n * This event is dispatched after a remote peer has successfully responded to\n * the identify protocol. Note that for this to be emitted, both peers must\n * have an identify service configured.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:identify', (event) => {\n * const identifyResult = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:identify': CustomEvent<IdentifyResult>\n\n /**\n * This event is dispatched when the peer store data for a peer has been\n * updated - e.g. their multiaddrs, protocols etc have changed.\n *\n * If they were previously known to this node, the old peer data will be\n * set in the `previous` field.\n *\n * This may be in response to the identify protocol running, a manual\n * update or some other event.\n */\n 'peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when the current node's peer record changes -\n * for example a transport started listening on a new address or a new\n * protocol handler was registered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('self:peer:update', (event) => {\n * const { peer } = event.detail\n * // ...\n * })\n * ```\n */\n 'self:peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when a transport begins listening on a new address\n */\n 'transport:listening': CustomEvent<Listener>\n\n /**\n * This event is dispatched when a transport stops listening on an address\n */\n 'transport:close': CustomEvent<Listener>\n\n /**\n * This event is dispatched when the connection manager has more than the\n * configured allowable max connections and has closed some connections to\n * bring the node back under the limit.\n */\n 'connection:prune': CustomEvent<Connection[]>\n\n /**\n * This event notifies listeners when new incoming or outgoing connections\n * are opened.\n */\n 'connection:open': CustomEvent<Connection>\n\n /**\n * This event notifies listeners when incoming or outgoing connections are\n * closed.\n */\n 'connection:close': CustomEvent<Connection>\n\n /**\n * This event notifies listeners that a TLS certificate is available for use\n */\n 'certificate:provision': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that a new TLS certificate is available for\n * use. Any previous certificate may no longer be valid.\n */\n 'certificate:renew': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that the node has started\n *\n * ```TypeScript\n * libp2p.addEventListener('start', (event) => {\n * console.info(libp2p.isStarted()) // true\n * })\n * ```\n */\n start: CustomEvent<Libp2p<T>>\n\n /**\n * This event notifies listeners that the node has stopped\n *\n * ```TypeScript\n * libp2p.addEventListener('stop', (event) => {\n * console.info(libp2p.isStarted()) // false\n * })\n * ```\n */\n stop: CustomEvent<Libp2p<T>>\n}\n\n/**\n * A map of user defined services available on the libp2p node via the\n * `services` key\n *\n * @example\n *\n * ```TypeScript\n * const node = await createLibp2p({\n * // ...other options\n * services: {\n * myService: myService({\n * // ...service options\n * })\n * }\n * })\n *\n * // invoke methods on the service\n * node.services.myService.anOperation()\n * ```\n */\nexport type ServiceMap = Record<string, unknown>\n\nexport type PendingDialStatus = 'queued' | 'active' | 'error' | 'success'\n\n/**\n * An item in the dial queue\n */\nexport interface PendingDial {\n /**\n * A unique identifier for this dial\n */\n id: string\n\n /**\n * The current status of the dial\n */\n status: PendingDialStatus\n\n /**\n * If known, this is the peer id that libp2p expects to be dialling\n */\n peerId?: PeerId\n\n /**\n * The list of multiaddrs that will be dialled. The returned connection will\n * use the first address that succeeds, all other dials part of this pending\n * dial will be cancelled.\n */\n multiaddrs: Multiaddr[]\n}\n\nexport type Libp2pStatus = 'starting' | 'started' | 'stopping' | 'stopped'\n\nexport interface IsDialableOptions extends AbortOptions {\n /**\n * If the dial attempt would open a protocol, and the multiaddr being dialed\n * is a circuit relay address, passing true here would cause the test to fail\n * because that protocol would not be allowed to run over a data/time limited\n * connection.\n */\n runOnLimitedConnection?: boolean\n}\n\nexport type TransportManagerDialProgressEvents =\n ProgressEvent<'transport-manager:selected-transport', string>\n\nexport type OpenConnectionProgressEvents =\n TransportManagerDialProgressEvents |\n ProgressEvent<'dial-queue:already-connected'> |\n ProgressEvent<'dial-queue:already-in-dial-queue'> |\n ProgressEvent<'dial-queue:add-to-dial-queue'> |\n ProgressEvent<'dial-queue:start-dial'> |\n ProgressEvent<'dial-queue:calculated-addresses', Address[]> |\n OutboundConnectionUpgradeEvents\n\nexport interface DialOptions extends AbortOptions, ProgressOptions {\n /**\n * If true, open a new connection to the remote even if one already exists\n */\n force?: boolean\n}\n\nexport interface DialProtocolOptions extends NewStreamOptions {\n\n}\n\n/**\n * Libp2p nodes implement this interface.\n */\nexport interface Libp2p<T extends ServiceMap = ServiceMap> extends Startable, TypedEventTarget<Libp2pEvents<T>> {\n /**\n * The PeerId is a unique identifier for a node on the network.\n *\n * It is the hash of an RSA public key or, for Ed25519 or secp256k1 keys,\n * the key itself.\n *\n * @example\n *\n * ```TypeScript\n * console.info(libp2p.peerId)\n * // PeerId(12D3Foo...)\n * ````\n */\n peerId: PeerId\n\n /**\n * The peer store holds information we know about other peers on the network.\n * - multiaddrs, supported protocols, etc.\n *\n * @example\n *\n * ```TypeScript\n * const peer = await libp2p.peerStore.get(peerId)\n * console.info(peer)\n * // { id: PeerId(12D3Foo...), addresses: [] ... }\n * ```\n */\n peerStore: PeerStore\n\n /**\n * The peer routing subsystem allows the user to find peers on the network\n * or to find peers close to binary keys.\n *\n * @example\n *\n * ```TypeScript\n * const peerInfo = await libp2p.peerRouting.findPeer(peerId)\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * ```\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.peerRouting.getClosestPeers(key)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n peerRouting: PeerRouting\n\n /**\n * The content routing subsystem allows the user to find providers for content,\n * let the network know they are providers for content, and get/put values to\n * the DHT.\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.contentRouting.findProviders(cid)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n contentRouting: ContentRouting\n\n /**\n * The metrics subsystem allows recording values to assess the health/performance\n * of the running node.\n *\n * @example\n *\n * ```TypeScript\n * const metric = libp2p.metrics.registerMetric({\n * 'my-metric'\n * })\n *\n * // later\n * metric.update(5)\n * ```\n */\n metrics?: Metrics\n\n /**\n * The logger used by this libp2p node\n */\n logger: ComponentLogger\n\n /**\n * The current status of the libp2p node\n */\n status: Libp2pStatus\n\n /**\n * Get a deduplicated list of peer advertising multiaddrs by concatenating\n * the listen addresses used by transports with any configured\n * announce addresses as well as observed addresses reported by peers.\n *\n * If Announce addrs are specified, configured listen addresses will be\n * ignored though observed addresses will still be included.\n *\n * @example\n *\n * ```TypeScript\n * const listenMa = libp2p.getMultiaddrs()\n * // [ <Multiaddr 047f00000106f9ba - /ip4/127.0.0.1/tcp/63930> ]\n * ```\n */\n getMultiaddrs(): Multiaddr[]\n\n /**\n * Returns a list of supported protocols\n *\n * @example\n *\n * ```TypeScript\n * const protocols = libp2p.getProtocols()\n * // [ '/ipfs/ping/1.0.0', '/ipfs/id/1.0.0' ]\n * ```\n */\n getProtocols(): string[]\n\n /**\n * Return a list of all connections this node has open, optionally filtering\n * by a PeerId\n *\n * @example\n *\n * ```TypeScript\n * for (const connection of libp2p.getConnections()) {\n * console.log(peerId, connection.remoteAddr.toString())\n * // Logs the PeerId string and the observed remote multiaddr of each Connection\n * }\n * ```\n */\n getConnections(peerId?: PeerId): Connection[]\n\n /**\n * Return the list of dials currently in progress or queued to start\n *\n * @example\n *\n * ```TypeScript\n * for (const pendingDial of libp2p.getDialQueue()) {\n * console.log(pendingDial)\n * }\n * ```\n */\n getDialQueue(): PendingDial[]\n\n /**\n * Return a list of all peers we currently have a connection open to\n */\n getPeers(): PeerId[]\n\n /**\n * Dials to the provided peer. If successful, the known metadata of the\n * peer will be added to the nodes `peerStore`.\n *\n * If a PeerId is passed as the first argument, the peer will need to have known multiaddrs for it in the PeerStore.\n *\n * @example\n *\n * ```TypeScript\n * const conn = await libp2p.dial(remotePeerId)\n *\n * // create a new stream within the connection\n * const stream = await conn.newStream(['/echo/1.1.0', '/echo/1.0.0'])\n *\n * // protocol negotiated: 'echo/1.0.0' means that the other party only supports the older version\n *\n * // ...\n * await conn.close()\n * ```\n */\n dial(peer: PeerId | Multiaddr | Multiaddr[], options?: DialOptions): Promise<Connection>\n\n /**\n * Dials to the provided peer and tries to handshake with the given protocols in order.\n * If successful, the known metadata of the peer will be added to the nodes `peerStore`,\n * and the `MuxedStream` will be returned together with the successful negotiated protocol.\n *\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n *\n * const { stream, protocol } = await libp2p.dialProtocol(remotePeerId, protocols)\n *\n * // Use this new stream like any other duplex stream\n * pipe([1, 2, 3], stream, consume)\n * ```\n */\n dialProtocol(peer: PeerId | Multiaddr | Multiaddr[], protocols: string | string[], options?: DialProtocolOptions): Promise<Stream>\n\n /**\n * Attempts to gracefully close an open connection to the given peer. If the\n * connection is not closed in the grace period, it will be forcefully closed.\n *\n * An AbortSignal can optionally be passed to control when the connection is\n * forcefully closed.\n *\n * @example\n *\n * ```TypeScript\n * await libp2p.hangUp(remotePeerId)\n * ```\n */\n hangUp(peer: PeerId | Multiaddr, options?: AbortOptions): Promise<void>\n\n /**\n * Sets up [multistream-select routing](https://github.com/multiformats/multistream-select) of protocols to their application handlers. Whenever a stream is opened on one of the provided protocols, the handler will be called. `handle` must be called in order to register a handler and support for a given protocol. This also informs other peers of the protocols you support.\n *\n * `libp2p.handle(protocols, handler, options)`\n *\n * In the event of a new handler for the same protocol being added and error\n * will be thrown. Pass `force: true` to override this.\n *\n * @example\n *\n * ```TypeScript\n * const handler = ({ connection, stream, protocol }) => {\n * // use stream or connection according to the needs\n * }\n *\n * libp2p.handle('/echo/1.0.0', handler, {\n * maxInboundStreams: 5,\n * maxOutboundStreams: 5\n * })\n * ```\n */\n handle(protocol: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise<void>\n\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.unhandle(['/echo/1.0.0'])\n * ```\n */\n unhandle(protocols: string[] | string, options?: AbortOptions): Promise<void>\n\n /**\n * Register a topology to be informed when peers are encountered that\n * support the specified protocol\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register('/echo/1.0.0', {\n * onConnect: (peer, connection) => {\n * // handle connect\n * },\n * onDisconnect: (peer, connection) => {\n * // handle disconnect\n * }\n * })\n * ```\n */\n register(protocol: string, topology: Topology, options?: AbortOptions): Promise<string>\n\n /**\n * Unregister topology to no longer be informed when peers connect or\n * disconnect.\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register(...)\n *\n * libp2p.unregister(id)\n * ```\n */\n unregister(id: string): void\n\n /**\n * Returns the public key for the passed PeerId. If the PeerId is of the 'RSA'\n * type this may mean searching the routing if the peer's key is not present\n * in the peer store.\n */\n getPublicKey(peer: Ed25519PeerId, options?: AbortOptions): Promise<Ed25519PublicKey>\n getPublicKey(peer: Secp256k1PeerId, options?: AbortOptions): Promise<Secp256k1PublicKey>\n getPublicKey(peer: RSAPeerId, options?: AbortOptions): Promise<RSAPublicKey>\n getPublicKey(peer: URLPeerId, options?: AbortOptions): Promise<never>\n getPublicKey(peer: PeerId, options?: AbortOptions): Promise<PublicKey>\n\n /**\n * Given the current node configuration, returns a promise of `true` or\n * `false` if the node would attempt to dial the passed multiaddr.\n *\n * This means a relevant transport is configured, and the connection gater\n * would not block the dial attempt.\n *\n * This may involve resolving DNS addresses so you should pass an AbortSignal.\n */\n isDialable(multiaddr: Multiaddr | Multiaddr[], options?: IsDialableOptions): Promise<boolean>\n\n /**\n * A set of user defined services\n */\n services: T\n}\n\n/**\n * Metadata about the current node\n */\nexport interface NodeInfo {\n /**\n * The implementation name\n */\n name: string\n\n /**\n * The implementation version\n */\n version: string\n\n /**\n * A string that contains information about the implementation and runtime\n */\n userAgent: string\n}\n\n/**\n * An object that contains an AbortSignal as\n * the optional `signal` property.\n *\n * @example\n *\n * ```TypeScript\n * const controller = new AbortController()\n *\n * aLongRunningOperation({\n * signal: controller.signal\n * })\n *\n * // later\n *\n * controller.abort()\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * An object that contains a Logger as the `log` property.\n */\nexport interface LoggerOptions {\n log: Logger\n}\n\n/**\n * An object that includes a trace object that is passed onwards.\n *\n * This is used by metrics method tracing to link function calls together.\n */\nexport interface TraceOptions {\n trace?: any\n}\n\n/**\n * A signal that needs to be cleared when no longer in use\n */\nexport interface ClearableSignal extends AbortSignal {\n clear(): void\n}\n\n/**\n * When a routing operation involves reading values, these options allow\n * controlling where the values are read from. By default libp2p will check\n * local caches but may not use the network if a valid local value is found,\n * these options allow tuning that behavior.\n */\nexport interface RoutingOptions extends AbortOptions, ProgressOptions, TraceOptions {\n /**\n * Pass `false` to not use the network\n *\n * @default true\n */\n useNetwork?: boolean\n\n /**\n * Pass `false` to not use cached values\n *\n * @default true\n */\n useCache?: boolean\n}\n\n/**\n * This symbol is used by libp2p services to define the capabilities they can\n * provide to other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of provided capabilities.\n */\nexport const serviceCapabilities = Symbol.for('@libp2p/service-capabilities')\n\n/**\n * This symbol is used by libp2p services to define the capabilities they\n * require from other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of required capabilities.\n */\nexport const serviceDependencies = Symbol.for('@libp2p/service-dependencies')\n\nexport * from './connection.js'\nexport * from './connection-encrypter.js'\nexport * from './connection-gater.js'\nexport * from './content-routing.js'\nexport * from './keys.js'\nexport * from './metrics.js'\nexport * from './peer-discovery.js'\nexport * from './peer-id.js'\nexport * from './peer-info.js'\nexport * from './peer-routing.js'\nexport * from './peer-store.js'\nexport * from './pubsub.js'\nexport * from './record.js'\nexport * from './stream-handler.js'\nexport * from './stream-muxer.js'\nexport * from './topology.js'\nexport * from './transport.js'\nexport * from './errors.js'\nexport * from 'main-event'\nexport * from './startable.js'\n", "/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n", "/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n", "import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n", "/**\n * @packageDocumentation\n *\n * A class that lets you do operations over a list of Uint8Arrays without\n * copying them.\n *\n * ```js\n * import { Uint8ArrayList } from 'uint8arraylist'\n *\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray()\n * // -> Uint8Array([0, 1, 2, 3, 4, 5])\n *\n * list.consume(3)\n * list.subarray()\n * // -> Uint8Array([3, 4, 5])\n *\n * // you can also iterate over the list\n * for (const buf of list) {\n * // ..do something with `buf`\n * }\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ## Converting Uint8ArrayLists to Uint8Arrays\n *\n * There are two ways to turn a `Uint8ArrayList` into a `Uint8Array` - `.slice` and `.subarray` and one way to turn a `Uint8ArrayList` into a `Uint8ArrayList` with different contents - `.sublist`.\n *\n * ### slice\n *\n * Slice follows the same semantics as [Uint8Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice) in that it creates a new `Uint8Array` and copies bytes into it using an optional offset & length.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.slice(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ### subarray\n *\n * Subarray attempts to follow the same semantics as [Uint8Array.subarray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray) with one important different - this is a no-copy operation, unless the requested bytes span two internal buffers in which case it is a copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0]) - no-copy\n *\n * list.subarray(2, 5)\n * // -> Uint8Array([2, 3, 4]) - copy\n * ```\n *\n * ### sublist\n *\n * Sublist creates and returns a new `Uint8ArrayList` that shares the underlying buffers with the original so is always a no-copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.sublist(0, 1)\n * // -> Uint8ArrayList([0]) - no-copy\n *\n * list.sublist(2, 5)\n * // -> Uint8ArrayList([2], [3, 4]) - no-copy\n * ```\n *\n * ## Inspiration\n *\n * Borrows liberally from [bl](https://www.npmjs.com/package/bl) but only uses native JS types.\n */\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc'\nimport { concat } from 'uint8arrays/concat'\nimport { equals } from 'uint8arrays/equals'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\nexport type Appendable = Uint8ArrayList | Uint8Array\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number): { buf: Uint8Array, index: number } {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\n\n/**\n * Check if object is a CID instance\n *\n * @example\n *\n * ```js\n * import { isUint8ArrayList, Uint8ArrayList } from 'uint8arraylist'\n *\n * isUint8ArrayList(true) // false\n * isUint8ArrayList([]) // false\n * isUint8ArrayList(new Uint8ArrayList()) // true\n * ```\n */\nexport function isUint8ArrayList (value: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList implements Iterable<Uint8Array> {\n private bufs: Uint8Array[]\n public length: number\n public readonly [symbol] = true\n\n constructor (...data: Appendable[]) {\n this.bufs = []\n this.length = 0\n\n if (data.length > 0) {\n this.appendAll(data)\n }\n }\n\n * [Symbol.iterator] (): Iterator<Uint8Array> {\n yield * this.bufs\n }\n\n get byteLength (): number {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append (...bufs: Appendable[]): void {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.push(...buf.bufs)\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend (...bufs: Appendable[]): void {\n this.prependAll(bufs)\n }\n\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.unshift(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.unshift(...buf.bufs)\n } else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number): number {\n const res = findBufAndOffset(this.bufs, index)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number): void {\n const res = findBufAndOffset(this.bufs, index)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable, offset: number = 0): void {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\n }\n } else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i))\n }\n } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number): void {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = []\n this.length = 0\n return\n }\n\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength\n this.length -= this.bufs[0].byteLength\n this.bufs.shift()\n } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\n }\n }\n\n /**\n * Extracts a section of an array and returns a new array.\n *\n * This is a copy operation as it is with Uint8Arrays and Arrays\n * - note this is different to the behaviour of Node Buffers.\n */\n slice (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a alloc from the given start and end element index.\n *\n * In the best case where the data extracted comes from a single Uint8Array\n * internally this is a no-copy operation otherwise it is a copy operation.\n */\n subarray (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a allocList from the given start and end element index.\n *\n * This is a no-copy operation.\n */\n sublist (beginInclusive?: number, endExclusive?: number): Uint8ArrayList {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList()\n list.length = length\n // don't loop, just set the bufs\n list.bufs = [...bufs]\n\n return list\n }\n\n private _subList (beginInclusive?: number, endExclusive?: number): { bufs: Uint8Array[], length: number } {\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? this.length\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: this.bufs, length: this.length }\n }\n\n const bufs: Uint8Array[] = []\n let offset = 0\n\n for (let i = 0; i < this.bufs.length; i++) {\n const buf = this.bufs[i]\n const bufStart = offset\n const bufEnd = bufStart + buf.byteLength\n\n // for next loop\n offset = bufEnd\n\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue\n }\n\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n\n if (sliceStartInBuf && sliceEndsInBuf) {\n // slice is wholly contained within this buffer\n if (beginInclusive === bufStart && endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n const start = beginInclusive - bufStart\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)))\n break\n }\n\n if (sliceStartInBuf) {\n // slice starts in this buffer\n if (beginInclusive === 0) {\n // requested whole buffer\n bufs.push(buf)\n continue\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart))\n continue\n }\n\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart))\n break\n }\n\n // slice started before this buffer and ends after it\n bufs.push(buf)\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n indexOf (search: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array')\n }\n\n const needle = search instanceof Uint8Array ? search : search.subarray()\n\n offset = Number(offset ?? 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M: number = needle.byteLength\n\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long')\n }\n\n // radix\n const radix: number = 256\n const rightmostPositions: Int32Array = new Int32Array(radix)\n\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c: number = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1\n }\n\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j\n }\n\n // Return offset of first match, -1 if no match\n const right = rightmostPositions\n const lastIndex = this.byteLength - needle.byteLength\n const lastPatIndex = needle.byteLength - 1\n let skip: number\n\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0\n\n for (let j = lastPatIndex; j >= 0; j--) {\n const char: number = this.get(i + j)\n\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char])\n break\n }\n }\n\n if (skip === 0) {\n return i\n }\n }\n\n return -1\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n equals (other: any): other is Uint8ArrayList {\n if (other == null) {\n return false\n }\n\n if (!(other instanceof Uint8ArrayList)) {\n return false\n }\n\n if (other.bufs.length !== this.bufs.length) {\n return false\n }\n\n for (let i = 0; i < this.bufs.length; i++) {\n if (!equals(this.bufs[i], other.bufs[i])) {\n return false\n }\n }\n\n return true\n }\n\n /**\n * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this\n * method if you know the total size of all the Uint8Arrays ahead of time.\n */\n static fromUint8Arrays (bufs: Uint8Array[], length?: number): Uint8ArrayList {\n const list = new Uint8ArrayList()\n list.bufs = bufs\n\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0)\n }\n\n list.length = length\n\n return list\n }\n}\n\n/*\nfunction indexOf (needle: Uint8Array, haystack: Uint8Array, offset = 0) {\n for (let i = offset; i < haystack.byteLength; i++) {\n for (let j = 0; j < needle.length; j++) {\n if (haystack[i + j] !== needle[j]) {\n break\n }\n\n if (j === needle.byteLength -1) {\n return i\n }\n }\n\n if (haystack.byteLength - i < needle.byteLength) {\n break\n }\n }\n\n return -1\n}\n*/\n", "/**\n * Internal webcrypto alias.\n * We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n * See utils.ts for details.\n * @module\n */\ndeclare const globalThis: Record<string, any> | undefined;\nexport const crypto: any =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n abstract clone(): T;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash function */\nexport type CHash = ReturnType<typeof createHasher>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof createOptHasher>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof createXOFer>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function createOptHasher<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): Hash<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\n\nexport function createXOFer<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): HashXOF<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport { randomBytes as randB } from '@noble/hashes/utils'\n\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes (length: number): Uint8Array {\n if (isNaN(length) || length <= 0) {\n throw new InvalidParametersError('random bytes length must be a Number bigger than 0')\n }\n return randB(length)\n}\n", "export default function pDefer() {\n\tconst deferred = {};\n\n\tdeferred.promise = new Promise((resolve, reject) => {\n\t\tdeferred.resolve = resolve;\n\t\tdeferred.reject = reject;\n\t});\n\n\treturn deferred;\n}\n", "/**\n * An abort error class that extends error\n */\nexport class AbortError extends Error {\n public type: string\n public code: string | string\n\n constructor (message?: string, code?: string, name?: string) {\n super(message ?? 'The operation was aborted')\n this.type = 'aborted'\n this.name = name ?? 'AbortError'\n this.code = code ?? 'ABORT_ERR'\n }\n}\n\nexport interface RaceSignalOptions {\n /**\n * The message for the error thrown if the signal aborts\n */\n errorMessage?: string\n\n /**\n * The code for the error thrown if the signal aborts\n */\n errorCode?: string\n\n /**\n * The name for the error thrown if the signal aborts\n */\n errorName?: string\n}\n\n/**\n * Race a promise against an abort signal\n */\nexport async function raceSignal <T> (promise: Promise<T>, signal?: AbortSignal, opts?: RaceSignalOptions): Promise<T> {\n if (signal == null) {\n return promise\n }\n\n if (signal.aborted) {\n // the passed promise may yet resolve or reject but the use has signalled\n // they are no longer interested so smother the error\n promise.catch(() => {})\n return Promise.reject(new AbortError(opts?.errorMessage, opts?.errorCode, opts?.errorName))\n }\n\n let listener\n\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage, opts?.errorCode, opts?.errorName)\n\n try {\n return await Promise.race([\n promise,\n new Promise<T>((resolve, reject) => {\n listener = () => {\n reject(error)\n }\n signal.addEventListener('abort', listener)\n })\n ])\n } finally {\n if (listener != null) {\n signal.removeEventListener('abort', listener)\n }\n }\n}\n", "/**\n * @packageDocumentation\n *\n * A pushable async generator that waits until the current value is consumed\n * before allowing a new value to be pushed.\n *\n * Useful for when you don't want to keep memory usage under control and/or\n * allow a downstream consumer to dictate how fast data flows through a pipe,\n * but you want to be able to apply a transform to that data.\n *\n * @example\n *\n * ```typescript\n * import { queuelessPushable } from 'it-queueless-pushable'\n *\n * const pushable = queuelessPushable<string>()\n *\n * // run asynchronously\n * Promise.resolve().then(async () => {\n * // push a value - the returned promise will not resolve until the value is\n * // read from the pushable\n * await pushable.push('hello')\n * })\n *\n * // read a value\n * const result = await pushable.next()\n * console.info(result) // { done: false, value: 'hello' }\n * ```\n */\n\nimport deferred from 'p-defer'\nimport { raceSignal } from 'race-signal'\nimport type { AbortOptions } from 'abort-error'\nimport type { RaceSignalOptions } from 'race-signal'\n\nexport interface Pushable<T> extends AsyncGenerator<T, void, unknown> {\n /**\n * End the iterable after all values in the buffer (if any) have been yielded. If an\n * error is passed the buffer is cleared immediately and the next iteration will\n * throw the passed error\n */\n end(err?: Error, options?: AbortOptions & RaceSignalOptions): Promise<void>\n\n /**\n * Push a value into the iterable. Values are yielded from the iterable in the order\n * they are pushed. Values not yet consumed from the iterable are buffered.\n */\n push(value: T, options?: AbortOptions & RaceSignalOptions): Promise<void>\n}\n\nclass QueuelessPushable <T> implements Pushable<T> {\n private readNext: PromiseWithResolvers<void>\n private haveNext: PromiseWithResolvers<void>\n private ended: boolean\n private nextResult: IteratorResult<T> | undefined\n private error?: Error\n\n constructor () {\n this.ended = false\n\n this.readNext = deferred()\n this.haveNext = deferred()\n }\n\n [Symbol.asyncIterator] (): AsyncGenerator<T, void, unknown> {\n return this\n }\n\n async next (): Promise<IteratorResult<T, void>> {\n if (this.nextResult == null) {\n // wait for the supplier to push a value\n await this.haveNext.promise\n }\n\n if (this.nextResult == null) {\n throw new Error('HaveNext promise resolved but nextResult was undefined')\n }\n\n const nextResult = this.nextResult\n this.nextResult = undefined\n\n // signal to the supplier that we read the value\n this.readNext.resolve()\n this.readNext = deferred()\n\n return nextResult\n }\n\n async throw (err?: Error): Promise<IteratorReturnResult<undefined>> {\n this.ended = true\n this.error = err\n\n if (err != null) {\n // this can cause unhandled promise rejections if nothing is awaiting the\n // next value so attach a dummy catch listener to the promise\n this.haveNext.promise.catch(() => {})\n this.haveNext.reject(err)\n }\n\n const result: IteratorReturnResult<undefined> = {\n done: true,\n value: undefined\n }\n\n return result\n }\n\n async return (): Promise<IteratorResult<T>> {\n const result: IteratorReturnResult<undefined> = {\n done: true,\n value: undefined\n }\n\n this.ended = true\n this.nextResult = result\n\n // let the consumer know we have a new value\n this.haveNext.resolve()\n\n return result\n }\n\n async push (value: T, options?: AbortOptions & RaceSignalOptions): Promise<void> {\n await this._push(value, options)\n }\n\n async end (err?: Error, options?: AbortOptions & RaceSignalOptions): Promise<void> {\n if (err != null) {\n await this.throw(err)\n } else {\n // abortable return\n await this._push(undefined, options)\n }\n }\n\n private async _push (value?: T, options?: AbortOptions & RaceSignalOptions): Promise<void> {\n if (value != null && this.ended) {\n throw this.error ?? new Error('Cannot push value onto an ended pushable')\n }\n\n // wait for all values to be read\n while (this.nextResult != null) {\n await this.readNext.promise\n }\n\n if (value != null) {\n this.nextResult = { done: false, value }\n } else {\n this.ended = true\n this.nextResult = { done: true, value: undefined }\n }\n\n // let the consumer know we have a new value\n this.haveNext.resolve()\n this.haveNext = deferred()\n\n // wait for the consumer to have finished processing the value and requested\n // the next one or for the passed signal to abort the waiting\n await raceSignal(\n this.readNext.promise,\n options?.signal,\n options\n )\n }\n}\n\nexport function queuelessPushable <T> (): Pushable<T> {\n return new QueuelessPushable<T>()\n}\n", "/**\n * The incoming stream ended before the expected number of bytes were read\n */\nexport class UnexpectedEOFError extends Error {\n name = 'UnexpectedEOFError'\n code = 'ERR_UNEXPECTED_EOF'\n}\n", "/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive bytes over streams.\n *\n * @example\n *\n * ```typescript\n * import { byteStream } from 'it-byte-stream'\n *\n * const stream = byteStream(duplex)\n *\n * // read the next chunk\n * const bytes = await stream.read()\n *\n * // read the next five bytes\n * const fiveBytes = await stream.read(5)\n *\n * // write bytes into the stream\n * await stream.write(Uint8Array.from([0, 1, 2, 3, 4]))\n * ```\n */\n\nimport { queuelessPushable } from 'it-queueless-pushable'\nimport { raceSignal } from 'race-signal'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { UnexpectedEOFError } from './errors.js'\nimport type { AbortOptions } from 'abort-error'\nimport type { Duplex } from 'it-stream-types'\n\nexport interface ReadOptions extends AbortOptions {\n bytes: number\n}\n\nexport interface ByteStream <Stream = unknown> {\n /**\n * Read bytes from the stream.\n *\n * If a required number of bytes is passed as an option, this will wait for\n * the underlying stream to supply that number of bytes, throwing an\n * `UnexpectedEOFError` if the stream closes before this happens.\n *\n * If no required number of bytes is passed, this will return `null` if the\n * underlying stream closes before supplying any bytes.\n */\n read(options: ReadOptions): Promise<Uint8ArrayList>\n read(options?: AbortOptions): Promise<Uint8ArrayList | null>\n\n /**\n * Write the passed bytes to the stream\n */\n write(input: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise<void>\n\n /**\n * Returns the underlying stream\n */\n unwrap(): Stream\n}\n\nexport interface ByteStreamOpts {\n /**\n * After the stream is unwrapped, any bytes that have been read from the\n * incoming stream will be yielded in-order as `Uint8Array`(s).\n *\n * To yield a single `Uint8ArrayList` with all unread bytes instead, pass\n * `false` here.\n */\n yieldBytes?: boolean\n}\n\nexport function byteStream <Stream extends Duplex<any, any, any>> (duplex: Stream, opts?: ByteStreamOpts): ByteStream<Stream> {\n const write = queuelessPushable()\n\n duplex.sink(write).catch(async (err: Error) => {\n await write.end(err)\n })\n\n duplex.sink = async (source: any) => {\n for await (const buf of source) {\n await write.push(buf)\n }\n\n await write.end()\n }\n\n let source: AsyncGenerator<any> = duplex.source\n\n if (duplex.source[Symbol.iterator] != null) {\n source = duplex.source[Symbol.iterator]()\n } else if (duplex.source[Symbol.asyncIterator] != null) {\n source = duplex.source[Symbol.asyncIterator]()\n }\n\n const readBuffer = new Uint8ArrayList()\n\n const W: ByteStream<Stream> = {\n read: async (options?: ReadOptions) => {\n options?.signal?.throwIfAborted()\n\n if (options?.bytes == null) {\n // just read whatever arrives\n const { done, value } = await raceSignal(source.next(), options?.signal)\n\n if (done === true) {\n return null\n }\n\n return value\n }\n\n while (readBuffer.byteLength < options.bytes) {\n const { value, done } = await raceSignal(source.next(), options?.signal)\n\n if (done === true) {\n throw new UnexpectedEOFError('unexpected end of input')\n }\n\n readBuffer.append(value)\n }\n\n const buf = readBuffer.sublist(0, options.bytes)\n readBuffer.consume(options.bytes)\n\n return buf\n },\n write: async (data, options?: AbortOptions) => {\n options?.signal?.throwIfAborted()\n\n // just write\n if (data instanceof Uint8Array) {\n await write.push(data, options)\n } else {\n await write.push(data.subarray(), options)\n }\n },\n unwrap: () => {\n if (readBuffer.byteLength > 0) {\n const originalStream = duplex.source\n duplex.source = (async function * () {\n if (opts?.yieldBytes === false) {\n yield readBuffer\n } else {\n yield * readBuffer\n }\n\n yield * originalStream\n }())\n }\n\n return duplex\n }\n }\n\n return W\n}\n", "export const PING_PROTOCOL = '/ipfs/ping/1.0.0'\nexport const PING_LENGTH = 32\nexport const PROTOCOL_VERSION = '1.0.0'\nexport const PROTOCOL_NAME = 'ping'\nexport const PROTOCOL_PREFIX = 'ipfs'\nexport const TIMEOUT = 10000\n\n// See https://github.com/libp2p/specs/blob/d4b5fb0152a6bb86cfd9ea/ping/ping.md?plain=1#L38-L43\n// The dialing peer MUST NOT keep more than one outbound stream for the ping protocol per peer.\n// The listening peer SHOULD accept at most two streams per peer since cross-stream behavior is\n// non-linear and stream writes occur asynchronously. The listening peer may perceive the\n// dialing peer closing and opening the wrong streams (for instance, closing stream B and\n// opening stream A even though the dialing peer is opening stream B and closing stream A).\nexport const MAX_INBOUND_STREAMS = 2\nexport const MAX_OUTBOUND_STREAMS = 1\n", "import { randomBytes } from '@libp2p/crypto'\nimport { ProtocolError, TimeoutError, serviceCapabilities } from '@libp2p/interface'\nimport { byteStream } from 'it-byte-stream'\nimport { setMaxListeners } from 'main-event'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { PROTOCOL_PREFIX, PROTOCOL_NAME, PING_LENGTH, PROTOCOL_VERSION, TIMEOUT, MAX_INBOUND_STREAMS, MAX_OUTBOUND_STREAMS } from './constants.js'\nimport type { PingComponents, PingInit, Ping as PingInterface } from './index.js'\nimport type { AbortOptions, Stream, PeerId, Startable, IncomingStreamData } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\n\nexport class Ping implements Startable, PingInterface {\n public readonly protocol: string\n private readonly components: PingComponents\n private started: boolean\n private readonly timeout: number\n private readonly maxInboundStreams: number\n private readonly maxOutboundStreams: number\n private readonly runOnLimitedConnection: boolean\n\n constructor (components: PingComponents, init: PingInit = {}) {\n this.components = components\n this.started = false\n this.protocol = `/${init.protocolPrefix ?? PROTOCOL_PREFIX}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`\n this.timeout = init.timeout ?? TIMEOUT\n this.maxInboundStreams = init.maxInboundStreams ?? MAX_INBOUND_STREAMS\n this.maxOutboundStreams = init.maxOutboundStreams ?? MAX_OUTBOUND_STREAMS\n this.runOnLimitedConnection = init.runOnLimitedConnection ?? true\n\n this.handleMessage = this.handleMessage.bind(this)\n }\n\n readonly [Symbol.toStringTag] = '@libp2p/ping'\n\n readonly [serviceCapabilities]: string[] = [\n '@libp2p/ping'\n ]\n\n async start (): Promise<void> {\n await this.components.registrar.handle(this.protocol, this.handleMessage, {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams,\n runOnLimitedConnection: this.runOnLimitedConnection\n })\n this.started = true\n }\n\n async stop (): Promise<void> {\n await this.components.registrar.unhandle(this.protocol)\n this.started = false\n }\n\n isStarted (): boolean {\n return this.started\n }\n\n /**\n * A handler to register with Libp2p to process ping messages\n */\n handleMessage (data: IncomingStreamData): void {\n const log = data.connection.log.newScope('ping')\n\n log.trace('ping from %p', data.connection.remotePeer)\n\n const { stream } = data\n const start = Date.now()\n const bytes = byteStream(stream)\n let pinged = false\n\n Promise.resolve().then(async () => {\n while (true) {\n const signal = AbortSignal.timeout(this.timeout)\n setMaxListeners(Infinity, signal)\n signal.addEventListener('abort', () => {\n stream?.abort(new TimeoutError('ping timeout'))\n })\n\n const buf = await bytes.read({\n bytes: PING_LENGTH,\n signal\n })\n await bytes.write(buf, {\n signal\n })\n\n pinged = true\n }\n })\n .catch(err => {\n // ignore the error if we've processed at least one ping, the remote\n // closed the stream and we handled or are handling the close cleanly\n if (pinged && err.name === 'UnexpectedEOFError' && stream.readStatus !== 'ready') {\n return\n }\n\n log.error('ping from %p failed with error - %e', data.connection.remotePeer, err)\n stream?.abort(err)\n })\n .finally(() => {\n const ms = Date.now() - start\n log('ping from %p complete in %dms', data.connection.remotePeer, ms)\n\n const signal = AbortSignal.timeout(this.timeout)\n setMaxListeners(Infinity, signal)\n\n stream.close({\n signal\n })\n .catch(err => {\n log.error('error closing ping stream from %p - %e', data.connection.remotePeer, err)\n stream?.abort(err)\n })\n })\n }\n\n /**\n * Ping a given peer and wait for its response, getting the operation latency.\n */\n async ping (peer: PeerId | Multiaddr | Multiaddr[], options: AbortOptions = {}): Promise<number> {\n const start = Date.now()\n const data = randomBytes(PING_LENGTH)\n const connection = await this.components.connectionManager.openConnection(peer, options)\n const log = connection.log.newScope('ping')\n let stream: Stream | undefined\n\n if (options.signal == null) {\n const signal = AbortSignal.timeout(this.timeout)\n\n options = {\n ...options,\n signal\n }\n }\n\n try {\n stream = await connection.newStream(this.protocol, {\n ...options,\n runOnLimitedConnection: this.runOnLimitedConnection\n })\n\n const bytes = byteStream(stream)\n\n const [, result] = await Promise.all([\n bytes.write(data, options),\n bytes.read({\n ...options,\n bytes: PING_LENGTH\n })\n ])\n\n const ms = Date.now() - start\n\n if (!uint8ArrayEquals(data, result.subarray())) {\n throw new ProtocolError(`Received wrong ping ack after ${ms}ms`)\n }\n\n log('ping %p complete in %dms', connection.remotePeer, ms)\n\n return ms\n } catch (err: any) {\n log.error('error while pinging %p', connection.remotePeer, err)\n\n stream?.abort(err)\n\n throw err\n } finally {\n if (stream != null) {\n await stream.close(options)\n }\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";8bAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,EAAA,SAAAC,ICyCM,IAAOC,EAAP,cAAsC,KAAK,CAC/C,OAAO,KAAO,yBAEd,YAAaC,EAAU,qBAAoB,CACzC,MAAMA,CAAO,EACb,KAAK,KAAO,wBACd,GAuMI,IAAOC,EAAP,cAA6B,KAAK,CACtC,OAAO,KAAO,gBAEd,YAAaC,EAAU,iBAAgB,CACrC,MAAMA,CAAO,EACb,KAAK,KAAO,eACd,GAMWC,EAAP,cAA4B,KAAK,CACrC,OAAO,KAAO,eAEd,YAAaD,EAAU,YAAW,CAChC,MAAMA,CAAO,EACb,KAAK,KAAO,cACd,GC+nBK,IAAME,EAAsB,OAAO,IAAI,8BAA8B,EAS/DC,GAAsB,OAAO,IAAI,8BAA8B,EC74BtE,SAAUC,EAAQC,EAAeC,EAAa,CAClD,GAAID,IAAMC,EACR,MAAO,GAGT,GAAID,EAAE,aAAeC,EAAE,WACrB,MAAO,GAGT,QAASC,EAAI,EAA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MR,GAAU,MACZ,MAAMA,EAAO,MAAMW,CAAO,CAE9B,CACF,GhB7GI,SAAUM,EAAMC,EAAiB,CAAA,EAAE,CACvC,OAAQC,GAAe,IAAIC,EAAUD,EAAYD,CAAI,CACvD",
|
|
6
|
+
"names": ["index_exports", "__export", "PING_PROTOCOL", "ping", "InvalidParametersError", "message", "ProtocolError", "message", "TimeoutError", "serviceCapabilities", "serviceDependencies", "equals", "a", "b", "i", "alloc", "size", "allocUnsafe", "concat", "arrays", "length", "acc", "curr", "output", "allocUnsafe", "offset", "arr", "symbol", "findBufAndOffset", "bufs", "index", "offset", "buf", "bufEnd", "isUint8ArrayList", "value", "Uint8ArrayList", "_Uint8ArrayList", "data", "length", "res", "i", "bytes", "beginInclusive", "endExclusive", "concat", "list", "bufStart", "sliceStartInBuf", "sliceEndsInBuf", "start", "search", "needle", "M", "radix", "rightmostPositions", "j", "right", "lastIndex", "lastPatIndex", "skip", "char", "byteOffset", "allocUnsafe", "littleEndian", "alloc", "other", "equals", "acc", "curr", "crypto", "randomBytes", "bytesLength", "crypto", "randomBytes", "length", "InvalidParametersError", "pDefer", "deferred", "resolve", "reject", "AbortError", "message", "code", "name", "raceSignal", "promise", "signal", "opts", "listener", "error", "resolve", "reject", "QueuelessPushable", "pDefer", "nextResult", "err", "result", "value", "options", "raceSignal", "queuelessPushable", "UnexpectedEOFError", "byteStream", "duplex", "opts", "write", "queuelessPushable", "err", "source", "buf", "readBuffer", "Uint8ArrayList", "options", "done", "value", "raceSignal", "UnexpectedEOFError", "data", "originalStream", "PING_PROTOCOL", "PROTOCOL_VERSION", "PROTOCOL_NAME", "PROTOCOL_PREFIX", "Ping", "components", "init", "PROTOCOL_PREFIX", "PROTOCOL_NAME", "PROTOCOL_VERSION", "serviceCapabilities", "data", "log", "stream", "start", "bytes", "byteStream", "pinged", "signal", "TimeoutError", "buf", "err", "ms", "peer", "options", "randomBytes", "connection", "result", "equals", "ProtocolError", "ping", "init", "components", "Ping"]
|
|
7
7
|
}
|
package/dist/src/index.d.ts
CHANGED
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
* console.info(rtt)
|
|
22
22
|
* ```
|
|
23
23
|
*/
|
|
24
|
-
import type { AbortOptions,
|
|
24
|
+
import type { AbortOptions, PeerId } from '@libp2p/interface';
|
|
25
25
|
import type { ConnectionManager, Registrar } from '@libp2p/interface-internal';
|
|
26
26
|
import type { Multiaddr } from '@multiformats/multiaddr';
|
|
27
27
|
export interface Ping {
|
|
@@ -48,7 +48,6 @@ export type PingServiceInit = PingInit;
|
|
|
48
48
|
export interface PingComponents {
|
|
49
49
|
registrar: Registrar;
|
|
50
50
|
connectionManager: ConnectionManager;
|
|
51
|
-
logger: ComponentLogger;
|
|
52
51
|
}
|
|
53
52
|
export declare function ping(init?: PingInit): (components: PingComponents) => Ping;
|
|
54
53
|
export { PING_PROTOCOL } from './constants.js';
|
package/dist/src/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAA;AAC7D,OAAO,KAAK,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAA;AAC9E,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAA;AAExD,MAAM,WAAW,IAAI;IACnB,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS,EAAE,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;CACtF;AAED;;GAEG;AACH,MAAM,MAAM,WAAW,GAAG,IAAI,CAAA;AAE9B,MAAM,WAAW,QAAQ;IACvB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B,sBAAsB,CAAC,EAAE,OAAO,CAAA;IAEhC;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AAED;;GAEG;AACH,MAAM,MAAM,eAAe,GAAG,QAAQ,CAAA;AAEtC,MAAM,WAAW,cAAc;IAC7B,SAAS,EAAE,SAAS,CAAA;IACpB,iBAAiB,EAAE,iBAAiB,CAAA;CACrC;AAED,wBAAgB,IAAI,CAAE,IAAI,GAAE,QAAa,GAAG,CAAC,UAAU,EAAE,cAAc,KAAK,IAAI,CAE/E;AAED,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAA"}
|
package/dist/src/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,IAAI,IAAI,SAAS,EAAE,MAAM,WAAW,CAAA;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,IAAI,IAAI,SAAS,EAAE,MAAM,WAAW,CAAA;AAoC7C,MAAM,UAAU,IAAI,CAAE,OAAiB,EAAE;IACvC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,IAAI,SAAS,CAAC,UAAU,EAAE,IAAI,CAAC,CAAA;AACxD,CAAC;AAED,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAA"}
|
package/dist/src/ping.d.ts
CHANGED
|
@@ -10,7 +10,6 @@ export declare class Ping implements Startable, PingInterface {
|
|
|
10
10
|
private readonly maxInboundStreams;
|
|
11
11
|
private readonly maxOutboundStreams;
|
|
12
12
|
private readonly runOnLimitedConnection;
|
|
13
|
-
private readonly log;
|
|
14
13
|
constructor(components: PingComponents, init?: PingInit);
|
|
15
14
|
readonly [Symbol.toStringTag] = "@libp2p/ping";
|
|
16
15
|
readonly [serviceCapabilities]: string[];
|
package/dist/src/ping.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ping.d.ts","sourceRoot":"","sources":["../../src/ping.ts"],"names":[],"mappings":"AACA,OAAO,EAA+B,mBAAmB,EAAE,MAAM,mBAAmB,CAAA;AAKpF,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,IAAI,IAAI,aAAa,EAAE,MAAM,YAAY,CAAA;AACjF,OAAO,KAAK,EAAE,YAAY,
|
|
1
|
+
{"version":3,"file":"ping.d.ts","sourceRoot":"","sources":["../../src/ping.ts"],"names":[],"mappings":"AACA,OAAO,EAA+B,mBAAmB,EAAE,MAAM,mBAAmB,CAAA;AAKpF,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,IAAI,IAAI,aAAa,EAAE,MAAM,YAAY,CAAA;AACjF,OAAO,KAAK,EAAE,YAAY,EAAU,MAAM,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAA;AACpG,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAA;AAExD,qBAAa,IAAK,YAAW,SAAS,EAAE,aAAa;IACnD,SAAgB,QAAQ,EAAE,MAAM,CAAA;IAChC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAgB;IAC3C,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAQ;IAChC,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAQ;IAC1C,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAQ;IAC3C,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAS;gBAEnC,UAAU,EAAE,cAAc,EAAE,IAAI,GAAE,QAAa;IAY5D,QAAQ,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,kBAAiB;IAE9C,QAAQ,CAAC,CAAC,mBAAmB,CAAC,EAAE,MAAM,EAAE,CAEvC;IAEK,KAAK,IAAK,OAAO,CAAC,IAAI,CAAC;IASvB,IAAI,IAAK,OAAO,CAAC,IAAI,CAAC;IAK5B,SAAS,IAAK,OAAO;IAIrB;;OAEG;IACH,aAAa,CAAE,IAAI,EAAE,kBAAkB,GAAG,IAAI;IAwD9C;;OAEG;IACG,IAAI,CAAE,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS,EAAE,EAAE,OAAO,GAAE,YAAiB,GAAG,OAAO,CAAC,MAAM,CAAC;CAqDjG"}
|
package/dist/src/ping.js
CHANGED
|
@@ -12,10 +12,8 @@ export class Ping {
|
|
|
12
12
|
maxInboundStreams;
|
|
13
13
|
maxOutboundStreams;
|
|
14
14
|
runOnLimitedConnection;
|
|
15
|
-
log;
|
|
16
15
|
constructor(components, init = {}) {
|
|
17
16
|
this.components = components;
|
|
18
|
-
this.log = components.logger.forComponent('libp2p:ping');
|
|
19
17
|
this.started = false;
|
|
20
18
|
this.protocol = `/${init.protocolPrefix ?? PROTOCOL_PREFIX}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`;
|
|
21
19
|
this.timeout = init.timeout ?? TIMEOUT;
|
|
@@ -47,7 +45,8 @@ export class Ping {
|
|
|
47
45
|
* A handler to register with Libp2p to process ping messages
|
|
48
46
|
*/
|
|
49
47
|
handleMessage(data) {
|
|
50
|
-
|
|
48
|
+
const log = data.connection.log.newScope('ping');
|
|
49
|
+
log.trace('ping from %p', data.connection.remotePeer);
|
|
51
50
|
const { stream } = data;
|
|
52
51
|
const start = Date.now();
|
|
53
52
|
const bytes = byteStream(stream);
|
|
@@ -75,19 +74,19 @@ export class Ping {
|
|
|
75
74
|
if (pinged && err.name === 'UnexpectedEOFError' && stream.readStatus !== 'ready') {
|
|
76
75
|
return;
|
|
77
76
|
}
|
|
78
|
-
|
|
77
|
+
log.error('ping from %p failed with error - %e', data.connection.remotePeer, err);
|
|
79
78
|
stream?.abort(err);
|
|
80
79
|
})
|
|
81
80
|
.finally(() => {
|
|
82
81
|
const ms = Date.now() - start;
|
|
83
|
-
|
|
82
|
+
log('ping from %p complete in %dms', data.connection.remotePeer, ms);
|
|
84
83
|
const signal = AbortSignal.timeout(this.timeout);
|
|
85
84
|
setMaxListeners(Infinity, signal);
|
|
86
85
|
stream.close({
|
|
87
86
|
signal
|
|
88
87
|
})
|
|
89
88
|
.catch(err => {
|
|
90
|
-
|
|
89
|
+
log.error('error closing ping stream from %p - %e', data.connection.remotePeer, err);
|
|
91
90
|
stream?.abort(err);
|
|
92
91
|
});
|
|
93
92
|
});
|
|
@@ -96,10 +95,10 @@ export class Ping {
|
|
|
96
95
|
* Ping a given peer and wait for its response, getting the operation latency.
|
|
97
96
|
*/
|
|
98
97
|
async ping(peer, options = {}) {
|
|
99
|
-
this.log('pinging %p', peer);
|
|
100
98
|
const start = Date.now();
|
|
101
99
|
const data = randomBytes(PING_LENGTH);
|
|
102
100
|
const connection = await this.components.connectionManager.openConnection(peer, options);
|
|
101
|
+
const log = connection.log.newScope('ping');
|
|
103
102
|
let stream;
|
|
104
103
|
if (options.signal == null) {
|
|
105
104
|
const signal = AbortSignal.timeout(this.timeout);
|
|
@@ -125,11 +124,11 @@ export class Ping {
|
|
|
125
124
|
if (!uint8ArrayEquals(data, result.subarray())) {
|
|
126
125
|
throw new ProtocolError(`Received wrong ping ack after ${ms}ms`);
|
|
127
126
|
}
|
|
128
|
-
|
|
127
|
+
log('ping %p complete in %dms', connection.remotePeer, ms);
|
|
129
128
|
return ms;
|
|
130
129
|
}
|
|
131
130
|
catch (err) {
|
|
132
|
-
|
|
131
|
+
log.error('error while pinging %p', connection.remotePeer, err);
|
|
133
132
|
stream?.abort(err);
|
|
134
133
|
throw err;
|
|
135
134
|
}
|
package/dist/src/ping.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ping.js","sourceRoot":"","sources":["../../src/ping.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAC5C,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAA;AACpF,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAC5C,OAAO,EAAE,MAAM,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AAC/D,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,WAAW,EAAE,gBAAgB,EAAE,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAA;AAKlJ,MAAM,OAAO,IAAI;IACC,QAAQ,CAAQ;IACf,UAAU,CAAgB;IACnC,OAAO,CAAS;IACP,OAAO,CAAQ;IACf,iBAAiB,CAAQ;IACzB,kBAAkB,CAAQ;IAC1B,sBAAsB,CAAS;
|
|
1
|
+
{"version":3,"file":"ping.js","sourceRoot":"","sources":["../../src/ping.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAC5C,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAA;AACpF,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAC5C,OAAO,EAAE,MAAM,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AAC/D,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,WAAW,EAAE,gBAAgB,EAAE,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAA;AAKlJ,MAAM,OAA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AC,CAAA;YAE/D,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,CAAA;YAElB,MAAM,GAAG,CAAA;QACX,CAAC;gBAAS,CAAC;YACT,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;gBACnB,MAAM,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;YAC7B,CAAC;QACH,CAAC;IACH,CAAC;CACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@libp2p/ping",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.37",
|
|
4
4
|
"description": "Implementation of Ping Protocol",
|
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
|
6
6
|
"homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/protocol-ping#readme",
|
|
@@ -43,17 +43,17 @@
|
|
|
43
43
|
"doc-check": "aegir doc-check"
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@libp2p/crypto": "^5.1.
|
|
47
|
-
"@libp2p/interface": "^2.
|
|
48
|
-
"@libp2p/interface-internal": "^2.3.
|
|
46
|
+
"@libp2p/crypto": "^5.1.8",
|
|
47
|
+
"@libp2p/interface": "^2.11.0",
|
|
48
|
+
"@libp2p/interface-internal": "^2.3.19",
|
|
49
49
|
"@multiformats/multiaddr": "^12.4.4",
|
|
50
50
|
"it-byte-stream": "^2.0.2",
|
|
51
51
|
"main-event": "^1.0.1",
|
|
52
52
|
"uint8arrays": "^5.1.0"
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
|
-
"@libp2p/logger": "^5.
|
|
56
|
-
"@libp2p/peer-id": "^5.1.
|
|
55
|
+
"@libp2p/logger": "^5.2.0",
|
|
56
|
+
"@libp2p/peer-id": "^5.1.9",
|
|
57
57
|
"aegir": "^47.0.14",
|
|
58
58
|
"it-pair": "^2.0.6",
|
|
59
59
|
"p-defer": "^4.0.1",
|
package/src/index.ts
CHANGED
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
*/
|
|
24
24
|
|
|
25
25
|
import { Ping as PingClass } from './ping.js'
|
|
26
|
-
import type { AbortOptions,
|
|
26
|
+
import type { AbortOptions, PeerId } from '@libp2p/interface'
|
|
27
27
|
import type { ConnectionManager, Registrar } from '@libp2p/interface-internal'
|
|
28
28
|
import type { Multiaddr } from '@multiformats/multiaddr'
|
|
29
29
|
|
|
@@ -56,7 +56,6 @@ export type PingServiceInit = PingInit
|
|
|
56
56
|
export interface PingComponents {
|
|
57
57
|
registrar: Registrar
|
|
58
58
|
connectionManager: ConnectionManager
|
|
59
|
-
logger: ComponentLogger
|
|
60
59
|
}
|
|
61
60
|
|
|
62
61
|
export function ping (init: PingInit = {}): (components: PingComponents) => Ping {
|
package/src/ping.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { setMaxListeners } from 'main-event'
|
|
|
5
5
|
import { equals as uint8ArrayEquals } from 'uint8arrays/equals'
|
|
6
6
|
import { PROTOCOL_PREFIX, PROTOCOL_NAME, PING_LENGTH, PROTOCOL_VERSION, TIMEOUT, MAX_INBOUND_STREAMS, MAX_OUTBOUND_STREAMS } from './constants.js'
|
|
7
7
|
import type { PingComponents, PingInit, Ping as PingInterface } from './index.js'
|
|
8
|
-
import type { AbortOptions,
|
|
8
|
+
import type { AbortOptions, Stream, PeerId, Startable, IncomingStreamData } from '@libp2p/interface'
|
|
9
9
|
import type { Multiaddr } from '@multiformats/multiaddr'
|
|
10
10
|
|
|
11
11
|
export class Ping implements Startable, PingInterface {
|
|
@@ -16,11 +16,9 @@ export class Ping implements Startable, PingInterface {
|
|
|
16
16
|
private readonly maxInboundStreams: number
|
|
17
17
|
private readonly maxOutboundStreams: number
|
|
18
18
|
private readonly runOnLimitedConnection: boolean
|
|
19
|
-
private readonly log: Logger
|
|
20
19
|
|
|
21
20
|
constructor (components: PingComponents, init: PingInit = {}) {
|
|
22
21
|
this.components = components
|
|
23
|
-
this.log = components.logger.forComponent('libp2p:ping')
|
|
24
22
|
this.started = false
|
|
25
23
|
this.protocol = `/${init.protocolPrefix ?? PROTOCOL_PREFIX}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`
|
|
26
24
|
this.timeout = init.timeout ?? TIMEOUT
|
|
@@ -59,7 +57,9 @@ export class Ping implements Startable, PingInterface {
|
|
|
59
57
|
* A handler to register with Libp2p to process ping messages
|
|
60
58
|
*/
|
|
61
59
|
handleMessage (data: IncomingStreamData): void {
|
|
62
|
-
|
|
60
|
+
const log = data.connection.log.newScope('ping')
|
|
61
|
+
|
|
62
|
+
log.trace('ping from %p', data.connection.remotePeer)
|
|
63
63
|
|
|
64
64
|
const { stream } = data
|
|
65
65
|
const start = Date.now()
|
|
@@ -92,12 +92,12 @@ export class Ping implements Startable, PingInterface {
|
|
|
92
92
|
return
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
-
|
|
95
|
+
log.error('ping from %p failed with error - %e', data.connection.remotePeer, err)
|
|
96
96
|
stream?.abort(err)
|
|
97
97
|
})
|
|
98
98
|
.finally(() => {
|
|
99
99
|
const ms = Date.now() - start
|
|
100
|
-
|
|
100
|
+
log('ping from %p complete in %dms', data.connection.remotePeer, ms)
|
|
101
101
|
|
|
102
102
|
const signal = AbortSignal.timeout(this.timeout)
|
|
103
103
|
setMaxListeners(Infinity, signal)
|
|
@@ -106,7 +106,7 @@ export class Ping implements Startable, PingInterface {
|
|
|
106
106
|
signal
|
|
107
107
|
})
|
|
108
108
|
.catch(err => {
|
|
109
|
-
|
|
109
|
+
log.error('error closing ping stream from %p - %e', data.connection.remotePeer, err)
|
|
110
110
|
stream?.abort(err)
|
|
111
111
|
})
|
|
112
112
|
})
|
|
@@ -116,11 +116,10 @@ export class Ping implements Startable, PingInterface {
|
|
|
116
116
|
* Ping a given peer and wait for its response, getting the operation latency.
|
|
117
117
|
*/
|
|
118
118
|
async ping (peer: PeerId | Multiaddr | Multiaddr[], options: AbortOptions = {}): Promise<number> {
|
|
119
|
-
this.log('pinging %p', peer)
|
|
120
|
-
|
|
121
119
|
const start = Date.now()
|
|
122
120
|
const data = randomBytes(PING_LENGTH)
|
|
123
121
|
const connection = await this.components.connectionManager.openConnection(peer, options)
|
|
122
|
+
const log = connection.log.newScope('ping')
|
|
124
123
|
let stream: Stream | undefined
|
|
125
124
|
|
|
126
125
|
if (options.signal == null) {
|
|
@@ -154,11 +153,11 @@ export class Ping implements Startable, PingInterface {
|
|
|
154
153
|
throw new ProtocolError(`Received wrong ping ack after ${ms}ms`)
|
|
155
154
|
}
|
|
156
155
|
|
|
157
|
-
|
|
156
|
+
log('ping %p complete in %dms', connection.remotePeer, ms)
|
|
158
157
|
|
|
159
158
|
return ms
|
|
160
159
|
} catch (err: any) {
|
|
161
|
-
|
|
160
|
+
log.error('error while pinging %p', connection.remotePeer, err)
|
|
162
161
|
|
|
163
162
|
stream?.abort(err)
|
|
164
163
|
|