libp2p 1.4.0 → 1.4.2-2281f802b

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/README.md CHANGED
@@ -86,15 +86,15 @@ It is complementary to the overarching libp2p project roadmap: <https://github.c
86
86
 
87
87
  ### Configuration
88
88
 
89
- For all the information on how you can configure libp2p see [CONFIGURATION.md](./doc/CONFIGURATION.md).
89
+ For all the information on how you can configure libp2p see [CONFIGURATION.md](https://github.com/libp2p/js-libp2p/blob/main/doc/CONFIGURATION.md).
90
90
 
91
91
  ## Limits
92
92
 
93
- For help configuring your node to resist malicious network peers, see [LIMITS.md](./doc/LIMITS.md)
93
+ For help configuring your node to resist malicious network peers, see [LIMITS.md](https://github.com/libp2p/js-libp2p/blob/main/doc/LIMITS.md)
94
94
 
95
95
  ## Getting started
96
96
 
97
- If you are starting your journey with `js-libp2p`, read the [GETTING\_STARTED.md](./doc/GETTING_STARTED.md) guide.
97
+ If you are starting your journey with `js-libp2p`, read the [GETTING\_STARTED.md](https://github.com/libp2p/js-libp2p/blob/main/doc/GETTING_STARTED.md) guide.
98
98
 
99
99
  ## Tutorials and Examples
100
100
 
@@ -200,8 +200,8 @@ The libp2p implementation in JavaScript is a work in progress. As such, there ar
200
200
 
201
201
  Licensed under either of
202
202
 
203
- - Apache 2.0, ([LICENSE-APACHE](LICENSE-APACHE) / <http://www.apache.org/licenses/LICENSE-2.0>)
204
- - MIT ([LICENSE-MIT](LICENSE-MIT) / <http://opensource.org/licenses/MIT>)
203
+ - Apache 2.0, ([LICENSE-APACHE](https://github.com/libp2p/js-libp2p/blob/main/packages/libp2p/LICENSE-APACHE) / <http://www.apache.org/licenses/LICENSE-2.0>)
204
+ - MIT ([LICENSE-MIT](https://github.com/libp2p/js-libp2p/blob/main/packages/libp2p/LICENSE-MIT) / <http://opensource.org/licenses/MIT>)
205
205
 
206
206
  # Contribution
207
207
 
package/dist/index.min.js CHANGED
@@ -4,7 +4,7 @@
4
4
  `));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
5
5
  ${e.join(`
6
6
  `)}`:`${t} :`}};zu=Jt;I.Constructed=zu;Jt.NAME="CONSTRUCTED";var es=class extends De{fromBER(e,t,n){return t}toBER(e){return lt}};es.override="EndOfContentValueBlock";var Yu,ts=class extends _e{constructor(e={}){super(e,es),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Yu=ts;I.EndOfContent=Yu;ts.NAME=qn;var Wu,er=class extends _e{constructor(e={}){super(e,De),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Wu=er;I.Null=Wu;er.NAME="NULL";var rs=class extends Pt(De){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=H.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=H.BufferSourceConverter.toUint8Array(e);return Dt(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Ja.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};rs.NAME="BooleanValueBlock";var ju,ns=class extends _e{constructor(e={}){super(e,rs),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};ju=ns;I.Boolean=ju;ns.NAME="BOOLEAN";var os=class extends Pt(yt){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=yt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===qn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Hu)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?yt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};os.NAME="OctetStringValueBlock";var Xu,Lt=class r extends _e{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},os),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=Ls(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?Jt.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${H.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return H.BufferSourceConverter.concat(e)}};Xu=Lt;I.OctetString=Xu;Lt.NAME=Hu;var ss=class extends Pt(yt){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=yt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===qn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==$u)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=a.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return o}let s=H.BufferSourceConverter.toUint8Array(e);if(!Dt(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=Ls(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return yt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return lt;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};ss.NAME="BitStringValueBlock";var Zu,nn=class extends _e{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},ss),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Jt.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};Zu=nn;I.BitString=Zu;nn.NAME=$u;var Qu;function Tg(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u=0,f=c<i?i:c,l=0;for(let h=f;h>=0;h--,l++){switch(!0){case l<a.length:u=s[i-l]+a[c-l]+t[0];break;default:u=s[i-l]+t[0]}switch(t[0]=u/10,!0){case l>=s.length:s=Yo(new Uint8Array([u%10]),s);break;default:s[i-l]=u%10}}return t[0]>0&&(s=Yo(t,s)),s}function Ku(r){if(r>=Hn.length)for(let e=Hn.length;e<=r;e++){let t=new Uint8Array([0]),n=Hn[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=Yo(t,n)),Hn.push(n)}return Hn[r]}function Ng(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,u,f=0;for(let l=c;l>=0;l--,f++)switch(u=s[i-f]-a[c-f]-t,!0){case u<0:t=1,s[i-f]=u+10;break;default:t=0,s[i-f]=u}if(t>0)for(let l=i-c+1;l>=0;l--,f++)if(u=s[i-f]-t,u<0)t=1,s[i-f]=u+10;else{t=0,s[i-f]=u;break}return s.slice()}var Gn=class extends Pt(De){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=Ja.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Mu(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let u=0;u<8;u++){if((o&1)===1)switch(n){case e:t=Ng(Ku(n),t),i="-";break;default:t=Tg(t,Ku(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=Vu.charAt(t[c]));return a===!1&&(i+=Vu.charAt(0)),i}};Qu=Gn;Gn.NAME="IntegerValueBlock";Object.defineProperty(Qu.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Ju,de=class r extends _e{constructor(e={}){super(e,Gn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Wo(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Wo();let t=BigInt(e),n=new $n,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(H.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${H.Convert.ToHex(a)}`)+t,f=H.BufferSourceConverter.toUint8Array(H.Convert.FromHex(u.toString(16)));f[0]|=128,n.write(f)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Ju=de;I.Integer=Ju;de.NAME="INTEGER";var ef,is=class extends de{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};ef=is;I.Enumerated=ef;is.NAME="ENUMERATED";var zn=class extends Pt(De){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=H.BufferSourceConverter.toUint8Array(e);if(!Dt(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Ar(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Wo();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Qt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",lt;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=H.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};zn.NAME="sidBlock";var as=class extends De{constructor({value:e=on,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new zn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,lt;t.push(o)}return ec(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new zn;if(o>Number.MAX_SAFE_INTEGER){Wo();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};as.NAME="ObjectIdentifierValueBlock";var tf,ct=class extends _e{constructor(e={}){super(e,as),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};tf=ct;I.ObjectIdentifier=tf;ct.NAME="OBJECT IDENTIFIER";var Yn=class extends Pt(Ct){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=H.BufferSourceConverter.toUint8Array(e);if(!Dt(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Ar(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Qt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",lt;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=H.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Yn.NAME="relativeSidBlock";var cs=class extends De{constructor({value:e=on,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Yn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,lt;n.push(s)}return ec(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new Yn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};cs.NAME="RelativeObjectIdentifierValueBlock";var rf,ls=class extends _e{constructor(e={}){super(e,cs),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};rf=ls;I.RelativeObjectIdentifier=rf;ls.NAME="RelativeObjectIdentifier";var nf,Ee=class extends Jt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};nf=Ee;I.Sequence=nf;Ee.NAME="SEQUENCE";var of,us=class extends Jt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};of=us;I.Set=of;us.NAME="SET";var fs=class extends Pt(De){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=on}toJSON(){return{...super.toJSON(),value:this.value}}};fs.NAME="StringValueBlock";var hs=class extends fs{};hs.NAME="SimpleStringValueBlock";var Ke=class extends Zo{constructor({...e}={}){super(e,hs)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,H.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};Ke.NAME="SIMPLE STRING";var ds=class extends Ke{fromBuffer(e){this.valueBlock.valueHexView=H.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=H.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=H.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(H.Convert.FromUtf8String(e)),this.valueBlock.value=e}};ds.NAME="Utf8StringValueBlock";var sf,kt=class extends ds{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};sf=kt;I.Utf8String=sf;kt.NAME="UTF8String";var ps=class extends Ke{fromBuffer(e){this.valueBlock.value=H.Convert.ToUtf16String(e),this.valueBlock.valueHexView=H.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(H.Convert.FromUtf16String(e))}};ps.NAME="BmpStringValueBlock";var af,ms=class extends ps{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};af=ms;I.BmpString=af;ms.NAME="BMPString";var gs=class extends Ke{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=Qt(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};gs.NAME="UniversalStringValueBlock";var cf,ys=class extends gs{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};cf=ys;I.UniversalString=cf;ys.NAME="UniversalString";var lf,ws=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};lf=ws;I.NumericString=lf;ws.NAME="NumericString";var uf,bs=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};uf=bs;I.PrintableString=uf;bs.NAME="PrintableString";var ff,Es=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};ff=Es;I.TeletexString=ff;Es.NAME="TeletexString";var hf,xs=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};hf=xs;I.VideotexString=hf;xs.NAME="VideotexString";var df,vs=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};df=vs;I.IA5String=df;vs.NAME="IA5String";var pf,As=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};pf=As;I.GraphicString=pf;As.NAME="GraphicString";var mf,Wn=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};mf=Wn;I.VisibleString=mf;Wn.NAME="VisibleString";var gf,Rs=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};gf=Rs;I.GeneralString=gf;Rs.NAME="GeneralString";var yf,_s=class extends Ke{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};yf=_s;I.CharacterString=yf;_s.NAME="CharacterString";var wf,jn=class extends Wn{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,H.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=qe(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=qe(this.month,2),t[2]=qe(this.day,2),t[3]=qe(this.hour,2),t[4]=qe(this.minute,2),t[5]=qe(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};wf=jn;I.UTCTime=wf;jn.NAME="UTCTime";var bf,Ss=class extends jn{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let l=new Number(e[e.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let l=1,h=n.indexOf("+"),g="";if(h===-1&&(h=n.indexOf("-"),l=-1),h!==-1){if(g=n.substring(h+1),n=n.substring(0,h),g.length!==2&&g.length!==4)throw new Error("Wrong input string for conversion");let d=parseInt(g.substring(0,2),10);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*d,g.length===4){if(d=parseInt(g.substring(2,4),10),isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");c=l*d}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let f=i.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let l=1;l<f.length;l++)switch(l){case 1:this.year=parseInt(f[l],10);break;case 2:this.month=parseInt(f[l],10);break;case 3:this.day=parseInt(f[l],10);break;case 4:this.hour=parseInt(f[l],10)+a;break;case 5:this.minute=parseInt(f[l],10)+c;break;case 6:this.second=parseInt(f[l],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(qe(this.year,4)),t.push(qe(this.month,2)),t.push(qe(this.day,2)),t.push(qe(this.hour,2)),t.push(qe(this.minute,2)),t.push(qe(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(qe(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};bf=Ss;I.GeneralizedTime=bf;Ss.NAME="GeneralizedTime";var Ef,Is=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Ef=Is;I.DATE=Ef;Is.NAME="DATE";var xf,Bs=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};xf=Bs;I.TimeOfDay=xf;Bs.NAME="TimeOfDay";var vf,Ts=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};vf=Ts;I.DateTime=vf;Ts.NAME="DateTime";var Af,Ns=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Af=Ns;I.Duration=Af;Ns.NAME="Duration";var Rf,Cs=class extends kt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Rf=Cs;I.TIME=Rf;Cs.NAME="TIME";function Lg(r){let{result:e}=sn(r),t=e.valueBlock.value;return{n:K(wt(t[1].toBigInt()),"base64url"),e:K(wt(t[2].toBigInt()),"base64url"),d:K(wt(t[3].toBigInt()),"base64url"),p:K(wt(t[4].toBigInt()),"base64url"),q:K(wt(t[5].toBigInt()),"base64url"),dp:K(wt(t[6].toBigInt()),"base64url"),dq:K(wt(t[7].toBigInt()),"base64url"),qi:K(wt(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function kg(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new y("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new Ee({value:[new de({value:0}),de.fromBigInt(bt(D(r.n,"base64url"))),de.fromBigInt(bt(D(r.e,"base64url"))),de.fromBigInt(bt(D(r.d,"base64url"))),de.fromBigInt(bt(D(r.p,"base64url"))),de.fromBigInt(bt(D(r.q,"base64url"))),de.fromBigInt(bt(D(r.dp,"base64url"))),de.fromBigInt(bt(D(r.dq,"base64url"))),de.fromBigInt(bt(D(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function Dg(r){let{result:e}=sn(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:K(wt(t[0].toBigInt()),"base64url"),e:K(wt(t[1].toBigInt()),"base64url")}}function Pg(r){if(r.n==null||r.e==null)throw new y("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new Ee({value:[new Ee({value:[new ct({value:"1.2.840.113549.1.1.1"}),new er]}),new nn({valueHex:new Ee({value:[de.fromBigInt(bt(D(r.n,"base64url"))),de.fromBigInt(bt(D(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function wt(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),o=0,s=0;for(;o<t;)n[o]=parseInt(e.slice(s,s+2),16),o+=1,s+=2;return n}function bt(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}var Og=16,rc=32,nc=1e4;async function Ug(r,e){let t=Ue.get(),o=new Ee({value:[new de({value:0}),new Ee({value:[new ct({value:"1.2.840.113549.1.1.1"}),new er]}),new Lt({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=vr(Og),a=await Za(jr,e,i,{c:nc,dkLen:rc}),c=vr(16),u=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),f=await t.subtle.encrypt({name:"AES-CBC",iv:c},u,s),l=new Ee({value:[new Lt({valueHex:i}),new de({value:nc}),new de({value:rc}),new Ee({value:[new ct({value:"1.2.840.113549.2.11"}),new er]})]}),h=new Ee({value:[new ct({value:"1.2.840.113549.1.5.13"}),new Ee({value:[new Ee({value:[new ct({value:"1.2.840.113549.1.5.12"}),l]}),new Ee({value:[new ct({value:"2.16.840.1.101.3.4.1.42"}),new Lt({valueHex:c})]})]})]}),d=new Ee({value:[h,new Lt({valueHex:f})]}).toBER(),p=new Uint8Array(d,0,d.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...K(p,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
7
- `)}async function Mg(r,e){let t=Ue.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=D(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=sn(o),{iv:i,salt:a,iterations:c,keySize:u,cipherText:f}=Fg(s),l=await Za(jr,e,a,{c,dkLen:u}),h=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),g=Xn(await t.subtle.decrypt({name:"AES-CBC",iv:i},h,f)),{result:d}=sn(g);n=_f(d)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=D(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=sn(o);n=_f(s)}else throw new y("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return oc(n)}function Fg(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new y("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new y("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=Xn(s.valueBlock.value[0].getValue()),a=nc,c=rc;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new y("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let u=e.valueBlock.value[1].valueBlock.value[1],f=u.valueBlock.value[0].toString();if(f!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(f!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new y("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let l=Xn(u.valueBlock.value[1].getValue());return{cipherText:Xn(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function _f(r){return Xn(r.valueBlock.value[2].getValue())}function Xn(r){return new Uint8Array(r,0,r.byteLength)}async function Sf(r){let e=await Ue.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await Tf(e);return{privateKey:t[0],publicKey:t[1]}}async function sc(r){let t=[await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Vg(r)],n=await Tf({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function If(r,e){let t=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ue.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Bf(r,e,t){let n=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ue.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function Tf(r){if(r.privateKey==null||r.publicKey==null)throw new y("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Ue.get().subtle.exportKey("jwk",r.privateKey),Ue.get().subtle.exportKey("jwk",r.publicKey)])}async function Vg(r){return Ue.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function ks(r){if(r.kty!=="RSA")throw new y("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new y("invalid key modulus","ERR_INVALID_KEY_MODULUS");return D(r.n,"base64url").length*8}var Qn=8192,Zn=class{_key;constructor(e){this._key=e}verify(e,t){return Bf(this._key,t,e)}marshal(){return tr.jwkToPkix(this._key)}get bytes(){return mt.encode({Type:te.RSA,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=Ae.digest(this.bytes);return et(e)?e.then(({bytes:t})=>t):e.bytes}},an=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return vr(16)}sign(e){return If(this._key,e)}get public(){if(this._publicKey==null)throw new y("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Zn(this._publicKey)}marshal(){return tr.jwkToPkcs1(this._key)}get bytes(){return gt.encode({Type:te.RSA,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=Ae.digest(this.bytes);return et(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return K(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return tr.exportToPem(this,e);if(t==="libp2p-key")return Jr(this.bytes,e);throw new y(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function oc(r){let e=tr.pkcs1ToJwk(r);if(ks(e)>Qn)throw new y("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await sc(e);return new an(t.privateKey,t.publicKey)}function Hg(r){let e=tr.pkixToJwk(r);if(ks(e)>Qn)throw new y("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Zn(e)}async function $g(r){if(ks(r)>Qn)throw new y("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await sc(r);return new an(e.privateKey,e.publicKey)}async function qg(r){if(r>Qn)throw new y("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Sf(r);return new an(e.privateKey,e.publicKey)}var fc={};be(fc,{Secp256k1PrivateKey:()=>eo,Secp256k1PublicKey:()=>Jn,generateKeyPair:()=>n0,unmarshalSecp256k1PrivateKey:()=>t0,unmarshalSecp256k1PublicKey:()=>r0});var Gg=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),rr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),nr=new Uint32Array(64),ac=class extends Wr{constructor(){super(64,32,8,!1),this.A=rr[0]|0,this.B=rr[1]|0,this.C=rr[2]|0,this.D=rr[3]|0,this.E=rr[4]|0,this.F=rr[5]|0,this.G=rr[6]|0,this.H=rr[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let l=0;l<16;l++,t+=4)nr[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let h=nr[l-15],g=nr[l-2],d=ot(h,7)^ot(h,18)^h>>>3,p=ot(g,17)^ot(g,19)^g>>>10;nr[l]=p+nr[l-7]+d+nr[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let h=ot(a,6)^ot(a,11)^ot(a,25),g=f+h+su(a,c,u)+Gg[l]+nr[l]|0,p=(ot(n,2)^ot(n,13)^ot(n,22))+iu(n,o,s)|0;f=u,u=c,c=a,a=i+g|0,i=s,s=o,o=n,n=g+p|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){nr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Nf=No(()=>new ac);function zg(r){let e=Un(r);pt(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:Yg,hexToBytes:Wg}=ko,Rr={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=Rr;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:Yg(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Rr,t=typeof r=="string"?Wg(r):r;Xr(t);let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:o,l:s}=Rr._parseInt(t.subarray(2)),{d:i,l:a}=Rr._parseInt(s);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s:i}},hexFromSig(r){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,t=u=>{let f=u.toString(16);return f.length&1?`0${f}`:f},n=e(t(r.s)),o=e(t(r.r)),s=n.length/2,i=o.length/2,a=t(s),c=t(i);return`30${t(i+s+4)}02${c}${o}02${a}${n}`}},Ot=BigInt(0),rt=BigInt(1),Kx=BigInt(2),Cf=BigInt(3),Hx=BigInt(4);function jg(r){let e=zg(r),{Fp:t}=e,n=e.toBytes||((d,p,m)=>{let w=p.toAffine();return It(Uint8Array.from([4]),t.toBytes(w.x),t.toBytes(w.y))}),o=e.fromBytes||(d=>{let p=d.subarray(1),m=t.fromBytes(p.subarray(0,t.BYTES)),w=t.fromBytes(p.subarray(t.BYTES,2*t.BYTES));return{x:m,y:w}});function s(d){let{a:p,b:m}=e,w=t.sqr(d),x=t.mul(w,d);return t.add(t.add(x,t.mul(d,p)),m)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function i(d){return typeof d=="bigint"&&Ot<d&&d<e.n}function a(d){if(!i(d))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(d){let{allowedPrivateKeyLengths:p,nByteLength:m,wrapPrivateKey:w,n:x}=e;if(p&&typeof d!="bigint"){if(Wt(d)&&(d=_t(d)),typeof d!="string"||!p.includes(d.length))throw new Error("Invalid key");d=d.padStart(m*2,"0")}let b;try{b=typeof d=="bigint"?d:St(ae("private key",d,m))}catch{throw new Error(`private key must be ${m} bytes, hex or bigint, not ${typeof d}`)}return w&&(b=Z(b,x)),a(b),b}let u=new Map;function f(d){if(!(d instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(p,m,w){if(this.px=p,this.py=m,this.pz=w,p==null||!t.isValid(p))throw new Error("x required");if(m==null||!t.isValid(m))throw new Error("y required");if(w==null||!t.isValid(w))throw new Error("z required")}static fromAffine(p){let{x:m,y:w}=p||{};if(!p||!t.isValid(m)||!t.isValid(w))throw new Error("invalid affine point");if(p instanceof l)throw new Error("projective point not allowed");let x=b=>t.eql(b,t.ZERO);return x(m)&&x(w)?l.ZERO:new l(m,w,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(p){let m=t.invertBatch(p.map(w=>w.pz));return p.map((w,x)=>w.toAffine(m[x])).map(l.fromAffine)}static fromHex(p){let m=l.fromAffine(o(ae("pointHex",p)));return m.assertValidity(),m}static fromPrivateKey(p){return l.BASE.multiply(c(p))}_setWindowSize(p){this._WINDOW_SIZE=p,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:p,y:m}=this.toAffine();if(!t.isValid(p)||!t.isValid(m))throw new Error("bad point: x or y not FE");let w=t.sqr(m),x=s(p);if(!t.eql(w,x))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:p}=this.toAffine();if(t.isOdd)return!t.isOdd(p);throw new Error("Field doesn't support isOdd")}equals(p){f(p);let{px:m,py:w,pz:x}=this,{px:b,py:A,pz:v}=p,S=t.eql(t.mul(m,v),t.mul(b,x)),N=t.eql(t.mul(w,v),t.mul(A,x));return S&&N}negate(){return new l(this.px,t.neg(this.py),this.pz)}double(){let{a:p,b:m}=e,w=t.mul(m,Cf),{px:x,py:b,pz:A}=this,v=t.ZERO,S=t.ZERO,N=t.ZERO,C=t.mul(x,x),q=t.mul(b,b),G=t.mul(A,A),U=t.mul(x,b);return U=t.add(U,U),N=t.mul(x,A),N=t.add(N,N),v=t.mul(p,N),S=t.mul(w,G),S=t.add(v,S),v=t.sub(q,S),S=t.add(q,S),S=t.mul(v,S),v=t.mul(U,v),N=t.mul(w,N),G=t.mul(p,G),U=t.sub(C,G),U=t.mul(p,U),U=t.add(U,N),N=t.add(C,C),C=t.add(N,C),C=t.add(C,G),C=t.mul(C,U),S=t.add(S,C),G=t.mul(b,A),G=t.add(G,G),C=t.mul(G,U),v=t.sub(v,C),N=t.mul(G,q),N=t.add(N,N),N=t.add(N,N),new l(v,S,N)}add(p){f(p);let{px:m,py:w,pz:x}=this,{px:b,py:A,pz:v}=p,S=t.ZERO,N=t.ZERO,C=t.ZERO,q=e.a,G=t.mul(e.b,Cf),U=t.mul(m,b),ue=t.mul(w,A),ce=t.mul(x,v),Je=t.add(m,w),R=t.add(b,A);Je=t.mul(Je,R),R=t.add(U,ue),Je=t.sub(Je,R),R=t.add(m,x);let L=t.add(b,v);return R=t.mul(R,L),L=t.add(U,ce),R=t.sub(R,L),L=t.add(w,x),S=t.add(A,v),L=t.mul(L,S),S=t.add(ue,ce),L=t.sub(L,S),C=t.mul(q,R),S=t.mul(G,ce),C=t.add(S,C),S=t.sub(ue,C),C=t.add(ue,C),N=t.mul(S,C),ue=t.add(U,U),ue=t.add(ue,U),ce=t.mul(q,ce),R=t.mul(G,R),ue=t.add(ue,ce),ce=t.sub(U,ce),ce=t.mul(q,ce),R=t.add(R,ce),U=t.mul(ue,R),N=t.add(N,U),U=t.mul(L,R),S=t.mul(Je,S),S=t.sub(S,U),U=t.mul(Je,ue),C=t.mul(L,C),C=t.add(C,U),new l(S,N,C)}subtract(p){return this.add(p.negate())}is0(){return this.equals(l.ZERO)}wNAF(p){return g.wNAFCached(this,u,p,m=>{let w=t.invertBatch(m.map(x=>x.pz));return m.map((x,b)=>x.toAffine(w[b])).map(l.fromAffine)})}multiplyUnsafe(p){let m=l.ZERO;if(p===Ot)return m;if(a(p),p===rt)return this;let{endo:w}=e;if(!w)return g.unsafeLadder(this,p);let{k1neg:x,k1:b,k2neg:A,k2:v}=w.splitScalar(p),S=m,N=m,C=this;for(;b>Ot||v>Ot;)b&rt&&(S=S.add(C)),v&rt&&(N=N.add(C)),C=C.double(),b>>=rt,v>>=rt;return x&&(S=S.negate()),A&&(N=N.negate()),N=new l(t.mul(N.px,w.beta),N.py,N.pz),S.add(N)}multiply(p){a(p);let m=p,w,x,{endo:b}=e;if(b){let{k1neg:A,k1:v,k2neg:S,k2:N}=b.splitScalar(m),{p:C,f:q}=this.wNAF(v),{p:G,f:U}=this.wNAF(N);C=g.constTimeNegate(A,C),G=g.constTimeNegate(S,G),G=new l(t.mul(G.px,b.beta),G.py,G.pz),w=C.add(G),x=q.add(U)}else{let{p:A,f:v}=this.wNAF(m);w=A,x=v}return l.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(p,m,w){let x=l.BASE,b=(v,S)=>S===Ot||S===rt||!v.equals(x)?v.multiplyUnsafe(S):v.multiply(S),A=b(this,m).add(b(p,w));return A.is0()?void 0:A}toAffine(p){let{px:m,py:w,pz:x}=this,b=this.is0();p==null&&(p=b?t.ONE:t.inv(x));let A=t.mul(m,p),v=t.mul(w,p),S=t.mul(x,p);if(b)return{x:t.ZERO,y:t.ZERO};if(!t.eql(S,t.ONE))throw new Error("invZ was invalid");return{x:A,y:v}}isTorsionFree(){let{h:p,isTorsionFree:m}=e;if(p===rt)return!0;if(m)return m(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:p,clearCofactor:m}=e;return p===rt?this:m?m(l,this):this.multiplyUnsafe(e.h)}toRawBytes(p=!0){return this.assertValidity(),n(l,this,p)}toHex(p=!0){return _t(this.toRawBytes(p))}}l.BASE=new l(e.Gx,e.Gy,t.ONE),l.ZERO=new l(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,g=Oo(l,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:i}}function Xg(r){let e=Un(r);return pt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Lf(r){let e=Xg(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(R){return Ot<R&&R<t.ORDER}function a(R){return Z(R,n)}function c(R){return Do(R,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:l,isWithinCurveOrder:h}=jg({...e,toBytes(R,L,M){let _=L.toAffine(),E=t.toBytes(_.x),T=It;return M?T(Uint8Array.from([L.hasEvenY()?2:3]),E):T(Uint8Array.from([4]),E,t.toBytes(_.y))},fromBytes(R){let L=R.length,M=R[0],_=R.subarray(1);if(L===o&&(M===2||M===3)){let E=St(_);if(!i(E))throw new Error("Point is not on curve");let T=l(E),k;try{k=t.sqrt(T)}catch(V){let Y=V instanceof Error?": "+V.message:"";throw new Error("Point is not on curve"+Y)}let P=(k&rt)===rt;return(M&1)===1!==P&&(k=t.neg(k)),{x:E,y:k}}else if(L===s&&M===4){let E=t.fromBytes(_.subarray(0,t.BYTES)),T=t.fromBytes(_.subarray(t.BYTES,2*t.BYTES));return{x:E,y:T}}else throw new Error(`Point of length ${L} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),g=R=>_t(Xt(R,e.nByteLength));function d(R){let L=n>>rt;return R>L}function p(R){return d(R)?a(-R):R}let m=(R,L,M)=>St(R.slice(L,M));class w{constructor(L,M,_){this.r=L,this.s=M,this.recovery=_,this.assertValidity()}static fromCompact(L){let M=e.nByteLength;return L=ae("compactSignature",L,M*2),new w(m(L,0,M),m(L,M,2*M))}static fromDER(L){let{r:M,s:_}=Rr.toSig(ae("DER",L));return new w(M,_)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(L){return new w(this.r,this.s,L)}recoverPublicKey(L){let{r:M,s:_,recovery:E}=this,T=N(ae("msgHash",L));if(E==null||![0,1,2,3].includes(E))throw new Error("recovery id invalid");let k=E===2||E===3?M+e.n:M;if(k>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let P=E&1?"03":"02",F=u.fromHex(P+g(k)),V=c(k),Y=a(-T*V),$=a(_*V),z=u.BASE.multiplyAndAddUnsafe(F,Y,$);if(!z)throw new Error("point at infinify");return z.assertValidity(),z}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return mr(this.toDERHex())}toDERHex(){return Rr.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return mr(this.toCompactHex())}toCompactHex(){return g(this.r)+g(this.s)}}let x={isValidPrivateKey(R){try{return f(R),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let R=_a(e.n);return yu(e.randomBytes(R),e.n)},precompute(R=8,L=u.BASE){return L._setWindowSize(R),L.multiply(BigInt(3)),L}};function b(R,L=!0){return u.fromPrivateKey(R).toRawBytes(L)}function A(R){let L=Wt(R),M=typeof R=="string",_=(L||M)&&R.length;return L?_===o||_===s:M?_===2*o||_===2*s:R instanceof u}function v(R,L,M=!0){if(A(R))throw new Error("first arg must be private key");if(!A(L))throw new Error("second arg must be public key");return u.fromHex(L).multiply(f(R)).toRawBytes(M)}let S=e.bits2int||function(R){let L=St(R),M=R.length*8-e.nBitLength;return M>0?L>>BigInt(M):L},N=e.bits2int_modN||function(R){return a(S(R))},C=On(e.nBitLength);function q(R){if(typeof R!="bigint")throw new Error("bigint expected");if(!(Ot<=R&&R<C))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Xt(R,e.nByteLength)}function G(R,L,M=U){if(["recovered","canonical"].some(oe=>oe in M))throw new Error("sign() legacy options not supported");let{hash:_,randomBytes:E}=e,{lowS:T,prehash:k,extraEntropy:P}=M;T==null&&(T=!0),R=ae("msgHash",R),k&&(R=ae("prehashed msgHash",_(R)));let F=N(R),V=f(L),Y=[q(V),q(F)];if(P!=null&&P!==!1){let oe=P===!0?E(t.BYTES):P;Y.push(ae("extraEntropy",oe))}let $=It(...Y),z=F;function fe(oe){let xe=S(oe);if(!h(xe))return;let ve=c(xe),me=u.BASE.multiply(xe).toAffine(),Te=a(me.x);if(Te===Ot)return;let xt=a(ve*a(z+Te*V));if(xt===Ot)return;let fr=(me.x===Te?0:2)|Number(me.y&rt),Cn=xt;return T&&d(xt)&&(Cn=p(xt),fr^=1),new w(Te,Cn,fr)}return{seed:$,k2sig:fe}}let U={lowS:e.lowS,prehash:!1},ue={lowS:e.lowS,prehash:!1};function ce(R,L,M=U){let{seed:_,k2sig:E}=G(R,L,M),T=e;return xa(T.hash.outputLen,T.nByteLength,T.hmac)(_,E)}u.BASE._setWindowSize(8);function Je(R,L,M,_=ue){let E=R;if(L=ae("msgHash",L),M=ae("publicKey",M),"strict"in _)throw new Error("options.strict was renamed to lowS");let{lowS:T,prehash:k}=_,P,F;try{if(typeof E=="string"||Wt(E))try{P=w.fromDER(E)}catch(me){if(!(me instanceof Rr.Err))throw me;P=w.fromCompact(E)}else if(typeof E=="object"&&typeof E.r=="bigint"&&typeof E.s=="bigint"){let{r:me,s:Te}=E;P=new w(me,Te)}else throw new Error("PARSE");F=u.fromHex(M)}catch(me){if(me.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(T&&P.hasHighS())return!1;k&&(L=e.hash(L));let{r:V,s:Y}=P,$=N(L),z=c(Y),fe=a($*z),oe=a(V*z),xe=u.BASE.multiplyAndAddUnsafe(F,fe,oe)?.toAffine();return xe?a(xe.x)===V:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:v,sign:ce,verify:Je,ProjectivePoint:u,Signature:w,utils:x}}function Zg(r){return{hash:r,hmac:(e,...t)=>Kn(r,e,To(...t)),randomBytes:Yr}}function kf(r,e){let t=n=>Lf({...r,...Zg(n)});return Object.freeze({...t(e),create:t})}var Of=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Df=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Qg=BigInt(1),cc=BigInt(2),Pf=(r,e)=>(r+e/cc)/e;function Jg(r){let e=Of,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,f=u*u*r%e,l=ee(f,t,e)*f%e,h=ee(l,t,e)*f%e,g=ee(h,cc,e)*u%e,d=ee(g,o,e)*g%e,p=ee(d,s,e)*d%e,m=ee(p,a,e)*p%e,w=ee(m,c,e)*m%e,x=ee(w,a,e)*p%e,b=ee(x,t,e)*f%e,A=ee(b,i,e)*d%e,v=ee(A,n,e)*u%e,S=ee(v,cc,e);if(!lc.eql(lc.sqr(S),r))throw new Error("Cannot find square root");return S}var lc=Po(Of,void 0,void 0,{sqrt:Jg}),ut=kf({a:BigInt(0),b:BigInt(7),Fp:lc,n:Df,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Df,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Qg*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=Pf(s*r,e),c=Pf(-n*r,e),u=Z(r-a*t-c*o,e),f=Z(-a*n-c*s,e),l=u>i,h=f>i;if(l&&(u=e-u),h&&(f=e-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:h,k2:f}}}},Nf),Zx=BigInt(0);var Qx=ut.ProjectivePoint;function Uf(){return ut.utils.randomPrivateKey()}function Mf(r,e){let t=Ae.digest(e instanceof Uint8Array?e:e.subarray());if(et(t))return t.then(({digest:n})=>ut.sign(n,r).toDERRawBytes()).catch(n=>{throw new y(String(n),"ERR_INVALID_INPUT")});try{return ut.sign(t.digest,r).toDERRawBytes()}catch(n){throw new y(String(n),"ERR_INVALID_INPUT")}}function Ff(r,e,t){let n=Ae.digest(t instanceof Uint8Array?t:t.subarray());if(et(n))return n.then(({digest:o})=>ut.verify(e,o,r)).catch(o=>{throw new y(String(o),"ERR_INVALID_INPUT")});try{return ut.verify(e,n.digest,r)}catch(o){throw new y(String(o),"ERR_INVALID_INPUT")}}function Vf(r){return ut.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Kf(r){try{ut.getPublicKey(r,!0)}catch(e){throw new y(String(e),"ERR_INVALID_PRIVATE_KEY")}}function uc(r){try{ut.ProjectivePoint.fromHex(r)}catch(e){throw new y(String(e),"ERR_INVALID_PUBLIC_KEY")}}function Hf(r){try{return ut.getPublicKey(r,!0)}catch(e){throw new y(String(e),"ERR_INVALID_PRIVATE_KEY")}}var Jn=class{_key;constructor(e){uc(e),this._key=e}verify(e,t){return Ff(this._key,t,e)}marshal(){return Vf(this._key)}get bytes(){return mt.encode({Type:te.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}async hash(){let e=Ae.digest(this.bytes),t;return et(e)?{bytes:t}=await e:t=e.bytes,t}},eo=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??Hf(e),Kf(this._key),uc(this._publicKey)}sign(e){return Mf(this._key,e)}get public(){return new Jn(this._publicKey)}marshal(){return this._key}get bytes(){return gt.encode({Type:te.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=Ae.digest(this.bytes);return et(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return K(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Jr(this.bytes,e);throw new y(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function t0(r){return new eo(r)}function r0(r){return new Jn(r)}async function n0(){let r=Uf();return new eo(r)}var or={rsa:ic,ed25519:Xa,secp256k1:fc};function hc(r){let e=Object.keys(or).join(" / ");return new y(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function dc(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return or[r];throw hc(r)}async function $f(r,e){return dc(r).generateKeyPair(e??2048)}function to(r){let e=mt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case te.RSA:return or.rsa.unmarshalRsaPublicKey(t);case te.Ed25519:return or.ed25519.unmarshalEd25519PublicKey(t);case te.Secp256k1:return or.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw hc(e.Type??"unknown")}}function qf(r,e){return e=(e??"rsa").toLowerCase(),dc(e),r.bytes}async function ro(r){let e=gt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case te.RSA:return or.rsa.unmarshalRsaPrivateKey(t);case te.Ed25519:return or.ed25519.unmarshalEd25519PrivateKey(t);case te.Secp256k1:return or.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw hc(e.Type??"RSA")}}function Gf(r,e){return e=(e??"rsa").toLowerCase(),dc(e),r.bytes}var je=Ft(Xf(),1);je.default.formatters.b=r=>r==null?"undefined":ne.baseEncode(r);je.default.formatters.t=r=>r==null?"undefined":Ge.baseEncode(r);je.default.formatters.m=r=>r==null?"undefined":Dn.baseEncode(r);je.default.formatters.p=r=>r==null?"undefined":r.toString();je.default.formatters.c=r=>r==null?"undefined":r.toString();je.default.formatters.k=r=>r==null?"undefined":r.toString();je.default.formatters.a=r=>r==null?"undefined":r.toString();function g0(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Os(){return{forComponent(r){return y0(r)}}}function y0(r){let e=g0(`${r}:trace`);return je.default.enabled(`${r}:trace`)&&je.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,je.default)(`${r}:trace`)),Object.assign((0,je.default)(r),{error:(0,je.default)(`${r}:error`),trace:e})}var w0=Symbol.for("nodejs.util.inspect.custom"),Zf=Object.values(qt).map(r=>r.decoder).reduce((r,e)=>r.or(e),qt.identity.decoder),Qf=114,pc=36,mc=37,no=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[qi]=!0;toString(){return this.string==null&&(this.string=ne.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return nt.createV1(Qf,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ie(this.multihash.bytes,e);if(typeof e=="string")return ye(e).equals(this);if(e?.multihash?.bytes!=null)return ie(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[w0](){return`PeerId(${this.toString()})`}},Sr=class extends no{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Ir=class extends no{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Br=class extends no{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function Jf(r){if(r.type==="RSA")return new Sr(r);if(r.type==="Ed25519")return new Ir(r);if(r.type==="secp256k1")return new Br(r);throw new y("Not a PeerId","ERR_INVALID_PARAMETERS")}function ye(r,e){if(e=e??Zf,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=dr(ne.decode(`z${r}`));return r.startsWith("12D")?new Ir({multihash:t}):r.startsWith("16U")?new Br({multihash:t}):new Sr({multihash:t})}return fn(Zf.decode(r))}function fn(r){try{let e=dr(r);if(e.code===$t.code){if(e.digest.length===pc)return new Ir({multihash:e});if(e.digest.length===mc)return new Br({multihash:e})}if(e.code===Ae.code)return new Sr({multihash:e})}catch{return b0(nt.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function b0(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==Qf)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===Ae.code)return new Sr({multihash:r.multihash});if(e.code===$t.code){if(e.digest.length===pc)return new Ir({multihash:r.multihash});if(e.digest.length===mc)return new Br({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function hn(r,e){return r.length===pc?new Ir({multihash:dt($t.code,r),privateKey:e}):r.length===mc?new Br({multihash:dt($t.code,r),privateKey:e}):new Sr({multihash:await Ae.digest(r),publicKey:r,privateKey:e})}function dn(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var Xe=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return dn(this.map.entries(),e=>[ye(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,ye(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return dn(this.map.keys(),e=>ye(e))}values(){return this.map.values()}get size(){return this.map.size}};var ft=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return dn(this.set.entries(),e=>{let t=ye(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=ye(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return dn(this.set.values(),e=>ye(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var eh=async()=>{let r=await $f("Ed25519"),e=await E0(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function E0(r){return hn(qf(r.public),Gf(r))}var rh=Symbol.for("@achingbrain/uint8arraylist");function th(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Us(r){return!!r?.[rh]}var we=class r{bufs;length;[rh]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Us(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Us(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=th(this.bufs,e);return t.buf[t.index]}set(e,t){let n=th(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Us(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Re(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Re(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,f=t>a&&t<=c;if(u&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Us(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let h=u;h>=0;h--){let g=this.get(l+h);if(n[h]!==g){f=Math.max(1,h-a[g]);break}}if(f===0)return l}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ne(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=At(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=At(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=At(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ne(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=At(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=At(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=At(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=At(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=At(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!ie(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var nh={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var oo;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.publicKey=t.bytes();break;case 2:o.payloadType=t.bytes();break;case 3:o.payload=t.bytes();break;case 5:o.signature=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(oo||(oo={}));var pn=class r{static createFromProtobuf=async e=>{let t=oo.decode(e),n=await hn(t.publicKey);return new r({peerId:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t.privateKey==null)throw new Error("Missing private key");let n=e.domain,o=e.codec,s=e.marshal(),i=oh(n,o,s),c=await(await ro(t.privateKey)).sign(i.subarray());return new r({peerId:t,payloadType:o,payload:s,signature:c})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new y("envelope signature is not valid for the given domain",nh.ERR_SIGNATURE_NOT_VALID);return n};peerId;payloadType;payload;signature;marshaled;constructor(e){let{peerId:t,payloadType:n,payload:o,signature:s}=e;this.peerId=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=oo.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return ie(this.marshal(),e.marshal())}async validate(e){let t=oh(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return to(this.peerId.publicKey).verify(t.subarray(),this.signature)}},oh=(r,e,t)=>{let n=D(r),o=Le(n.byteLength),s=Le(e.length),i=Le(t.length);return new we(o,n,s,e,i,t)};function sh(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Ms=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let h=Number.parseInt(l,e);if(!Number.isNaN(h))return h});if(f===void 0)break;if(s*=e,s+=f,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var ih=45,x0=15,mn=new Ms;function gc(r){if(!(r.length>x0))return mn.new(r).parseWith(()=>mn.readIPv4Addr())}function yc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>ih))return mn.new(r).parseWith(()=>mn.readIPv6Addr())}function Fs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>ih))return mn.new(r).parseWith(()=>mn.readIPAddr())}var m1=parseInt("0xFFFF",16),g1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function gn(r){return!!gc(r)}function yn(r){return!!yc(r)}function Vs(r){return!!Fs(r)}var lh=gn,S0=yn,wc=function(r){let e=0;if(r=r.toString().trim(),lh(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(S0(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=lh(t[n]),i;s&&(i=wc(t[n]),t[n]=K(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,K(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},uh=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var wn={},bc={},B0=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,-1,"memory"]];B0.forEach(r=>{let e=T0(...r);bc[e.code]=e,wn[e.name]=e});function T0(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function X(r){if(typeof r=="number"){if(bc[r]!=null)return bc[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(wn[r]!=null)return wn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var J1=X("ip4"),eA=X("ip6"),tA=X("ipcidr");function xc(r,e){switch(X(r).code){case 4:case 41:return C0(e);case 42:return dh(e);case 6:case 273:case 33:case 132:return mh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return dh(e);case 421:return P0(e);case 444:return ph(e);case 445:return ph(e);case 466:return D0(e);default:return K(e,"base16")}}function vc(r,e){switch(X(r).code){case 4:return fh(e);case 41:return fh(e);case 42:return hh(e);case 6:case 273:case 33:case 132:return Ac(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return hh(e);case 421:return L0(e);case 444:return O0(e);case 445:return U0(e);case 466:return k0(e);default:return D(e,"base16")}}var Ec=Object.values(qt).map(r=>r.decoder),N0=function(){let r=Ec[0].or(Ec[1]);return Ec.slice(2).forEach(e=>r=r.or(e)),r}();function fh(r){if(!Vs(r))throw new Error("invalid ip address");return wc(r)}function C0(r){let e=uh(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Vs(e))throw new Error("invalid ip address");return e}function Ac(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function mh(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function hh(r){let e=D(r),t=Uint8Array.from(Le(e.length));return Re([t,e],t.length+e.length)}function dh(r){let e=it(r);if(r=r.slice(he(e)),r.length!==e)throw new Error("inconsistent lengths");return K(r)}function L0(r){let e;r[0]==="Q"||r[0]==="1"?e=dr(ne.decode(`z${r}`)).bytes:e=nt.parse(r).multihash.bytes;let t=Uint8Array.from(Le(e.length));return Re([t,e],t.length+e.length)}function k0(r){let e=N0.decode(r),t=Uint8Array.from(Le(e.length));return Re([t,e],t.length+e.length)}function D0(r){let e=it(r),t=r.slice(he(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+K(t,"base64url")}function P0(r){let e=it(r),t=r.slice(he(e));if(t.length!==e)throw new Error("inconsistent lengths");return K(t,"base58btc")}function O0(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=Ge.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ac(n);return Re([t,o],t.length+o.length)}function U0(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Ge.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ac(n);return Re([t,o],t.length+o.length)}function ph(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=K(e,"base32"),o=mh(t);return`${n}:${o}`}function gh(r){r=Rc(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=X(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw wh("invalid address: "+r);if(a.path===!0){n=Rc(o.slice(s).join("/")),e.push([a.code,vc(a.code,n)]),t.push([a.code,n]);break}let c=vc(a.code,o[s]);e.push([a.code,c]),t.push([a.code,xc(a.code,c)])}return{string:yh(t),bytes:Sc(e),tuples:e,stringTuples:t,path:n}}function _c(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=it(r,o),i=he(s),a=X(s),c=M0(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw wh("Invalid address Uint8Array: "+K(r,"base16"));e.push([s,u]);let f=xc(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:yh(t),tuples:e,stringTuples:t,path:n}}function yh(r){let e=[];return r.map(t=>{let n=X(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Rc(e.join("/"))}function Sc(r){return Re(r.map(e=>{let t=X(e[0]),n=Uint8Array.from(Le(t.code));return e.length>1&&e[1]!=null&&(n=Re([n,e[1]])),n}))}function M0(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=it(e instanceof Uint8Array?e:Uint8Array.from(e));return t+he(t)}}function Rc(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function wh(r){return new Error("Error parsing address: "+r)}var F0=Symbol.for("nodejs.util.inspect.custom"),Ic=Symbol.for("@multiformats/js-multiaddr/multiaddr"),V0=[X("dns").code,X("dns4").code,X("dns6").code,X("dnsaddr").code],Ks=class r{bytes;#e;#t;#s;#a;[Ic]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=_c(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=gh(e)}else if(sr(e))t=_c(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#s=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=X("tcp"),a=X("udp"),c=X("ip4"),u=X("ip6"),f=X("dns6"),l=X("ip6zone");for(let[g,d]of this.stringTuples())g===l.code&&(s=`%${d??""}`),V0.includes(g)&&(t=i.name,o=443,n=`${d??""}${s}`,e=g===f.code?6:4),(g===i.code||g===a.code)&&(t=X(g).name,o=parseInt(d??"")),(g===c.code||g===u.code)&&(t=X(g).name,n=`${d??""}${s}`,e=g===u.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},X(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>X(e).name)}tuples(){return this.#t}stringTuples(){return this.#s}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(Sc(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===wn.p2p.code&&e.push([n,o]),n===wn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?K(ne.decode(`z${n}`),"base58btc"):K(nt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return ie(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=bn.get(t.name);if(n==null)throw new y(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>re(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[F0](){return`Multiaddr(${this.#e})`}};var bn=new Map;function sr(r){return!!r?.[Ic]}function re(r){return new Ks(r)}var bh="libp2p-peer-record",Eh=Uint8Array.from([3,1]);var so;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Ve((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let a={multiaddr:new Uint8Array(0)},c=i==null?s.len:s.pos+i;for(;s.pos<c;){let u=s.uint32();switch(u>>>3){case 1:a.multiaddr=s.bytes();break;default:s.skipType(u&7);break}}return a})),o),n.encode=s=>Fe(s,n.codec()),n.decode=s=>Me(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ve((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},i=o==null?n.len:n.pos+o;for(;n.pos<i;){let a=n.uint32();switch(a>>>3){case 1:s.peerId=n.bytes();break;case 2:s.seq=n.uint64();break;case 3:s.addresses.push(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return s})),t),r.encode=n=>Fe(n,r.codec()),r.decode=n=>Me(n,r.codec())})(so||(so={}));var Tr=class r{static createFromProtobuf=e=>{let t=so.decode(e),n=fn(t.peerId),o=(t.addresses??[]).map(i=>re(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=bh;static CODEC=Eh;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=so.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!sh(this.multiaddrs,e.multiaddrs))}};function K0(r){return r[Symbol.asyncIterator]!=null}function H0(r){if(K0(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var io=H0;var Tc=Ft(vh(),1);var co=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Nc=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Ah=r=>globalThis.DOMException===void 0?new Nc(r):new DOMException(r),Rh=r=>{let e=r.reason===void 0?Ah("This operation was aborted."):r.reason;return e instanceof Error?e:Ah(e)};function lo(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&f(Rh(h)),h.addEventListener("abort",()=>{f(Rh(h))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new co;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){f(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(l.message=o??`Promise timed out after ${t} milliseconds`,f(l))},t),(async()=>{try{u(await r)}catch(h){f(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function Cc(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var uo=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=Cc(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var ir=class extends Tc.default{#e;#t;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#i;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:uo,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#c=e.interval,this.#r=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#b(){return this.#t||this.#s<this.#a}get#E(){return this.#o<this.#u}#x(){this.#o--,this.#f(),this.emit("next")}#v(){this.#w(),this.#y(),this.#l=void 0}get#A(){let e=Date.now();if(this.#n===void 0){let t=this.#p-e;if(t<0)this.#s=this.#e?this.#o:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#v()},t)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#o===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#A;if(this.#b&&this.#E){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#s===0&&this.#o===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#s=this.#e?this.#o:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#u=e,this.#h()}async#R(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#o++,this.#s++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=lo(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#R(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof co&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#x()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#h(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#i}};var ar={},En=r=>{r.addEventListener("message",e=>{En.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{En.dispatchEvent("message",r,e)})};En.addEventListener=(r,e)=>{ar[r]==null&&(ar[r]=[]),ar[r].push(e)};En.removeEventListener=(r,e)=>{ar[r]!=null&&(ar[r]=ar[r].filter(t=>t===e))};En.dispatchEvent=function(r,e,t){ar[r]!=null&&ar[r].forEach(n=>n(e,t))};var Lc=En;var kc="lock:worker:request-read",Dc="lock:worker:release-read",Pc="lock:master:grant-read",Oc="lock:worker:request-write",Uc="lock:worker:release-write",Mc="lock:master:grant-write";var _h=(r=21)=>Math.random().toString().substring(2);var Sh=(r,e,t,n,o)=>(s,i)=>{if(i.data.type!==t)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=f=>{if(f==null||f.data==null)return;let l={type:f.data.type,name:f.data.name,identifier:f.data.identifier};l.type===n&&l.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})}}}))},Ih=(r,e,t,n)=>async()=>{let o=_h();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},G0={singleProcess:!1},Bh=r=>{if(r=Object.assign({},G0,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return Lc.addEventListener("message",Sh(t,"requestReadLock",kc,Dc,Pc)),Lc.addEventListener("message",Sh(t,"requestWriteLock",Oc,Uc,Mc)),t}return{isWorker:!0,readLock:t=>Ih(t,kc,Pc,Dc),writeLock:t=>Ih(t,Oc,Mc,Uc)}};var Nr={},cr;async function Fc(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>lo((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var z0=(r,e)=>{if(cr.isWorker===!0)return{readLock:cr.readLock(r,e),writeLock:cr.writeLock(r,e)};let t=new ir({concurrency:1}),n;return{async readLock(){if(n!=null)return Fc(n,e);n=new ir({concurrency:e.concurrency,autoStart:!1});let o=n,s=Fc(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,Fc(t,e)}}},Y0={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Vc(r){let e=Object.assign({},Y0,r);return cr==null&&(cr=Bh(e),cr.isWorker!==!0&&(cr.addEventListener("requestReadLock",t=>{Nr[t.data.name]!=null&&Nr[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),cr.addEventListener("requestWriteLock",async t=>{Nr[t.data.name]!=null&&Nr[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Nr[e.name]==null&&(Nr[e.name]=z0(e.name,e)),Nr[e.name]}var Se={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var xn;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ve((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:"",value:new Uint8Array(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=i.bytes();break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Fe(i,o.codec()),o.decode=i=>Me(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ve((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),qs.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=qs.codec().decode(i,i.uint32());break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Fe(i,o.codec()),o.decode=i=>Me(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ve((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),$s.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.addresses.push($s.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(u.key,u.value);break}case 7:{let u=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(u.key,u.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>Fe(o,r.codec()),r.decode=o=>Me(o,r.codec())})(xn||(xn={}));var $s;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.multiaddr=t.bytes();break;case 2:o.isCertified=t.bool();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})($s||($s={}));var qs;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.value=t.uint32();break;case 2:o.expiry=t.uint64();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(qs||(qs={}));function vn(r,e){let t=xn.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=Jf({...r,publicKey:r.publicKey}));let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:re(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Ut="/",Th=new TextEncoder().encode(Ut),Gs=Th[0],Cr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=D(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Gs)throw new Error("Invalid key")}toString(e="utf8"){return K(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ut))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Th),this._buf[0]!==Gs){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Gs,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Gs;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ut).slice(1)}type(){return W0(this.baseNamespace())}name(){return j0(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ut)||(e+=Ut),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ut):new r(e.slice(0,-1).join(Ut))}child(e){return this.toString()===Ut?e:e.toString()===Ut?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...X0(e.map(t=>t.namespaces()))])}};function W0(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function j0(r){let e=r.split(":");return e[e.length-1]}function X0(r){return[].concat(...r)}var Kc="/peers/";function An(r){if(!vo(r)||r.type==null)throw new y("Invalid PeerId",Se.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Cr(`${Kc}${e}`)}async function Nh(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=re(o.multiaddr)),!sr(o.multiaddr))throw new y("Multiaddr was invalid",Se.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function Ys(r,e,t,n){if(e==null)throw new y("Invalid PeerData",Se.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!ie(e.publicKey,r.publicKey))throw new y("publicKey bytes do not match peer id publicKey bytes",Se.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new y("peer id did not match existing peer id",Se.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=zs(l,{validate:Ch})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=zs(l,{validate:Lh,map:kh})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,g]of l)g==null?a.delete(h):a.set(h,g);a=zs([...a.entries()],{validate:Ch})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[g,d]of l)d==null?h.delete(g):h.set(g,d);c=zs([...h.entries()],{validate:Lh,map:kh})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f={addresses:await Nh(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((l,h)=>l.localeCompare(h)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:u};return r.type!=="RSA"&&delete f.publicKey,f}function zs(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function Ch(r,e){if(typeof r!="string")throw new y("Metadata key must be a string",Se.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new y("Metadata value must be a Uint8Array",Se.ERR_INVALID_PARAMETERS)}function Lh(r,e){if(typeof r!="string")throw new y("Tag name must be a string",Se.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new y("Tag value must be an integer",Se.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new y("Tag value must be between 0-100",Se.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new y("Tag ttl must be an integer",Se.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new y("Tag ttl must be between greater than 0",Se.ERR_INVALID_PARAMETERS)}}function kh(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function Ws(r,e,t){let n=r.toString().split("/")[2],o=Ge.decode(n),s=fn(o),i=t.get(s);if(i!=null)return i;let a=vn(s,e);return t.set(s,a),a}function Z0(r,e){return r==null?{}:{prefix:Kc,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Ws(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Ws(n.key,n.value,e),Ws(o.key,o.value,e)))}}var js=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Vc({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(An(e))}async delete(e){if(this.peerId.equals(e))throw new y("Cannot delete self peer",Se.ERR_INVALID_PARAMETERS);await this.datastore.delete(An(e))}async load(e){let t=await this.datastore.get(An(e));return vn(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Ys(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Ys(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Ys(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new Xe;for await(let{key:n,value:o}of this.datastore.query(Z0(e??{},t))){let s=Ws(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(An(e)),n=vn(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,o){let s=xn.encode(t);return n!=null&&ie(s,n)?{peer:vn(e,s),previous:o,updated:!1}:(await this.datastore.put(An(e),s),{peer:vn(e,s),previous:o,updated:!0})}};var Xs=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new js(e,t)}async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await io(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await pn.openAndCertify(e,Tr.DOMAIN);if(t?.equals(n.peerId)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let o=Tr.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(s?.peerRecordEnvelope!=null){let i=await pn.createFromProtobuf(s.peerRecordEnvelope),a=Tr.createFromProtobuf(i.payload);if(a.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(i=>({isCertified:!0,multiaddr:i}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function Q0(r){return r[Symbol.asyncIterator]!=null}function J0(r){if(Q0(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Hc=J0;function ey(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Dh=ey;function ty(r){return r[Symbol.asyncIterator]!=null}function ry(r,e){if(ty(r))return async function*(){for await(let a of r)await e(a)&&(yield a)}();let t=Dh(r),{value:n,done:o}=t.next();if(o===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){await s&&(yield n);for await(let a of t)await e(a)&&(yield a)}();let i=e;return function*(){s===!0&&(yield n);for(let a of t)i(a)&&(yield a)}()}var Lr=ry;function ny(r){return r[Symbol.asyncIterator]!=null}function oy(r,e){return ny(r)?async function*(){yield*(await io(r)).sort(e)}():function*(){yield*io(r).sort(e)}()}var $c=oy;function sy(r){return r[Symbol.asyncIterator]!=null}function iy(r,e){return sy(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var qc=iy;var Zs=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Hc(this.putMany(e,n)),e=[],await Hc(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Lr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Lr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>$c(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Lr(n,()=>o++>=s)}return e.limit!=null&&(n=qc(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Lr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Lr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>$c(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Lr(n,()=>s++>=o)}return e.limit!=null&&(n=qc(n,e.limit)),n}};var Uh=Ft(Gc(),1);function Mh(r){return r=r??new Error("Not Found"),(0,Uh.default)(r,"ERR_NOT_FOUND")}var Qs=class extends Zs{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw Mh();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new Cr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Cr(e)}};function Fh(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var ly=r=>r;function zc(r,e){let t=r.getPeerId();return t!=null&&ye(t).equals(e)&&(r=r.decapsulate(re(`/p2p/${e.toString()}`))),r}var Js=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??ly,this._updatePeerStoreAddresses=Fh(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>re(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>re(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>re(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>re(e))}addObservedAddr(e){e=zc(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=zc(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=zc(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>re(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var Yc=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=Os())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Pl(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},uy=["metrics","connectionProtector","dns"],fy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Vh(r={}){let e=new Yc(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!fy.includes(o)){let i=e.components[o];if(i==null&&!uy.includes(o))throw new y(`${o} not set`,"ERR_SERVICE_MISSING");return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}var Hh=Ft(Kh(),1),hy=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],dy=hy.map(r=>new Hh.Netmask(r));function py(r){for(let e of dy)if(e.contains(r))return!0;return!1}function my(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function ei(r){return gn(r)?py(r):yn(r)?my(r):void 0}function $h(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!ei(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var gy=r=>r.toString().split("/").slice(1),ho=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),W=r=>({match:e=>ho(t=>t===r).match(e),pattern:r}),ni=()=>({match:r=>ho(e=>typeof e=="string").match(r),pattern:"{string}"}),oi=()=>({match:r=>ho(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Ie=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ne.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ti=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{ua.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),$e=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),Ze=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),Q=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function le(...r){function e(o){let s=gy(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matches:t,exactMatch:n}}var jc=Q(W("dns4"),ni()),Xc=Q(W("dns6"),ni()),Zc=Q(W("dnsaddr"),ni()),qh=Q(W("dns"),ni()),SR=le(jc),IR=le(Xc),BR=le(Zc),TR=le(Ze(qh,Zc,jc,Xc)),Gh=Q(W("ip4"),ho(gn)),zh=Q(W("ip6"),ho(yn)),Yh=Ze(Gh,zh),Et=Ze(Yh,qh,jc,Xc,Zc),NR=le(Et),CR=le(Gh),LR=le(zh),kR=le(Yh),si=Q(Et,W("tcp"),oi()),po=Q(Et,W("udp"),oi()),yy=Ze(si,po),DR=le(si),PR=le(po),Qc=Q(po,W("quic")),ii=Q(po,W("quic-v1")),wy=Ze(Qc,ii),OR=le(Qc),UR=le(ii),Wc=Ze(Et,si,po,Qc,ii),Wh=Ze(Q(Wc,W("ws"),$e(Ie()))),MR=le(Wh),jh=Ze(Q(Wc,W("wss"),$e(Ie())),Q(Wc,W("tls"),W("ws"),$e(Ie()))),FR=le(jh),Xh=Q(yy,W("webrtc-direct"),ti(),$e(ti()),$e(Ie())),VR=le(Xh),Zh=Q(ii,W("webtransport"),ti(),ti(),$e(Ie())),KR=le(Zh),ri=Ze(Wh,jh,Q(si,$e(Ie())),Q(wy,$e(Ie())),Q(Et,$e(Ie())),Xh,Zh,Ie()),HR=le(ri),by=Q(ri,W("p2p-circuit"),Ie()),mo=le(by),Ey=Ze(Q(ri,W("p2p-circuit"),W("webrtc"),Ie()),Q(ri,W("webrtc"),$e(Ie())),W("webrtc")),$R=le(Ey),xy=Ze(Q(Et,W("tcp"),oi(),W("http"),$e(Ie())),Q(Et,W("http"),$e(Ie()))),qR=le(xy),vy=Ze(Q(Et,W("tcp"),Ze(Q(W("443"),W("http")),Q(oi(),W("https"))),$e(Ie())),Q(Et,W("tls"),W("http"),$e(Ie())),Q(Et,W("https"),$e(Ie()))),GR=le(vy);function Jc(r){try{let{address:e}=r.nodeAddress();return!!ei(e)}catch{return!0}}function Ay(r,e){let t=Jc(r.multiaddr),n=Jc(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Ry(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function _y(r,e){let t=mo.exactMatch(r.multiaddr),n=mo.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Rn(r,e){let t=Ay(r,e);if(t!==0)return t;let n=_y(r,e);return n!==0?n:Ry(r,e)}var lr=class extends Event{constructor(e,t){super(e),this.detail=t}};function ai(r){let e=[Qe.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var el=60;function ci(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:Qe[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Qe[e.type],TTL:e.TTL??e.ttl??el,data:e.data instanceof Uint8Array?K(e.data):e.data}))}}var Sy=4;function tl(r,e={}){let t=new ir({concurrency:e.queryConcurrency??Sy});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),ai(o.types).forEach(a=>{s.append("type",Qe[a])}),o.onProgress?.(new lr("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=ci(await a.json());return o.onProgress?.(new lr("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function Qh(){return[tl("https://cloudflare-dns.com/dns-query"),tl("https://dns.google/resolve")]}var td=Ft(ed(),1);var rl=class{lru;constructor(e){this.lru=(0,td.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return ci({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Qe[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??el)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function rd(r){return new rl(r)}var Iy=1e3,li=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=rd(e.cacheSize??Iy),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Qh())}async query(e,t={}){let n=ai(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new lr("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,types:n});for(let f of u.Answer)this.cache.add(e,f);return u}catch(u){a.push(u),t.onProgress?.(new lr("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var Qe;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Qe||(Qe={}));function nd(r={}){return new li(r)}var By=32,{code:Ty}=X("dnsaddr"),kr=async function(e,t={}){let n=t.maxRecursiveDepth??By;if(n===0)throw new y("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([u])=>u===Ty)??[],i=await(t?.dns??nd()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[Qe.TXT]}),a=e.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=re(f);if(f.startsWith("/dnsaddr")){let h=await l.resolve({...t,maxRecursiveDepth:n-1});c.push(...h.map(g=>g.toString()))}else c.push(l.toString())}return c};var hd=Ft(fd(),1),hi=hd.default;var Mt;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Mt||(Mt={}));var B;(function(r){r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(B||(B={}));var Py={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:kr},addressSorter:Rn},transportManager:{faultTolerance:Vt.FATAL_ALL}};async function dd(r){let e=hi(Py,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new y(Mt.ERR_PROTECTOR_REQUIRED,B.ERR_PROTECTOR_REQUIRED);if(!(await hn(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new y("Private key doesn't match peer id",B.ERR_INVALID_KEY);return e}var pd=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Oy=new WeakMap;function Uy({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(pd());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(pd())},f=()=>{o&&o.removeEventListener("abort",u)},l=new Promise((h,g)=>{i=()=>{f(),h(n)},a=g,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",u,{once:!0}),Oy.set(l,()=>{c(s),s=null,i()}),l}}var My=Uy(),md=My;var di=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new ol}async consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new y("Rate limit exceeded","ERR_RATE_LIMIT_EXCEEDED",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await md(a)}return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},ol=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function pi(r){if(vo(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:ye(t),r.forEach(n=>{if(!sr(n))throw new y("Invalid Multiaddr",B.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new y("Multiaddrs must all have the same peer id or have no peer id",B.ERR_INVALID_PARAMETERS)}else{let s=ye(o);if(e==null||!e.equals(s))throw new y("Multiaddrs must all have the same peer id or have no peer id",B.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}function pe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var mi=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},In=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new mi(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new mi(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var sl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function gi(r={}){return Fy(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Fy(r,e){e=e??{};let t=e.onEnd,n=new In,o,s,i,a=pe(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,w)=>{s=x=>{s=null,n.push(x);try{m(r(n))}catch(b){w(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=pe()})}},u=m=>s!=null?s(m):(n.push(m),o),f=m=>(n=new In,s!=null?s({error:m}):(n.push({error:m}),o)),l=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:m})},h=m=>i?o:(i=!0,m!=null?f(m):u({done:!0})),g=()=>(n=new In,h(),{done:!0}),d=m=>(h(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:g,throw:d,push:l,end:h,get readableLength(){return n.size},onEmpty:async m=>{let w=m?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let x,b;w!=null&&(x=new Promise((A,v)=>{b=()=>{v(new sl)},w.addEventListener("abort",b)}));try{await Promise.race([a.promise,x])}finally{b!=null&&w!=null&&w?.removeEventListener("abort",b)}}},t==null)return o;let p=o;return o={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(m){return p.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return p.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(m){return p.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return p.readableLength},onEmpty:m=>p.onEmpty(m)},o}var il=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function yi(r,e,t,n){let o=new il(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{let a=u=>{try{if(n?.filter?.(u)===!1)return}catch(f){r.removeEventListener(e,a),t?.removeEventListener("abort",c),i(f);return}r.removeEventListener(e,a),t?.removeEventListener("abort",c),s(u)},c=()=>{r.removeEventListener(e,a),t?.removeEventListener("abort",c),i(o)};r.addEventListener(e,a),t?.addEventListener("abort",c)})}var wi=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Bn(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new wi(t?.errorMessage,t?.errorCode));let n,o=new wi(t?.errorMessage,t?.errorCode);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var bi=class{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=pe(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(new Kt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Vy(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ei=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(e,t,n=0){this.id=Vy(),this.status="queued",this.fn=e,this.priority=n,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,Oe(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&this.controller.abort(new Kt)}async join(e={}){let t=new bi(new Error("where").stack,e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Bn(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.signal?.removeEventListener("abort",this.onAbort)})}};function Ky(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var Tn=class extends hr{concurrency;queue;pending;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){if(this.queue[this.size-1]?.priority>=e.priority){this.queue.push(e);return}let t=Ky(this.queue,e,(n,o)=>o.priority-n.priority);this.queue.splice(t,0,e)}async add(e,t){t?.signal?.throwIfAborted();let n=new Ei(e,t,t?.priority),o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{throw this.safeDispatchEvent("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Kt)}),this.clear()}async onEmpty(e){this.size!==0&&await yi(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await yi(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await yi(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=gi({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new y("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var xi=class extends Tn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var vi="last-dial-failure";var Ai=5,Ri=100,_i=50,gd=1e3*60*7;var Dr={minConnections:Ai,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:gd,autoDialDiscoveredPeersDebounce:10},Si=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??Dr.minConnections,this.autoDialPriority=t.autoDialPriority??Dr.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Dr.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Dr.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Dr.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Dr.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new xi({concurrency:t.autoDialConcurrency??Dr.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",o=>{this.log.error("error during auto-dial",o.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{this.log.error(o)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{this.log.error(o)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new ft(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[u=>u.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",u.id),!1):e.has(u.id)?(this.log.trace("not autodialing %p because they are already connected",u.id),!1):n.has(u.id)?(this.log.trace("not autodialing %p because they are already being dialed",u.id),!1):this.queue.has(u.id)?(this.log.trace("not autodialing %p because they are already being autodialed",u.id),!1):!0]}),s=o.sort(()=>Math.random()>.5?1:-1),i=new Xe;for(let u of s)i.has(u.id)||i.set(u.id,[...u.tags.values()].reduce((f,l)=>f+l.value,0));let c=s.sort((u,f)=>{let l=i.get(u.id)??0,h=i.get(f.id)??0;return l>h?-1:l<h?1:0}).filter(u=>{let f=u.metadata.get(vi);if(f==null)return!0;let l=parseInt(K(f));return isNaN(l)?!0:Date.now()-l>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let u of c)this.queue.add(async()=>{let f=this.connectionManager.getConnectionsMap().size;if(f>=this.minConnections){this.log("got enough connections now %d/%d",f,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(f=>{this.log.error("could not connect to peerStore stored peer",f)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var yd={maxConnections:Ri,allow:[]},Ii=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??yd.maxConnections,this.allow=t.allow??yd.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=Math.max(t-this.maxConnections,0);if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;this.log("max connections limit exceeded %d/%d, pruning %d connection(s)",t,this.maxConnections,n);let o=new Xe;for(let a of e){let c=a.remotePeer;if(!o.has(c)){o.set(c,0);try{let u=await this.peerStore.get(c);o.set(c,[...u.tags.values()].reduce((f,l)=>f+l.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",u)}}}let s=e.sort((a,c)=>{let u=o.get(a.remotePeer)??0,f=o.get(c.remotePeer)??0;if(u>f)return 1;if(u<f)return-1;let l=a.timeline.open,h=c.timeline.open;return l<h?1:l>h?-1:0}),i=[];for(let a of s)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||i.push(a),i.length===n)break;await Promise.all(i.map(async a=>{try{await a.close()}catch(c){this.log.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:i})}};function wd(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}async function bd(r,e){let t=!1;for(let o of bn.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var go={addressSorter:Rn,maxParallelDials:_i,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:kr}},Bi=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??go.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??go.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??go.maxDialQueueLength,this.dialTimeout=t.dialTimeout??go.dialTimeout,this.connections=t.connections??new Xe,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,Oe(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))bn.set(n,o);this.queue=new Tn({concurrency:t.maxParallelDials??go.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,Oe(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=pi(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new y("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),this.queue.add(async a=>{let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),u.map(({multiaddr:f})=>f.toString()).forEach(f=>{a?.multiaddrs.add(f)})}catch(f){throw c.clear(),f}try{let f=0,l=[];for(let h of u){if(f===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",f,n),new y("Peer had more than maxPeerAddrsToDial",B.ERR_TOO_MANY_ADDRESSES);f++;try{let g=await this.components.transportManager.dial(h.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",h.multiaddr),g}catch(g){if(this.log.error("dial failed to %a",h.multiaddr,g),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[vi]:D(Date.now().toString())}})}catch(d){this.log.error("could not update last dial failure key for %p",n,d)}if(c.aborted)throw new y(g.message,Ro);l.push(g)}}throw l.length===1?l[0]:new Ao(l,"All multiaddr dials failed",B.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal})}createDialAbortController(e){let t=wd([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return Oe(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(l=>({multiaddr:re(l),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new y("Tried to dial self",B.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new y("The dial request is blocked by gater.allowDialPeer",B.ERR_PEER_DIAL_INTERCEPTED);if(o.length===0){this.log("loading multiaddrs for %p",e);try{let l=await this.components.peerStore.get(e);o.push(...l.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:h})=>h.toString()))}catch(l){if(l.code!==B.ERR_NOT_FOUND)throw l}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let l=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:h})=>h.toString())),o.push(...l.multiaddrs.map(h=>({multiaddr:h,isCertified:!1})))}catch(l){l.code!==B.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,l)}}}let s=(await Promise.all(o.map(async l=>{let h=await bd(l.multiaddr,{dns:this.components.dns,...n,log:this.log});return h.length===1&&h[0].equals(l.multiaddr)?l:h.map(g=>({multiaddr:g,isCertified:!1}))}))).flat();if(e!=null){let l=`/p2p/${e.toString()}`;s=s.map(h=>h.multiaddr.protos().pop()?.path===!0?h:h.multiaddr.getPeerId()==null?{multiaddr:h.multiaddr.encapsulate(l),isCertified:h.isCertified}:h)}let i=s.filter(l=>{if(this.components.transportManager.transportForMultiaddr(l.multiaddr)==null)return!1;let h=l.multiaddr.getPeerId();return e!=null&&h!=null?e.equals(h):!0}),a=new Map;for(let l of i){let h=l.multiaddr.toString(),g=a.get(h);if(g!=null){g.isCertified=g.isCertified||l.isCertified||!1;continue}a.set(h,l)}let c=[...a.values()];if(c.length===0)throw new y("The dial request has no valid addresses",B.ERR_NO_VALID_ADDRESSES);let u=[];for(let l of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(l.multiaddr)||u.push(l);let f=u.sort(this.addressSorter);if(f.length===0)throw new y("The connection gater denied all addresses in the dial request",B.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:l})=>l.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",f.map(({multiaddr:l})=>l.toString())),f}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnTransientConnection===!1?n.find(o=>!mo.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var zy=50,Pr={minConnections:Ai,maxConnections:Ri,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},Ti=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Pr.maxConnections;let n=t.minConnections??Pr.minConnections;if(this.maxConnections<n)throw new y("Connection Manager maxConnections must be greater than minConnections",B.ERR_INVALID_PARAMETERS);this.connections=new Xe,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map(o=>re(o)),this.deny=(t.deny??[]).map(o=>re(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Pr.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new di({points:t.inboundConnectionThreshold??Pr.inboundConnectionThreshold,duration:1}),this.autoDial=new Si({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??Pr.autoDialConcurrency,autoDialPriority:t.autoDialPriority??Pr.autoDialPriority,maxQueueLength:t.autoDialMaxQueueLength??Pr.autoDialMaxQueueLength}),this.connectionPruner=new Ii({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Bi(e,{addressSorter:t.addressSorter??Rn,maxParallelDials:t.maxParallelDials??_i,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:kr},connections:this.connections})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(Dl)]});await Promise.all(e.map(async t=>{await this.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new y("Not started",B.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=pi(e);if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??zy}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>re(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};function Yy(r){return r[Symbol.asyncIterator]!=null}function Wy(...r){let e=[];for(let t of r)Yy(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=gi({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var yo=Wy;var Ni=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new y("No content routers available",B.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ft;for await(let s of yo(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new y("No content routers available",B.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new y(Mt.NOT_STARTED_YET,B.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new y(Mt.NOT_STARTED_YET,B.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var Ci=globalThis.CustomEvent??Event;async function*dl(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,s=[],i=pe(),a=pe(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let d of r){if(s.length===t&&(i=pe(),await i.promise),f)break;let p={done:!1};s.push(p),d().then(m=>{p.done=!0,p.ok=!0,p.value=m,o.dispatchEvent(new Ci("task-complete"))},m=>{p.done=!0,p.err=m,o.dispatchEvent(new Ci("task-complete"))})}c=!0,o.dispatchEvent(new Ci("task-complete"))}catch(d){u=d,o.dispatchEvent(new Ci("task-complete"))}});function l(){return n?s[0]?.done:!!s.find(d=>d.done)}function*h(){for(;s.length>0&&s[0].done;){let d=s[0];if(s.shift(),d.ok)yield d.value;else throw f=!0,i.resolve(),d.err;i.resolve()}}function*g(){for(;l();)for(let d=0;d<s.length;d++)if(s[d].done){let p=s[d];if(s.splice(d,1),d--,p.ok)yield p.value;else throw f=!0,i.resolve(),p.err;i.resolve()}}for(;;){if(l()||(a=pe(),await a.promise),u!=null)throw u;if(n?yield*h():yield*g(),c&&s.length===0)break}}var Li=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}async findPeer(e,t){if(this.routers.length===0)throw new y("No peer routers available",B.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new y("Should not try to find self",B.ERR_FIND_SELF);let n=this,o=yo(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new y(Mt.NOT_FOUND,B.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new y("No peer routers available",B.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ft;for await(let s of dl(async function*(){let i=yo(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}};var pl=32,ml=64,ki=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new y(`No handler registered for protocol ${e}`,B.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new y(`Handler already registered for protocol ${e}`,B.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=hi.bind({ignoreUndefined:!0})({maxInboundStreams:pl,maxOutboundStreams:ml},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new y("invalid topology",B.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.onDisconnect?.(t)}}).catch(n=>{n.code!==B.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.onDisconnect?.(t.id)}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.transient&&a.notifyOnTransient!==!0||a.onConnect?.(o,n)}}};var gl=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ed(r){let{name:e,metrics:t}=r,n;return t!=null?n=new gl({name:e,metrics:t}):n=new Map,n}var Di=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=Ed({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Vt.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(t==null)throw new y("Transport must have a valid tag",B.ERR_INVALID_KEY);if(this.transports.has(t))throw new y(`There is already a transport with the tag ${t}`,B.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.transportForMultiaddr(e);if(n==null)throw new y(`No transport available for address ${String(e)}`,B.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=B.ERR_TRANSPORT_DIAL_FAILED),o}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}transportForMultiaddr(e){for(let t of this.transports.values())if(t.filter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new y("Not started",B.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let s=o.filter(e),i=[];for(let u of s){this.log("creating listener for %s on %a",n,u);let f=o.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(n)??[];l==null&&(l=[],this.listeners.set(n,l)),l.push(f),f.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:f})}),f.addEventListener("close",()=>{let h=l.findIndex(g=>g===f);l.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),i.push(f.listen(u))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Vt.NO_FATAL)throw new y(`Transport (${n}) could not listen on any available address`,B.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Vt.FATAL_ALL)throw new y(n,B.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Be="/multistream/1.0.0";var yl=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=pe(),this.haveNext=pe()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=pe(),e}async throw(e){return this.ended=!0,e!=null&&this.haveNext.reject(e),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");if(this.nextResult!=null&&(await this.readNext.promise,this.nextResult!=null))throw new Error("NeedNext promise resolved but nextResult was not consumed");e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=pe(),await Bn(this.readNext.promise,t?.signal,t)}};function xd(){return new yl}var Pi=class extends Error{code;constructor(e,t){super(e),this.code=t}},wl=class extends Pi{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function vd(r,e){let t=xd();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new we;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new wl("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:h}=await Promise.race([n.next(),u]);return l===!0?new we:h}for(;o.byteLength<i;){let{value:l,done:h}=await Promise.race([n.next(),u]);if(h===!0)throw new Pi("unexpected end of input","ERR_UNEXPECTED_EOF");o.append(l)}let f=o.sublist(0,i);return o.consume(i),f}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Oi=class extends Error{code;constructor(e,t){super(e),this.code=t}};function wo(r,e={}){let t=vd(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=he(e.maxDataLength));let n=e?.lengthDecoder??it,o=e?.lengthEncoder??Le;return{read:async i=>{let a=-1,c=new we;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Oi("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Oi("message length too long","ERR_MSG_DATA_TOO_LONG");return t.read(a,i)},write:async(i,a)=>{await t.write(new we(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new we(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var jy=D(`
7
+ `)}async function Mg(r,e){let t=Ue.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=D(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=sn(o),{iv:i,salt:a,iterations:c,keySize:u,cipherText:f}=Fg(s),l=await Za(jr,e,a,{c,dkLen:u}),h=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),g=Xn(await t.subtle.decrypt({name:"AES-CBC",iv:i},h,f)),{result:d}=sn(g);n=_f(d)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=D(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=sn(o);n=_f(s)}else throw new y("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return oc(n)}function Fg(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new y("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new y("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=Xn(s.valueBlock.value[0].getValue()),a=nc,c=rc;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new y("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let u=e.valueBlock.value[1].valueBlock.value[1],f=u.valueBlock.value[0].toString();if(f!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(f!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new y("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let l=Xn(u.valueBlock.value[1].getValue());return{cipherText:Xn(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function _f(r){return Xn(r.valueBlock.value[2].getValue())}function Xn(r){return new Uint8Array(r,0,r.byteLength)}async function Sf(r){let e=await Ue.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await Tf(e);return{privateKey:t[0],publicKey:t[1]}}async function sc(r){let t=[await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Vg(r)],n=await Tf({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function If(r,e){let t=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ue.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Bf(r,e,t){let n=await Ue.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ue.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function Tf(r){if(r.privateKey==null||r.publicKey==null)throw new y("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Ue.get().subtle.exportKey("jwk",r.privateKey),Ue.get().subtle.exportKey("jwk",r.publicKey)])}async function Vg(r){return Ue.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function ks(r){if(r.kty!=="RSA")throw new y("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new y("invalid key modulus","ERR_INVALID_KEY_MODULUS");return D(r.n,"base64url").length*8}var Qn=8192,Zn=class{_key;constructor(e){this._key=e}verify(e,t){return Bf(this._key,t,e)}marshal(){return tr.jwkToPkix(this._key)}get bytes(){return mt.encode({Type:te.RSA,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=Ae.digest(this.bytes);return et(e)?e.then(({bytes:t})=>t):e.bytes}},an=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return vr(16)}sign(e){return If(this._key,e)}get public(){if(this._publicKey==null)throw new y("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Zn(this._publicKey)}marshal(){return tr.jwkToPkcs1(this._key)}get bytes(){return gt.encode({Type:te.RSA,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=Ae.digest(this.bytes);return et(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return K(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return tr.exportToPem(this,e);if(t==="libp2p-key")return Jr(this.bytes,e);throw new y(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function oc(r){let e=tr.pkcs1ToJwk(r);if(ks(e)>Qn)throw new y("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await sc(e);return new an(t.privateKey,t.publicKey)}function Hg(r){let e=tr.pkixToJwk(r);if(ks(e)>Qn)throw new y("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Zn(e)}async function $g(r){if(ks(r)>Qn)throw new y("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await sc(r);return new an(e.privateKey,e.publicKey)}async function qg(r){if(r>Qn)throw new y("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Sf(r);return new an(e.privateKey,e.publicKey)}var fc={};be(fc,{Secp256k1PrivateKey:()=>eo,Secp256k1PublicKey:()=>Jn,generateKeyPair:()=>n0,unmarshalSecp256k1PrivateKey:()=>t0,unmarshalSecp256k1PublicKey:()=>r0});var Gg=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),rr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),nr=new Uint32Array(64),ac=class extends Wr{constructor(){super(64,32,8,!1),this.A=rr[0]|0,this.B=rr[1]|0,this.C=rr[2]|0,this.D=rr[3]|0,this.E=rr[4]|0,this.F=rr[5]|0,this.G=rr[6]|0,this.H=rr[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let l=0;l<16;l++,t+=4)nr[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let h=nr[l-15],g=nr[l-2],d=ot(h,7)^ot(h,18)^h>>>3,p=ot(g,17)^ot(g,19)^g>>>10;nr[l]=p+nr[l-7]+d+nr[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let h=ot(a,6)^ot(a,11)^ot(a,25),g=f+h+su(a,c,u)+Gg[l]+nr[l]|0,p=(ot(n,2)^ot(n,13)^ot(n,22))+iu(n,o,s)|0;f=u,u=c,c=a,a=i+g|0,i=s,s=o,o=n,n=g+p|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){nr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Nf=No(()=>new ac);function zg(r){let e=Un(r);pt(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:Yg,hexToBytes:Wg}=ko,Rr={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=Rr;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:Yg(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Rr,t=typeof r=="string"?Wg(r):r;Xr(t);let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:o,l:s}=Rr._parseInt(t.subarray(2)),{d:i,l:a}=Rr._parseInt(s);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s:i}},hexFromSig(r){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,t=u=>{let f=u.toString(16);return f.length&1?`0${f}`:f},n=e(t(r.s)),o=e(t(r.r)),s=n.length/2,i=o.length/2,a=t(s),c=t(i);return`30${t(i+s+4)}02${c}${o}02${a}${n}`}},Ot=BigInt(0),rt=BigInt(1),Kx=BigInt(2),Cf=BigInt(3),Hx=BigInt(4);function jg(r){let e=zg(r),{Fp:t}=e,n=e.toBytes||((d,p,m)=>{let w=p.toAffine();return It(Uint8Array.from([4]),t.toBytes(w.x),t.toBytes(w.y))}),o=e.fromBytes||(d=>{let p=d.subarray(1),m=t.fromBytes(p.subarray(0,t.BYTES)),w=t.fromBytes(p.subarray(t.BYTES,2*t.BYTES));return{x:m,y:w}});function s(d){let{a:p,b:m}=e,w=t.sqr(d),x=t.mul(w,d);return t.add(t.add(x,t.mul(d,p)),m)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function i(d){return typeof d=="bigint"&&Ot<d&&d<e.n}function a(d){if(!i(d))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(d){let{allowedPrivateKeyLengths:p,nByteLength:m,wrapPrivateKey:w,n:x}=e;if(p&&typeof d!="bigint"){if(Wt(d)&&(d=_t(d)),typeof d!="string"||!p.includes(d.length))throw new Error("Invalid key");d=d.padStart(m*2,"0")}let b;try{b=typeof d=="bigint"?d:St(ae("private key",d,m))}catch{throw new Error(`private key must be ${m} bytes, hex or bigint, not ${typeof d}`)}return w&&(b=Z(b,x)),a(b),b}let u=new Map;function f(d){if(!(d instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(p,m,w){if(this.px=p,this.py=m,this.pz=w,p==null||!t.isValid(p))throw new Error("x required");if(m==null||!t.isValid(m))throw new Error("y required");if(w==null||!t.isValid(w))throw new Error("z required")}static fromAffine(p){let{x:m,y:w}=p||{};if(!p||!t.isValid(m)||!t.isValid(w))throw new Error("invalid affine point");if(p instanceof l)throw new Error("projective point not allowed");let x=b=>t.eql(b,t.ZERO);return x(m)&&x(w)?l.ZERO:new l(m,w,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(p){let m=t.invertBatch(p.map(w=>w.pz));return p.map((w,x)=>w.toAffine(m[x])).map(l.fromAffine)}static fromHex(p){let m=l.fromAffine(o(ae("pointHex",p)));return m.assertValidity(),m}static fromPrivateKey(p){return l.BASE.multiply(c(p))}_setWindowSize(p){this._WINDOW_SIZE=p,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:p,y:m}=this.toAffine();if(!t.isValid(p)||!t.isValid(m))throw new Error("bad point: x or y not FE");let w=t.sqr(m),x=s(p);if(!t.eql(w,x))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:p}=this.toAffine();if(t.isOdd)return!t.isOdd(p);throw new Error("Field doesn't support isOdd")}equals(p){f(p);let{px:m,py:w,pz:x}=this,{px:b,py:A,pz:v}=p,S=t.eql(t.mul(m,v),t.mul(b,x)),N=t.eql(t.mul(w,v),t.mul(A,x));return S&&N}negate(){return new l(this.px,t.neg(this.py),this.pz)}double(){let{a:p,b:m}=e,w=t.mul(m,Cf),{px:x,py:b,pz:A}=this,v=t.ZERO,S=t.ZERO,N=t.ZERO,C=t.mul(x,x),q=t.mul(b,b),G=t.mul(A,A),U=t.mul(x,b);return U=t.add(U,U),N=t.mul(x,A),N=t.add(N,N),v=t.mul(p,N),S=t.mul(w,G),S=t.add(v,S),v=t.sub(q,S),S=t.add(q,S),S=t.mul(v,S),v=t.mul(U,v),N=t.mul(w,N),G=t.mul(p,G),U=t.sub(C,G),U=t.mul(p,U),U=t.add(U,N),N=t.add(C,C),C=t.add(N,C),C=t.add(C,G),C=t.mul(C,U),S=t.add(S,C),G=t.mul(b,A),G=t.add(G,G),C=t.mul(G,U),v=t.sub(v,C),N=t.mul(G,q),N=t.add(N,N),N=t.add(N,N),new l(v,S,N)}add(p){f(p);let{px:m,py:w,pz:x}=this,{px:b,py:A,pz:v}=p,S=t.ZERO,N=t.ZERO,C=t.ZERO,q=e.a,G=t.mul(e.b,Cf),U=t.mul(m,b),ue=t.mul(w,A),ce=t.mul(x,v),Je=t.add(m,w),R=t.add(b,A);Je=t.mul(Je,R),R=t.add(U,ue),Je=t.sub(Je,R),R=t.add(m,x);let L=t.add(b,v);return R=t.mul(R,L),L=t.add(U,ce),R=t.sub(R,L),L=t.add(w,x),S=t.add(A,v),L=t.mul(L,S),S=t.add(ue,ce),L=t.sub(L,S),C=t.mul(q,R),S=t.mul(G,ce),C=t.add(S,C),S=t.sub(ue,C),C=t.add(ue,C),N=t.mul(S,C),ue=t.add(U,U),ue=t.add(ue,U),ce=t.mul(q,ce),R=t.mul(G,R),ue=t.add(ue,ce),ce=t.sub(U,ce),ce=t.mul(q,ce),R=t.add(R,ce),U=t.mul(ue,R),N=t.add(N,U),U=t.mul(L,R),S=t.mul(Je,S),S=t.sub(S,U),U=t.mul(Je,ue),C=t.mul(L,C),C=t.add(C,U),new l(S,N,C)}subtract(p){return this.add(p.negate())}is0(){return this.equals(l.ZERO)}wNAF(p){return g.wNAFCached(this,u,p,m=>{let w=t.invertBatch(m.map(x=>x.pz));return m.map((x,b)=>x.toAffine(w[b])).map(l.fromAffine)})}multiplyUnsafe(p){let m=l.ZERO;if(p===Ot)return m;if(a(p),p===rt)return this;let{endo:w}=e;if(!w)return g.unsafeLadder(this,p);let{k1neg:x,k1:b,k2neg:A,k2:v}=w.splitScalar(p),S=m,N=m,C=this;for(;b>Ot||v>Ot;)b&rt&&(S=S.add(C)),v&rt&&(N=N.add(C)),C=C.double(),b>>=rt,v>>=rt;return x&&(S=S.negate()),A&&(N=N.negate()),N=new l(t.mul(N.px,w.beta),N.py,N.pz),S.add(N)}multiply(p){a(p);let m=p,w,x,{endo:b}=e;if(b){let{k1neg:A,k1:v,k2neg:S,k2:N}=b.splitScalar(m),{p:C,f:q}=this.wNAF(v),{p:G,f:U}=this.wNAF(N);C=g.constTimeNegate(A,C),G=g.constTimeNegate(S,G),G=new l(t.mul(G.px,b.beta),G.py,G.pz),w=C.add(G),x=q.add(U)}else{let{p:A,f:v}=this.wNAF(m);w=A,x=v}return l.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(p,m,w){let x=l.BASE,b=(v,S)=>S===Ot||S===rt||!v.equals(x)?v.multiplyUnsafe(S):v.multiply(S),A=b(this,m).add(b(p,w));return A.is0()?void 0:A}toAffine(p){let{px:m,py:w,pz:x}=this,b=this.is0();p==null&&(p=b?t.ONE:t.inv(x));let A=t.mul(m,p),v=t.mul(w,p),S=t.mul(x,p);if(b)return{x:t.ZERO,y:t.ZERO};if(!t.eql(S,t.ONE))throw new Error("invZ was invalid");return{x:A,y:v}}isTorsionFree(){let{h:p,isTorsionFree:m}=e;if(p===rt)return!0;if(m)return m(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:p,clearCofactor:m}=e;return p===rt?this:m?m(l,this):this.multiplyUnsafe(e.h)}toRawBytes(p=!0){return this.assertValidity(),n(l,this,p)}toHex(p=!0){return _t(this.toRawBytes(p))}}l.BASE=new l(e.Gx,e.Gy,t.ONE),l.ZERO=new l(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,g=Oo(l,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:i}}function Xg(r){let e=Un(r);return pt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Lf(r){let e=Xg(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(R){return Ot<R&&R<t.ORDER}function a(R){return Z(R,n)}function c(R){return Do(R,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:l,isWithinCurveOrder:h}=jg({...e,toBytes(R,L,M){let _=L.toAffine(),E=t.toBytes(_.x),T=It;return M?T(Uint8Array.from([L.hasEvenY()?2:3]),E):T(Uint8Array.from([4]),E,t.toBytes(_.y))},fromBytes(R){let L=R.length,M=R[0],_=R.subarray(1);if(L===o&&(M===2||M===3)){let E=St(_);if(!i(E))throw new Error("Point is not on curve");let T=l(E),k;try{k=t.sqrt(T)}catch(V){let Y=V instanceof Error?": "+V.message:"";throw new Error("Point is not on curve"+Y)}let P=(k&rt)===rt;return(M&1)===1!==P&&(k=t.neg(k)),{x:E,y:k}}else if(L===s&&M===4){let E=t.fromBytes(_.subarray(0,t.BYTES)),T=t.fromBytes(_.subarray(t.BYTES,2*t.BYTES));return{x:E,y:T}}else throw new Error(`Point of length ${L} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),g=R=>_t(Xt(R,e.nByteLength));function d(R){let L=n>>rt;return R>L}function p(R){return d(R)?a(-R):R}let m=(R,L,M)=>St(R.slice(L,M));class w{constructor(L,M,_){this.r=L,this.s=M,this.recovery=_,this.assertValidity()}static fromCompact(L){let M=e.nByteLength;return L=ae("compactSignature",L,M*2),new w(m(L,0,M),m(L,M,2*M))}static fromDER(L){let{r:M,s:_}=Rr.toSig(ae("DER",L));return new w(M,_)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(L){return new w(this.r,this.s,L)}recoverPublicKey(L){let{r:M,s:_,recovery:E}=this,T=N(ae("msgHash",L));if(E==null||![0,1,2,3].includes(E))throw new Error("recovery id invalid");let k=E===2||E===3?M+e.n:M;if(k>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let P=E&1?"03":"02",F=u.fromHex(P+g(k)),V=c(k),Y=a(-T*V),$=a(_*V),z=u.BASE.multiplyAndAddUnsafe(F,Y,$);if(!z)throw new Error("point at infinify");return z.assertValidity(),z}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return mr(this.toDERHex())}toDERHex(){return Rr.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return mr(this.toCompactHex())}toCompactHex(){return g(this.r)+g(this.s)}}let x={isValidPrivateKey(R){try{return f(R),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let R=_a(e.n);return yu(e.randomBytes(R),e.n)},precompute(R=8,L=u.BASE){return L._setWindowSize(R),L.multiply(BigInt(3)),L}};function b(R,L=!0){return u.fromPrivateKey(R).toRawBytes(L)}function A(R){let L=Wt(R),M=typeof R=="string",_=(L||M)&&R.length;return L?_===o||_===s:M?_===2*o||_===2*s:R instanceof u}function v(R,L,M=!0){if(A(R))throw new Error("first arg must be private key");if(!A(L))throw new Error("second arg must be public key");return u.fromHex(L).multiply(f(R)).toRawBytes(M)}let S=e.bits2int||function(R){let L=St(R),M=R.length*8-e.nBitLength;return M>0?L>>BigInt(M):L},N=e.bits2int_modN||function(R){return a(S(R))},C=On(e.nBitLength);function q(R){if(typeof R!="bigint")throw new Error("bigint expected");if(!(Ot<=R&&R<C))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Xt(R,e.nByteLength)}function G(R,L,M=U){if(["recovered","canonical"].some(oe=>oe in M))throw new Error("sign() legacy options not supported");let{hash:_,randomBytes:E}=e,{lowS:T,prehash:k,extraEntropy:P}=M;T==null&&(T=!0),R=ae("msgHash",R),k&&(R=ae("prehashed msgHash",_(R)));let F=N(R),V=f(L),Y=[q(V),q(F)];if(P!=null&&P!==!1){let oe=P===!0?E(t.BYTES):P;Y.push(ae("extraEntropy",oe))}let $=It(...Y),z=F;function fe(oe){let xe=S(oe);if(!h(xe))return;let ve=c(xe),me=u.BASE.multiply(xe).toAffine(),Te=a(me.x);if(Te===Ot)return;let xt=a(ve*a(z+Te*V));if(xt===Ot)return;let fr=(me.x===Te?0:2)|Number(me.y&rt),Cn=xt;return T&&d(xt)&&(Cn=p(xt),fr^=1),new w(Te,Cn,fr)}return{seed:$,k2sig:fe}}let U={lowS:e.lowS,prehash:!1},ue={lowS:e.lowS,prehash:!1};function ce(R,L,M=U){let{seed:_,k2sig:E}=G(R,L,M),T=e;return xa(T.hash.outputLen,T.nByteLength,T.hmac)(_,E)}u.BASE._setWindowSize(8);function Je(R,L,M,_=ue){let E=R;if(L=ae("msgHash",L),M=ae("publicKey",M),"strict"in _)throw new Error("options.strict was renamed to lowS");let{lowS:T,prehash:k}=_,P,F;try{if(typeof E=="string"||Wt(E))try{P=w.fromDER(E)}catch(me){if(!(me instanceof Rr.Err))throw me;P=w.fromCompact(E)}else if(typeof E=="object"&&typeof E.r=="bigint"&&typeof E.s=="bigint"){let{r:me,s:Te}=E;P=new w(me,Te)}else throw new Error("PARSE");F=u.fromHex(M)}catch(me){if(me.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(T&&P.hasHighS())return!1;k&&(L=e.hash(L));let{r:V,s:Y}=P,$=N(L),z=c(Y),fe=a($*z),oe=a(V*z),xe=u.BASE.multiplyAndAddUnsafe(F,fe,oe)?.toAffine();return xe?a(xe.x)===V:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:v,sign:ce,verify:Je,ProjectivePoint:u,Signature:w,utils:x}}function Zg(r){return{hash:r,hmac:(e,...t)=>Kn(r,e,To(...t)),randomBytes:Yr}}function kf(r,e){let t=n=>Lf({...r,...Zg(n)});return Object.freeze({...t(e),create:t})}var Of=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Df=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Qg=BigInt(1),cc=BigInt(2),Pf=(r,e)=>(r+e/cc)/e;function Jg(r){let e=Of,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,f=u*u*r%e,l=ee(f,t,e)*f%e,h=ee(l,t,e)*f%e,g=ee(h,cc,e)*u%e,d=ee(g,o,e)*g%e,p=ee(d,s,e)*d%e,m=ee(p,a,e)*p%e,w=ee(m,c,e)*m%e,x=ee(w,a,e)*p%e,b=ee(x,t,e)*f%e,A=ee(b,i,e)*d%e,v=ee(A,n,e)*u%e,S=ee(v,cc,e);if(!lc.eql(lc.sqr(S),r))throw new Error("Cannot find square root");return S}var lc=Po(Of,void 0,void 0,{sqrt:Jg}),ut=kf({a:BigInt(0),b:BigInt(7),Fp:lc,n:Df,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Df,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Qg*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=Pf(s*r,e),c=Pf(-n*r,e),u=Z(r-a*t-c*o,e),f=Z(-a*n-c*s,e),l=u>i,h=f>i;if(l&&(u=e-u),h&&(f=e-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:u,k2neg:h,k2:f}}}},Nf),Zx=BigInt(0);var Qx=ut.ProjectivePoint;function Uf(){return ut.utils.randomPrivateKey()}function Mf(r,e){let t=Ae.digest(e instanceof Uint8Array?e:e.subarray());if(et(t))return t.then(({digest:n})=>ut.sign(n,r).toDERRawBytes()).catch(n=>{throw new y(String(n),"ERR_INVALID_INPUT")});try{return ut.sign(t.digest,r).toDERRawBytes()}catch(n){throw new y(String(n),"ERR_INVALID_INPUT")}}function Ff(r,e,t){let n=Ae.digest(t instanceof Uint8Array?t:t.subarray());if(et(n))return n.then(({digest:o})=>ut.verify(e,o,r)).catch(o=>{throw new y(String(o),"ERR_INVALID_INPUT")});try{return ut.verify(e,n.digest,r)}catch(o){throw new y(String(o),"ERR_INVALID_INPUT")}}function Vf(r){return ut.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Kf(r){try{ut.getPublicKey(r,!0)}catch(e){throw new y(String(e),"ERR_INVALID_PRIVATE_KEY")}}function uc(r){try{ut.ProjectivePoint.fromHex(r)}catch(e){throw new y(String(e),"ERR_INVALID_PUBLIC_KEY")}}function Hf(r){try{return ut.getPublicKey(r,!0)}catch(e){throw new y(String(e),"ERR_INVALID_PRIVATE_KEY")}}var Jn=class{_key;constructor(e){uc(e),this._key=e}verify(e,t){return Ff(this._key,t,e)}marshal(){return Vf(this._key)}get bytes(){return mt.encode({Type:te.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}async hash(){let e=Ae.digest(this.bytes),t;return et(e)?{bytes:t}=await e:t=e.bytes,t}},eo=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??Hf(e),Kf(this._key),uc(this._publicKey)}sign(e){return Mf(this._key,e)}get public(){return new Jn(this._publicKey)}marshal(){return this._key}get bytes(){return gt.encode({Type:te.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=Ae.digest(this.bytes);return et(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return K(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Jr(this.bytes,e);throw new y(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function t0(r){return new eo(r)}function r0(r){return new Jn(r)}async function n0(){let r=Uf();return new eo(r)}var or={rsa:ic,ed25519:Xa,secp256k1:fc};function hc(r){let e=Object.keys(or).join(" / ");return new y(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function dc(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return or[r];throw hc(r)}async function $f(r,e){return dc(r).generateKeyPair(e??2048)}function to(r){let e=mt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case te.RSA:return or.rsa.unmarshalRsaPublicKey(t);case te.Ed25519:return or.ed25519.unmarshalEd25519PublicKey(t);case te.Secp256k1:return or.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw hc(e.Type??"unknown")}}function qf(r,e){return e=(e??"rsa").toLowerCase(),dc(e),r.bytes}async function ro(r){let e=gt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case te.RSA:return or.rsa.unmarshalRsaPrivateKey(t);case te.Ed25519:return or.ed25519.unmarshalEd25519PrivateKey(t);case te.Secp256k1:return or.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw hc(e.Type??"RSA")}}function Gf(r,e){return e=(e??"rsa").toLowerCase(),dc(e),r.bytes}var je=Ft(Xf(),1);je.default.formatters.b=r=>r==null?"undefined":ne.baseEncode(r);je.default.formatters.t=r=>r==null?"undefined":Ge.baseEncode(r);je.default.formatters.m=r=>r==null?"undefined":Dn.baseEncode(r);je.default.formatters.p=r=>r==null?"undefined":r.toString();je.default.formatters.c=r=>r==null?"undefined":r.toString();je.default.formatters.k=r=>r==null?"undefined":r.toString();je.default.formatters.a=r=>r==null?"undefined":r.toString();function g0(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Os(){return{forComponent(r){return y0(r)}}}function y0(r){let e=g0(`${r}:trace`);return je.default.enabled(`${r}:trace`)&&je.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,je.default)(`${r}:trace`)),Object.assign((0,je.default)(r),{error:(0,je.default)(`${r}:error`),trace:e})}var w0=Symbol.for("nodejs.util.inspect.custom"),Zf=Object.values(qt).map(r=>r.decoder).reduce((r,e)=>r.or(e),qt.identity.decoder),Qf=114,pc=36,mc=37,no=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[qi]=!0;toString(){return this.string==null&&(this.string=ne.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return nt.createV1(Qf,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ie(this.multihash.bytes,e);if(typeof e=="string")return ye(e).equals(this);if(e?.multihash?.bytes!=null)return ie(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[w0](){return`PeerId(${this.toString()})`}},Sr=class extends no{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Ir=class extends no{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Br=class extends no{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function Jf(r){if(r.type==="RSA")return new Sr(r);if(r.type==="Ed25519")return new Ir(r);if(r.type==="secp256k1")return new Br(r);throw new y("Not a PeerId","ERR_INVALID_PARAMETERS")}function ye(r,e){if(e=e??Zf,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=dr(ne.decode(`z${r}`));return r.startsWith("12D")?new Ir({multihash:t}):r.startsWith("16U")?new Br({multihash:t}):new Sr({multihash:t})}return fn(Zf.decode(r))}function fn(r){try{let e=dr(r);if(e.code===$t.code){if(e.digest.length===pc)return new Ir({multihash:e});if(e.digest.length===mc)return new Br({multihash:e})}if(e.code===Ae.code)return new Sr({multihash:e})}catch{return b0(nt.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function b0(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==Qf)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===Ae.code)return new Sr({multihash:r.multihash});if(e.code===$t.code){if(e.digest.length===pc)return new Ir({multihash:r.multihash});if(e.digest.length===mc)return new Br({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function hn(r,e){return r.length===pc?new Ir({multihash:dt($t.code,r),privateKey:e}):r.length===mc?new Br({multihash:dt($t.code,r),privateKey:e}):new Sr({multihash:await Ae.digest(r),publicKey:r,privateKey:e})}function dn(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var Xe=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return dn(this.map.entries(),e=>[ye(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,ye(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return dn(this.map.keys(),e=>ye(e))}values(){return this.map.values()}get size(){return this.map.size}};var ft=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return dn(this.set.entries(),e=>{let t=ye(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=ye(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return dn(this.set.values(),e=>ye(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var eh=async()=>{let r=await $f("Ed25519"),e=await E0(r);if(e.type==="Ed25519")return e;throw new Error(`Generated unexpected PeerId type "${e.type}"`)};async function E0(r){return hn(qf(r.public),Gf(r))}var rh=Symbol.for("@achingbrain/uint8arraylist");function th(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Us(r){return!!r?.[rh]}var we=class r{bufs;length;[rh]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Us(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Us(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=th(this.bufs,e);return t.buf[t.index]}set(e,t){let n=th(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Us(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Re(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Re(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,f=t>a&&t<=c;if(u&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Us(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let h=u;h>=0;h--){let g=this.get(l+h);if(n[h]!==g){f=Math.max(1,h-a[g]);break}}if(f===0)return l}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ne(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=At(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=At(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=At(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ne(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=At(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=At(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=At(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=At(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=At(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!ie(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var nh={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var oo;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.publicKey=t.bytes();break;case 2:o.payloadType=t.bytes();break;case 3:o.payload=t.bytes();break;case 5:o.signature=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(oo||(oo={}));var pn=class r{static createFromProtobuf=async e=>{let t=oo.decode(e),n=await hn(t.publicKey);return new r({peerId:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t.privateKey==null)throw new Error("Missing private key");let n=e.domain,o=e.codec,s=e.marshal(),i=oh(n,o,s),c=await(await ro(t.privateKey)).sign(i.subarray());return new r({peerId:t,payloadType:o,payload:s,signature:c})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new y("envelope signature is not valid for the given domain",nh.ERR_SIGNATURE_NOT_VALID);return n};peerId;payloadType;payload;signature;marshaled;constructor(e){let{peerId:t,payloadType:n,payload:o,signature:s}=e;this.peerId=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=oo.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return ie(this.marshal(),e.marshal())}async validate(e){let t=oh(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return to(this.peerId.publicKey).verify(t.subarray(),this.signature)}},oh=(r,e,t)=>{let n=D(r),o=Le(n.byteLength),s=Le(e.length),i=Le(t.length);return new we(o,n,s,e,i,t)};function sh(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Ms=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let h=Number.parseInt(l,e);if(!Number.isNaN(h))return h});if(f===void 0)break;if(s*=e,s+=f,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var ih=45,x0=15,mn=new Ms;function gc(r){if(!(r.length>x0))return mn.new(r).parseWith(()=>mn.readIPv4Addr())}function yc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>ih))return mn.new(r).parseWith(()=>mn.readIPv6Addr())}function Fs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>ih))return mn.new(r).parseWith(()=>mn.readIPAddr())}var m1=parseInt("0xFFFF",16),g1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function gn(r){return!!gc(r)}function yn(r){return!!yc(r)}function Vs(r){return!!Fs(r)}var lh=gn,S0=yn,wc=function(r){let e=0;if(r=r.toString().trim(),lh(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(S0(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=lh(t[n]),i;s&&(i=wc(t[n]),t[n]=K(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,K(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},uh=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var wn={},bc={},B0=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,-1,"memory"]];B0.forEach(r=>{let e=T0(...r);bc[e.code]=e,wn[e.name]=e});function T0(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function X(r){if(typeof r=="number"){if(bc[r]!=null)return bc[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(wn[r]!=null)return wn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var J1=X("ip4"),eA=X("ip6"),tA=X("ipcidr");function xc(r,e){switch(X(r).code){case 4:case 41:return C0(e);case 42:return dh(e);case 6:case 273:case 33:case 132:return mh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return dh(e);case 421:return P0(e);case 444:return ph(e);case 445:return ph(e);case 466:return D0(e);default:return K(e,"base16")}}function vc(r,e){switch(X(r).code){case 4:return fh(e);case 41:return fh(e);case 42:return hh(e);case 6:case 273:case 33:case 132:return Ac(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return hh(e);case 421:return L0(e);case 444:return O0(e);case 445:return U0(e);case 466:return k0(e);default:return D(e,"base16")}}var Ec=Object.values(qt).map(r=>r.decoder),N0=function(){let r=Ec[0].or(Ec[1]);return Ec.slice(2).forEach(e=>r=r.or(e)),r}();function fh(r){if(!Vs(r))throw new Error("invalid ip address");return wc(r)}function C0(r){let e=uh(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Vs(e))throw new Error("invalid ip address");return e}function Ac(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function mh(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function hh(r){let e=D(r),t=Uint8Array.from(Le(e.length));return Re([t,e],t.length+e.length)}function dh(r){let e=it(r);if(r=r.slice(he(e)),r.length!==e)throw new Error("inconsistent lengths");return K(r)}function L0(r){let e;r[0]==="Q"||r[0]==="1"?e=dr(ne.decode(`z${r}`)).bytes:e=nt.parse(r).multihash.bytes;let t=Uint8Array.from(Le(e.length));return Re([t,e],t.length+e.length)}function k0(r){let e=N0.decode(r),t=Uint8Array.from(Le(e.length));return Re([t,e],t.length+e.length)}function D0(r){let e=it(r),t=r.slice(he(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+K(t,"base64url")}function P0(r){let e=it(r),t=r.slice(he(e));if(t.length!==e)throw new Error("inconsistent lengths");return K(t,"base58btc")}function O0(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=Ge.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ac(n);return Re([t,o],t.length+o.length)}function U0(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Ge.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ac(n);return Re([t,o],t.length+o.length)}function ph(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=K(e,"base32"),o=mh(t);return`${n}:${o}`}function gh(r){r=Rc(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=X(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw wh("invalid address: "+r);if(a.path===!0){n=Rc(o.slice(s).join("/")),e.push([a.code,vc(a.code,n)]),t.push([a.code,n]);break}let c=vc(a.code,o[s]);e.push([a.code,c]),t.push([a.code,xc(a.code,c)])}return{string:yh(t),bytes:Sc(e),tuples:e,stringTuples:t,path:n}}function _c(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=it(r,o),i=he(s),a=X(s),c=M0(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw wh("Invalid address Uint8Array: "+K(r,"base16"));e.push([s,u]);let f=xc(s,u);if(t.push([s,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:yh(t),tuples:e,stringTuples:t,path:n}}function yh(r){let e=[];return r.map(t=>{let n=X(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Rc(e.join("/"))}function Sc(r){return Re(r.map(e=>{let t=X(e[0]),n=Uint8Array.from(Le(t.code));return e.length>1&&e[1]!=null&&(n=Re([n,e[1]])),n}))}function M0(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=it(e instanceof Uint8Array?e:Uint8Array.from(e));return t+he(t)}}function Rc(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function wh(r){return new Error("Error parsing address: "+r)}var F0=Symbol.for("nodejs.util.inspect.custom"),Ic=Symbol.for("@multiformats/js-multiaddr/multiaddr"),V0=[X("dns").code,X("dns4").code,X("dns6").code,X("dnsaddr").code],Ks=class r{bytes;#e;#t;#s;#a;[Ic]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=_c(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=gh(e)}else if(sr(e))t=_c(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#s=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=X("tcp"),a=X("udp"),c=X("ip4"),u=X("ip6"),f=X("dns6"),l=X("ip6zone");for(let[g,d]of this.stringTuples())g===l.code&&(s=`%${d??""}`),V0.includes(g)&&(t=i.name,o=443,n=`${d??""}${s}`,e=g===f.code?6:4),(g===i.code||g===a.code)&&(t=X(g).name,o=parseInt(d??"")),(g===c.code||g===u.code)&&(t=X(g).name,n=`${d??""}${s}`,e=g===u.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},X(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>X(e).name)}tuples(){return this.#t}stringTuples(){return this.#s}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(Sc(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===wn.p2p.code&&e.push([n,o]),n===wn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?K(ne.decode(`z${n}`),"base58btc"):K(nt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return ie(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=bn.get(t.name);if(n==null)throw new y(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>re(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[F0](){return`Multiaddr(${this.#e})`}};var bn=new Map;function sr(r){return!!r?.[Ic]}function re(r){return new Ks(r)}var bh="libp2p-peer-record",Eh=Uint8Array.from([3,1]);var so;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Ve((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let a={multiaddr:new Uint8Array(0)},c=i==null?s.len:s.pos+i;for(;s.pos<c;){let u=s.uint32();switch(u>>>3){case 1:a.multiaddr=s.bytes();break;default:s.skipType(u&7);break}}return a})),o),n.encode=s=>Fe(s,n.codec()),n.decode=s=>Me(s,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ve((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o)=>{let s={peerId:new Uint8Array(0),seq:0n,addresses:[]},i=o==null?n.len:n.pos+o;for(;n.pos<i;){let a=n.uint32();switch(a>>>3){case 1:s.peerId=n.bytes();break;case 2:s.seq=n.uint64();break;case 3:s.addresses.push(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return s})),t),r.encode=n=>Fe(n,r.codec()),r.decode=n=>Me(n,r.codec())})(so||(so={}));var Tr=class r{static createFromProtobuf=e=>{let t=so.decode(e),n=fn(t.peerId),o=(t.addresses??[]).map(i=>re(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=bh;static CODEC=Eh;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=so.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!sh(this.multiaddrs,e.multiaddrs))}};function K0(r){return r[Symbol.asyncIterator]!=null}function H0(r){if(K0(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var io=H0;var Tc=Ft(vh(),1);var co=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Nc=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Ah=r=>globalThis.DOMException===void 0?new Nc(r):new DOMException(r),Rh=r=>{let e=r.reason===void 0?Ah("This operation was aborted."):r.reason;return e instanceof Error?e:Ah(e)};function lo(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&f(Rh(h)),h.addEventListener("abort",()=>{f(Rh(h))})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let l=new co;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){f(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(l.message=o??`Promise timed out after ${t} milliseconds`,f(l))},t),(async()=>{try{u(await r)}catch(h){f(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function Cc(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var uo=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=Cc(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var ir=class extends Tc.default{#e;#t;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#i;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:uo,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#c=e.interval,this.#r=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#b(){return this.#t||this.#s<this.#a}get#E(){return this.#o<this.#u}#x(){this.#o--,this.#f(),this.emit("next")}#v(){this.#w(),this.#y(),this.#l=void 0}get#A(){let e=Date.now();if(this.#n===void 0){let t=this.#p-e;if(t<0)this.#s=this.#e?this.#o:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#v()},t)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#o===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#A;if(this.#b&&this.#E){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#s===0&&this.#o===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#s=this.#e?this.#o:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#u=e,this.#h()}async#R(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#o++,this.#s++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=lo(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#R(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof co&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#x()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#h(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#i}};var ar={},En=r=>{r.addEventListener("message",e=>{En.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{En.dispatchEvent("message",r,e)})};En.addEventListener=(r,e)=>{ar[r]==null&&(ar[r]=[]),ar[r].push(e)};En.removeEventListener=(r,e)=>{ar[r]!=null&&(ar[r]=ar[r].filter(t=>t===e))};En.dispatchEvent=function(r,e,t){ar[r]!=null&&ar[r].forEach(n=>n(e,t))};var Lc=En;var kc="lock:worker:request-read",Dc="lock:worker:release-read",Pc="lock:master:grant-read",Oc="lock:worker:request-write",Uc="lock:worker:release-write",Mc="lock:master:grant-write";var _h=(r=21)=>Math.random().toString().substring(2);var Sh=(r,e,t,n,o)=>(s,i)=>{if(i.data.type!==t)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=f=>{if(f==null||f.data==null)return;let l={type:f.data.type,name:f.data.name,identifier:f.data.identifier};l.type===n&&l.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})}}}))},Ih=(r,e,t,n)=>async()=>{let o=_h();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},G0={singleProcess:!1},Bh=r=>{if(r=Object.assign({},G0,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return Lc.addEventListener("message",Sh(t,"requestReadLock",kc,Dc,Pc)),Lc.addEventListener("message",Sh(t,"requestWriteLock",Oc,Uc,Mc)),t}return{isWorker:!0,readLock:t=>Ih(t,kc,Pc,Dc),writeLock:t=>Ih(t,Oc,Mc,Uc)}};var Nr={},cr;async function Fc(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>lo((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var z0=(r,e)=>{if(cr.isWorker===!0)return{readLock:cr.readLock(r,e),writeLock:cr.writeLock(r,e)};let t=new ir({concurrency:1}),n;return{async readLock(){if(n!=null)return Fc(n,e);n=new ir({concurrency:e.concurrency,autoStart:!1});let o=n,s=Fc(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,Fc(t,e)}}},Y0={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Vc(r){let e=Object.assign({},Y0,r);return cr==null&&(cr=Bh(e),cr.isWorker!==!0&&(cr.addEventListener("requestReadLock",t=>{Nr[t.data.name]!=null&&Nr[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),cr.addEventListener("requestWriteLock",async t=>{Nr[t.data.name]!=null&&Nr[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Nr[e.name]==null&&(Nr[e.name]=z0(e.name,e)),Nr[e.name]}var Se={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var xn;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ve((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:"",value:new Uint8Array(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=i.bytes();break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Fe(i,o.codec()),o.decode=i=>Me(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ve((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),qs.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:c.key=i.string();break;case 2:c.value=qs.codec().decode(i,i.uint32());break;default:i.skipType(f&7);break}}return c})),s),o.encode=i=>Fe(i,o.codec()),o.decode=i=>Me(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ve((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),$s.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.addresses.push($s.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(u.key,u.value);break}case 7:{let u=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(u.key,u.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>Fe(o,r.codec()),r.decode=o=>Me(o,r.codec())})(xn||(xn={}));var $s;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.multiaddr=t.bytes();break;case 2:o.isCertified=t.bool();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})($s||($s={}));var qs;(function(r){let e;r.codec=()=>(e==null&&(e=Ve((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.value=t.uint32();break;case 2:o.expiry=t.uint64();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>Fe(t,r.codec()),r.decode=t=>Me(t,r.codec())})(qs||(qs={}));function vn(r,e){let t=xn.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=Jf({...r,publicKey:r.publicKey}));let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:re(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Ut="/",Th=new TextEncoder().encode(Ut),Gs=Th[0],Cr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=D(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Gs)throw new Error("Invalid key")}toString(e="utf8"){return K(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ut))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Th),this._buf[0]!==Gs){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Gs,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Gs;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ut).slice(1)}type(){return W0(this.baseNamespace())}name(){return j0(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ut)||(e+=Ut),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ut):new r(e.slice(0,-1).join(Ut))}child(e){return this.toString()===Ut?e:e.toString()===Ut?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...X0(e.map(t=>t.namespaces()))])}};function W0(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function j0(r){let e=r.split(":");return e[e.length-1]}function X0(r){return[].concat(...r)}var Kc="/peers/";function An(r){if(!vo(r)||r.type==null)throw new y("Invalid PeerId",Se.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Cr(`${Kc}${e}`)}async function Nh(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=re(o.multiaddr)),!sr(o.multiaddr))throw new y("Multiaddr was invalid",Se.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function Ys(r,e,t,n){if(e==null)throw new y("Invalid PeerData",Se.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!ie(e.publicKey,r.publicKey))throw new y("publicKey bytes do not match peer id publicKey bytes",Se.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new y("peer id did not match existing peer id",Se.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=zs(l,{validate:Ch})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=zs(l,{validate:Lh,map:kh})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(l=>({isCertified:!1,multiaddr:l}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let l=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,g]of l)g==null?a.delete(h):a.set(h,g);a=zs([...a.entries()],{validate:Ch})}if(e.tags!=null){let l=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[g,d]of l)d==null?h.delete(g):h.set(g,d);c=zs([...h.entries()],{validate:Lh,map:kh})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let f={addresses:await Nh(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((l,h)=>l.localeCompare(h)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:u};return r.type!=="RSA"&&delete f.publicKey,f}function zs(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function Ch(r,e){if(typeof r!="string")throw new y("Metadata key must be a string",Se.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new y("Metadata value must be a Uint8Array",Se.ERR_INVALID_PARAMETERS)}function Lh(r,e){if(typeof r!="string")throw new y("Tag name must be a string",Se.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new y("Tag value must be an integer",Se.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new y("Tag value must be between 0-100",Se.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new y("Tag ttl must be an integer",Se.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new y("Tag ttl must be between greater than 0",Se.ERR_INVALID_PARAMETERS)}}function kh(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function Ws(r,e,t){let n=r.toString().split("/")[2],o=Ge.decode(n),s=fn(o),i=t.get(s);if(i!=null)return i;let a=vn(s,e);return t.set(s,a),a}function Z0(r,e){return r==null?{}:{prefix:Kc,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Ws(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Ws(n.key,n.value,e),Ws(o.key,o.value,e)))}}var js=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Vc({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(An(e))}async delete(e){if(this.peerId.equals(e))throw new y("Cannot delete self peer",Se.ERR_INVALID_PARAMETERS);await this.datastore.delete(An(e))}async load(e){let t=await this.datastore.get(An(e));return vn(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Ys(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Ys(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await Ys(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new Xe;for await(let{key:n,value:o}of this.datastore.query(Z0(e??{},t))){let s=Ws(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(An(e)),n=vn(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,o){let s=xn.encode(t);return n!=null&&ie(s,n)?{peer:vn(e,s),previous:o,updated:!1}:(await this.datastore.put(An(e),s),{peer:vn(e,s),previous:o,updated:!0})}};var Xs=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new js(e,t)}async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await io(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await pn.openAndCertify(e,Tr.DOMAIN);if(t?.equals(n.peerId)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let o=Tr.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(s?.peerRecordEnvelope!=null){let i=await pn.createFromProtobuf(s.peerRecordEnvelope),a=Tr.createFromProtobuf(i.payload);if(a.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(i=>({isCertified:!0,multiaddr:i}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function Q0(r){return r[Symbol.asyncIterator]!=null}function J0(r){if(Q0(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Hc=J0;function ey(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Dh=ey;function ty(r){return r[Symbol.asyncIterator]!=null}function ry(r,e){if(ty(r))return async function*(){for await(let a of r)await e(a)&&(yield a)}();let t=Dh(r),{value:n,done:o}=t.next();if(o===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){await s&&(yield n);for await(let a of t)await e(a)&&(yield a)}();let i=e;return function*(){s===!0&&(yield n);for(let a of t)i(a)&&(yield a)}()}var Lr=ry;function ny(r){return r[Symbol.asyncIterator]!=null}function oy(r,e){return ny(r)?async function*(){yield*(await io(r)).sort(e)}():function*(){yield*io(r).sort(e)}()}var $c=oy;function sy(r){return r[Symbol.asyncIterator]!=null}function iy(r,e){return sy(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var qc=iy;var Zs=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Hc(this.putMany(e,n)),e=[],await Hc(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Lr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Lr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>$c(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Lr(n,()=>o++>=s)}return e.limit!=null&&(n=qc(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Lr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Lr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>$c(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Lr(n,()=>s++>=o)}return e.limit!=null&&(n=qc(n,e.limit)),n}};var Uh=Ft(Gc(),1);function Mh(r){return r=r??new Error("Not Found"),(0,Uh.default)(r,"ERR_NOT_FOUND")}var Qs=class extends Zs{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw Mh();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new Cr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Cr(e)}};function Fh(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var ly=r=>r;function zc(r,e){let t=r.getPeerId();return t!=null&&ye(t).equals(e)&&(r=r.decapsulate(re(`/p2p/${e.toString()}`))),r}var Js=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??ly,this._updatePeerStoreAddresses=Fh(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>re(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>re(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>re(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>re(e))}addObservedAddr(e){e=zc(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=zc(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=zc(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>re(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var Yc=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=Os())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Pl(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},uy=["metrics","connectionProtector","dns"],fy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Vh(r={}){let e=new Yc(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!fy.includes(o)){let i=e.components[o];if(i==null&&!uy.includes(o))throw new y(`${o} not set`,"ERR_SERVICE_MISSING");return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}var Hh=Ft(Kh(),1),hy=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],dy=hy.map(r=>new Hh.Netmask(r));function py(r){for(let e of dy)if(e.contains(r))return!0;return!1}function my(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function ei(r){return gn(r)?py(r):yn(r)?my(r):void 0}function $h(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!ei(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var gy=r=>r.toString().split("/").slice(1),ho=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),W=r=>({match:e=>ho(t=>t===r).match(e),pattern:r}),ni=()=>({match:r=>ho(e=>typeof e=="string").match(r),pattern:"{string}"}),oi=()=>({match:r=>ho(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Ie=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ne.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ti=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{ua.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),$e=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),Ze=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),Q=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function le(...r){function e(o){let s=gy(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matches:t,exactMatch:n}}var jc=Q(W("dns4"),ni()),Xc=Q(W("dns6"),ni()),Zc=Q(W("dnsaddr"),ni()),qh=Q(W("dns"),ni()),SR=le(jc),IR=le(Xc),BR=le(Zc),TR=le(Ze(qh,Zc,jc,Xc)),Gh=Q(W("ip4"),ho(gn)),zh=Q(W("ip6"),ho(yn)),Yh=Ze(Gh,zh),Et=Ze(Yh,qh,jc,Xc,Zc),NR=le(Et),CR=le(Gh),LR=le(zh),kR=le(Yh),si=Q(Et,W("tcp"),oi()),po=Q(Et,W("udp"),oi()),yy=Ze(si,po),DR=le(si),PR=le(po),Qc=Q(po,W("quic")),ii=Q(po,W("quic-v1")),wy=Ze(Qc,ii),OR=le(Qc),UR=le(ii),Wc=Ze(Et,si,po,Qc,ii),Wh=Ze(Q(Wc,W("ws"),$e(Ie()))),MR=le(Wh),jh=Ze(Q(Wc,W("wss"),$e(Ie())),Q(Wc,W("tls"),W("ws"),$e(Ie()))),FR=le(jh),Xh=Q(yy,W("webrtc-direct"),ti(),$e(ti()),$e(Ie())),VR=le(Xh),Zh=Q(ii,W("webtransport"),ti(),ti(),$e(Ie())),KR=le(Zh),ri=Ze(Wh,jh,Q(si,$e(Ie())),Q(wy,$e(Ie())),Q(Et,$e(Ie())),Xh,Zh,Ie()),HR=le(ri),by=Q(ri,W("p2p-circuit"),Ie()),mo=le(by),Ey=Ze(Q(ri,W("p2p-circuit"),W("webrtc"),Ie()),Q(ri,W("webrtc"),$e(Ie())),W("webrtc")),$R=le(Ey),xy=Ze(Q(Et,W("tcp"),oi(),W("http"),$e(Ie())),Q(Et,W("http"),$e(Ie()))),qR=le(xy),vy=Ze(Q(Et,W("tcp"),Ze(Q(W("443"),W("http")),Q(oi(),W("https"))),$e(Ie())),Q(Et,W("tls"),W("http"),$e(Ie())),Q(Et,W("https"),$e(Ie()))),GR=le(vy);function Jc(r){try{let{address:e}=r.nodeAddress();return!!ei(e)}catch{return!0}}function Ay(r,e){let t=Jc(r.multiaddr),n=Jc(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Ry(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function _y(r,e){let t=mo.exactMatch(r.multiaddr),n=mo.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Rn(r,e){let t=Ay(r,e);if(t!==0)return t;let n=_y(r,e);return n!==0?n:Ry(r,e)}var lr=class extends Event{constructor(e,t){super(e),this.detail=t}};function ai(r){let e=[Qe.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var el=60;function ci(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:Qe[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Qe[e.type],TTL:e.TTL??e.ttl??el,data:e.data instanceof Uint8Array?K(e.data):e.data}))}}var Sy=4;function tl(r,e={}){let t=new ir({concurrency:e.queryConcurrency??Sy});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),ai(o.types).forEach(a=>{s.append("type",Qe[a])}),o.onProgress?.(new lr("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=ci(await a.json());return o.onProgress?.(new lr("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function Qh(){return[tl("https://cloudflare-dns.com/dns-query"),tl("https://dns.google/resolve")]}var td=Ft(ed(),1);var rl=class{lru;constructor(e){this.lru=(0,td.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return ci({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Qe[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??el)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function rd(r){return new rl(r)}var Iy=1e3,li=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=rd(e.cacheSize??Iy),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Qh())}async query(e,t={}){let n=ai(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new lr("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,types:n});for(let f of u.Answer)this.cache.add(e,f);return u}catch(u){a.push(u),t.onProgress?.(new lr("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var Qe;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Qe||(Qe={}));function nd(r={}){return new li(r)}var By=32,{code:Ty}=X("dnsaddr"),kr=async function(e,t={}){let n=t.maxRecursiveDepth??By;if(n===0)throw new y("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([u])=>u===Ty)??[],i=await(t?.dns??nd()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[Qe.TXT]}),a=e.getPeerId(),c=[];for(let u of i.Answer){let f=u.data.split("=")[1];if(f==null||a!=null&&!f.includes(a))continue;let l=re(f);if(f.startsWith("/dnsaddr")){let h=await l.resolve({...t,maxRecursiveDepth:n-1});c.push(...h.map(g=>g.toString()))}else c.push(l.toString())}return c};var hd=Ft(fd(),1),hi=hd.default;var Mt;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Mt||(Mt={}));var B;(function(r){r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(B||(B={}));var Py={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:kr},addressSorter:Rn},transportManager:{faultTolerance:Vt.FATAL_ALL}};async function dd(r){let e=hi(Py,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new y(Mt.ERR_PROTECTOR_REQUIRED,B.ERR_PROTECTOR_REQUIRED);if(!(await hn(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new y("Private key doesn't match peer id",B.ERR_INVALID_KEY);return e}var pd=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Oy=new WeakMap;function Uy({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(pd());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(pd())},f=()=>{o&&o.removeEventListener("abort",u)},l=new Promise((h,g)=>{i=()=>{f(),h(n)},a=g,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",u,{once:!0}),Oy.set(l,()=>{c(s),s=null,i()}),l}}var My=Uy(),md=My;var di=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new ol}async consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new y("Rate limit exceeded","ERR_RATE_LIMIT_EXCEEDED",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await md(a)}return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},ol=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function pi(r){if(vo(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:ye(t),r.forEach(n=>{if(!sr(n))throw new y("Invalid Multiaddr",B.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new y("Multiaddrs must all have the same peer id or have no peer id",B.ERR_INVALID_PARAMETERS)}else{let s=ye(o);if(e==null||!e.equals(s))throw new y("Multiaddrs must all have the same peer id or have no peer id",B.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}function pe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var mi=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},In=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new mi(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new mi(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var sl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function gi(r={}){return Fy(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Fy(r,e){e=e??{};let t=e.onEnd,n=new In,o,s,i,a=pe(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,w)=>{s=x=>{s=null,n.push(x);try{m(r(n))}catch(b){w(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=pe()})}},u=m=>s!=null?s(m):(n.push(m),o),f=m=>(n=new In,s!=null?s({error:m}):(n.push({error:m}),o)),l=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:m})},h=m=>i?o:(i=!0,m!=null?f(m):u({done:!0})),g=()=>(n=new In,h(),{done:!0}),d=m=>(h(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:g,throw:d,push:l,end:h,get readableLength(){return n.size},onEmpty:async m=>{let w=m?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let x,b;w!=null&&(x=new Promise((A,v)=>{b=()=>{v(new sl)},w.addEventListener("abort",b)}));try{await Promise.race([a.promise,x])}finally{b!=null&&w!=null&&w?.removeEventListener("abort",b)}}},t==null)return o;let p=o;return o={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(m){return p.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return p.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(m){return p.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return p.readableLength},onEmpty:m=>p.onEmpty(m)},o}var il=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function yi(r,e,t,n){let o=new il(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{let a=u=>{try{if(n?.filter?.(u)===!1)return}catch(f){r.removeEventListener(e,a),t?.removeEventListener("abort",c),i(f);return}r.removeEventListener(e,a),t?.removeEventListener("abort",c),s(u)},c=()=>{r.removeEventListener(e,a),t?.removeEventListener("abort",c),i(o)};r.addEventListener(e,a),t?.addEventListener("abort",c)})}var wi=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Bn(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new wi(t?.errorMessage,t?.errorCode));let n,o=new wi(t?.errorMessage,t?.errorCode);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var bi=class{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=pe(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Kt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Vy(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ei=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(e,t,n=0){this.id=Vy(),this.status="queued",this.fn=e,this.priority=n,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,Oe(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Kt),this.cleanup())}async join(e={}){let t=new bi(new Error("where").stack,e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Bn(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function Ky(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var Tn=class extends hr{concurrency;queue;pending;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){if(this.queue[this.size-1]?.priority>=e.priority){this.queue.push(e);return}let t=Ky(this.queue,e,(n,o)=>o.priority-n.priority);this.queue.splice(t,0,e)}async add(e,t){t?.signal?.throwIfAborted();let n=new Ei(e,t,t?.priority),o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Kt)}),this.clear()}async onEmpty(e){this.size!==0&&await yi(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await yi(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await yi(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=gi({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new y("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var xi=class extends Tn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var vi="last-dial-failure";var Ai=5,Ri=100,_i=50,gd=1e3*60*7;var Dr={minConnections:Ai,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:gd,autoDialDiscoveredPeersDebounce:10},Si=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??Dr.minConnections,this.autoDialPriority=t.autoDialPriority??Dr.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Dr.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Dr.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Dr.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Dr.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new xi({concurrency:t.autoDialConcurrency??Dr.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",o=>{this.log.error("error during auto-dial",o.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{this.log.error(o)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{this.log.error(o)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new ft(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[u=>u.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",u.id),!1):e.has(u.id)?(this.log.trace("not autodialing %p because they are already connected",u.id),!1):n.has(u.id)?(this.log.trace("not autodialing %p because they are already being dialed",u.id),!1):this.queue.has(u.id)?(this.log.trace("not autodialing %p because they are already being autodialed",u.id),!1):!0]}),s=o.sort(()=>Math.random()>.5?1:-1),i=new Xe;for(let u of s)i.has(u.id)||i.set(u.id,[...u.tags.values()].reduce((f,l)=>f+l.value,0));let c=s.sort((u,f)=>{let l=i.get(u.id)??0,h=i.get(f.id)??0;return l>h?-1:l<h?1:0}).filter(u=>{let f=u.metadata.get(vi);if(f==null)return!0;let l=parseInt(K(f));return isNaN(l)?!0:Date.now()-l>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let u of c)this.queue.add(async()=>{let f=this.connectionManager.getConnectionsMap().size;if(f>=this.minConnections){this.log("got enough connections now %d/%d",f,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(f=>{this.log.error("could not connect to peerStore stored peer",f)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var yd={maxConnections:Ri,allow:[]},Ii=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??yd.maxConnections,this.allow=t.allow??yd.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=Math.max(t-this.maxConnections,0);if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;this.log("max connections limit exceeded %d/%d, pruning %d connection(s)",t,this.maxConnections,n);let o=new Xe;for(let a of e){let c=a.remotePeer;if(!o.has(c)){o.set(c,0);try{let u=await this.peerStore.get(c);o.set(c,[...u.tags.values()].reduce((f,l)=>f+l.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",u)}}}let s=e.sort((a,c)=>{let u=o.get(a.remotePeer)??0,f=o.get(c.remotePeer)??0;if(u>f)return 1;if(u<f)return-1;let l=a.timeline.open,h=c.timeline.open;return l<h?1:l>h?-1:0}),i=[];for(let a of s)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||i.push(a),i.length===n)break;await Promise.all(i.map(async a=>{try{await a.close()}catch(c){this.log.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:i})}};function wd(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}async function bd(r,e){let t=!1;for(let o of bn.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var go={addressSorter:Rn,maxParallelDials:_i,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:kr}},Bi=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??go.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??go.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??go.maxDialQueueLength,this.dialTimeout=t.dialTimeout??go.dialTimeout,this.connections=t.connections??new Xe,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,Oe(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))bn.set(n,o);this.queue=new Tn({concurrency:t.maxParallelDials??go.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,Oe(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=pi(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new y("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),this.queue.add(async a=>{let c=this.createDialAbortController(a?.signal),u;try{u=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),u.map(({multiaddr:f})=>f.toString()).forEach(f=>{a?.multiaddrs.add(f)})}catch(f){throw c.clear(),f}try{let f=0,l=[];for(let h of u){if(f===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",f,n),new y("Peer had more than maxPeerAddrsToDial",B.ERR_TOO_MANY_ADDRESSES);f++;try{let g=await this.components.transportManager.dial(h.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",h.multiaddr),g}catch(g){if(this.log.error("dial failed to %a",h.multiaddr,g),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[vi]:D(Date.now().toString())}})}catch(d){this.log.error("could not update last dial failure key for %p",n,d)}if(c.aborted)throw new y(g.message,Ro);l.push(g)}}throw l.length===1?l[0]:new Ao(l,"All multiaddr dials failed",B.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal})}createDialAbortController(e){let t=wd([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return Oe(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(l=>({multiaddr:re(l),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new y("Tried to dial self",B.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new y("The dial request is blocked by gater.allowDialPeer",B.ERR_PEER_DIAL_INTERCEPTED);if(o.length===0){this.log("loading multiaddrs for %p",e);try{let l=await this.components.peerStore.get(e);o.push(...l.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:h})=>h.toString()))}catch(l){if(l.code!==B.ERR_NOT_FOUND)throw l}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let l=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:h})=>h.toString())),o.push(...l.multiaddrs.map(h=>({multiaddr:h,isCertified:!1})))}catch(l){l.code!==B.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,l)}}}let s=(await Promise.all(o.map(async l=>{let h=await bd(l.multiaddr,{dns:this.components.dns,...n,log:this.log});return h.length===1&&h[0].equals(l.multiaddr)?l:h.map(g=>({multiaddr:g,isCertified:!1}))}))).flat();if(e!=null){let l=`/p2p/${e.toString()}`;s=s.map(h=>h.multiaddr.protos().pop()?.path===!0?h:h.multiaddr.getPeerId()==null?{multiaddr:h.multiaddr.encapsulate(l),isCertified:h.isCertified}:h)}let i=s.filter(l=>{if(this.components.transportManager.transportForMultiaddr(l.multiaddr)==null)return!1;let h=l.multiaddr.getPeerId();return e!=null&&h!=null?e.equals(h):!0}),a=new Map;for(let l of i){let h=l.multiaddr.toString(),g=a.get(h);if(g!=null){g.isCertified=g.isCertified||l.isCertified||!1;continue}a.set(h,l)}let c=[...a.values()];if(c.length===0)throw new y("The dial request has no valid addresses",B.ERR_NO_VALID_ADDRESSES);let u=[];for(let l of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(l.multiaddr)||u.push(l);let f=u.sort(this.addressSorter);if(f.length===0)throw new y("The connection gater denied all addresses in the dial request",B.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:l})=>l.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",f.map(({multiaddr:l})=>l.toString())),f}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnTransientConnection===!1?n.find(o=>!mo.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var zy=50,Pr={minConnections:Ai,maxConnections:Ri,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},Ti=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Pr.maxConnections;let n=t.minConnections??Pr.minConnections;if(this.maxConnections<n)throw new y("Connection Manager maxConnections must be greater than minConnections",B.ERR_INVALID_PARAMETERS);this.connections=new Xe,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map(o=>re(o)),this.deny=(t.deny??[]).map(o=>re(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Pr.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new di({points:t.inboundConnectionThreshold??Pr.inboundConnectionThreshold,duration:1}),this.autoDial=new Si({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??Pr.autoDialConcurrency,autoDialPriority:t.autoDialPriority??Pr.autoDialPriority,maxQueueLength:t.autoDialMaxQueueLength??Pr.autoDialMaxQueueLength}),this.connectionPruner=new Ii({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Bi(e,{addressSorter:t.addressSorter??Rn,maxParallelDials:t.maxParallelDials??_i,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:kr},connections:this.connections})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(Dl)]});await Promise.all(e.map(async t=>{await this.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new y("Not started",B.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=pi(e);if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??zy}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>re(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};function Yy(r){return r[Symbol.asyncIterator]!=null}function Wy(...r){let e=[];for(let t of r)Yy(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=gi({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var yo=Wy;var Ni=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new y("No content routers available",B.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ft;for await(let s of yo(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new y("No content routers available",B.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new y(Mt.NOT_STARTED_YET,B.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new y(Mt.NOT_STARTED_YET,B.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var Ci=globalThis.CustomEvent??Event;async function*dl(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,s=[],i=pe(),a=pe(),c=!1,u,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let d of r){if(s.length===t&&(i=pe(),await i.promise),f)break;let p={done:!1};s.push(p),d().then(m=>{p.done=!0,p.ok=!0,p.value=m,o.dispatchEvent(new Ci("task-complete"))},m=>{p.done=!0,p.err=m,o.dispatchEvent(new Ci("task-complete"))})}c=!0,o.dispatchEvent(new Ci("task-complete"))}catch(d){u=d,o.dispatchEvent(new Ci("task-complete"))}});function l(){return n?s[0]?.done:!!s.find(d=>d.done)}function*h(){for(;s.length>0&&s[0].done;){let d=s[0];if(s.shift(),d.ok)yield d.value;else throw f=!0,i.resolve(),d.err;i.resolve()}}function*g(){for(;l();)for(let d=0;d<s.length;d++)if(s[d].done){let p=s[d];if(s.splice(d,1),d--,p.ok)yield p.value;else throw f=!0,i.resolve(),p.err;i.resolve()}}for(;;){if(l()||(a=pe(),await a.promise),u!=null)throw u;if(n?yield*h():yield*g(),c&&s.length===0)break}}var Li=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}async findPeer(e,t){if(this.routers.length===0)throw new y("No peer routers available",B.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new y("Should not try to find self",B.ERR_FIND_SELF);let n=this,o=yo(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new y(Mt.NOT_FOUND,B.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new y("No peer routers available",B.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ft;for await(let s of dl(async function*(){let i=yo(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}};var pl=32,ml=64,ki=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new y(`No handler registered for protocol ${e}`,B.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new y(`Handler already registered for protocol ${e}`,B.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=hi.bind({ignoreUndefined:!0})({maxInboundStreams:pl,maxOutboundStreams:ml},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new y("invalid topology",B.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.onDisconnect?.(t)}}).catch(n=>{n.code!==B.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.onDisconnect?.(t.id)}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.transient&&a.notifyOnTransient!==!0||a.onConnect?.(o,n)}}};var gl=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ed(r){let{name:e,metrics:t}=r,n;return t!=null?n=new gl({name:e,metrics:t}):n=new Map,n}var Di=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=Ed({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Vt.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(t==null)throw new y("Transport must have a valid tag",B.ERR_INVALID_KEY);if(this.transports.has(t))throw new y(`There is already a transport with the tag ${t}`,B.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.transportForMultiaddr(e);if(n==null)throw new y(`No transport available for address ${String(e)}`,B.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=B.ERR_TRANSPORT_DIAL_FAILED),o}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}transportForMultiaddr(e){for(let t of this.transports.values())if(t.filter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new y("Not started",B.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let s=o.filter(e),i=[];for(let u of s){this.log("creating listener for %s on %a",n,u);let f=o.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(n)??[];l==null&&(l=[],this.listeners.set(n,l)),l.push(f),f.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:f})}),f.addEventListener("close",()=>{let h=l.findIndex(g=>g===f);l.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:f})}),i.push(f.listen(u))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Vt.NO_FATAL)throw new y(`Transport (${n}) could not listen on any available address`,B.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Vt.FATAL_ALL)throw new y(n,B.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Be="/multistream/1.0.0";var yl=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=pe(),this.haveNext=pe()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=pe(),e}async throw(e){return this.ended=!0,e!=null&&this.haveNext.reject(e),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");if(this.nextResult!=null&&(await this.readNext.promise,this.nextResult!=null))throw new Error("NeedNext promise resolved but nextResult was not consumed");e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=pe(),await Bn(this.readNext.promise,t?.signal,t)}};function xd(){return new yl}var Pi=class extends Error{code;constructor(e,t){super(e),this.code=t}},wl=class extends Pi{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function vd(r,e){let t=xd();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new we;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new wl("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:h}=await Promise.race([n.next(),u]);return l===!0?new we:h}for(;o.byteLength<i;){let{value:l,done:h}=await Promise.race([n.next(),u]);if(h===!0)throw new Pi("unexpected end of input","ERR_UNEXPECTED_EOF");o.append(l)}let f=o.sublist(0,i);return o.consume(i),f}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Oi=class extends Error{code;constructor(e,t){super(e),this.code=t}};function wo(r,e={}){let t=vd(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=he(e.maxDataLength));let n=e?.lengthDecoder??it,o=e?.lengthEncoder??Le;return{read:async i=>{let a=-1,c=new we;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Oi("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Oi("message length too long","ERR_MSG_DATA_TOO_LONG");return t.read(a,i)},write:async(i,a)=>{await t.write(new we(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new we(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var jy=D(`
8
8
  `);async function Or(r,e,t){await r.write(e,t)}async function Ad(r,e,t){await r.writeV(e,t)}async function Xy(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==jy[0])throw e.log.error("Invalid mss message - missing newline",t),new y("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return t.sublist(0,-1)}async function ur(r,e){let t=await Xy(r,e);return K(t.subarray())}async function bo(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return Zy(r,e[0],t);let n=wo(r,{...t,maxDataLength:1024}),o=e.shift();if(o==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',Be,o);let s=D(`${Be}
9
9
  `),i=D(`${o}
10
10
  `);await Ad(n,[s,i],t),t.log.trace("select: reading multistream-select header");let a=await ur(n,t);if(t.log.trace('select: read "%s"',a),a===Be&&(t.log.trace("select: reading protocol response"),a=await ur(n,t),t.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of e){t.log.trace('select: write "%s"',c),await Or(n,D(`${c}
@@ -17,7 +17,7 @@ ${e.join(`
17
17
  `),t),t.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new we(...e.map(i=>Fi.single(D(`${i}
18
18
  `))),D(`
19
19
  `));t.log.trace('handle: respond with "%s" for %s',e,o),await Or(n,s,t),t.log.trace('handle: responded with "%s" for %s',e,o);continue}t.log('handle: respond with "na" for "%s"',o),await Or(n,D(`na
20
- `),t),t.log('handle: responded with "na" for "%s"',o)}}var tw=500,vl=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[kl]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new y("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new y("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&t?.runOnTransientConnection!==!0)throw new y("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(tw);Oe(1/0,t),e={...e,signal:t}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async t=>t.close(e))),this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(t=>{t.abort(e)}),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function _d(r){return new vl(r)}var rw=3e4;function nw(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==B.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return pl}function ow(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==B.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return t.maxOutboundStreams??ml}function Sd(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Vi=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,t.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??2e3,this.events=e.events}async shouldBlockConnection(e,t,n){let o=this.components.connectionGater[n];if(o!==void 0&&await o(e,t))throw new y(`The multiaddr connection is blocked by gater.${n}`,B.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new y("connection denied",B.ERR_CONNECTION_DENIED);let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{e.abort(new y("inbound upgrade timeout",Ro))};u.addEventListener("abort",f,{once:!0}),Oe(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new y("The multiaddr connection is blocked by gater.acceptConnection",B.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let l=e;if(t?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(e.log("protecting the inbound connection"),l=await h.protect(e))}try{if(o=l,t?.skipEncryption!==!0){({conn:o,remotePeer:s,protocol:c}=await this._encryptInbound(l));let h={...l,...o};await this.shouldBlockConnection(s,h,"denyInboundEncryptedConnection")}else{let h=e.remoteAddr.getPeerId();if(h==null)throw new y("inbound connection that skipped encryption must have a peer id",B.ERR_INVALID_MULTIADDR);let g=ye(h);c="native",s=g}if(i=o,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexInbound({...l,...o},this.muxers);a=h.muxerFactory,i=h.stream}}catch(h){throw e.log.error("failed to upgrade inbound connection",h),h}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:s,transient:t?.transient})}finally{u.removeEventListener("abort",f),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){let n=e.remoteAddr.getPeerId(),o;n!=null&&(o=ye(n),await this.shouldBlockConnection(o,e,"denyOutboundConnection"));let s,i,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let f=e;if(t?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(f=await l.protect(e))}try{if(s=f,t?.skipEncryption!==!0){({conn:s,remotePeer:i,protocol:c}=await this._encryptOutbound(f,o));let l={...f,...s};await this.shouldBlockConnection(i,l,"denyOutboundEncryptedConnection")}else{if(o==null)throw new y("Encryption was skipped but no peer id was passed",B.ERR_INVALID_PEER);c="native",i=o}if(a=s,t?.muxerFactory!=null)u=t.muxerFactory;else if(this.muxers.size>0){let l=await this._multiplexOutbound({...f,...s},this.muxers);u=l.muxerFactory,a=l.stream}}catch(l){throw e.log.error("failed to upgrade outbound connection",l),await e.close(l),l}return await this.shouldBlockConnection(i,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:i,transient:t?.transient})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,transient:c}=e,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:d=>{l!=null&&Promise.resolve().then(async()=>{let p=this.components.registrar.getProtocols(),{stream:m,protocol:w}=await Eo(d,p,{log:d.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",w);let x=nw(w,this.components.registrar);if(Sd(w,"inbound",l)===x){let A=new y(`Too many inbound protocol streams for protocol "${w}" - limit ${x}`,B.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(A),A}d.source=m.source,d.sink=m.sink,d.protocol=w,m.closeWrite!=null&&(d.closeWrite=m.closeWrite),m.closeRead!=null&&(d.closeRead=m.closeRead),m.close!=null&&(d.close=m.close),await this.components.peerStore.merge(i,{protocols:[w]}),this.components.metrics?.trackProtocolStream(d,l),this._onStream({connection:l,stream:d,protocol:w})}).catch(async p=>{l.log.error("error handling incoming stream id %s",d.id,p.message,p.code,p.stack),d.timeline.close==null&&await d.close()})}}),f=async(d,p={})=>{if(u==null)throw new y("Stream is not multiplexed",B.ERR_MUXER_UNAVAILABLE);l.log("starting new stream for protocols %s",d);let m=await u.newStream();l.log.trace("started new stream %s for protocols %s",m.id,d);try{if(p.signal==null){m.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d);let v=AbortSignal.timeout(rw);Oe(1/0,v),p={...p,signal:v}}m.log.trace("selecting protocol from protocols %s",d);let{stream:w,protocol:x}=await bo(m,d,{...p,log:m.log,yieldBytes:!0});m.log("selected protocol %s",x);let b=ow(x,this.components.registrar,p);if(Sd(x,"outbound",l)>=b){let v=new y(`Too many outbound protocol streams for protocol "${x}" - limit ${b}`,B.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw m.abort(v),v}return await this.components.peerStore.merge(i,{protocols:[x]}),m.source=w.source,m.sink=w.sink,m.protocol=x,w.closeWrite!=null&&(m.closeWrite=w.closeWrite),w.closeRead!=null&&(m.closeRead=w.closeRead),w.close!=null&&(m.close=w.close),this.components.metrics?.trackProtocolStream(m,l),m}catch(w){throw l.log.error("could not create new stream for protocols %s",d,w),m.timeline.close==null&&m.abort(w),w.code!=null?w:new y(String(w),B.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(d=>{l.log.error("error piping data through muxer",d)}));let h=o.timeline;o.timeline=new Proxy(h,{set:(...d)=>(l!=null&&d[1]==="close"&&d[2]!=null&&h.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(p){l.log.error("error closing connection after timeline close",p)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(p=>{l.log.error("error thrown while dispatching connection:close event",p)}),Reflect.set(...d))}),o.timeline.upgraded=Date.now();let g=()=>{throw new y("connection is not multiplexed",B.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=_d({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:t,transient:c,logger:this.components.logger,newStream:f??g,getStreams:()=>u!=null?u.streams:[],close:async d=>{u!=null&&(l.log.trace("close muxer"),await u.close(d)),l.log.trace("close maconn"),await o.close(d),l.log.trace("closed maconn")},abort:d=>{o.abort(d),u?.abort(d)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:s,options:i}=this.components.registrar.getHandler(o);if(t.transient&&i.runOnTransientConnection!==!0)throw new y("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:o}=await Eo(e,t,{log:e.log}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using",o),{...await s.secureInbound(this.components.peerId,n),protocol:o}}catch(n){throw e.log.error("encrypting inbound connection to %p failed",n),new y(n.message,B.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",n);try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await bo(e,n,{log:e.log,yieldBytes:!0}),i=this.connectionEncryption.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %s",t,i),{...await i.secureOutbound(this.components.peerId,o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %p failed",o),new y(o.message,B.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:s}=await bo(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new y(String(o),B.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{let{stream:o,protocol:s}=await Eo(e,n,{log:e.log}),i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new y(String(o),B.ERR_MUXER_UNAVAILABLE)}}};var Id="1.4.0",Bd="libp2p";var Al=class extends hr{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new hr,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new Yi(a.type,{detail:a.detail}));return c||u},Oe(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Os(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=Vh({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:Bd,version:Id},logger:this.logger,events:t,datastore:e.datastore??new Qs,connectionGater:$h(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new Xs(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(o)),this.components.upgrader=new Vi(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),muxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Di(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ti(this.components,e.connectionManager)),this.configureComponent("registrar",new ki(this.components)),this.configureComponent("addressManager",new Js(this.components,e.addresses));let s=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Li(this.components,{routers:s}));let i=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Ni(this.components,{routers:i})),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[Hi]!=null&&(this.log("registering service %s for content routing",a),i.push(u[Hi])),u[Gi]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[Gi])),u[$i]!=null&&(this.log("registering service %s for peer discovery",a),u[$i].addEventListener?.("peer",f=>{this.#e(f)}))}}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new ft;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new y("no protocols were provided to open a stream",B.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw new y("no protocols were provided to open a stream",B.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){sr(e)&&(e=ye(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let s=await this.peerStore.get(e);if(s.id.publicKey!=null)return s.id.publicKey}catch(s){if(s.code!==B.ERR_NOT_FOUND)throw s}let n=Re([D("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(n,t);return to(o),await this.peerStore.patch(e,{publicKey:o}),o}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error(new Error(B.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function Td(r={}){let e=r.peerId??=await eh();if(e.privateKey==null)throw new y("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return r.privateKey??=await ro(e.privateKey),new Al(await dd(r))}async function iw(r={}){let e=await Td(r);return r.start!==!1&&await e.start(),e}return $d(aw);})();
20
+ `),t),t.log('handle: responded with "na" for "%s"',o)}}var tw=500,vl=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[kl]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new y("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new y("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&t?.runOnTransientConnection!==!0)throw new y("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(tw);Oe(1/0,t),e={...e,signal:t}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async t=>t.close(e))),this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(t=>{t.abort(e)}),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function _d(r){return new vl(r)}var rw=3e4;function nw(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==B.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return pl}function ow(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==B.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return t.maxOutboundStreams??ml}function Sd(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Vi=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,t.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??2e3,this.events=e.events}async shouldBlockConnection(e,t,n){let o=this.components.connectionGater[n];if(o!==void 0&&await o(e,t))throw new y(`The multiaddr connection is blocked by gater.${n}`,B.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new y("connection denied",B.ERR_CONNECTION_DENIED);let o,s,i,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),f=()=>{e.abort(new y("inbound upgrade timeout",Ro))};u.addEventListener("abort",f,{once:!0}),Oe(1/0,u);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new y("The multiaddr connection is blocked by gater.acceptConnection",B.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let l=e;if(t?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(e.log("protecting the inbound connection"),l=await h.protect(e))}try{if(o=l,t?.skipEncryption!==!0){({conn:o,remotePeer:s,protocol:c}=await this._encryptInbound(l));let h={...l,...o};await this.shouldBlockConnection(s,h,"denyInboundEncryptedConnection")}else{let h=e.remoteAddr.getPeerId();if(h==null)throw new y("inbound connection that skipped encryption must have a peer id",B.ERR_INVALID_MULTIADDR);let g=ye(h);c="native",s=g}if(i=o,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexInbound({...l,...o},this.muxers);a=h.muxerFactory,i=h.stream}}catch(h){throw e.log.error("failed to upgrade inbound connection",h),h}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:s,transient:t?.transient})}finally{u.removeEventListener("abort",f),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){let n=e.remoteAddr.getPeerId(),o;n!=null&&(o=ye(n),await this.shouldBlockConnection(o,e,"denyOutboundConnection"));let s,i,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let f=e;if(t?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(f=await l.protect(e))}try{if(s=f,t?.skipEncryption!==!0){({conn:s,remotePeer:i,protocol:c}=await this._encryptOutbound(f,o));let l={...f,...s};await this.shouldBlockConnection(i,l,"denyOutboundEncryptedConnection")}else{if(o==null)throw new y("Encryption was skipped but no peer id was passed",B.ERR_INVALID_PEER);c="native",i=o}if(a=s,t?.muxerFactory!=null)u=t.muxerFactory;else if(this.muxers.size>0){let l=await this._multiplexOutbound({...f,...s},this.muxers);u=l.muxerFactory,a=l.stream}}catch(l){throw e.log.error("failed to upgrade outbound connection",l),await e.close(l),l}return await this.shouldBlockConnection(i,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:i,transient:t?.transient})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,transient:c}=e,u,f,l;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:d=>{l!=null&&Promise.resolve().then(async()=>{let p=this.components.registrar.getProtocols(),{stream:m,protocol:w}=await Eo(d,p,{log:d.log,yieldBytes:!1});if(l==null)return;l.log("incoming stream opened on %s",w);let x=nw(w,this.components.registrar);if(Sd(w,"inbound",l)===x){let A=new y(`Too many inbound protocol streams for protocol "${w}" - limit ${x}`,B.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw d.abort(A),A}d.source=m.source,d.sink=m.sink,d.protocol=w,m.closeWrite!=null&&(d.closeWrite=m.closeWrite),m.closeRead!=null&&(d.closeRead=m.closeRead),m.close!=null&&(d.close=m.close),await this.components.peerStore.merge(i,{protocols:[w]}),this.components.metrics?.trackProtocolStream(d,l),this._onStream({connection:l,stream:d,protocol:w})}).catch(async p=>{l.log.error("error handling incoming stream id %s",d.id,p.message,p.code,p.stack),d.timeline.close==null&&await d.close()})}}),f=async(d,p={})=>{if(u==null)throw new y("Stream is not multiplexed",B.ERR_MUXER_UNAVAILABLE);l.log("starting new stream for protocols %s",d);let m=await u.newStream();l.log.trace("started new stream %s for protocols %s",m.id,d);try{if(p.signal==null){m.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",d);let v=AbortSignal.timeout(rw);Oe(1/0,v),p={...p,signal:v}}m.log.trace("selecting protocol from protocols %s",d);let{stream:w,protocol:x}=await bo(m,d,{...p,log:m.log,yieldBytes:!0});m.log("selected protocol %s",x);let b=ow(x,this.components.registrar,p),A=Sd(x,"outbound",l);if(A>=b){let v=new y(`Too many outbound protocol streams for protocol "${x}" - ${A}/${b}`,B.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw m.abort(v),v}return await this.components.peerStore.merge(i,{protocols:[x]}),m.source=w.source,m.sink=w.sink,m.protocol=x,w.closeWrite!=null&&(m.closeWrite=w.closeWrite),w.closeRead!=null&&(m.closeRead=w.closeRead),w.close!=null&&(m.close=w.close),this.components.metrics?.trackProtocolStream(m,l),m}catch(w){throw l.log.error("could not create new stream for protocols %s",d,w),m.timeline.close==null&&m.abort(w),w.code!=null?w:new y(String(w),B.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(d=>{l.log.error("error piping data through muxer",d)}));let h=o.timeline;o.timeline=new Proxy(h,{set:(...d)=>(l!=null&&d[1]==="close"&&d[2]!=null&&h.close==null&&(async()=>{try{l.status==="open"&&await l.close()}catch(p){l.log.error("error closing connection after timeline close",p)}finally{this.events.safeDispatchEvent("connection:close",{detail:l})}})().catch(p=>{l.log.error("error thrown while dispatching connection:close event",p)}),Reflect.set(...d))}),o.timeline.upgraded=Date.now();let g=()=>{throw new y("connection is not multiplexed",B.ERR_CONNECTION_NOT_MULTIPLEXED)};return l=_d({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:t,transient:c,logger:this.components.logger,newStream:f??g,getStreams:()=>u!=null?u.streams:[],close:async d=>{u!=null&&(l.log.trace("close muxer"),await u.close(d)),l.log.trace("close maconn"),await o.close(d),l.log.trace("closed maconn")},abort:d=>{o.abort(d),u?.abort(d)}}),this.events.safeDispatchEvent("connection:open",{detail:l}),l}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:s,options:i}=this.components.registrar.getHandler(o);if(t.transient&&i.runOnTransientConnection!==!0)throw new y("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:o}=await Eo(e,t,{log:e.log}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using",o),{...await s.secureInbound(this.components.peerId,n),protocol:o}}catch(n){throw e.log.error("encrypting inbound connection to %p failed",n),new y(n.message,B.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",n);try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await bo(e,n,{log:e.log,yieldBytes:!0}),i=this.connectionEncryption.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %s",t,i),{...await i.secureOutbound(this.components.peerId,o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %p failed",o),new y(o.message,B.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:s}=await bo(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new y(String(o),B.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{let{stream:o,protocol:s}=await Eo(e,n,{log:e.log}),i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new y(String(o),B.ERR_MUXER_UNAVAILABLE)}}};var Id="1.4.2-2281f802b",Bd="libp2p";var Al=class extends hr{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new hr,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),u=this.dispatchEvent(new Yi(a.type,{detail:a.detail}));return c||u},Oe(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Os(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=Vh({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:Bd,version:Id},logger:this.logger,events:t,datastore:e.datastore??new Qs,connectionGater:$h(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new Xs(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(u=>u.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(o)),this.components.upgrader=new Vi(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),muxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Di(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ti(this.components,e.connectionManager)),this.configureComponent("registrar",new ki(this.components)),this.configureComponent("addressManager",new Js(this.components,e.addresses));let s=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Li(this.components,{routers:s}));let i=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Ni(this.components,{routers:i})),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",f=>{this.#e(f)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],u=c(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=u,this.configureComponent(a,u),u[Hi]!=null&&(this.log("registering service %s for content routing",a),i.push(u[Hi])),u[Gi]!=null&&(this.log("registering service %s for peer routing",a),s.push(u[Gi])),u[$i]!=null&&(this.log("registering service %s for peer discovery",a),u[$i].addEventListener?.("peer",f=>{this.#e(f)}))}}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new ft;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new y("no protocols were provided to open a stream",B.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw new y("no protocols were provided to open a stream",B.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){sr(e)&&(e=ye(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let s=await this.peerStore.get(e);if(s.id.publicKey!=null)return s.id.publicKey}catch(s){if(s.code!==B.ERR_NOT_FOUND)throw s}let n=Re([D("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(n,t);return to(o),await this.peerStore.patch(e,{publicKey:o}),o}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error(new Error(B.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function Td(r={}){let e=r.peerId??=await eh();if(e.privateKey==null)throw new y("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return r.privateKey??=await ro(e.privateKey),new Al(await dd(r))}async function iw(r={}){let e=await Td(r);return r.start!==!1&&await e.start(),e}return $d(aw);})();
21
21
  /*! Bundled license information:
22
22
 
23
23
  pvtsutils/build/index.js:
@@ -25,7 +25,7 @@ export type ServiceFactoryMap<T extends Record<string, unknown> = Record<string,
25
25
  [Property in keyof T]: (components: Components) => T[Property];
26
26
  };
27
27
  /**
28
- * For Libp2p configurations and modules details read the [Configuration Document](./CONFIGURATION.md).
28
+ * For Libp2p configurations and modules details read the [Configuration Document](https://github.com/libp2p/js-libp2p/tree/main/doc/CONFIGURATION.md).
29
29
  */
30
30
  export interface Libp2pInit<T extends ServiceMap = {
31
31
  x: Record<string, unknown>;
@@ -336,7 +336,7 @@ export class DefaultUpgrader {
336
336
  const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.registrar, options);
337
337
  const streamCount = countStreams(protocol, 'outbound', connection);
338
338
  if (streamCount >= outgoingLimit) {
339
- const err = new CodeError(`Too many outbound protocol streams for protocol "${protocol}" - limit ${outgoingLimit}`, codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);
339
+ const err = new CodeError(`Too many outbound protocol streams for protocol "${protocol}" - ${streamCount}/${outgoingLimit}`, codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);
340
340
  muxedStream.abort(err);
341
341
  throw err;
342
342
  }
@@ -1 +1 @@
1
- {"version":3,"file":"upgrader.js","sourceRoot":"","sources":["../../src/upgrader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAC3E,OAAO,KAAK,GAAG,MAAM,4BAA4B,CAAA;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAA;AAClD,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AACxD,OAAO,EAAE,uBAAuB,EAAE,MAAM,mCAAmC,CAAA;AAC3E,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAA;AACnC,OAAO,EAAE,2BAA2B,EAAE,4BAA4B,EAAE,MAAM,gBAAgB,CAAA;AAI1F,MAAM,+BAA+B,GAAG,KAAK,CAAA;AAiC7C,SAAS,uBAAuB,CAAE,QAAgB,EAAE,SAAoB;IACtE,IAAI,CAAC;QACH,MAAM,EAAE,OAAO,EAAE,GAAG,SAAS,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;QAElD,OAAO,OAAO,CAAC,iBAAiB,CAAA;IAClC,CAAC;IAAC,OAAO,GAAQ,EAAE,CAAC;QAClB,IAAI,GAAG,CAAC,IAAI,KAAK,KAAK,CAAC,2BAA2B,EAAE,CAAC;YACnD,MAAM,GAAG,CAAA;QACX,CAAC;IACH,CAAC;IAED,OAAO,2BAA2B,CAAA;AACpC,CAAC;AAED,SAAS,uBAAuB,CAAE,QAAgB,EAAE,SAAoB,EAAE,UAA4B,EAAE;IACtG,IAAI,CAAC;QACH,MAAM,EAAE,OAAO,EAAE,GAAG,SAAS,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;QAElD,IAAI,OAAO,CAAC,kBAAkB,IAAI,IAAI,EAAE,CAAC;YACvC,OAAO,O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AE;gBACnE,GAAG,EAAE,UAAU,CAAC,GAAG;aACpB,CAAC,CAAA;YACF,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAA;YAEzC,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,CAAA;QACjC,CAAC;QAAC,OAAO,GAAQ,EAAE,CAAC;YAClB,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,uCAAuC,EAAE,GAAG,CAAC,CAAA;YAClE,MAAM,IAAI,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,qBAAqB,CAAC,CAAA;QAC/D,CAAC;IACH,CAAC;CACF"}
@@ -1,3 +1,3 @@
1
- export declare const version = "1.4.0";
1
+ export declare const version = "1.4.2-2281f802b";
2
2
  export declare const name = "libp2p";
3
3
  //# sourceMappingURL=version.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,UAAU,CAAA;AAC9B,eAAO,MAAM,IAAI,WAAW,CAAA"}
1
+ {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,oBAAoB,CAAA;AACxC,eAAO,MAAM,IAAI,WAAW,CAAA"}
@@ -1,3 +1,3 @@
1
- export const version = '1.4.0';
1
+ export const version = '1.4.2-2281f802b';
2
2
  export const name = 'libp2p';
3
3
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAA;AAC9B,MAAM,CAAC,MAAM,IAAI,GAAG,QAAQ,CAAA"}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,iBAAiB,CAAA;AACxC,MAAM,CAAC,MAAM,IAAI,GAAG,QAAQ,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2p",
3
- "version": "1.4.0",
3
+ "version": "1.4.2-2281f802b",
4
4
  "description": "JavaScript implementation of libp2p, a modular peer to peer network stack",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/libp2p#readme",
@@ -85,16 +85,16 @@
85
85
  "test:webkit": "aegir test -t browser -f \"./dist/test/**/*.spec.js\" -- --browser webkit"
86
86
  },
87
87
  "dependencies": {
88
- "@libp2p/crypto": "^4.0.6",
89
- "@libp2p/interface": "^1.2.0",
90
- "@libp2p/interface-internal": "^1.1.0",
91
- "@libp2p/logger": "^4.0.10",
92
- "@libp2p/multistream-select": "^5.1.7",
93
- "@libp2p/peer-collections": "^5.1.10",
94
- "@libp2p/peer-id": "^4.0.10",
95
- "@libp2p/peer-id-factory": "^4.0.10",
96
- "@libp2p/peer-store": "^10.0.14",
97
- "@libp2p/utils": "^5.3.0",
88
+ "@libp2p/crypto": "4.0.6-2281f802b",
89
+ "@libp2p/interface": "1.2.0-2281f802b",
90
+ "@libp2p/interface-internal": "1.1.0-2281f802b",
91
+ "@libp2p/logger": "4.0.10-2281f802b",
92
+ "@libp2p/multistream-select": "5.1.7-2281f802b",
93
+ "@libp2p/peer-collections": "5.1.10-2281f802b",
94
+ "@libp2p/peer-id": "4.0.10-2281f802b",
95
+ "@libp2p/peer-id-factory": "4.0.10-2281f802b",
96
+ "@libp2p/peer-store": "10.0.15-2281f802b",
97
+ "@libp2p/utils": "5.3.1-2281f802b",
98
98
  "@multiformats/dns": "^1.0.5",
99
99
  "@multiformats/multiaddr": "^12.2.1",
100
100
  "@multiformats/multiaddr-matcher": "^1.2.0",
@@ -109,13 +109,13 @@
109
109
  },
110
110
  "devDependencies": {
111
111
  "@chainsafe/libp2p-yamux": "^6.0.2",
112
- "@libp2p/circuit-relay-v2": "^1.0.19",
113
- "@libp2p/identify": "^1.0.18",
114
- "@libp2p/interface-compliance-tests": "^5.4.0",
115
- "@libp2p/mplex": "^10.0.19",
116
- "@libp2p/plaintext": "^1.0.19",
117
- "@libp2p/tcp": "^9.0.20",
118
- "@libp2p/websockets": "^8.0.19",
112
+ "@libp2p/circuit-relay-v2": "1.0.20-2281f802b",
113
+ "@libp2p/identify": "1.0.19-2281f802b",
114
+ "@libp2p/interface-compliance-tests": "5.4.1-2281f802b",
115
+ "@libp2p/mplex": "10.0.20-2281f802b",
116
+ "@libp2p/plaintext": "1.0.20-2281f802b",
117
+ "@libp2p/tcp": "9.0.22-2281f802b",
118
+ "@libp2p/websockets": "8.0.20-2281f802b",
119
119
  "@multiformats/mafmt": "^12.1.6",
120
120
  "aegir": "^42.2.5",
121
121
  "delay": "^6.0.0",
package/src/index.ts CHANGED
@@ -29,7 +29,7 @@ export type ServiceFactoryMap<T extends Record<string, unknown> = Record<string,
29
29
  }
30
30
 
31
31
  /**
32
- * For Libp2p configurations and modules details read the [Configuration Document](./CONFIGURATION.md).
32
+ * For Libp2p configurations and modules details read the [Configuration Document](https://github.com/libp2p/js-libp2p/tree/main/doc/CONFIGURATION.md).
33
33
  */
34
34
  export interface Libp2pInit<T extends ServiceMap = { x: Record<string, unknown> }> {
35
35
  /**
package/src/upgrader.ts CHANGED
@@ -471,7 +471,7 @@ export class DefaultUpgrader implements Upgrader {
471
471
  const streamCount = countStreams(protocol, 'outbound', connection)
472
472
 
473
473
  if (streamCount >= outgoingLimit) {
474
- const err = new CodeError(`Too many outbound protocol streams for protocol "${protocol}" - limit ${outgoingLimit}`, codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS)
474
+ const err = new CodeError(`Too many outbound protocol streams for protocol "${protocol}" - ${streamCount}/${outgoingLimit}`, codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS)
475
475
  muxedStream.abort(err)
476
476
 
477
477
  throw err
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '1.4.0'
1
+ export const version = '1.4.2-2281f802b'
2
2
  export const name = 'libp2p'
@@ -1,14 +0,0 @@
1
- {
2
- "Libp2pInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.Libp2pInit.html",
3
- ".:Libp2pInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.Libp2pInit.html",
4
- "Libp2pOptions": "https://libp2p.github.io/js-libp2p/types/libp2p.index.Libp2pOptions.html",
5
- ".:Libp2pOptions": "https://libp2p.github.io/js-libp2p/types/libp2p.index.Libp2pOptions.html",
6
- "ServiceFactoryMap": "https://libp2p.github.io/js-libp2p/types/libp2p.index.ServiceFactoryMap.html",
7
- ".:ServiceFactoryMap": "https://libp2p.github.io/js-libp2p/types/libp2p.index.ServiceFactoryMap.html",
8
- "createLibp2p": "https://libp2p.github.io/js-libp2p/functions/libp2p.index.createLibp2p.html",
9
- ".:createLibp2p": "https://libp2p.github.io/js-libp2p/functions/libp2p.index.createLibp2p.html",
10
- "name": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.name.html",
11
- "./version:name": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.name.html",
12
- "version": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.version.html",
13
- "./version:version": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.version.html"
14
- }