@libp2p/circuit-relay-v2 1.0.13-2370d1c39 → 1.0.13-9891ecd73

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.
Files changed (2) hide show
  1. package/dist/index.min.js +1 -1
  2. package/package.json +21 -21
package/dist/index.min.js CHANGED
@@ -4,7 +4,7 @@
4
4
  `));let e=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return t.length?`${e} :
5
5
  ${t.join(`
6
6
  `)}`:`${e} :`}};Cc=Ke;T.Constructed=Cc;Ke.NAME="CONSTRUCTED";var Xn=class extends St{fromBER(t,e,n){return e}toBER(t){return Qt}};Xn.override="EndOfContentValueBlock";var Uc,Jn=class extends xt{constructor(t={}){super(t,Xn),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Uc=Jn;T.EndOfContent=Uc;Jn.NAME=nn;var Dc,qe=class extends xt{constructor(t={}){super(t,St),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(t,e,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,e+n>t.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):e+n}toBER(t,e){let n=new ArrayBuffer(2);if(!t){let s=new Uint8Array(n);s[0]=5,s[1]=0}return e&&e.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Dc=qe;T.Null=Dc;qe.NAME="NULL";var Qn=class extends Se(St){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=K.BufferSourceConverter.toUint8Array(e.valueHex):this.valueHexView=new Uint8Array(1),t&&(this.value=t)}get value(){for(let t of this.valueHexView)if(t>0)return!0;return!1}set value(t){this.valueHexView[0]=t?255:0}fromBER(t,e,n){let s=K.BufferSourceConverter.toUint8Array(t);return Be(this,s,e,n)?(this.valueHexView=s.subarray(e,e+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,yo.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Qn.NAME="BooleanValueBlock";var Oc,ts=class extends xt{constructor(t={}){super(t,Qn),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Oc=ts;T.Boolean=Oc;ts.NAME="BOOLEAN";var es=class extends Se(oe){constructor({isConstructed:t=!1,...e}={}){super(e),this.isConstructed=t}fromBER(t,e,n){let s=0;if(this.isConstructed){if(this.isHexOnly=!1,s=oe.prototype.fromBER.call(this,t,e,n),s===-1)return s;for(let i=0;i<this.value.length;i++){let o=this.value[i].constructor.NAME;if(o===nn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(o!==Rc)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,s=super.fromBER(t,e,n),this.blockLength=n;return s}toBER(t,e){return this.isConstructed?oe.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};es.NAME="OctetStringValueBlock";var Pc,Ee=class r extends xt{constructor({idBlock:t={},lenBlock:e={},...n}={}){var s,i;(s=n.isConstructed)!==null&&s!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},es),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(t,e,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),e;if(!this.valueBlock.isConstructed){let i=(t instanceof ArrayBuffer?new Uint8Array(t):t).subarray(e,e+n);try{if(i.byteLength){let o=Rs(i,0,i.byteLength);o.offset!==-1&&o.offset===n&&(this.valueBlock.value=[o.result])}}catch{}}return super.fromBER(t,e,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?Ke.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${K.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let t=[];for(let e of this.valueBlock.value)e instanceof r&&t.push(e.valueBlock.valueHexView);return K.BufferSourceConverter.concat(t)}};Pc=Ee;T.OctetString=Pc;Ee.NAME=Rc;var rs=class extends Se(oe){constructor({unusedBits:t=0,isConstructed:e=!1,...n}={}){super(n),this.unusedBits=t,this.isConstructed=e,this.blockLength=this.valueHexView.byteLength}fromBER(t,e,n){if(!n)return e;let s=-1;if(this.isConstructed){if(s=oe.prototype.fromBER.call(this,t,e,n),s===-1)return s;for(let a of this.value){let c=a.constructor.NAME;if(c===nn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Nc)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let f=a.valueBlock;if(this.unusedBits>0&&f.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=f.unusedBits}return s}let i=K.BufferSourceConverter.toUint8Array(t);if(!Be(this,i,e,n))return-1;let o=i.subarray(e,e+n);if(this.unusedBits=o[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=o.subarray(1);try{if(a.byteLength){let c=Rs(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=o.subarray(1),this.blockLength=o.length,e+n}toBER(t,e){if(this.isConstructed)return oe.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Qt;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}}};rs.NAME="BitStringValueBlock";var Vc,Cr=class extends xt{constructor({idBlock:t={},lenBlock:e={},...n}={}){var s,i;(s=n.isConstructed)!==null&&s!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},rs),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(t,e,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(t,e,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Ke.prototype.onAsciiEncoding.call(this);{let t=[],e=this.valueBlock.valueHexView;for(let s of e)t.push(s.toString(2).padStart(8,"0"));let n=t.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};Vc=Cr;T.BitString=Vc;Cr.NAME=Nc;var Mc;function Vd(r,t){let e=new Uint8Array([0]),n=new Uint8Array(r),s=new Uint8Array(t),i=n.slice(0),o=i.length-1,a=s.slice(0),c=a.length-1,f=0,u=c<o?o:c,l=0;for(let h=u;h>=0;h--,l++){switch(!0){case l<a.length:f=i[o-l]+a[c-l]+e[0];break;default:f=i[o-l]+e[0]}switch(e[0]=f/10,!0){case l>=i.length:i=$n(new Uint8Array([f%10]),i);break;default:i[o-l]=f%10}}return e[0]>0&&(i=$n(e,i)),i}function kc(r){if(r>=en.length)for(let t=en.length;t<=r;t++){let e=new Uint8Array([0]),n=en[t-1].slice(0);for(let s=n.length-1;s>=0;s--){let i=new Uint8Array([(n[s]<<1)+e[0]]);e[0]=i[0]/10,n[s]=i[0]%10}e[0]>0&&(n=$n(e,n)),en.push(n)}return en[r]}function Md(r,t){let e=0,n=new Uint8Array(r),s=new Uint8Array(t),i=n.slice(0),o=i.length-1,a=s.slice(0),c=a.length-1,f,u=0;for(let l=c;l>=0;l--,u++)switch(f=i[o-u]-a[c-u]-e,!0){case f<0:e=1,i[o-u]=f+10;break;default:e=0,i[o-u]=f}if(e>0)for(let l=o-c+1;l>=0;l--,u++)if(f=i[o-u]-e,f<0)e=1,i[o-u]=f+10;else{e=0,i[o-u]=f;break}return i.slice()}var sn=class extends Se(St){constructor({value:t,...e}={}){super(e),this._valueDec=0,e.valueHex&&this.setValueHex(),t!==void 0&&(this.valueDec=t)}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=yo.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Sc(t))}get valueDec(){return this._valueDec}fromDER(t,e,n,s=0){let i=this.fromBER(t,e,n);if(i===-1)return i;let o=this.valueHexView;return o[0]===0&&o[1]&128?this.valueHexView=o.subarray(1):s!==0&&o.length<s&&(s-o.length>1&&(s=o.length+1),this.valueHexView=o.subarray(s-o.length)),i}toDER(t=!1){let e=this.valueHexView;switch(!0){case(e[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(e,1),this.valueHexView=n}break;case(e[0]===0&&(e[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(t)}fromBER(t,e,n){let s=super.fromBER(t,e,n);return s===-1||this.setValueHex(),s}toBER(t){return t?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let t=this.valueHexView.length*8-1,e=new Uint8Array(this.valueHexView.length*8/3),n=0,s,i=this.valueHexView,o="",a=!1;for(let c=i.byteLength-1;c>=0;c--){s=i[c];for(let f=0;f<8;f++){if((s&1)===1)switch(n){case t:e=Md(kc(n),e),o="-";break;default:e=Vd(e,kc(n))}n++,s>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(o+=Ic.charAt(e[c]));return a===!1&&(o+=Ic.charAt(0)),o}};Mc=sn;sn.NAME="IntegerValueBlock";Object.defineProperty(Mc.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Hc,ft=class r extends xt{constructor(t={}){super(t,sn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Gn(),BigInt(this.valueBlock.toString())}static fromBigInt(t){Gn();let e=BigInt(t),n=new rn,s=e.toString(16).replace(/^-/,""),i=new Uint8Array(K.Convert.FromHex(s));if(e<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let f=BigInt(`0x${K.Convert.ToHex(a)}`)+e,u=K.BufferSourceConverter.toUint8Array(K.Convert.FromHex(f.toString(16)));u[0]|=128,n.write(u)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new r({valueHex:n.final()})}convertToDER(){let t=new r({valueHex:this.valueBlock.valueHexView});return t.valueBlock.toDER(),t}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()}`}};Hc=ft;T.Integer=Hc;ft.NAME="INTEGER";var Fc,ns=class extends ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Fc=ns;T.Enumerated=Fc;ns.NAME="ENUMERATED";var on=class extends Se(St){constructor({valueDec:t=-1,isFirstSid:e=!1,...n}={}){super(n),this.valueDec=t,this.isFirstSid=e}fromBER(t,e,n){if(!n)return e;let s=K.BufferSourceConverter.toUint8Array(t);if(!Be(this,s,e,n))return-1;let i=s.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,!!(i[a]&128));a++);let o=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)o[a]=this.valueHexView[a];return this.valueHexView=o,i[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=or(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){Gn();let e=BigInt(t).toString(2);for(;e.length%7;)e="0"+e;let n=new Uint8Array(e.length/7);for(let s=0;s<n.length;s++)n[s]=parseInt(e.slice(s*7,s*7+7),2)+(s+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let s=this.valueHexView,i=new Uint8Array(this.blockLength);for(let o=0;o<this.blockLength-1;o++)i[o]=s[o]|128;return i[this.blockLength-1]=s[this.blockLength-1],i.buffer}let e=Fe(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",Qt;let n=new Uint8Array(e.byteLength);if(!t){let s=new Uint8Array(e),i=e.byteLength-1;for(let o=0;o<i;o++)n[o]=s[o]|128;n[i]=s[i]}return n}toString(){let t="";if(this.isHexOnly)t=K.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let e=this.valueDec;this.valueDec<=39?t="0.":this.valueDec<=79?(t="1.",e-=40):(t="2.",e-=80),t+=e.toString()}else t=this.valueDec.toString();return t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};on.NAME="sidBlock";var ss=class extends St{constructor({value:t=Ur,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let s=e;for(;n>0;){let i=new on;if(s=i.fromBER(t,s,n),s===-1)return this.blockLength=0,this.error=i.error,s;this.value.length===0&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return s}toBER(t){let e=[];for(let n=0;n<this.value.length;n++){let s=this.value[n].toBER(t);if(s.byteLength===0)return this.error=this.value[n].error,Qt;e.push(s)}return bo(e)}fromString(t){this.value=[];let e=0,n=0,s="",i=!1;do if(n=t.indexOf(".",e),n===-1?s=t.substring(e):s=t.substring(e,n),e=n+1,i){let o=this.value[0],a=0;switch(o.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(s,10);if(isNaN(c))return;o.valueDec=c+a,i=!1}else{let o=new on;if(s>Number.MAX_SAFE_INTEGER){Gn();let a=BigInt(s);o.valueBigInt=a}else if(o.valueDec=parseInt(s,10),isNaN(o.valueDec))return;this.value.length||(o.isFirstSid=!0,i=!0),this.value.push(o)}while(n!==-1)}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let s=this.value[n].toString();n!==0&&(t=`${t}.`),e?(s=`{${s}}`,this.value[n].isFirstSid?t=`2.{${s} - 80}`:t+=s):t+=s}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};ss.NAME="ObjectIdentifierValueBlock";var Kc,Jt=class extends xt{constructor(t={}){super(t,ss),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Kc=Jt;T.ObjectIdentifier=Kc;Jt.NAME="OBJECT IDENTIFIER";var an=class extends Se(ve){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let s=K.BufferSourceConverter.toUint8Array(t);if(!Be(this,s,e,n))return-1;let i=s.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,!!(i[a]&128));a++);let o=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)o[a]=this.valueHexView[a];return this.valueHexView=o,i[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=or(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let s=this.valueHexView,i=new Uint8Array(this.blockLength);for(let o=0;o<this.blockLength-1;o++)i[o]=s[o]|128;return i[this.blockLength-1]=s[this.blockLength-1],i.buffer}let e=Fe(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",Qt;let n=new Uint8Array(e.byteLength);if(!t){let s=new Uint8Array(e),i=e.byteLength-1;for(let o=0;o<i;o++)n[o]=s[o]|128;n[i]=s[i]}return n.buffer}toString(){let t="";return this.isHexOnly?t=K.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};an.NAME="relativeSidBlock";var is=class extends St{constructor({value:t=Ur,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let s=e;for(;n>0;){let i=new an;if(s=i.fromBER(t,s,n),s===-1)return this.blockLength=0,this.error=i.error,s;this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return s}toBER(t,e){let n=[];for(let s=0;s<this.value.length;s++){let i=this.value[s].toBER(t);if(i.byteLength===0)return this.error=this.value[s].error,Qt;n.push(i)}return bo(n)}fromString(t){this.value=[];let e=0,n=0,s="";do{n=t.indexOf(".",e),n===-1?s=t.substring(e):s=t.substring(e,n),e=n+1;let i=new an;if(i.valueDec=parseInt(s,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(n!==-1);return!0}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let s=this.value[n].toString();n!==0&&(t=`${t}.`),e&&(s=`{${s}}`),t+=s}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};is.NAME="RelativeObjectIdentifierValueBlock";var qc,os=class extends xt{constructor(t={}){super(t,is),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};qc=os;T.RelativeObjectIdentifier=qc;os.NAME="RelativeObjectIdentifier";var $c,yt=class extends Ke{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};$c=yt;T.Sequence=$c;yt.NAME="SEQUENCE";var Gc,as=class extends Ke{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Gc=as;T.Set=Gc;as.NAME="SET";var cs=class extends Se(St){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=Ur}toJSON(){return{...super.toJSON(),value:this.value}}};cs.NAME="StringValueBlock";var ls=class extends cs{};ls.NAME="SimpleStringValueBlock";var kt=class extends Wn{constructor({...t}={}){super(t,ls)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,K.BufferSourceConverter.toUint8Array(t))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e);for(let s=0;s<e;s++)n[s]=t.charCodeAt(s);this.valueBlock.value=t}};kt.NAME="SIMPLE STRING";var us=class extends kt{fromBuffer(t){this.valueBlock.valueHexView=K.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=K.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=K.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(K.Convert.FromUtf8String(t)),this.valueBlock.value=t}};us.NAME="Utf8StringValueBlock";var zc,Ae=class extends us{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};zc=Ae;T.Utf8String=zc;Ae.NAME="UTF8String";var fs=class extends kt{fromBuffer(t){this.valueBlock.value=K.Convert.ToUtf16String(t),this.valueBlock.valueHexView=K.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(K.Convert.FromUtf16String(t))}};fs.NAME="BmpStringValueBlock";var jc,hs=class extends fs{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};jc=hs;T.BmpString=jc;hs.NAME="BMPString";var ds=class extends kt{fromBuffer(t){let e=ArrayBuffer.isView(t)?t.slice().buffer:t.slice(0),n=new Uint8Array(e);for(let s=0;s<n.length;s+=4)n[s]=n[s+3],n[s+1]=n[s+2],n[s+2]=0,n[s+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(e))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e*4);for(let s=0;s<e;s++){let i=Fe(t.charCodeAt(s),8),o=new Uint8Array(i);if(o.length>4)continue;let a=4-o.length;for(let c=o.length-1;c>=0;c--)n[s*4+c+a]=o[c]}this.valueBlock.value=t}};ds.NAME="UniversalStringValueBlock";var Wc,ps=class extends ds{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Wc=ps;T.UniversalString=Wc;ps.NAME="UniversalString";var Yc,ms=class extends kt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Yc=ms;T.NumericString=Yc;ms.NAME="NumericString";var Zc,gs=class extends kt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Zc=gs;T.PrintableString=Zc;gs.NAME="PrintableString";var Xc,ys=class extends kt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Xc=ys;T.TeletexString=Xc;ys.NAME="TeletexString";var Jc,bs=class extends kt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Jc=bs;T.VideotexString=Jc;bs.NAME="VideotexString";var Qc,ws=class extends kt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Qc=ws;T.IA5String=Qc;ws.NAME="IA5String";var tl,xs=class extends kt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};tl=xs;T.GraphicString=tl;xs.NAME="GraphicString";var el,cn=class extends kt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};el=cn;T.VisibleString=el;cn.NAME="VisibleString";var rl,vs=class extends kt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};rl=vs;T.GeneralString=rl;vs.NAME="GeneralString";var nl,Es=class extends kt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};nl=Es;T.CharacterString=nl;Es.NAME="CharacterString";var sl,ln=class extends cn{constructor({value:t,valueDate:e,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,t){this.fromString(t),this.valueBlock.valueHexView=new Uint8Array(t.length);for(let s=0;s<t.length;s++)this.valueBlock.valueHexView[s]=t.charCodeAt(s)}e&&(this.fromDate(e),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(t){this.fromString(String.fromCharCode.apply(null,K.BufferSourceConverter.toUint8Array(t)))}toBuffer(){let t=this.toString(),e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return e}fromDate(t){this.year=t.getUTCFullYear(),this.month=t.getUTCMonth()+1,this.day=t.getUTCDate(),this.hour=t.getUTCHours(),this.minute=t.getUTCMinutes(),this.second=t.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(t){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(t);if(n===null){this.error="Wrong input string for conversion";return}let s=parseInt(n[1],10);s>=50?this.year=1900+s:this.year=2e3+s,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(t="iso"){if(t==="iso"){let e=new Array(7);return e[0]=Lt(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=Lt(this.month,2),e[2]=Lt(this.day,2),e[3]=Lt(this.hour,2),e[4]=Lt(this.minute,2),e[5]=Lt(this.second,2),e[6]="Z",e.join("")}return super.toString(t)}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}}};sl=ln;T.UTCTime=sl;ln.NAME="UTCTime";var il,As=class extends ln{constructor(t={}){var e;super(t),(e=this.millisecond)!==null&&e!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(t){super.fromDate(t),this.millisecond=t.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(t){let e=!1,n="",s="",i=0,o,a=0,c=0;if(t[t.length-1]==="Z")n=t.substring(0,t.length-1),e=!0;else{let l=new Number(t[t.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=t}if(e){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("+"),b="";if(h===-1&&(h=n.indexOf("-"),l=-1),h!==-1){if(b=n.substring(h+1),n=n.substring(0,h),b.length!==2&&b.length!==4)throw new Error("Wrong input string for conversion");let m=parseInt(b.substring(0,2),10);if(isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*m,b.length===4){if(m=parseInt(b.substring(2,4),10),isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");c=l*m}}}let f=n.indexOf(".");if(f===-1&&(f=n.indexOf(",")),f!==-1){let l=new Number(`0${n.substring(f)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");i=l.valueOf(),s=n.substring(0,f)}else s=n;switch(!0){case s.length===8:if(o=/(\d{4})(\d{2})(\d{2})/ig,f!==-1)throw new Error("Wrong input string for conversion");break;case s.length===10:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,f!==-1){let l=60*i;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 s.length===12:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,f!==-1){let l=60*i;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case s.length===14:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,f!==-1){let l=1e3*i;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let u=o.exec(s);if(u===null)throw new Error("Wrong input string for conversion");for(let l=1;l<u.length;l++)switch(l){case 1:this.year=parseInt(u[l],10);break;case 2:this.month=parseInt(u[l],10);break;case 3:this.day=parseInt(u[l],10);break;case 4:this.hour=parseInt(u[l],10)+a;break;case 5:this.minute=parseInt(u[l],10)+c;break;case 6:this.second=parseInt(u[l],10);break;default:throw new Error("Wrong input string for conversion")}if(e===!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(t="iso"){if(t==="iso"){let e=[];return e.push(Lt(this.year,4)),e.push(Lt(this.month,2)),e.push(Lt(this.day,2)),e.push(Lt(this.hour,2)),e.push(Lt(this.minute,2)),e.push(Lt(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(Lt(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};il=As;T.GeneralizedTime=il;As.NAME="GeneralizedTime";var ol,Bs=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};ol=Bs;T.DATE=ol;Bs.NAME="DATE";var al,Ss=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};al=Ss;T.TimeOfDay=al;Ss.NAME="TimeOfDay";var cl,Ts=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};cl=Ts;T.DateTime=cl;Ts.NAME="DateTime";var ll,Is=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};ll=Is;T.Duration=ll;Is.NAME="Duration";var ul,ks=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};ul=ks;T.TIME=ul;ks.NAME="TIME";function Fd(r){let{result:t}=Dr(r),e=t.valueBlock.value;return{n:W(ae(e[1].toBigInt()),"base64url"),e:W(ae(e[2].toBigInt()),"base64url"),d:W(ae(e[3].toBigInt()),"base64url"),p:W(ae(e[4].toBigInt()),"base64url"),q:W(ae(e[5].toBigInt()),"base64url"),dp:W(ae(e[6].toBigInt()),"base64url"),dq:W(ae(e[7].toBigInt()),"base64url"),qi:W(ae(e[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function Kd(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 L("JWK was missing components","ERR_INVALID_PARAMETERS");let e=new yt({value:[new ft({value:0}),ft.fromBigInt(ce(Q(r.n,"base64url"))),ft.fromBigInt(ce(Q(r.e,"base64url"))),ft.fromBigInt(ce(Q(r.d,"base64url"))),ft.fromBigInt(ce(Q(r.p,"base64url"))),ft.fromBigInt(ce(Q(r.q,"base64url"))),ft.fromBigInt(ce(Q(r.dp,"base64url"))),ft.fromBigInt(ce(Q(r.dq,"base64url"))),ft.fromBigInt(ce(Q(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function qd(r){let{result:t}=Dr(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:W(ae(e[0].toBigInt()),"base64url"),e:W(ae(e[1].toBigInt()),"base64url")}}function $d(r){if(r.n==null||r.e==null)throw new L("JWK was missing components","ERR_INVALID_PARAMETERS");let e=new yt({value:[new yt({value:[new Jt({value:"1.2.840.113549.1.1.1"}),new qe]}),new Cr({valueHex:new yt({value:[ft.fromBigInt(ce(Q(r.n,"base64url"))),ft.fromBigInt(ce(Q(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function ae(r){let t=r.toString(16);t.length%2>0&&(t=`0${t}`);let e=t.length/2,n=new Uint8Array(e),s=0,i=0;for(;s<e;)n[s]=parseInt(t.slice(i,i+2),16),s+=1,i+=2;return n}function ce(r){let t=[];return r.forEach(function(e){let n=e.toString(16);n.length%2>0&&(n=`0${n}`),t.push(n)}),BigInt("0x"+t.join(""))}var Gd=16,xo=32,vo=1e4;async function zd(r,t){let e=It.get(),s=new yt({value:[new ft({value:0}),new yt({value:[new Jt({value:"1.2.840.113549.1.1.1"}),new qe]}),new Ee({valueHex:r.marshal()})]}).toBER(),i=new Uint8Array(s,0,s.byteLength),o=ir(Gd),a=await mo(Tr,t,o,{c:vo,dkLen:xo}),c=ir(16),f=await e.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),u=await e.subtle.encrypt({name:"AES-CBC",iv:c},f,i),l=new yt({value:[new Ee({valueHex:o}),new ft({value:vo}),new ft({value:xo}),new yt({value:[new Jt({value:"1.2.840.113549.2.11"}),new qe]})]}),h=new yt({value:[new Jt({value:"1.2.840.113549.1.5.13"}),new yt({value:[new yt({value:[new Jt({value:"1.2.840.113549.1.5.12"}),l]}),new yt({value:[new Jt({value:"2.16.840.1.101.3.4.1.42"}),new Ee({valueHex:c})]})]})]}),m=new yt({value:[h,new Ee({valueHex:u})]}).toBER(),d=new Uint8Array(m,0,m.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...W(d,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
7
- `)}async function jd(r,t){let e=It.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let s=Q(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=Dr(s),{iv:o,salt:a,iterations:c,keySize:f,cipherText:u}=Wd(i),l=await mo(Tr,t,a,{c,dkLen:f}),h=await e.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),b=un(await e.subtle.decrypt({name:"AES-CBC",iv:o},h,u)),{result:m}=Dr(b);n=fl(m)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let s=Q(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=Dr(s);n=fl(i)}else throw new L("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return Eo(n)}function Wd(r){let t=r.valueBlock.value[0];if(t.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new L("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=t.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new L("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let i=n.valueBlock.value[1],o=un(i.valueBlock.value[0].getValue()),a=vo,c=xo;if(i.valueBlock.value.length===3)a=Number(i.valueBlock.value[1].toBigInt()),c=Number(i.valueBlock.value[2].toBigInt());else if(i.valueBlock.value.length===2)throw new L("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let f=t.valueBlock.value[1].valueBlock.value[1],u=f.valueBlock.value[0].toString();if(u!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(u!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new L("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let l=un(f.valueBlock.value[1].getValue());return{cipherText:un(r.valueBlock.value[1].getValue()),salt:o,iterations:a,keySize:c,iv:l}}function fl(r){return un(r.valueBlock.value[2].getValue())}function un(r){return new Uint8Array(r,0,r.byteLength)}async function hl(r){let t=await It.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await ml(t);return{privateKey:e[0],publicKey:e[1]}}async function Ao(r){let e=[await It.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Yd(r)],n=await ml({privateKey:e[0],publicKey:e[1]});return{privateKey:n[0],publicKey:n[1]}}async function dl(r,t){let e=await It.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await It.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function pl(r,t,e){let n=await It.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return It.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function ml(r){if(r.privateKey==null||r.publicKey==null)throw new L("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([It.get().subtle.exportKey("jwk",r.privateKey),It.get().subtle.exportKey("jwk",r.publicKey)])}async function Yd(r){return It.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 Ns(r){if(r.kty!=="RSA")throw new L("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new L("invalid key modulus","ERR_INVALID_KEY_MODULUS");return Q(r.n,"base64url").length*8}var hn=8192,fn=class{_key;constructor(t){this._key=t}verify(t,e){return pl(this._key,e,t)}marshal(){return $e.jwkToPkix(this._key)}get bytes(){return se.encode({Type:rt.RSA,Data:this.marshal()}).subarray()}equals(t){return ut(this.bytes,t.bytes)}hash(){let t=pt.digest(this.bytes);return Kt(t)?t.then(({bytes:e})=>e):t.bytes}},Or=class{_key;_publicKey;constructor(t,e){this._key=t,this._publicKey=e}genSecret(){return ir(16)}sign(t){return dl(this._key,t)}get public(){if(this._publicKey==null)throw new L("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new fn(this._publicKey)}marshal(){return $e.jwkToPkcs1(this._key)}get bytes(){return ie.encode({Type:rt.RSA,Data:this.marshal()}).subarray()}equals(t){return ut(this.bytes,t.bytes)}hash(){let t=pt.digest(this.bytes);return Kt(t)?t.then(({bytes:e})=>e):t.bytes}async id(){let t=await this.public.hash();return W(t,"base58btc")}async export(t,e="pkcs-8"){if(e==="pkcs-8")return $e.exportToPem(this,t);if(e==="libp2p-key")return Rr(this.bytes,t);throw new L(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function Eo(r){let t=$e.pkcs1ToJwk(r);if(Ns(t)>hn)throw new L("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Ao(t);return new Or(e.privateKey,e.publicKey)}function Xd(r){let t=$e.pkixToJwk(r);if(Ns(t)>hn)throw new L("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new fn(t)}async function Jd(r){if(Ns(r)>hn)throw new L("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await Ao(r);return new Or(t.privateKey,t.publicKey)}async function Qd(r){if(r>hn)throw new L("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await hl(r);return new Or(t.privateKey,t.publicKey)}var Ro={};gt(Ro,{Secp256k1PrivateKey:()=>pn,Secp256k1PublicKey:()=>dn,generateKeyPair:()=>pp,unmarshalSecp256k1PrivateKey:()=>hp,unmarshalSecp256k1PublicKey:()=>dp});var tp=(r,t,e)=>r&t^~r&e,ep=(r,t,e)=>r&t^r&e^t&e,rp=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]),Ge=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ze=new Uint32Array(64),So=class extends Sr{constructor(){super(64,32,8,!1),this.A=Ge[0]|0,this.B=Ge[1]|0,this.C=Ge[2]|0,this.D=Ge[3]|0,this.E=Ge[4]|0,this.F=Ge[5]|0,this.G=Ge[6]|0,this.H=Ge[7]|0}get(){let{A:t,B:e,C:n,D:s,E:i,F:o,G:a,H:c}=this;return[t,e,n,s,i,o,a,c]}set(t,e,n,s,i,o,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=s|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(t,e){for(let l=0;l<16;l++,e+=4)ze[l]=t.getUint32(e,!1);for(let l=16;l<64;l++){let h=ze[l-15],b=ze[l-2],m=Wt(h,7)^Wt(h,18)^h>>>3,d=Wt(b,17)^Wt(b,19)^b>>>10;ze[l]=d+ze[l-7]+m+ze[l-16]|0}let{A:n,B:s,C:i,D:o,E:a,F:c,G:f,H:u}=this;for(let l=0;l<64;l++){let h=Wt(a,6)^Wt(a,11)^Wt(a,25),b=u+h+tp(a,c,f)+rp[l]+ze[l]|0,d=(Wt(n,2)^Wt(n,13)^Wt(n,22))+ep(n,s,i)|0;u=f,f=c,c=a,a=o+b|0,o=i,i=s,s=n,n=b+d|0}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(n,s,i,o,a,c,f,u)}roundClean(){ze.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var gl=Tn(()=>new So);function np(r){let t=Zr(r);ne(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:s}=t;if(e){if(!n.eql(s,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:sp,hexToBytes:ip}=Rn,ar={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(r){let{Err:t}=ar;if(r.length<2||r[0]!==2)throw new t("Invalid signature integer tag");let e=r[1],n=r.subarray(2,e+2);if(!e||n.length!==e)throw new t("Invalid signature integer: wrong length");if(n[0]&128)throw new t("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return{d:sp(n),l:r.subarray(e+2)}},toSig(r){let{Err:t}=ar,e=typeof r=="string"?ip(r):r;if(!Yt(e))throw new Error("ui8a expected");let n=e.length;if(n<2||e[0]!=48)throw new t("Invalid signature tag");if(e[1]!==n-2)throw new t("Invalid signature: incorrect length");let{d:s,l:i}=ar._parseInt(e.subarray(2)),{d:o,l:a}=ar._parseInt(i);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:s,s:o}},hexFromSig(r){let t=f=>Number.parseInt(f[0],16)&8?"00"+f:f,e=f=>{let u=f.toString(16);return u.length&1?`0${u}`:u},n=t(e(r.s)),s=t(e(r.r)),i=n.length/2,o=s.length/2,a=e(i),c=e(o);return`30${e(o+i+4)}02${c}${s}02${a}${n}`}},Te=BigInt(0),Gt=BigInt(1),Vy=BigInt(2),yl=BigInt(3),My=BigInt(4);function op(r){let t=np(r),{Fp:e}=t,n=t.toBytes||((m,d,p)=>{let y=d.toAffine();return ge(Uint8Array.from([4]),e.toBytes(y.x),e.toBytes(y.y))}),s=t.fromBytes||(m=>{let d=m.subarray(1),p=e.fromBytes(d.subarray(0,e.BYTES)),y=e.fromBytes(d.subarray(e.BYTES,2*e.BYTES));return{x:p,y}});function i(m){let{a:d,b:p}=t,y=e.sqr(m),A=e.mul(y,m);return e.add(e.add(A,e.mul(m,d)),p)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function o(m){return typeof m=="bigint"&&Te<m&&m<t.n}function a(m){if(!o(m))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(m){let{allowedPrivateKeyLengths:d,nByteLength:p,wrapPrivateKey:y,n:A}=t;if(d&&typeof m!="bigint"){if(Yt(m)&&(m=pe(m)),typeof m!="string"||!d.includes(m.length))throw new Error("Invalid key");m=m.padStart(p*2,"0")}let w;try{w=typeof m=="bigint"?m:me(it("private key",m,p))}catch{throw new Error(`private key must be ${p} bytes, hex or bigint, not ${typeof m}`)}return y&&(w=X(w,A)),a(w),w}let f=new Map;function u(m){if(!(m instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(d,p,y){if(this.px=d,this.py=p,this.pz=y,d==null||!e.isValid(d))throw new Error("x required");if(p==null||!e.isValid(p))throw new Error("y required");if(y==null||!e.isValid(y))throw new Error("z required")}static fromAffine(d){let{x:p,y}=d||{};if(!d||!e.isValid(p)||!e.isValid(y))throw new Error("invalid affine point");if(d instanceof l)throw new Error("projective point not allowed");let A=w=>e.eql(w,e.ZERO);return A(p)&&A(y)?l.ZERO:new l(p,y,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(d){let p=e.invertBatch(d.map(y=>y.pz));return d.map((y,A)=>y.toAffine(p[A])).map(l.fromAffine)}static fromHex(d){let p=l.fromAffine(s(it("pointHex",d)));return p.assertValidity(),p}static fromPrivateKey(d){return l.BASE.multiply(c(d))}_setWindowSize(d){this._WINDOW_SIZE=d,f.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!e.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:d,y:p}=this.toAffine();if(!e.isValid(d)||!e.isValid(p))throw new Error("bad point: x or y not FE");let y=e.sqr(p),A=i(d);if(!e.eql(y,A))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:d}=this.toAffine();if(e.isOdd)return!e.isOdd(d);throw new Error("Field doesn't support isOdd")}equals(d){u(d);let{px:p,py:y,pz:A}=this,{px:w,py:_,pz:x}=d,S=e.eql(e.mul(p,x),e.mul(w,A)),R=e.eql(e.mul(y,x),e.mul(_,A));return S&&R}negate(){return new l(this.px,e.neg(this.py),this.pz)}double(){let{a:d,b:p}=t,y=e.mul(p,yl),{px:A,py:w,pz:_}=this,x=e.ZERO,S=e.ZERO,R=e.ZERO,N=e.mul(A,A),z=e.mul(w,w),$=e.mul(_,_),P=e.mul(A,w);return P=e.add(P,P),R=e.mul(A,_),R=e.add(R,R),x=e.mul(d,R),S=e.mul(y,$),S=e.add(x,S),x=e.sub(z,S),S=e.add(z,S),S=e.mul(x,S),x=e.mul(P,x),R=e.mul(y,R),$=e.mul(d,$),P=e.sub(N,$),P=e.mul(d,P),P=e.add(P,R),R=e.add(N,N),N=e.add(R,N),N=e.add(N,$),N=e.mul(N,P),S=e.add(S,N),$=e.mul(w,_),$=e.add($,$),N=e.mul($,P),x=e.sub(x,N),R=e.mul($,z),R=e.add(R,R),R=e.add(R,R),new l(x,S,R)}add(d){u(d);let{px:p,py:y,pz:A}=this,{px:w,py:_,pz:x}=d,S=e.ZERO,R=e.ZERO,N=e.ZERO,z=t.a,$=e.mul(t.b,yl),P=e.mul(p,w),ct=e.mul(y,_),ot=e.mul(A,x),Ft=e.add(p,y),v=e.add(w,_);Ft=e.mul(Ft,v),v=e.add(P,ct),Ft=e.sub(Ft,v),v=e.add(p,A);let k=e.add(w,x);return v=e.mul(v,k),k=e.add(P,ot),v=e.sub(v,k),k=e.add(y,A),S=e.add(_,x),k=e.mul(k,S),S=e.add(ct,ot),k=e.sub(k,S),N=e.mul(z,v),S=e.mul($,ot),N=e.add(S,N),S=e.sub(ct,N),N=e.add(ct,N),R=e.mul(S,N),ct=e.add(P,P),ct=e.add(ct,P),ot=e.mul(z,ot),v=e.mul($,v),ct=e.add(ct,ot),ot=e.sub(P,ot),ot=e.mul(z,ot),v=e.add(v,ot),P=e.mul(ct,v),R=e.add(R,P),P=e.mul(k,v),S=e.mul(Ft,S),S=e.sub(S,P),P=e.mul(Ft,ct),N=e.mul(k,N),N=e.add(N,P),new l(S,R,N)}subtract(d){return this.add(d.negate())}is0(){return this.equals(l.ZERO)}wNAF(d){return b.wNAFCached(this,f,d,p=>{let y=e.invertBatch(p.map(A=>A.pz));return p.map((A,w)=>A.toAffine(y[w])).map(l.fromAffine)})}multiplyUnsafe(d){let p=l.ZERO;if(d===Te)return p;if(a(d),d===Gt)return this;let{endo:y}=t;if(!y)return b.unsafeLadder(this,d);let{k1neg:A,k1:w,k2neg:_,k2:x}=y.splitScalar(d),S=p,R=p,N=this;for(;w>Te||x>Te;)w&Gt&&(S=S.add(N)),x&Gt&&(R=R.add(N)),N=N.double(),w>>=Gt,x>>=Gt;return A&&(S=S.negate()),_&&(R=R.negate()),R=new l(e.mul(R.px,y.beta),R.py,R.pz),S.add(R)}multiply(d){a(d);let p=d,y,A,{endo:w}=t;if(w){let{k1neg:_,k1:x,k2neg:S,k2:R}=w.splitScalar(p),{p:N,f:z}=this.wNAF(x),{p:$,f:P}=this.wNAF(R);N=b.constTimeNegate(_,N),$=b.constTimeNegate(S,$),$=new l(e.mul($.px,w.beta),$.py,$.pz),y=N.add($),A=z.add(P)}else{let{p:_,f:x}=this.wNAF(p);y=_,A=x}return l.normalizeZ([y,A])[0]}multiplyAndAddUnsafe(d,p,y){let A=l.BASE,w=(x,S)=>S===Te||S===Gt||!x.equals(A)?x.multiplyUnsafe(S):x.multiply(S),_=w(this,p).add(w(d,y));return _.is0()?void 0:_}toAffine(d){let{px:p,py:y,pz:A}=this,w=this.is0();d==null&&(d=w?e.ONE:e.inv(A));let _=e.mul(p,d),x=e.mul(y,d),S=e.mul(A,d);if(w)return{x:e.ZERO,y:e.ZERO};if(!e.eql(S,e.ONE))throw new Error("invZ was invalid");return{x:_,y:x}}isTorsionFree(){let{h:d,isTorsionFree:p}=t;if(d===Gt)return!0;if(p)return p(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:d,clearCofactor:p}=t;return d===Gt?this:p?p(l,this):this.multiplyUnsafe(t.h)}toRawBytes(d=!0){return this.assertValidity(),n(l,this,d)}toHex(d=!0){return pe(this.toRawBytes(d))}}l.BASE=new l(t.Gx,t.Gy,e.ONE),l.ZERO=new l(e.ZERO,e.ONE,e.ZERO);let h=t.nBitLength,b=Ln(l,t.endo?Math.ceil(h/2):h);return{CURVE:t,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:o}}function ap(r){let t=Zr(r);return ne(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function bl(r){let t=ap(r),{Fp:e,n}=t,s=e.BYTES+1,i=2*e.BYTES+1;function o(v){return Te<v&&v<e.ORDER}function a(v){return X(v,n)}function c(v){return Nn(v,n)}let{ProjectivePoint:f,normPrivateKeyToScalar:u,weierstrassEquation:l,isWithinCurveOrder:h}=op({...t,toBytes(v,k,V){let E=k.toAffine(),g=e.toBytes(E.x),I=ge;return V?I(Uint8Array.from([k.hasEvenY()?2:3]),g):I(Uint8Array.from([4]),g,e.toBytes(E.y))},fromBytes(v){let k=v.length,V=v[0],E=v.subarray(1);if(k===s&&(V===2||V===3)){let g=me(E);if(!o(g))throw new Error("Point is not on curve");let I=l(g),C=e.sqrt(I),D=(C&Gt)===Gt;return(V&1)===1!==D&&(C=e.neg(C)),{x:g,y:C}}else if(k===i&&V===4){let g=e.fromBytes(E.subarray(0,e.BYTES)),I=e.fromBytes(E.subarray(e.BYTES,2*e.BYTES));return{x:g,y:I}}else throw new Error(`Point of length ${k} was invalid. Expected ${s} compressed bytes or ${i} uncompressed bytes`)}}),b=v=>pe(Me(v,t.nByteLength));function m(v){let k=n>>Gt;return v>k}function d(v){return m(v)?a(-v):v}let p=(v,k,V)=>me(v.slice(k,V));class y{constructor(k,V,E){this.r=k,this.s=V,this.recovery=E,this.assertValidity()}static fromCompact(k){let V=t.nByteLength;return k=it("compactSignature",k,V*2),new y(p(k,0,V),p(k,V,2*V))}static fromDER(k){let{r:V,s:E}=ar.toSig(it("DER",k));return new y(V,E)}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(k){return new y(this.r,this.s,k)}recoverPublicKey(k){let{r:V,s:E,recovery:g}=this,I=R(it("msgHash",k));if(g==null||![0,1,2,3].includes(g))throw new Error("recovery id invalid");let C=g===2||g===3?V+t.n:V;if(C>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let D=g&1?"03":"02",M=f.fromHex(D+b(C)),F=c(C),Y=a(-I*F),q=a(E*F),G=f.BASE.multiplyAndAddUnsafe(M,Y,q);if(!G)throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return Je(this.toDERHex())}toDERHex(){return ar.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Je(this.toCompactHex())}toCompactHex(){return b(this.r)+b(this.s)}}let A={isValidPrivateKey(v){try{return u(v),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let v=qi(t.n);return sc(t.randomBytes(v),t.n)},precompute(v=8,k=f.BASE){return k._setWindowSize(v),k.multiply(BigInt(3)),k}};function w(v,k=!0){return f.fromPrivateKey(v).toRawBytes(k)}function _(v){let k=Yt(v),V=typeof v=="string",E=(k||V)&&v.length;return k?E===s||E===i:V?E===2*s||E===2*i:v instanceof f}function x(v,k,V=!0){if(_(v))throw new Error("first arg must be private key");if(!_(k))throw new Error("second arg must be public key");return f.fromHex(k).multiply(u(v)).toRawBytes(V)}let S=t.bits2int||function(v){let k=me(v),V=v.length*8-t.nBitLength;return V>0?k>>BigInt(V):k},R=t.bits2int_modN||function(v){return a(S(v))},N=Yr(t.nBitLength);function z(v){if(typeof v!="bigint")throw new Error("bigint expected");if(!(Te<=v&&v<N))throw new Error(`bigint expected < 2^${t.nBitLength}`);return Me(v,t.nByteLength)}function $(v,k,V=P){if(["recovered","canonical"].some(nt=>nt in V))throw new Error("sign() legacy options not supported");let{hash:E,randomBytes:g}=t,{lowS:I,prehash:C,extraEntropy:D}=V;I==null&&(I=!0),v=it("msgHash",v),C&&(v=it("prehashed msgHash",E(v)));let M=R(v),F=u(k),Y=[z(F),z(M)];if(D!=null){let nt=D===!0?g(e.BYTES):D;Y.push(it("extraEntropy",nt))}let q=ge(...Y),G=M;function lt(nt){let bt=S(nt);if(!h(bt))return;let wt=c(bt),ht=f.BASE.multiply(bt).toAffine(),vt=a(ht.x);if(vt===Te)return;let le=a(wt*a(G+vt*F));if(le===Te)return;let Ye=(ht.x===vt?0:2)|Number(ht.y&Gt),qr=le;return I&&m(le)&&(qr=d(le),Ye^=1),new y(vt,qr,Ye)}return{seed:q,k2sig:lt}}let P={lowS:t.lowS,prehash:!1},ct={lowS:t.lowS,prehash:!1};function ot(v,k,V=P){let{seed:E,k2sig:g}=$(v,k,V),I=t;return Mi(I.hash.outputLen,I.nByteLength,I.hmac)(E,g)}f.BASE._setWindowSize(8);function Ft(v,k,V,E=ct){let g=v;if(k=it("msgHash",k),V=it("publicKey",V),"strict"in E)throw new Error("options.strict was renamed to lowS");let{lowS:I,prehash:C}=E,D,M;try{if(typeof g=="string"||Yt(g))try{D=y.fromDER(g)}catch(ht){if(!(ht instanceof ar.Err))throw ht;D=y.fromCompact(g)}else if(typeof g=="object"&&typeof g.r=="bigint"&&typeof g.s=="bigint"){let{r:ht,s:vt}=g;D=new y(ht,vt)}else throw new Error("PARSE");M=f.fromHex(V)}catch(ht){if(ht.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(I&&D.hasHighS())return!1;C&&(k=t.hash(k));let{r:F,s:Y}=D,q=R(k),G=c(Y),lt=a(q*G),nt=a(F*G),bt=f.BASE.multiplyAndAddUnsafe(M,lt,nt)?.toAffine();return bt?a(bt.x)===F:!1}return{CURVE:t,getPublicKey:w,getSharedSecret:x,sign:ot,verify:Ft,ProjectivePoint:f,Signature:y,utils:A}}function cp(r){return{hash:r,hmac:(t,...e)=>tn(r,t,Sn(...e)),randomBytes:Br}}function wl(r,t){let e=n=>bl({...r,...cp(n)});return Object.freeze({...e(t),create:e})}var El=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),xl=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),lp=BigInt(1),To=BigInt(2),vl=(r,t)=>(r+t/To)/t;function up(r){let t=El,e=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),f=r*r*r%t,u=f*f*r%t,l=et(u,e,t)*u%t,h=et(l,e,t)*u%t,b=et(h,To,t)*f%t,m=et(b,s,t)*b%t,d=et(m,i,t)*m%t,p=et(d,a,t)*d%t,y=et(p,c,t)*p%t,A=et(y,a,t)*d%t,w=et(A,e,t)*u%t,_=et(w,o,t)*m%t,x=et(_,n,t)*f%t,S=et(x,To,t);if(!Io.eql(Io.sqr(S),r))throw new Error("Cannot find square root");return S}var Io=_n(El,void 0,void 0,{sqrt:up}),te=wl({a:BigInt(0),b:BigInt(7),Fp:Io,n:xl,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=xl,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-lp*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=e,o=BigInt("0x100000000000000000000000000000000"),a=vl(i*r,t),c=vl(-n*r,t),f=X(r-a*e-c*s,t),u=X(-a*n-c*i,t),l=f>o,h=u>o;if(l&&(f=t-f),h&&(u=t-u),f>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:f,k2neg:h,k2:u}}}},gl),Wy=BigInt(0);var Yy=te.ProjectivePoint;function Al(){return te.utils.randomPrivateKey()}function Bl(r,t){let e=pt.digest(t instanceof Uint8Array?t:t.subarray());if(Kt(e))return e.then(({digest:n})=>te.sign(n,r).toDERRawBytes()).catch(n=>{throw new L(String(n),"ERR_INVALID_INPUT")});try{return te.sign(e.digest,r).toDERRawBytes()}catch(n){throw new L(String(n),"ERR_INVALID_INPUT")}}function Sl(r,t,e){let n=pt.digest(e instanceof Uint8Array?e:e.subarray());if(Kt(n))return n.then(({digest:s})=>te.verify(t,s,r)).catch(s=>{throw new L(String(s),"ERR_INVALID_INPUT")});try{return te.verify(t,n.digest,r)}catch(s){throw new L(String(s),"ERR_INVALID_INPUT")}}function Tl(r){return te.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Il(r){try{te.getPublicKey(r,!0)}catch(t){throw new L(String(t),"ERR_INVALID_PRIVATE_KEY")}}function ko(r){try{te.ProjectivePoint.fromHex(r)}catch(t){throw new L(String(t),"ERR_INVALID_PUBLIC_KEY")}}function kl(r){try{return te.getPublicKey(r,!0)}catch(t){throw new L(String(t),"ERR_INVALID_PRIVATE_KEY")}}var dn=class{_key;constructor(t){ko(t),this._key=t}verify(t,e){return Sl(this._key,e,t)}marshal(){return Tl(this._key)}get bytes(){return se.encode({Type:rt.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return ut(this.bytes,t.bytes)}async hash(){let t=pt.digest(this.bytes),e;return Kt(t)?{bytes:e}=await t:e=t.bytes,e}},pn=class{_key;_publicKey;constructor(t,e){this._key=t,this._publicKey=e??kl(t),Il(this._key),ko(this._publicKey)}sign(t){return Bl(this._key,t)}get public(){return new dn(this._publicKey)}marshal(){return this._key}get bytes(){return ie.encode({Type:rt.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return ut(this.bytes,t.bytes)}hash(){let t=pt.digest(this.bytes);return Kt(t)?t.then(({bytes:e})=>e):t.bytes}async id(){let t=await this.public.hash();return W(t,"base58btc")}async export(t,e="libp2p-key"){if(e==="libp2p-key")return Rr(this.bytes,t);throw new L(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function hp(r){return new pn(r)}function dp(r){return new dn(r)}async function pp(){let r=Al();return new pn(r)}var cr={rsa:Bo,ed25519:po,secp256k1:Ro};function Rl(r){let t=Object.keys(cr).join(" / ");return new L(`invalid or unsupported key type ${r}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function Nl(r){let t=se.decode(r),e=t.Data??new Uint8Array;switch(t.Type){case rt.RSA:return cr.rsa.unmarshalRsaPublicKey(e);case rt.Ed25519:return cr.ed25519.unmarshalEd25519PublicKey(e);case rt.Secp256k1:return cr.secp256k1.unmarshalSecp256k1PublicKey(e);default:throw Rl(t.Type??"unknown")}}async function _l(r){let t=ie.decode(r),e=t.Data??new Uint8Array;switch(t.Type){case rt.RSA:return cr.rsa.unmarshalRsaPrivateKey(e);case rt.Ed25519:return cr.ed25519.unmarshalEd25519PrivateKey(e);case rt.Secp256k1:return cr.secp256k1.unmarshalSecp256k1PrivateKey(e);default:throw Rl(t.Type??"RSA")}}var Cl=Symbol.for("@achingbrain/uint8arraylist");function Ll(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let s=e+n.byteLength;if(t<s)return{buf:n,index:t-e};e=s}throw new RangeError("index is out of bounds")}function _s(r){return!!r?.[Cl]}var ee=class r{bufs;length;[Cl]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(_s(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(_s(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Ll(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Ll(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(_s(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:s}=this._subList(t,e);return Tt(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:Tt(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),i=new r;return i.length=s,i.bufs=[...n],i}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],a=s,c=a+o.byteLength;if(s=c,t>=c)continue;let f=t>=a&&t<c,u=e>a&&e<=c;if(f&&u){if(t===a&&e===c){n.push(o);break}let l=t-a;n.push(o.subarray(l,l+(e-t)));break}if(f){if(t===0){n.push(o);continue}n.push(o.subarray(t-a));continue}if(u){if(e===c){n.push(o);break}n.push(o.subarray(0,e-a));break}n.push(o)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!_s(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let l=0;l<i;l++)o[l]=-1;for(let l=0;l<s;l++)o[n[l]]=l;let a=o,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let l=e;l<=c;l+=u){u=0;for(let h=f;h>=0;h--){let b=this.get(l+h);if(n[h]!==b){u=Math.max(1,h-a[b]);break}}if(u===0)return l}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=_t(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let s=he(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,e,n),this.write(s,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let s=he(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,e,n),this.write(s,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let s=he(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,e,n),this.write(s,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=_t(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let s=he(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,e,n),this.write(s,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let s=he(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e,n),this.write(s,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let s=he(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,e,n),this.write(s,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let s=he(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,e,n),this.write(s,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let s=he(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,e,n),this.write(s,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!ut(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((s,i)=>s+i.byteLength,0)),n.length=e,n}};var Ul={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var mn;(function(r){let t;r.codec=()=>(t==null&&(t=Vt((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&e.payload.byteLength>0&&(n.uint32(26),n.bytes(e.payload)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:s.publicKey=e.bytes();break;case 2:s.payloadType=e.bytes();break;case 3:s.payload=e.bytes();break;case 5:s.signature=e.bytes();break;default:e.skipType(o&7);break}}return s})),t),r.encode=e=>Pt(e,r.codec()),r.decode=e=>Ot(e,r.codec())})(mn||(mn={}));var gn=class r{static createFromProtobuf=async t=>{let e=mn.decode(t),n=await Fa(e.publicKey);return new r({peerId:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e)=>{if(e.privateKey==null)throw new Error("Missing private key");let n=t.domain,s=t.codec,i=t.marshal(),o=Dl(n,s,i),c=await(await _l(e.privateKey)).sign(o.subarray());return new r({peerId:e,payloadType:s,payload:i,signature:c})};static openAndCertify=async(t,e)=>{let n=await r.createFromProtobuf(t);if(!await n.validate(e))throw new L("envelope signature is not valid for the given domain",Ul.ERR_SIGNATURE_NOT_VALID);return n};peerId;payloadType;payload;signature;marshaled;constructor(t){let{peerId:e,payloadType:n,payload:s,signature:i}=t;this.peerId=e,this.payloadType=n,this.payload=s,this.signature=i}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=mn.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return ut(this.marshal(),t.marshal())}async validate(t){let e=Dl(t,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return Nl(this.peerId.publicKey).verify(e.subarray(),this.signature)}},Dl=(r,t,e)=>{let n=Q(r),s=qt(n.byteLength),i=qt(t.length),o=qt(e.length);return new ee(s,n,i,t,o,e)};var Ls=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,s){return this.readAtomically(()=>{let i=0,o=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let h=Number.parseInt(l,t);if(!Number.isNaN(h))return h});if(u===void 0)break;if(i*=t,i+=u,i>f||(o+=1,e!==void 0&&o>e))return}if(o!==0)return!n&&c&&o>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let s=n*2;if(n<e.length-3){let o=this.readSeparator(":",n,()=>this.readIPv4Addr());if(o!==void 0)return e[s]=o[0],e[s+1]=o[1],e[s+2]=o[2],e[s+3]=o[3],[s+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[s,!1];e[s]=i>>8,e[s+1]=i&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,s]=t(e);if(n===16)return e;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),o=16-(n+2),[a]=t(i.subarray(0,o));return e.set(i.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Ol=45,mp=15,Pr=new Ls;function No(r){if(!(r.length>mp))return Pr.new(r).parseWith(()=>Pr.readIPv4Addr())}function _o(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ol))return Pr.new(r).parseWith(()=>Pr.readIPv6Addr())}function Cs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ol))return Pr.new(r).parseWith(()=>Pr.readIPAddr())}var Ub=parseInt("0xFFFF",16),Db=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Ml(r){return!!No(r)}function Hl(r){return!!_o(r)}function Us(r){return!!Cs(r)}var Fl=Ml,xp=Hl,Lo=function(r){let t=0;if(r=r.toString().trim(),Fl(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(xp(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=Fl(e[n]),o;i&&(o=Lo(e[n]),e[n]=W(o.slice(0,2),"base16")),o!=null&&++n<8&&e.splice(n,0,W(o.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let i=[n,1];for(n=9-e.length;n>0;n--)i.push("0");e.splice.apply(e,i)}let s=new Uint8Array(t+16);for(n=0;n<e.length;n++){let i=parseInt(e[n],16);s[t++]=i>>8&255,s[t++]=i&255}return s}throw new Error("invalid ip address")},Kl=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let s=[];for(let i=0;i<e;i++)s.push(r[t+i]);return s.join(".")}if(e===16){let s=[];for(let i=0;i<e;i+=2)s.push(n.getUint16(t+i).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Vr={},Co={},Ep=[[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"]];Ep.forEach(r=>{let t=Ap(...r);Co[t.code]=t,Vr[t.name]=t});function Ap(r,t,e,n,s){return{code:r,size:t,name:e,resolvable:!!n,path:!!s}}function J(r){if(typeof r=="number"){if(Co[r]!=null)return Co[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Vr[r]!=null)return Vr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var bw=J("ip4"),ww=J("ip6"),xw=J("ipcidr");function Do(r,t){switch(J(r).code){case 4:case 41:return Sp(t);case 42:return Gl(t);case 6:case 273:case 33:case 132:return jl(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Gl(t);case 421:return Rp(t);case 444:return zl(t);case 445:return zl(t);case 466:return kp(t);default:return W(t,"base16")}}function Oo(r,t){switch(J(r).code){case 4:return ql(t);case 41:return ql(t);case 42:return $l(t);case 6:case 273:case 33:case 132:return Po(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return $l(t);case 421:return Tp(t);case 444:return Np(t);case 445:return _p(t);case 466:return Ip(t);default:return Q(t,"base16")}}var Uo=Object.values(Le).map(r=>r.decoder),Bp=function(){let r=Uo[0].or(Uo[1]);return Uo.slice(2).forEach(t=>r=r.or(t)),r}();function ql(r){if(!Us(r))throw new Error("invalid ip address");return Lo(r)}function Sp(r){let t=Kl(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!Us(t))throw new Error("invalid ip address");return t}function Po(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function jl(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function $l(r){let t=Q(r),e=Uint8Array.from(qt(t.length));return Tt([e,t],e.length+t.length)}function Gl(r){let t=we(r);if(r=r.slice(At(t)),r.length!==t)throw new Error("inconsistent lengths");return W(r)}function Tp(r){let t;r[0]==="Q"||r[0]==="1"?t=Ze(dt.decode(`z${r}`)).bytes:t=Ct.parse(r).multihash.bytes;let e=Uint8Array.from(qt(t.length));return Tt([e,t],e.length+t.length)}function Ip(r){let t=Bp.decode(r),e=Uint8Array.from(qt(t.length));return Tt([e,t],e.length+t.length)}function kp(r){let t=we(r),e=r.slice(At(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+W(e,"base64url")}function Rp(r){let t=we(r),e=r.slice(At(t));if(e.length!==t)throw new Error("inconsistent lengths");return W(e,"base58btc")}function Np(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=fe.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Po(n);return Tt([e,s],e.length+s.length)}function _p(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=fe.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Po(n);return Tt([e,s],e.length+s.length)}function zl(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=W(t,"base32"),s=jl(e);return`${n}:${s}`}function Wl(r){r=Vo(r);let t=[],e=[],n=null,s=r.split("/").slice(1);if(s.length===1&&s[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i<s.length;i++){let o=s[i],a=J(o);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(i++,i>=s.length)throw Zl("invalid address: "+r);if(a.path===!0){n=Vo(s.slice(i).join("/")),t.push([a.code,Oo(a.code,n)]),e.push([a.code,n]);break}let c=Oo(a.code,s[i]);t.push([a.code,c]),e.push([a.code,Do(a.code,c)])}return{string:Yl(e),bytes:Ho(t),tuples:t,stringTuples:e,path:n}}function Mo(r){let t=[],e=[],n=null,s=0;for(;s<r.length;){let i=we(r,s),o=At(i),a=J(i),c=Lp(a,r.slice(s+o));if(c===0){t.push([i]),e.push([i]),s+=o;continue}let f=r.slice(s+o,s+o+c);if(s+=c+o,s>r.length)throw Zl("Invalid address Uint8Array: "+W(r,"base16"));t.push([i,f]);let u=Do(i,f);if(e.push([i,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:Yl(e),tuples:t,stringTuples:e,path:n}}function Yl(r){let t=[];return r.map(e=>{let n=J(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Vo(t.join("/"))}function Ho(r){return Tt(r.map(t=>{let e=J(t[0]),n=Uint8Array.from(qt(e.code));return t.length>1&&t[1]!=null&&(n=Tt([n,t[1]])),n}))}function Lp(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=we(t instanceof Uint8Array?t:Uint8Array.from(t));return e+At(e)}}function Vo(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function Zl(r){return new Error("Error parsing address: "+r)}var Cp=Symbol.for("nodejs.util.inspect.custom"),Fo=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Up=[J("dns").code,J("dns4").code,J("dns6").code,J("dnsaddr").code],Ds=class r{bytes;#t;#e;#r;#n;[Fo]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Mo(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Wl(t)}else if(Jl(t))e=Mo(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,s,i="",o=J("tcp"),a=J("udp"),c=J("ip4"),f=J("ip6"),u=J("dns6"),l=J("ip6zone");for(let[b,m]of this.stringTuples())b===l.code&&(i=`%${m??""}`),Up.includes(b)&&(e=o.name,s=443,n=`${m??""}${i}`,t=b===u.code?6:4),(b===o.code||b===a.code)&&(e=J(b).name,s=parseInt(m??"")),(b===c.code||b===f.code)&&(e=J(b).name,n=`${m??""}${i}`,t=b===f.code?6:4);if(t==null||e==null||n==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:s}}protos(){return this.#e.map(([t])=>Object.assign({},J(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>J(t).name)}tuples(){return this.#e}stringTuples(){return this.#r}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),s=n.lastIndexOf(e);if(s<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,s))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(Ho(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,s])=>{n===Vr.p2p.code&&t.push([n,s]),n===Vr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?W(dt.decode(`z${n}`),"base58btc"):W(Ct.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return ut(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(i=>i.resolvable);if(e==null)return[this];let n=Xl.get(e.name);if(n==null)throw new L(`no available resolver for ${e.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,t)).map(i=>new r(i))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[Cp](){return`Multiaddr(${this.#t})`}};var Xl=new Map;function Jl(r){return!!r?.[Fo]}function Rt(r){return new Ds(r)}function Mt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Os=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function Ps(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new Os(e?.errorMessage,e?.errorCode));let n,s=new Os(e?.errorMessage,e?.errorCode);try{return await Promise.race([r,new Promise((i,o)=>{n=()=>{o(s)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var Ko=class{needNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.needNext=Mt(),this.haveNext=Mt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("Have next but next was undefined");let t=this.nextResult;return this.nextResult=void 0,this.needNext.resolve(),this.needNext=Mt(),t}async throw(t){return this.ended=!0,t!=null&&this.haveNext.reject(t),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return await this._push(void 0),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");this.nextResult!=null&&await this.needNext.promise,t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Mt(),await Ps(this.needNext.promise,e?.signal,e)}};function Ql(){return new Ko}var Vs=class extends Error{code;constructor(t,e){super(t),this.code=e}},qo=class extends Vs{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted"}};function tu(r,t){let e=Ql();r.sink(e).catch(async o=>{await e.end(o)}),r.sink=async o=>{for await(let a of o)await e.push(a);await e.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 s=new ee;return{read:async(o,a)=>{a?.signal?.throwIfAborted();let c,f=new Promise((u,l)=>{c=()=>{l(new qo("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(o==null){let{done:l,value:h}=await Promise.race([n.next(),f]);return l===!0?new ee:h}for(;s.byteLength<o;){let{value:l,done:h}=await Promise.race([n.next(),f]);if(h===!0)throw new Vs("unexpected end of input","ERR_UNEXPECTED_EOF");s.append(l)}let u=s.sublist(0,o);return s.consume(o),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(o,a)=>{a?.signal?.throwIfAborted(),o instanceof Uint8Array?await e.push(o,a):await e.push(o.subarray(),a)},unwrap:()=>{if(s.byteLength>0){let o=r.source;r.source=async function*(){t?.yieldBytes===!1?yield s:yield*s,yield*o}()}return r}}}var Ms=class extends Error{code;constructor(t,e){super(t),this.code=e}};function eu(r,t={}){let e=tu(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=At(t.maxDataLength));let n=t?.lengthDecoder??we,s=t?.lengthEncoder??qt;return{read:async o=>{let a=-1,c=new ee;for(;;){c.append(await e.read(1,o));try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ms("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Ms("message length too long","ERR_MSG_DATA_TOO_LONG");return e.read(a,o)},write:async(o,a)=>{await e.write(new ee(s(o.byteLength),o),a)},writeV:async(o,a)=>{let c=new ee(...o.flatMap(f=>[s(f.byteLength),f]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function je(r,t){let e=eu(r,t),n={read:async(s,i)=>{let o=await e.read(i);return s.decode(o)},write:async(s,i,o)=>{await e.write(i.encode(s),o)},writeV:async(s,i,o)=>{await e.writeV(s.map(a=>i.encode(a)),o)},pb:s=>({read:async i=>n.read(s,i),write:async(i,o)=>n.write(i,s,o),writeV:async(i,o)=>n.writeV(i,s,o),unwrap:()=>n}),unwrap:()=>e.unwrap()};return n}var Hs="/libp2p/relay";var ru="circuit-relay-source",nu="circuit-relay-relay";var su=BigInt(131072),zt="/libp2p/circuit/relay/0.2.0/hop",lr="/libp2p/circuit/relay/0.2.0/stop",iu=30*1e3,ou=30*1e3,yn=300,au="ERR_NO_ROUTERS_AVAILABLE",$o="ERR_RELAYED_DIAL",cu="ERR_HOP_REQUEST_FAILED",Fs="ERR_TRANSFER_LIMIT_EXCEEDED";var Z;(function(r){let t;(function(s){s.RESERVE="RESERVE",s.CONNECT="CONNECT",s.STATUS="STATUS"})(t=r.Type||(r.Type={}));let e;(function(s){s[s.RESERVE=0]="RESERVE",s[s.CONNECT=1]="CONNECT",s[s.STATUS=2]="STATUS"})(e||(e={})),function(s){s.codec=()=>nr(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Vt((s,i,o={})=>{o.lengthDelimited!==!1&&i.fork(),s.type!=null&&(i.uint32(8),r.Type.codec().encode(s.type,i)),s.peer!=null&&(i.uint32(18),Mr.codec().encode(s.peer,i)),s.reservation!=null&&(i.uint32(26),Ks.codec().encode(s.reservation,i)),s.limit!=null&&(i.uint32(34),Hr.codec().encode(s.limit,i)),s.status!=null&&(i.uint32(40),H.codec().encode(s.status,i)),o.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let o={},a=i==null?s.len:s.pos+i;for(;s.pos<a;){let c=s.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(s);break;case 2:o.peer=Mr.codec().decode(s,s.uint32());break;case 3:o.reservation=Ks.codec().decode(s,s.uint32());break;case 4:o.limit=Hr.codec().decode(s,s.uint32());break;case 5:o.status=H.codec().decode(s);break;default:s.skipType(c&7);break}}return o})),n),r.encode=s=>Pt(s,r.codec()),r.decode=s=>Ot(s,r.codec())})(Z||(Z={}));var Ht;(function(r){let t;(function(s){s.CONNECT="CONNECT",s.STATUS="STATUS"})(t=r.Type||(r.Type={}));let e;(function(s){s[s.CONNECT=0]="CONNECT",s[s.STATUS=1]="STATUS"})(e||(e={})),function(s){s.codec=()=>nr(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Vt((s,i,o={})=>{o.lengthDelimited!==!1&&i.fork(),s.type!=null&&(i.uint32(8),r.Type.codec().encode(s.type,i)),s.peer!=null&&(i.uint32(18),Mr.codec().encode(s.peer,i)),s.limit!=null&&(i.uint32(26),Hr.codec().encode(s.limit,i)),s.status!=null&&(i.uint32(32),H.codec().encode(s.status,i)),o.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let o={},a=i==null?s.len:s.pos+i;for(;s.pos<a;){let c=s.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(s);break;case 2:o.peer=Mr.codec().decode(s,s.uint32());break;case 3:o.limit=Hr.codec().decode(s,s.uint32());break;case 4:o.status=H.codec().decode(s);break;default:s.skipType(c&7);break}}return o})),n),r.encode=s=>Pt(s,r.codec()),r.decode=s=>Ot(s,r.codec())})(Ht||(Ht={}));var Mr;(function(r){let t;r.codec=()=>(t==null&&(t=Vt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.id!=null&&e.id.byteLength>0&&(n.uint32(10),n.bytes(e.id)),e.addrs!=null)for(let i of e.addrs)n.uint32(18),n.bytes(i);s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={id:new Uint8Array(0),addrs:[]},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:s.id=e.bytes();break;case 2:s.addrs.push(e.bytes());break;default:e.skipType(o&7);break}}return s})),t),r.encode=e=>Pt(e,r.codec()),r.decode=e=>Ot(e,r.codec())})(Mr||(Mr={}));var Ks;(function(r){let t;r.codec=()=>(t==null&&(t=Vt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.expire!=null&&e.expire!==0n&&(n.uint32(8),n.uint64(e.expire)),e.addrs!=null)for(let i of e.addrs)n.uint32(18),n.bytes(i);e.voucher!=null&&(n.uint32(26),n.bytes(e.voucher)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={expire:0n,addrs:[]},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:s.expire=e.uint64();break;case 2:s.addrs.push(e.bytes());break;case 3:s.voucher=e.bytes();break;default:e.skipType(o&7);break}}return s})),t),r.encode=e=>Pt(e,r.codec()),r.decode=e=>Ot(e,r.codec())})(Ks||(Ks={}));var Hr;(function(r){let t;r.codec=()=>(t==null&&(t=Vt((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.duration!=null&&(n.uint32(8),n.uint32(e.duration)),e.data!=null&&(n.uint32(16),n.uint64(e.data)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:s.duration=e.uint32();break;case 2:s.data=e.uint64();break;default:e.skipType(o&7);break}}return s})),t),r.encode=e=>Pt(e,r.codec()),r.decode=e=>Ot(e,r.codec())})(Hr||(Hr={}));var H;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(H||(H={}));var Go;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(Go||(Go={}));(function(r){r.codec=()=>nr(Go)})(H||(H={}));var qs;(function(r){let t;r.codec=()=>(t==null&&(t=Vt((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.relay!=null&&e.relay.byteLength>0&&(n.uint32(10),n.bytes(e.relay)),e.peer!=null&&e.peer.byteLength>0&&(n.uint32(18),n.bytes(e.peer)),e.expiration!=null&&e.expiration!==0n&&(n.uint32(24),n.uint64(e.expiration)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={relay:new Uint8Array(0),peer:new Uint8Array(0),expiration:0n},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:s.relay=e.bytes();break;case 2:s.peer=e.bytes();break;case 3:s.expiration=e.uint64();break;default:e.skipType(o&7);break}}return s})),t),r.encode=e=>Pt(e,r.codec()),r.decode=e=>Ot(e,r.codec())})(qs||(qs={}));function lu(r){let t=new globalThis.AbortController;function e(){t.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let i of r){if(i?.aborted===!0){e();break}i?.addEventListener!=null&&i.addEventListener("abort",e)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}async function*uu(r,t,e){let n=t.remaining;for await(let s of r){let i=BigInt(s.byteLength);if(t.remaining-i<0){let o=Number(t.remaining);t.remaining=0n;try{o!==0&&(yield s.subarray(0,o))}catch(a){e.log.error(a)}throw new L(`data limit of ${n} bytes exceeded`,Fs)}t.remaining-=i,yield s}}function fu(r,t,e,n,s){function i(l){r.abort(l),t.abort(l)}let o=[e];n?.duration!=null&&o.push(AbortSignal.timeout(n.duration));let a=lu(o),c=!1,f=!1,u;n?.data!=null&&(u={remaining:n.data}),queueMicrotask(()=>{let l=()=>{t.abort(new L(`duration limit of ${n?.duration} ms exceeded`,Fs))};a.addEventListener("abort",l,{once:!0}),t.sink(u==null?r.source:uu(r.source,u,s)).catch(h=>{s.log.error("error while relaying streams src -> dst",h),i(h)}).finally(()=>{c=!0,f&&(a.removeEventListener("abort",l),a.clear())})}),queueMicrotask(()=>{let l=()=>{r.abort(new L(`duration limit of ${n?.duration} ms exceeded`,Fs))};a.addEventListener("abort",l,{once:!0}),r.sink(u==null?t.source:uu(t.source,u,s)).catch(h=>{s.log.error("error while relaying streams dst -> src",h),i(h)}).finally(()=>{f=!0,c&&(a.removeEventListener("abort",l),a.clear())})})}async function $s(r){let t=new TextEncoder().encode(r),e=await pt.digest(t);return Ct.createV0(e)}function zo(r){let t=r*BigInt(1e3),e=new Date().getTime();return Number(t-BigInt(e))}var bu=ya(gu(),1);var Op=Object.prototype.toString,Pp=r=>Op.call(r)==="[object Error]",Vp=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed"]);function jo(r){return r&&Pp(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:Vp.has(r.message):!1}var Wo=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}},yu=(r,t,e)=>{let n=e.retries-(t-1);return r.attemptNumber=t,r.retriesLeft=n,r};async function Yo(r,t){return new Promise((e,n)=>{t={onFailedAttempt(){},retries:10,shouldRetry:()=>!0,...t};let s=bu.default.operation(t),i=()=>{s.stop(),n(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",i,{once:!0});let o=()=>{t.signal?.removeEventListener("abort",i),s.stop()};s.attempt(async a=>{try{let c=await r(a);o(),e(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof Wo)throw c.originalError;if(c instanceof TypeError&&!jo(c))throw c;if(yu(c,a,t),await t.shouldRetry(c)||(s.stop(),n(c)),await t.onFailedAttempt(c),!s.retry(c))throw s.mainError()}catch(f){yu(f,a,t),o(),n(f)}}})})}var Gs=class extends Nt{contentRouting;timeout;started;bootDelay;log;constructor(t,e){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:advert-service"),this.contentRouting=t.contentRouting,this.bootDelay=e?.bootDelay??ou,this.started=!1}isStarted(){return this.started}start(){this.started||(this.timeout=setTimeout(()=>{this._advertiseService().catch(t=>{this.log.error("could not advertise service",t)})},this.bootDelay),this.started=!0)}stop(){try{clearTimeout(this.timeout)}catch{}this.started=!1}async _advertiseService(){await Yo(async()=>{try{let t=await $s(Hs);await this.contentRouting.provide(t),this.safeDispatchEvent("advert:success",{detail:void 0})}catch(t){if(this.safeDispatchEvent("advert:error",{detail:t}),t.code===au){this.log.error("a content router, such as a DHT, must be provided in order to advertise the relay service",t),this.stop();return}throw this.log.error("could not advertise service",t),t}})}};function Zo(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:t(s)}}};return e}var Ie=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return Zo(this.map.entries(),t=>[Ce(t[0]),t[1]])}forEach(t){this.map.forEach((e,n)=>{t(e,Ce(n),this)})}get(t){return this.map.get(t.toString())}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),e)}keys(){return Zo(this.map.keys(),t=>Ce(t))}values(){return this.map.values()}get size(){return this.map.size}};var zs=class{reservations=new Ie;_started=!1;interval;maxReservations;reservationClearInterval;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;constructor(t={}){this.maxReservations=t.maxReservations??15,this.reservationClearInterval=t.reservationClearInterval??3e5,this.applyDefaultLimit=t.applyDefaultLimit!==!1,this.reservationTtl=t.reservationTtl??72e5,this.defaultDurationLimit=t.defaultDurationLimit??12e4,this.defaultDataLimit=t.defaultDataLimit??su}isStarted(){return this._started}start(){this._started||(this._started=!0,this.interval=setInterval(()=>{let t=new Date().getTime();this.reservations.forEach((e,n)=>{e.expire.getTime()<t&&this.reservations.delete(n)})},this.reservationClearInterval))}stop(){clearInterval(this.interval)}reserve(t,e,n){if(this.reservations.size>=this.maxReservations&&!this.reservations.has(t))return{status:H.RESERVATION_REFUSED};let s=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),this.reservations.set(t,{addr:e,expire:s,limit:i}),{status:H.OK,expire:Math.round(s.getTime()/1e3)}}removeReservation(t){this.reservations.delete(t)}hasReservation(t){return this.reservations.has(t)}get(t){return this.reservations.get(t)}};var js=class r{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:t,peer:e,expiration:n}){this.relay=t,this.peer=e,this.expiration=n}marshal(){return qs.encode({relay:this.relay.toBytes(),peer:this.peer.toBytes(),expiration:BigInt(this.expiration)})}equals(t){return!(!(t instanceof r)||!this.peer.equals(t.peer)||!this.relay.equals(t.relay)||this.expiration!==t.expiration)}};var wu=r=>r.protoCodes().includes(290),qp={maxOutboundStopStreams:yn},Xo=class extends Nt{registrar;peerStore;addressManager;peerId;connectionManager;connectionGater;reservationStore;advertService;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:server"),this.registrar=t.registrar,this.peerStore=t.peerStore,this.addressManager=t.addressManager,this.peerId=t.peerId,this.connectionManager=t.connectionManager,this.connectionGater=t.connectionGater,this.started=!1,this.hopTimeout=e?.hopTimeout??iu,this.shutdownController=new AbortController,this.maxInboundHopStreams=e.maxInboundHopStreams,this.maxOutboundHopStreams=e.maxOutboundHopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??qp.maxOutboundStopStreams,xn(1/0,this.shutdownController.signal),e.advertise!=null&&e.advertise!==!1&&(this.advertService=new Gs(t,e.advertise===!0?void 0:e.advertise),this.advertService.addEventListener("advert:success",()=>{this.safeDispatchEvent("relay:advert:success",{})}),this.advertService.addEventListener("advert:error",n=>{this.safeDispatchEvent("relay:advert:error",{detail:n.detail})})),this.reservationStore=new zs(e.reservations)}isStarted(){return this.started}async start(){this.started||(this.advertService?.start(),await this.registrar.handle(zt,t=>{this.onHop(t).catch(e=>{this.log.error(e)})},{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnTransientConnection:!0}),this.reservationStore.start(),this.started=!0)}async stop(){this.advertService?.stop(),this.reservationStore.stop(),this.shutdownController.abort(),await this.registrar.unhandle(zt),this.started=!1}async onHop({connection:t,stream:e}){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n=Mt(),s=setTimeout(()=>{n.reject("timed out")},this.hopTimeout),i=je(e);try{let o=await Promise.race([i.pb(Z).read(),n.promise]);if(o?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",o.type),await Promise.race([this.handleHopProtocol({connection:t,stream:i,request:o}),n.promise])}catch(o){this.log.error("error while handling hop",o),await i.pb(Z).write({type:Z.Type.STATUS,status:H.MALFORMED_MESSAGE}),e.abort(o)}finally{clearTimeout(s)}}async handleHopProtocol({stream:t,request:e,connection:n}){switch(this.log("received hop message"),e.type){case Z.Type.RESERVE:await this.handleReserve({stream:t,request:e,connection:n});break;case Z.Type.CONNECT:await this.handleConnect({stream:t,request:e,connection:n});break;default:this.log.error("invalid hop request type %s via peer %p",e.type,n.remotePeer),await t.pb(Z).write({type:Z.Type.STATUS,status:H.UNEXPECTED_MESSAGE})}}async handleReserve({stream:t,request:e,connection:n}){let s=t.pb(Z);if(this.log("hop reserve request from %p",n.remotePeer),wu(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await s.write({type:Z.Type.STATUS,status:H.PERMISSION_DENIED});return}if(await this.connectionGater.denyInboundRelayReservation?.(n.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",n.remotePeer),await s.write({type:Z.Type.STATUS,status:H.PERMISSION_DENIED});return}let i=this.reservationStore.reserve(n.remotePeer,n.remoteAddr);if(i.status!==H.OK){await s.write({type:Z.Type.STATUS,status:i.status});return}try{if(i.expire!=null){let o=i.expire*1e3-Date.now();await this.peerStore.merge(n.remotePeer,{tags:{[ru]:{value:1,ttl:o}}})}await s.write({type:Z.Type.STATUS,status:H.OK,reservation:await this.makeReservation(n.remotePeer,BigInt(i.expire??0)),limit:this.reservationStore.get(n.remotePeer)?.limit}),this.log("sent confirmation response to %s",n.remotePeer)}catch(o){this.log.error("failed to send confirmation response to %p",n.remotePeer,o),this.reservationStore.removeReservation(n.remotePeer)}}async makeReservation(t,e){let n=[];for(let i of this.addressManager.getAddresses())i.toString().includes("/p2p-circuit")||n.push(i.bytes);let s=await gn.seal(new js({peer:t,relay:this.peerId,expiration:Number(e)}),this.peerId);return{addrs:n,expire:e,voucher:s.marshal()}}async handleConnect({stream:t,request:e,connection:n}){let s=t.pb(Z);if(wu(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await s.write({type:Z.Type.STATUS,status:H.PERMISSION_DENIED});return}this.log("hop connect request from %p",n.remotePeer);let i;try{if(e.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");e.peer.addrs.forEach(Rt),i=Wr(e.peer.id)}catch(l){this.log.error("invalid hop connect request via peer %p %s",n.remotePeer,l),await s.write({type:Z.Type.STATUS,status:H.MALFORMED_MESSAGE});return}if(!this.reservationStore.hasReservation(i)){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",i,n.remotePeer,H.NO_RESERVATION),await s.write({type:Z.Type.STATUS,status:H.NO_RESERVATION});return}if(await this.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,i)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,i),await s.write({type:Z.Type.STATUS,status:H.PERMISSION_DENIED});return}let o=this.connectionManager.getConnections(i);if(o.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",i,n.remotePeer),await s.write({type:Z.Type.STATUS,status:H.NO_RESERVATION});return}let a=o[0],c=await this.stopHop({connection:a,request:{type:Ht.Type.CONNECT,peer:{id:n.remotePeer.toBytes(),addrs:[]}}});if(c==null){this.log.error("failed to open stream to destination peer %p",a?.remotePeer),await s.write({type:Z.Type.STATUS,status:H.CONNECTION_FAILED});return}await s.write({type:Z.Type.STATUS,status:H.OK});let f=t.unwrap();this.log("connection from %p to %p established - merging streams",n.remotePeer,i);let u=this.reservationStore.get(i)?.limit;fu(f,c,this.shutdownController.signal,u,{log:this.log})}async stopHop({connection:t,request:e}){this.log("starting circuit relay v2 stop request to %s",t.remotePeer);let n=await t.newStream([lr],{maxOutboundStreams:this.maxOutboundStopStreams,runOnTransientConnection:!0}),s=je(n),i=s.pb(Ht);await i.write(e);let o;try{o=await i.read()}catch{this.log.error("error parsing stop message response from %p",t.remotePeer)}if(o==null){this.log.error("could not read response from %p",t.remotePeer),await n.close();return}if(o.status===H.OK)return this.log("stop request to %p was successful",t.remotePeer),s.unwrap();this.log("stop request failed with code %d",o.status),await n.close()}get reservations(){return this.reservationStore.reservations}};function xu(r={}){return t=>new Xo(t,r)}var Ws=class extends Nt{peerId;peerStore;contentRouting;registrar;started;topologyId;log;constructor(t){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.started=!1,this.peerId=t.peerId,this.peerStore=t.peerStore,this.contentRouting=t.contentRouting,this.registrar=t.registrar}isStarted(){return this.started}async start(){this.topologyId=await this.registrar.register(zt,{notifyOnTransient:!0,onConnect:t=>{this.safeDispatchEvent("relay:discover",{detail:t})}}),this.started=!0}afterStart(){this.discover().catch(t=>{this.log.error("error discovering relays",t)})}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async discover(){this.log("searching peer store for relays");let t=await this.peerStore.all({filters:[e=>e.protocols.includes(zt)],orders:[()=>Math.random()<.5?1:-1]});for(let e of t)this.log("found relay peer %p in content peer store",e.id),this.safeDispatchEvent("relay:discover",{detail:e.id});this.log("found %d relay peers in peer store",t.length);try{this.log("searching content routing for relays");let e=await $s(Hs),n=0;for await(let s of this.contentRouting.findProviders(e))if(s.multiaddrs.length>0&&!s.id.equals(this.peerId)){let i=s.id;n++,await this.peerStore.merge(i,{multiaddrs:s.multiaddrs}),this.log("found relay peer %p in content routing",i),this.safeDispatchEvent("relay:discover",{detail:i})}this.log("found %d relay peers in content routing",n)}catch(e){this.log.error("failed when finding relays on the network",e)}}};var Ys=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Fr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Ys(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new Ys(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Qo=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function vu(r={}){return $p(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function $p(r,t){t=t??{};let e=t.onEnd,n=new Fr,s,i,o,a=Mt(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((p,y)=>{i=A=>{i=null,n.push(A);try{p(r(n))}catch(w){y(w)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Mt()})}},f=p=>i!=null?i(p):(n.push(p),s),u=p=>(n=new Fr,i!=null?i({error:p}):(n.push({error:p}),s)),l=p=>{if(o)return s;if(t?.objectMode!==!0&&p?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:p})},h=p=>o?s:(o=!0,p!=null?u(p):f({done:!0})),b=()=>(n=new Fr,h(),{done:!0}),m=p=>(h(p),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:b,throw:m,push:l,end:h,get readableLength(){return n.size},onEmpty:async p=>{let y=p?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let A,w;y!=null&&(A=new Promise((_,x)=>{w=()=>{x(new Qo)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,A])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},e==null)return s;let d=s;return s={[Symbol.asyncIterator](){return this},next(){return d.next()},throw(p){return d.throw(p),e!=null&&(e(p),e=void 0),{done:!0}},return(){return d.return(),e!=null&&(e(),e=void 0),{done:!0}},push:l,end(p){return d.end(p),e!=null&&(e(p),e=void 0),s},get readableLength(){return d.readableLength},onEmpty:p=>d.onEmpty(p)},s}var ta=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function Zs(r,t,e,n){let s=new ta(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(s):new Promise((i,o)=>{let a=f=>{n?.filter?.(f)!==!1&&(r.removeEventListener(t,a),e?.removeEventListener("abort",c),i(f))},c=()=>{r.removeEventListener(t,a),e?.removeEventListener("abort",c),o(s)};r.addEventListener(t,a),e?.addEventListener("abort",c)})}var Xs=class{deferred;signal;where;constructor(t,e){this.signal=e,this.deferred=Mt(),this.where=t,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(new Re)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Gp(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Js=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(t,e,n=0){this.id=Gp(),this.status="queued",this.fn=t,this.priority=n,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,xn(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&this.controller.abort(new Re)}async join(t={}){let e=new Xs(new Error("where").stack,t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await Ps(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.signal?.removeEventListener("abort",this.onAbort)})}};function zp(r,t,e){let n=0,s=r.length;for(;s>0;){let i=Math.trunc(s/2),o=n+i;e(r[o],t)<=0?(n=++o,s-=i+1):s=i}return n}var Qs=class extends Nt{concurrency;queue;pending;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.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 t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){if(this.queue[this.size-1]?.priority>=t.priority){this.queue.push(t);return}let e=zp(this.queue,t,(n,s)=>s.priority-n.priority);this.queue.splice(e,0,t)}async add(t,e){e?.signal?.throwIfAborted();let n=new Js(t,e,e?.priority),s=n.join(e).then(i=>(this.safeDispatchEvent("completed",{detail:i}),i)).catch(i=>{throw this.safeDispatchEvent("error",{detail:i}),i});return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),s}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Re)}),this.clear()}async onEmpty(t){this.size!==0&&await Zs(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await Zs(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Zs(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=vu({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},s=c=>{c.detail!=null&&e.push(c.detail)},i=c=>{n(c.detail)},o=()=>{n()},a=()=>{n(new L("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",s),this.addEventListener("error",i),this.addEventListener("idle",o),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("error",i),this.removeEventListener("idle",o),t?.signal?.removeEventListener("abort",a),n()}}};var ti=class extends Qs{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var Wp=60*1e3*10,Yp=60*1e3*5,Zp=30*1e3,ei=class extends Nt{peerId;connectionManager;transportManager;peerStore;events;reserveQueue;reservations;maxDiscoveredRelays;maxReservationQueueLength;reservationCompletionTimeout;started;log;constructor(t,e){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=t.peerId,this.connectionManager=t.connectionManager,this.transportManager=t.transportManager,this.peerStore=t.peerStore,this.events=t.events,this.reservations=new Ie,this.maxDiscoveredRelays=e?.discoverRelays??0,this.maxReservationQueueLength=e?.maxReservationQueueLength??100,this.reservationCompletionTimeout=e?.reservationCompletionTimeout??1e4,this.started=!1,this.reserveQueue=new ti({concurrency:e?.reservationConcurrency??1,metricName:"libp2p_relay_reservation_queue",metrics:t.metrics}),this.events.addEventListener("peer:disconnect",n=>{this.#e(n.detail)})}isStarted(){return this.started}start(){this.started=!0}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:t})=>{clearTimeout(t)}),this.reservations.clear(),this.started=!1}async addRelay(t,e){if(this.peerId.equals(t)){this.log("not trying to use self as relay");return}if(this.reserveQueue.size>this.maxReservationQueueLength){this.log("not adding relay as the queue is full");return}if(this.reserveQueue.has(t)){this.log("relay peer is already in the reservation queue");return}this.log("add relay %p",t),await this.reserveQueue.add(async()=>{try{let n=this.reservations.get(t);if(n!=null){if(zo(n.reservation.expire)>Wp){this.log("already have reservation on relay peer %p and it expires in more than 10 minutes",t);return}clearTimeout(n.timeout),this.reservations.delete(t)}if(e==="discovered"&&[...this.reservations.values()].reduce((u,l)=>(l.type==="discovered"&&u++,u),0)>=this.maxDiscoveredRelays){this.log("already have enough discovered relays");return}let s=AbortSignal.timeout(this.reservationCompletionTimeout),i=await this.connectionManager.openConnection(t,{signal:s});if(i.remoteAddr.protoNames().includes("p2p-circuit")){this.log("not creating reservation over relayed connection");return}let o=await this.#t(i,{signal:s});this.log("created reservation on relay peer %p",t);let a=zo(o.expire),c=Math.min(Math.max(a-Yp,Zp),Math.pow(2,31)-1),f=setTimeout(()=>{this.addRelay(t,e).catch(u=>{this.log.error("could not refresh reservation to relay %p",t,u)})},c);this.reservations.set(t,{timeout:f,reservation:o,type:e}),await this.peerStore.merge(t,{tags:{[nu]:{value:1,ttl:a}}}),await this.transportManager.listen([Rt(`/p2p/${t.toString()}/p2p-circuit`)])}catch(n){this.log.error("could not reserve slot on %p",t,n);let s=this.reservations.get(t);s!=null&&clearTimeout(s.timeout),this.reservations.delete(t)}},{peerId:t})}hasReservation(t){return this.reservations.has(t)}getReservation(t){return this.reservations.get(t)?.reservation}async#t(t,e){e.signal?.throwIfAborted(),this.log("requesting reservation from %p",t.remotePeer);let n=await t.newStream(zt,e),i=je(n).pb(Z);await i.write({type:Z.Type.RESERVE},e);let o;try{o=await i.read(e)}catch(c){throw this.log.error("error parsing reserve message response from %p because",t.remotePeer,c),n.abort(c),c}finally{await n.close()}if(o.status===H.OK&&o.reservation!=null){let c=!1,f=t.remoteAddr.bytes;for(let u of o.reservation.addrs)if(ut(f,u)){c=!0;break}return c||o.reservation.addrs.push(f),o.reservation}let a=`reservation failed with status ${o.status??"undefined"}`;throw this.log.error(a),new Error(a)}#e(t){let e=this.reservations.get(t);e!=null&&(this.log("connection to relay %p closed, removing reservation from local store",t),clearTimeout(e.timeout),this.reservations.delete(t),this.safeDispatchEvent("relay:removed",{detail:t}),this.reservations.size<this.maxDiscoveredRelays&&(this.log("not enough relays %d/%d",this.reservations.size,this.maxDiscoveredRelays),this.safeDispatchEvent("relay:not-enough-relays",{})))}};function ea(r){let{stream:t,remoteAddr:e,logger:n}=r,s=n.forComponent("libp2p:stream:converter"),i=!1,o=!1,a=t.close.bind(t);t.close=async h=>{await a(h),l(!0)};let c=t.abort.bind(t);t.abort=h=>{c(h),l(!0)};let f=t.sink.bind(t);t.sink=async h=>{try{await f(h)}catch(b){b.type!=="aborted"&&s.error("%s error in sink",e,b)}finally{o=!0,l()}};let u={log:s,sink:t.sink,source:async function*(){try{for await(let h of t.source)h instanceof Uint8Array?yield h:yield*h}finally{i=!0,l()}}(),remoteAddr:e,timeline:{open:Date.now(),close:void 0},close:t.close,abort:t.abort};function l(h){h===!0&&(i=!0,o=!0),i&&o&&u.timeline.close==null&&(u.timeline.close=Date.now())}return u}var Xp=B("dns4"),Jp=B("dns6"),Qp=B("dnsaddr"),fr=at(B("dns"),Qp,Xp,Jp),si=at(B("ip4"),B("ip6")),Kr=at(U(si,B("tcp")),U(fr,B("tcp"))),ii=U(si,B("udp")),t0=U(ii,B("utp")),e0=U(ii,B("quic")),r0=U(ii,B("quic-v1")),ra=at(U(Kr,B("ws")),U(fr,B("ws"))),ri=at(U(ra,B("p2p")),ra),na=at(U(Kr,B("wss")),U(fr,B("wss")),U(Kr,B("tls"),B("ws")),U(fr,B("tls"),B("ws"))),ni=at(U(na,B("p2p")),na),sa=at(U(Kr,B("http")),U(si,B("http")),U(fr,B("http"))),ia=at(U(Kr,B("https")),U(si,B("https")),U(fr,B("https"))),Eu=U(ii,B("webrtc-direct"),B("certhash")),Su=at(U(Eu,B("p2p")),Eu),Au=U(r0,B("webtransport"),B("certhash"),B("certhash")),Tu=at(U(Au,B("p2p")),Au),Iu=at(U(ri,B("p2p-webrtc-star"),B("p2p")),U(ni,B("p2p-webrtc-star"),B("p2p")),U(ri,B("p2p-webrtc-star")),U(ni,B("p2p-webrtc-star"))),Dv=at(U(ri,B("p2p-websocket-star"),B("p2p")),U(ni,B("p2p-websocket-star"),B("p2p")),U(ri,B("p2p-websocket-star")),U(ni,B("p2p-websocket-star"))),ku=at(U(sa,B("p2p-webrtc-direct"),B("p2p")),U(ia,B("p2p-webrtc-direct"),B("p2p")),U(sa,B("p2p-webrtc-direct")),U(ia,B("p2p-webrtc-direct"))),hr=at(ra,na,sa,ia,Iu,ku,Kr,t0,e0,fr,Su,Tu),Ov=at(U(hr,B("p2p-stardust"),B("p2p")),U(hr,B("p2p-stardust"))),We=at(U(hr,B("p2p")),Iu,ku,Su,Tu,B("p2p")),Bu=at(U(We,B("p2p-circuit"),We),U(We,B("p2p-circuit")),U(B("p2p-circuit"),We),U(hr,B("p2p-circuit")),U(B("p2p-circuit"),hr),B("p2p-circuit")),Ru=()=>at(U(Bu,Ru),Bu),ke=Ru(),Pv=at(U(ke,We,ke),U(We,ke),U(ke,We),ke,We);var Vv=at(U(ke,B("webrtc"),B("p2p")),U(ke,B("webrtc")),U(hr,B("webrtc"),B("p2p")),U(hr,B("webrtc")),B("webrtc"));function Nu(r){function t(e){let n;try{n=Rt(e)}catch{return!1}let s=r(n.protoNames());return s===null?!1:s===!0||s===!1?s:s.length===0}return t}function U(...r){function t(e){if(e.length<r.length)return null;let n=e;return r.some(s=>(n=typeof s=="function"?s().partialMatch(e):s.partialMatch(e),Array.isArray(n)&&(e=n),n===null)),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:Nu(t),partialMatch:t}}function at(...r){function t(n){let s=null;return r.some(i=>{let o=typeof i=="function"?i().partialMatch(n):i.partialMatch(n);return o!=null?(s=o,!0):!1}),s}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:Nu(t),partialMatch:t}}function B(r){let t=r;function e(s){let i;try{i=Rt(s)}catch{return!1}let o=i.protoNames();return o.length===1&&o[0]===t}function n(s){return s.length===0?null:s[0]===t?s.slice(1):null}return{toString:function(){return t},matches:e,partialMatch:n}}var oa=class extends Nt{connectionManager;relayStore;listeningAddrs;log;constructor(t){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=t.connectionManager,this.relayStore=t.relayStore,this.listeningAddrs=new Ie,this.relayStore.addEventListener("relay:removed",this._onRemoveRelayPeer)}_onRemoveRelayPeer=t=>{this.#t(t.detail)};async listen(t){this.log("listen on %a",t);let e=t.decapsulate("/p2p-circuit"),n=await this.connectionManager.openConnection(e);if(!this.relayStore.hasReservation(n.remotePeer)){this.log("making reservation on peer %p",n.remotePeer),await this.relayStore.addRelay(n.remotePeer,"configured");return}let s=this.relayStore.getReservation(n.remotePeer);if(s==null)throw new L("Did not have reservation after making reservation","ERR_NO_RESERVATION");if(this.listeningAddrs.has(n.remotePeer)){this.log("already listening on relay %p",n.remotePeer);return}this.listeningAddrs.set(n.remotePeer,s.addrs.map(i=>Rt(i).encapsulate("/p2p-circuit"))),this.safeDispatchEvent("listening",{})}getAddrs(){return[...this.listeningAddrs.values()].flat()}async close(){}#t(t){let e=this.listeningAddrs.has(t);this.log("relay peer removed %p - had reservation",t,e),this.listeningAddrs.delete(t),e&&(this.log.trace("removing relay event listener for peer %p",t),this.relayStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),this.safeDispatchEvent("close",{}))}};function _u(r){return new oa(r)}var s0=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(Rt)}catch{return!1}return!0},aa={maxInboundStopStreams:yn,maxOutboundStopStreams:yn,stopTimeout:3e4},oi=class{discovery;registrar;peerStore;connectionManager;transportManager;peerId;upgrader;addressManager;connectionGater;reservationStore;logger;maxInboundStopStreams;maxOutboundStopStreams;stopTimeout;started;log;constructor(t,e){this.log=t.logger.forComponent("libp2p:circuit-relay:transport"),this.registrar=t.registrar,this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.transportManager=t.transportManager,this.logger=t.logger,this.peerId=t.peerId,this.upgrader=t.upgrader,this.addressManager=t.addressManager,this.connectionGater=t.connectionGater,this.maxInboundStopStreams=e.maxInboundStopStreams??aa.maxInboundStopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??aa.maxOutboundStopStreams,this.stopTimeout=e.stopTimeout??aa.stopTimeout,e.discoverRelays!=null&&e.discoverRelays>0&&(this.discovery=new Ws(t),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(s=>{this.log.error("could not add discovered relay %p",n.detail,s)})})),this.reservationStore=new ei(t,e),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.discover().catch(n=>{this.log.error("could not discover relays",n)})}),this.started=!1}isStarted(){return this.started}async start(){this.reservationStore.start(),await this.registrar.handle(lr,t=>{this.onStop(t).catch(e=>{this.log.error("error while handling STOP protocol",e),t.stream.abort(e)})},{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnTransientConnection:!0}),await this.discovery?.start(),this.started=!0}afterStart(){this.discovery?.afterStart()}async stop(){this.discovery?.stop(),this.reservationStore.stop(),await this.registrar.unhandle(lr),this.started=!1}[xa]=!0;[Symbol.toStringTag]="libp2p/circuit-relay-v2";async dial(t,e={}){if(t.protoCodes().filter(m=>m===290).length!==1){let m="Invalid circuit relay address";throw this.log.error(m,t),new L(m,$o)}let n=t.toString().split("/p2p-circuit"),s=Rt(n[0]),i=Rt(n[n.length-1]),o=s.getPeerId(),a=i.getPeerId();if(o==null||a==null){let m=`Circuit relay dial to ${t.toString()} failed as address did not have peer ids`;throw this.log.error(m),new L(m,$o)}let c=Ce(o),f=Ce(a),u=!1,h=this.connectionManager.getConnections(c)[0];h==null&&(await this.peerStore.merge(c,{multiaddrs:[s]}),h=await this.connectionManager.openConnection(c,e),u=!0);let b;try{return b=await h.newStream(zt),await this.connectV2({stream:b,connection:h,destinationPeer:f,destinationAddr:i,relayAddr:s,ma:t,disconnectOnFailure:u})}catch(m){throw this.log.error("circuit relay dial to destination %p via relay %p failed",f,c,m),b?.abort(m),u&&await h.close(),m}}async connectV2({stream:t,connection:e,destinationPeer:n,destinationAddr:s,relayAddr:i,ma:o,disconnectOnFailure:a}){try{let c=je(t),f=c.pb(Z);await f.write({type:Z.Type.CONNECT,peer:{id:n.toBytes(),addrs:[Rt(s).bytes]}});let u=await f.read();if(u.status!==H.OK)throw new L(`failed to connect via relay with status ${u?.status?.toString()??"undefined"}`,cu);let l=ea({stream:c.unwrap(),remoteAddr:o,localAddr:i.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`),logger:this.logger});return this.log("new outbound transient connection %a",l.remoteAddr),await this.upgrader.upgradeOutbound(l,{transient:!0})}catch(c){throw this.log.error(`Circuit relay dial to destination ${n.toString()} via relay ${e.remotePeer.toString()} failed`,c),a&&await e.close(),c}}createListener(t){return _u({connectionManager:this.connectionManager,relayStore:this.reservationStore,logger:this.logger})}filter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>ke.matches(e))}async onStop({connection:t,stream:e}){if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(u){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on",u)}let n=AbortSignal.timeout(this.stopTimeout),s=je(e).pb(Ht),i=await s.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,i.type),i?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await s.write({type:Ht.Type.STATUS,status:H.MALFORMED_MESSAGE},{signal:n}),await e.close();return}if(i.type!==Ht.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:Ht.Type.STATUS,status:H.UNEXPECTED_MESSAGE},{signal:n}),await e.close();return}if(!s0(i)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:Ht.Type.STATUS,status:H.MALFORMED_MESSAGE},{signal:n}),await e.close();return}let o=Wr(i.peer.id);if(await this.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,o)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await s.write({type:Ht.Type.STATUS,status:H.PERMISSION_DENIED},{signal:n}),await e.close();return}this.log.trace("sending success response to %p",t.remotePeer),await s.write({type:Ht.Type.STATUS,status:H.OK},{signal:n});let a=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${o.toString()}`),c=this.addressManager.getAddresses()[0],f=ea({stream:s.unwrap().unwrap(),remoteAddr:a,localAddr:c,logger:this.logger});this.log("new inbound transient connection %a",f.remoteAddr),await this.upgrader.upgradeInbound(f,{transient:!0}),this.log("%s connection %a upgraded","inbound",f.remoteAddr)}};function Lu(r={}){return t=>new oi(t,r)}return zu(i0);})();
7
+ `)}async function jd(r,t){let e=It.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let s=Q(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=Dr(s),{iv:o,salt:a,iterations:c,keySize:f,cipherText:u}=Wd(i),l=await mo(Tr,t,a,{c,dkLen:f}),h=await e.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),b=un(await e.subtle.decrypt({name:"AES-CBC",iv:o},h,u)),{result:m}=Dr(b);n=fl(m)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let s=Q(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=Dr(s);n=fl(i)}else throw new L("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return Eo(n)}function Wd(r){let t=r.valueBlock.value[0];if(t.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new L("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=t.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new L("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let i=n.valueBlock.value[1],o=un(i.valueBlock.value[0].getValue()),a=vo,c=xo;if(i.valueBlock.value.length===3)a=Number(i.valueBlock.value[1].toBigInt()),c=Number(i.valueBlock.value[2].toBigInt());else if(i.valueBlock.value.length===2)throw new L("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let f=t.valueBlock.value[1].valueBlock.value[1],u=f.valueBlock.value[0].toString();if(u!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(u!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new L("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let l=un(f.valueBlock.value[1].getValue());return{cipherText:un(r.valueBlock.value[1].getValue()),salt:o,iterations:a,keySize:c,iv:l}}function fl(r){return un(r.valueBlock.value[2].getValue())}function un(r){return new Uint8Array(r,0,r.byteLength)}async function hl(r){let t=await It.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await ml(t);return{privateKey:e[0],publicKey:e[1]}}async function Ao(r){let e=[await It.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Yd(r)],n=await ml({privateKey:e[0],publicKey:e[1]});return{privateKey:n[0],publicKey:n[1]}}async function dl(r,t){let e=await It.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await It.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function pl(r,t,e){let n=await It.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return It.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function ml(r){if(r.privateKey==null||r.publicKey==null)throw new L("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([It.get().subtle.exportKey("jwk",r.privateKey),It.get().subtle.exportKey("jwk",r.publicKey)])}async function Yd(r){return It.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 Ns(r){if(r.kty!=="RSA")throw new L("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new L("invalid key modulus","ERR_INVALID_KEY_MODULUS");return Q(r.n,"base64url").length*8}var hn=8192,fn=class{_key;constructor(t){this._key=t}verify(t,e){return pl(this._key,e,t)}marshal(){return $e.jwkToPkix(this._key)}get bytes(){return se.encode({Type:rt.RSA,Data:this.marshal()}).subarray()}equals(t){return ut(this.bytes,t.bytes)}hash(){let t=pt.digest(this.bytes);return Kt(t)?t.then(({bytes:e})=>e):t.bytes}},Or=class{_key;_publicKey;constructor(t,e){this._key=t,this._publicKey=e}genSecret(){return ir(16)}sign(t){return dl(this._key,t)}get public(){if(this._publicKey==null)throw new L("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new fn(this._publicKey)}marshal(){return $e.jwkToPkcs1(this._key)}get bytes(){return ie.encode({Type:rt.RSA,Data:this.marshal()}).subarray()}equals(t){return ut(this.bytes,t.bytes)}hash(){let t=pt.digest(this.bytes);return Kt(t)?t.then(({bytes:e})=>e):t.bytes}async id(){let t=await this.public.hash();return W(t,"base58btc")}async export(t,e="pkcs-8"){if(e==="pkcs-8")return $e.exportToPem(this,t);if(e==="libp2p-key")return Rr(this.bytes,t);throw new L(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function Eo(r){let t=$e.pkcs1ToJwk(r);if(Ns(t)>hn)throw new L("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Ao(t);return new Or(e.privateKey,e.publicKey)}function Xd(r){let t=$e.pkixToJwk(r);if(Ns(t)>hn)throw new L("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new fn(t)}async function Jd(r){if(Ns(r)>hn)throw new L("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await Ao(r);return new Or(t.privateKey,t.publicKey)}async function Qd(r){if(r>hn)throw new L("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await hl(r);return new Or(t.privateKey,t.publicKey)}var Ro={};gt(Ro,{Secp256k1PrivateKey:()=>pn,Secp256k1PublicKey:()=>dn,generateKeyPair:()=>pp,unmarshalSecp256k1PrivateKey:()=>hp,unmarshalSecp256k1PublicKey:()=>dp});var tp=(r,t,e)=>r&t^~r&e,ep=(r,t,e)=>r&t^r&e^t&e,rp=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]),Ge=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ze=new Uint32Array(64),So=class extends Sr{constructor(){super(64,32,8,!1),this.A=Ge[0]|0,this.B=Ge[1]|0,this.C=Ge[2]|0,this.D=Ge[3]|0,this.E=Ge[4]|0,this.F=Ge[5]|0,this.G=Ge[6]|0,this.H=Ge[7]|0}get(){let{A:t,B:e,C:n,D:s,E:i,F:o,G:a,H:c}=this;return[t,e,n,s,i,o,a,c]}set(t,e,n,s,i,o,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=s|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(t,e){for(let l=0;l<16;l++,e+=4)ze[l]=t.getUint32(e,!1);for(let l=16;l<64;l++){let h=ze[l-15],b=ze[l-2],m=Wt(h,7)^Wt(h,18)^h>>>3,d=Wt(b,17)^Wt(b,19)^b>>>10;ze[l]=d+ze[l-7]+m+ze[l-16]|0}let{A:n,B:s,C:i,D:o,E:a,F:c,G:f,H:u}=this;for(let l=0;l<64;l++){let h=Wt(a,6)^Wt(a,11)^Wt(a,25),b=u+h+tp(a,c,f)+rp[l]+ze[l]|0,d=(Wt(n,2)^Wt(n,13)^Wt(n,22))+ep(n,s,i)|0;u=f,f=c,c=a,a=o+b|0,o=i,i=s,s=n,n=b+d|0}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(n,s,i,o,a,c,f,u)}roundClean(){ze.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var gl=Tn(()=>new So);function np(r){let t=Zr(r);ne(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:s}=t;if(e){if(!n.eql(s,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:sp,hexToBytes:ip}=Rn,ar={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(r){let{Err:t}=ar;if(r.length<2||r[0]!==2)throw new t("Invalid signature integer tag");let e=r[1],n=r.subarray(2,e+2);if(!e||n.length!==e)throw new t("Invalid signature integer: wrong length");if(n[0]&128)throw new t("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return{d:sp(n),l:r.subarray(e+2)}},toSig(r){let{Err:t}=ar,e=typeof r=="string"?ip(r):r;if(!Yt(e))throw new Error("ui8a expected");let n=e.length;if(n<2||e[0]!=48)throw new t("Invalid signature tag");if(e[1]!==n-2)throw new t("Invalid signature: incorrect length");let{d:s,l:i}=ar._parseInt(e.subarray(2)),{d:o,l:a}=ar._parseInt(i);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:s,s:o}},hexFromSig(r){let t=f=>Number.parseInt(f[0],16)&8?"00"+f:f,e=f=>{let u=f.toString(16);return u.length&1?`0${u}`:u},n=t(e(r.s)),s=t(e(r.r)),i=n.length/2,o=s.length/2,a=e(i),c=e(o);return`30${e(o+i+4)}02${c}${s}02${a}${n}`}},Te=BigInt(0),Gt=BigInt(1),Vy=BigInt(2),yl=BigInt(3),My=BigInt(4);function op(r){let t=np(r),{Fp:e}=t,n=t.toBytes||((m,d,p)=>{let y=d.toAffine();return ge(Uint8Array.from([4]),e.toBytes(y.x),e.toBytes(y.y))}),s=t.fromBytes||(m=>{let d=m.subarray(1),p=e.fromBytes(d.subarray(0,e.BYTES)),y=e.fromBytes(d.subarray(e.BYTES,2*e.BYTES));return{x:p,y}});function i(m){let{a:d,b:p}=t,y=e.sqr(m),A=e.mul(y,m);return e.add(e.add(A,e.mul(m,d)),p)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function o(m){return typeof m=="bigint"&&Te<m&&m<t.n}function a(m){if(!o(m))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(m){let{allowedPrivateKeyLengths:d,nByteLength:p,wrapPrivateKey:y,n:A}=t;if(d&&typeof m!="bigint"){if(Yt(m)&&(m=pe(m)),typeof m!="string"||!d.includes(m.length))throw new Error("Invalid key");m=m.padStart(p*2,"0")}let w;try{w=typeof m=="bigint"?m:me(it("private key",m,p))}catch{throw new Error(`private key must be ${p} bytes, hex or bigint, not ${typeof m}`)}return y&&(w=X(w,A)),a(w),w}let f=new Map;function u(m){if(!(m instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(d,p,y){if(this.px=d,this.py=p,this.pz=y,d==null||!e.isValid(d))throw new Error("x required");if(p==null||!e.isValid(p))throw new Error("y required");if(y==null||!e.isValid(y))throw new Error("z required")}static fromAffine(d){let{x:p,y}=d||{};if(!d||!e.isValid(p)||!e.isValid(y))throw new Error("invalid affine point");if(d instanceof l)throw new Error("projective point not allowed");let A=w=>e.eql(w,e.ZERO);return A(p)&&A(y)?l.ZERO:new l(p,y,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(d){let p=e.invertBatch(d.map(y=>y.pz));return d.map((y,A)=>y.toAffine(p[A])).map(l.fromAffine)}static fromHex(d){let p=l.fromAffine(s(it("pointHex",d)));return p.assertValidity(),p}static fromPrivateKey(d){return l.BASE.multiply(c(d))}_setWindowSize(d){this._WINDOW_SIZE=d,f.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!e.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:d,y:p}=this.toAffine();if(!e.isValid(d)||!e.isValid(p))throw new Error("bad point: x or y not FE");let y=e.sqr(p),A=i(d);if(!e.eql(y,A))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:d}=this.toAffine();if(e.isOdd)return!e.isOdd(d);throw new Error("Field doesn't support isOdd")}equals(d){u(d);let{px:p,py:y,pz:A}=this,{px:w,py:_,pz:x}=d,S=e.eql(e.mul(p,x),e.mul(w,A)),R=e.eql(e.mul(y,x),e.mul(_,A));return S&&R}negate(){return new l(this.px,e.neg(this.py),this.pz)}double(){let{a:d,b:p}=t,y=e.mul(p,yl),{px:A,py:w,pz:_}=this,x=e.ZERO,S=e.ZERO,R=e.ZERO,N=e.mul(A,A),z=e.mul(w,w),$=e.mul(_,_),P=e.mul(A,w);return P=e.add(P,P),R=e.mul(A,_),R=e.add(R,R),x=e.mul(d,R),S=e.mul(y,$),S=e.add(x,S),x=e.sub(z,S),S=e.add(z,S),S=e.mul(x,S),x=e.mul(P,x),R=e.mul(y,R),$=e.mul(d,$),P=e.sub(N,$),P=e.mul(d,P),P=e.add(P,R),R=e.add(N,N),N=e.add(R,N),N=e.add(N,$),N=e.mul(N,P),S=e.add(S,N),$=e.mul(w,_),$=e.add($,$),N=e.mul($,P),x=e.sub(x,N),R=e.mul($,z),R=e.add(R,R),R=e.add(R,R),new l(x,S,R)}add(d){u(d);let{px:p,py:y,pz:A}=this,{px:w,py:_,pz:x}=d,S=e.ZERO,R=e.ZERO,N=e.ZERO,z=t.a,$=e.mul(t.b,yl),P=e.mul(p,w),ct=e.mul(y,_),ot=e.mul(A,x),Ft=e.add(p,y),v=e.add(w,_);Ft=e.mul(Ft,v),v=e.add(P,ct),Ft=e.sub(Ft,v),v=e.add(p,A);let k=e.add(w,x);return v=e.mul(v,k),k=e.add(P,ot),v=e.sub(v,k),k=e.add(y,A),S=e.add(_,x),k=e.mul(k,S),S=e.add(ct,ot),k=e.sub(k,S),N=e.mul(z,v),S=e.mul($,ot),N=e.add(S,N),S=e.sub(ct,N),N=e.add(ct,N),R=e.mul(S,N),ct=e.add(P,P),ct=e.add(ct,P),ot=e.mul(z,ot),v=e.mul($,v),ct=e.add(ct,ot),ot=e.sub(P,ot),ot=e.mul(z,ot),v=e.add(v,ot),P=e.mul(ct,v),R=e.add(R,P),P=e.mul(k,v),S=e.mul(Ft,S),S=e.sub(S,P),P=e.mul(Ft,ct),N=e.mul(k,N),N=e.add(N,P),new l(S,R,N)}subtract(d){return this.add(d.negate())}is0(){return this.equals(l.ZERO)}wNAF(d){return b.wNAFCached(this,f,d,p=>{let y=e.invertBatch(p.map(A=>A.pz));return p.map((A,w)=>A.toAffine(y[w])).map(l.fromAffine)})}multiplyUnsafe(d){let p=l.ZERO;if(d===Te)return p;if(a(d),d===Gt)return this;let{endo:y}=t;if(!y)return b.unsafeLadder(this,d);let{k1neg:A,k1:w,k2neg:_,k2:x}=y.splitScalar(d),S=p,R=p,N=this;for(;w>Te||x>Te;)w&Gt&&(S=S.add(N)),x&Gt&&(R=R.add(N)),N=N.double(),w>>=Gt,x>>=Gt;return A&&(S=S.negate()),_&&(R=R.negate()),R=new l(e.mul(R.px,y.beta),R.py,R.pz),S.add(R)}multiply(d){a(d);let p=d,y,A,{endo:w}=t;if(w){let{k1neg:_,k1:x,k2neg:S,k2:R}=w.splitScalar(p),{p:N,f:z}=this.wNAF(x),{p:$,f:P}=this.wNAF(R);N=b.constTimeNegate(_,N),$=b.constTimeNegate(S,$),$=new l(e.mul($.px,w.beta),$.py,$.pz),y=N.add($),A=z.add(P)}else{let{p:_,f:x}=this.wNAF(p);y=_,A=x}return l.normalizeZ([y,A])[0]}multiplyAndAddUnsafe(d,p,y){let A=l.BASE,w=(x,S)=>S===Te||S===Gt||!x.equals(A)?x.multiplyUnsafe(S):x.multiply(S),_=w(this,p).add(w(d,y));return _.is0()?void 0:_}toAffine(d){let{px:p,py:y,pz:A}=this,w=this.is0();d==null&&(d=w?e.ONE:e.inv(A));let _=e.mul(p,d),x=e.mul(y,d),S=e.mul(A,d);if(w)return{x:e.ZERO,y:e.ZERO};if(!e.eql(S,e.ONE))throw new Error("invZ was invalid");return{x:_,y:x}}isTorsionFree(){let{h:d,isTorsionFree:p}=t;if(d===Gt)return!0;if(p)return p(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:d,clearCofactor:p}=t;return d===Gt?this:p?p(l,this):this.multiplyUnsafe(t.h)}toRawBytes(d=!0){return this.assertValidity(),n(l,this,d)}toHex(d=!0){return pe(this.toRawBytes(d))}}l.BASE=new l(t.Gx,t.Gy,e.ONE),l.ZERO=new l(e.ZERO,e.ONE,e.ZERO);let h=t.nBitLength,b=Ln(l,t.endo?Math.ceil(h/2):h);return{CURVE:t,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:o}}function ap(r){let t=Zr(r);return ne(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function bl(r){let t=ap(r),{Fp:e,n}=t,s=e.BYTES+1,i=2*e.BYTES+1;function o(v){return Te<v&&v<e.ORDER}function a(v){return X(v,n)}function c(v){return Nn(v,n)}let{ProjectivePoint:f,normPrivateKeyToScalar:u,weierstrassEquation:l,isWithinCurveOrder:h}=op({...t,toBytes(v,k,V){let E=k.toAffine(),g=e.toBytes(E.x),I=ge;return V?I(Uint8Array.from([k.hasEvenY()?2:3]),g):I(Uint8Array.from([4]),g,e.toBytes(E.y))},fromBytes(v){let k=v.length,V=v[0],E=v.subarray(1);if(k===s&&(V===2||V===3)){let g=me(E);if(!o(g))throw new Error("Point is not on curve");let I=l(g),C=e.sqrt(I),D=(C&Gt)===Gt;return(V&1)===1!==D&&(C=e.neg(C)),{x:g,y:C}}else if(k===i&&V===4){let g=e.fromBytes(E.subarray(0,e.BYTES)),I=e.fromBytes(E.subarray(e.BYTES,2*e.BYTES));return{x:g,y:I}}else throw new Error(`Point of length ${k} was invalid. Expected ${s} compressed bytes or ${i} uncompressed bytes`)}}),b=v=>pe(Me(v,t.nByteLength));function m(v){let k=n>>Gt;return v>k}function d(v){return m(v)?a(-v):v}let p=(v,k,V)=>me(v.slice(k,V));class y{constructor(k,V,E){this.r=k,this.s=V,this.recovery=E,this.assertValidity()}static fromCompact(k){let V=t.nByteLength;return k=it("compactSignature",k,V*2),new y(p(k,0,V),p(k,V,2*V))}static fromDER(k){let{r:V,s:E}=ar.toSig(it("DER",k));return new y(V,E)}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(k){return new y(this.r,this.s,k)}recoverPublicKey(k){let{r:V,s:E,recovery:g}=this,I=R(it("msgHash",k));if(g==null||![0,1,2,3].includes(g))throw new Error("recovery id invalid");let C=g===2||g===3?V+t.n:V;if(C>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let D=g&1?"03":"02",M=f.fromHex(D+b(C)),F=c(C),Y=a(-I*F),q=a(E*F),G=f.BASE.multiplyAndAddUnsafe(M,Y,q);if(!G)throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return Je(this.toDERHex())}toDERHex(){return ar.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Je(this.toCompactHex())}toCompactHex(){return b(this.r)+b(this.s)}}let A={isValidPrivateKey(v){try{return u(v),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let v=qi(t.n);return sc(t.randomBytes(v),t.n)},precompute(v=8,k=f.BASE){return k._setWindowSize(v),k.multiply(BigInt(3)),k}};function w(v,k=!0){return f.fromPrivateKey(v).toRawBytes(k)}function _(v){let k=Yt(v),V=typeof v=="string",E=(k||V)&&v.length;return k?E===s||E===i:V?E===2*s||E===2*i:v instanceof f}function x(v,k,V=!0){if(_(v))throw new Error("first arg must be private key");if(!_(k))throw new Error("second arg must be public key");return f.fromHex(k).multiply(u(v)).toRawBytes(V)}let S=t.bits2int||function(v){let k=me(v),V=v.length*8-t.nBitLength;return V>0?k>>BigInt(V):k},R=t.bits2int_modN||function(v){return a(S(v))},N=Yr(t.nBitLength);function z(v){if(typeof v!="bigint")throw new Error("bigint expected");if(!(Te<=v&&v<N))throw new Error(`bigint expected < 2^${t.nBitLength}`);return Me(v,t.nByteLength)}function $(v,k,V=P){if(["recovered","canonical"].some(nt=>nt in V))throw new Error("sign() legacy options not supported");let{hash:E,randomBytes:g}=t,{lowS:I,prehash:C,extraEntropy:D}=V;I==null&&(I=!0),v=it("msgHash",v),C&&(v=it("prehashed msgHash",E(v)));let M=R(v),F=u(k),Y=[z(F),z(M)];if(D!=null){let nt=D===!0?g(e.BYTES):D;Y.push(it("extraEntropy",nt))}let q=ge(...Y),G=M;function lt(nt){let bt=S(nt);if(!h(bt))return;let wt=c(bt),ht=f.BASE.multiply(bt).toAffine(),vt=a(ht.x);if(vt===Te)return;let le=a(wt*a(G+vt*F));if(le===Te)return;let Ye=(ht.x===vt?0:2)|Number(ht.y&Gt),qr=le;return I&&m(le)&&(qr=d(le),Ye^=1),new y(vt,qr,Ye)}return{seed:q,k2sig:lt}}let P={lowS:t.lowS,prehash:!1},ct={lowS:t.lowS,prehash:!1};function ot(v,k,V=P){let{seed:E,k2sig:g}=$(v,k,V),I=t;return Mi(I.hash.outputLen,I.nByteLength,I.hmac)(E,g)}f.BASE._setWindowSize(8);function Ft(v,k,V,E=ct){let g=v;if(k=it("msgHash",k),V=it("publicKey",V),"strict"in E)throw new Error("options.strict was renamed to lowS");let{lowS:I,prehash:C}=E,D,M;try{if(typeof g=="string"||Yt(g))try{D=y.fromDER(g)}catch(ht){if(!(ht instanceof ar.Err))throw ht;D=y.fromCompact(g)}else if(typeof g=="object"&&typeof g.r=="bigint"&&typeof g.s=="bigint"){let{r:ht,s:vt}=g;D=new y(ht,vt)}else throw new Error("PARSE");M=f.fromHex(V)}catch(ht){if(ht.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(I&&D.hasHighS())return!1;C&&(k=t.hash(k));let{r:F,s:Y}=D,q=R(k),G=c(Y),lt=a(q*G),nt=a(F*G),bt=f.BASE.multiplyAndAddUnsafe(M,lt,nt)?.toAffine();return bt?a(bt.x)===F:!1}return{CURVE:t,getPublicKey:w,getSharedSecret:x,sign:ot,verify:Ft,ProjectivePoint:f,Signature:y,utils:A}}function cp(r){return{hash:r,hmac:(t,...e)=>tn(r,t,Sn(...e)),randomBytes:Br}}function wl(r,t){let e=n=>bl({...r,...cp(n)});return Object.freeze({...e(t),create:e})}var El=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),xl=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),lp=BigInt(1),To=BigInt(2),vl=(r,t)=>(r+t/To)/t;function up(r){let t=El,e=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),f=r*r*r%t,u=f*f*r%t,l=et(u,e,t)*u%t,h=et(l,e,t)*u%t,b=et(h,To,t)*f%t,m=et(b,s,t)*b%t,d=et(m,i,t)*m%t,p=et(d,a,t)*d%t,y=et(p,c,t)*p%t,A=et(y,a,t)*d%t,w=et(A,e,t)*u%t,_=et(w,o,t)*m%t,x=et(_,n,t)*f%t,S=et(x,To,t);if(!Io.eql(Io.sqr(S),r))throw new Error("Cannot find square root");return S}var Io=_n(El,void 0,void 0,{sqrt:up}),te=wl({a:BigInt(0),b:BigInt(7),Fp:Io,n:xl,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=xl,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-lp*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=e,o=BigInt("0x100000000000000000000000000000000"),a=vl(i*r,t),c=vl(-n*r,t),f=X(r-a*e-c*s,t),u=X(-a*n-c*i,t),l=f>o,h=u>o;if(l&&(f=t-f),h&&(u=t-u),f>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:f,k2neg:h,k2:u}}}},gl),Wy=BigInt(0);var Yy=te.ProjectivePoint;function Al(){return te.utils.randomPrivateKey()}function Bl(r,t){let e=pt.digest(t instanceof Uint8Array?t:t.subarray());if(Kt(e))return e.then(({digest:n})=>te.sign(n,r).toDERRawBytes()).catch(n=>{throw new L(String(n),"ERR_INVALID_INPUT")});try{return te.sign(e.digest,r).toDERRawBytes()}catch(n){throw new L(String(n),"ERR_INVALID_INPUT")}}function Sl(r,t,e){let n=pt.digest(e instanceof Uint8Array?e:e.subarray());if(Kt(n))return n.then(({digest:s})=>te.verify(t,s,r)).catch(s=>{throw new L(String(s),"ERR_INVALID_INPUT")});try{return te.verify(t,n.digest,r)}catch(s){throw new L(String(s),"ERR_INVALID_INPUT")}}function Tl(r){return te.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Il(r){try{te.getPublicKey(r,!0)}catch(t){throw new L(String(t),"ERR_INVALID_PRIVATE_KEY")}}function ko(r){try{te.ProjectivePoint.fromHex(r)}catch(t){throw new L(String(t),"ERR_INVALID_PUBLIC_KEY")}}function kl(r){try{return te.getPublicKey(r,!0)}catch(t){throw new L(String(t),"ERR_INVALID_PRIVATE_KEY")}}var dn=class{_key;constructor(t){ko(t),this._key=t}verify(t,e){return Sl(this._key,e,t)}marshal(){return Tl(this._key)}get bytes(){return se.encode({Type:rt.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return ut(this.bytes,t.bytes)}async hash(){let t=pt.digest(this.bytes),e;return Kt(t)?{bytes:e}=await t:e=t.bytes,e}},pn=class{_key;_publicKey;constructor(t,e){this._key=t,this._publicKey=e??kl(t),Il(this._key),ko(this._publicKey)}sign(t){return Bl(this._key,t)}get public(){return new dn(this._publicKey)}marshal(){return this._key}get bytes(){return ie.encode({Type:rt.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return ut(this.bytes,t.bytes)}hash(){let t=pt.digest(this.bytes);return Kt(t)?t.then(({bytes:e})=>e):t.bytes}async id(){let t=await this.public.hash();return W(t,"base58btc")}async export(t,e="libp2p-key"){if(e==="libp2p-key")return Rr(this.bytes,t);throw new L(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function hp(r){return new pn(r)}function dp(r){return new dn(r)}async function pp(){let r=Al();return new pn(r)}var cr={rsa:Bo,ed25519:po,secp256k1:Ro};function Rl(r){let t=Object.keys(cr).join(" / ");return new L(`invalid or unsupported key type ${r}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function Nl(r){let t=se.decode(r),e=t.Data??new Uint8Array;switch(t.Type){case rt.RSA:return cr.rsa.unmarshalRsaPublicKey(e);case rt.Ed25519:return cr.ed25519.unmarshalEd25519PublicKey(e);case rt.Secp256k1:return cr.secp256k1.unmarshalSecp256k1PublicKey(e);default:throw Rl(t.Type??"unknown")}}async function _l(r){let t=ie.decode(r),e=t.Data??new Uint8Array;switch(t.Type){case rt.RSA:return cr.rsa.unmarshalRsaPrivateKey(e);case rt.Ed25519:return cr.ed25519.unmarshalEd25519PrivateKey(e);case rt.Secp256k1:return cr.secp256k1.unmarshalSecp256k1PrivateKey(e);default:throw Rl(t.Type??"RSA")}}var Cl=Symbol.for("@achingbrain/uint8arraylist");function Ll(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let s=e+n.byteLength;if(t<s)return{buf:n,index:t-e};e=s}throw new RangeError("index is out of bounds")}function _s(r){return!!r?.[Cl]}var ee=class r{bufs;length;[Cl]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(_s(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(_s(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Ll(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Ll(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(_s(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:s}=this._subList(t,e);return Tt(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:Tt(n,s)}sublist(t,e){let{bufs:n,length:s}=this._subList(t,e),i=new r;return i.length=s,i.bufs=[...n],i}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],a=s,c=a+o.byteLength;if(s=c,t>=c)continue;let f=t>=a&&t<c,u=e>a&&e<=c;if(f&&u){if(t===a&&e===c){n.push(o);break}let l=t-a;n.push(o.subarray(l,l+(e-t)));break}if(f){if(t===0){n.push(o);continue}n.push(o.subarray(t-a));continue}if(u){if(e===c){n.push(o);break}n.push(o.subarray(0,e-a));break}n.push(o)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!_s(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let l=0;l<i;l++)o[l]=-1;for(let l=0;l<s;l++)o[n[l]]=l;let a=o,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let l=e;l<=c;l+=u){u=0;for(let h=f;h>=0;h--){let b=this.get(l+h);if(n[h]!==b){u=Math.max(1,h-a[b]);break}}if(u===0)return l}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=_t(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let s=he(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,e,n),this.write(s,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let s=he(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,e,n),this.write(s,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let s=he(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,e,n),this.write(s,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=_t(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let s=he(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,e,n),this.write(s,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let s=he(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e,n),this.write(s,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let s=he(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,e,n),this.write(s,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let s=he(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,e,n),this.write(s,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let s=he(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,e,n),this.write(s,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!ut(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((s,i)=>s+i.byteLength,0)),n.length=e,n}};var Ul={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var mn;(function(r){let t;r.codec=()=>(t==null&&(t=Vt((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&e.payload.byteLength>0&&(n.uint32(26),n.bytes(e.payload)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:s.publicKey=e.bytes();break;case 2:s.payloadType=e.bytes();break;case 3:s.payload=e.bytes();break;case 5:s.signature=e.bytes();break;default:e.skipType(o&7);break}}return s})),t),r.encode=e=>Pt(e,r.codec()),r.decode=e=>Ot(e,r.codec())})(mn||(mn={}));var gn=class r{static createFromProtobuf=async t=>{let e=mn.decode(t),n=await Fa(e.publicKey);return new r({peerId:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e)=>{if(e.privateKey==null)throw new Error("Missing private key");let n=t.domain,s=t.codec,i=t.marshal(),o=Dl(n,s,i),c=await(await _l(e.privateKey)).sign(o.subarray());return new r({peerId:e,payloadType:s,payload:i,signature:c})};static openAndCertify=async(t,e)=>{let n=await r.createFromProtobuf(t);if(!await n.validate(e))throw new L("envelope signature is not valid for the given domain",Ul.ERR_SIGNATURE_NOT_VALID);return n};peerId;payloadType;payload;signature;marshaled;constructor(t){let{peerId:e,payloadType:n,payload:s,signature:i}=t;this.peerId=e,this.payloadType=n,this.payload=s,this.signature=i}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=mn.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return ut(this.marshal(),t.marshal())}async validate(t){let e=Dl(t,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return Nl(this.peerId.publicKey).verify(e.subarray(),this.signature)}},Dl=(r,t,e)=>{let n=Q(r),s=qt(n.byteLength),i=qt(t.length),o=qt(e.length);return new ee(s,n,i,t,o,e)};var Ls=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,s){return this.readAtomically(()=>{let i=0,o=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let h=Number.parseInt(l,t);if(!Number.isNaN(h))return h});if(u===void 0)break;if(i*=t,i+=u,i>f||(o+=1,e!==void 0&&o>e))return}if(o!==0)return!n&&c&&o>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let s=n*2;if(n<e.length-3){let o=this.readSeparator(":",n,()=>this.readIPv4Addr());if(o!==void 0)return e[s]=o[0],e[s+1]=o[1],e[s+2]=o[2],e[s+3]=o[3],[s+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[s,!1];e[s]=i>>8,e[s+1]=i&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,s]=t(e);if(n===16)return e;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),o=16-(n+2),[a]=t(i.subarray(0,o));return e.set(i.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Ol=45,mp=15,Pr=new Ls;function No(r){if(!(r.length>mp))return Pr.new(r).parseWith(()=>Pr.readIPv4Addr())}function _o(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ol))return Pr.new(r).parseWith(()=>Pr.readIPv6Addr())}function Cs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ol))return Pr.new(r).parseWith(()=>Pr.readIPAddr())}var Ub=parseInt("0xFFFF",16),Db=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Ml(r){return!!No(r)}function Hl(r){return!!_o(r)}function Us(r){return!!Cs(r)}var Fl=Ml,xp=Hl,Lo=function(r){let t=0;if(r=r.toString().trim(),Fl(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(xp(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=Fl(e[n]),o;i&&(o=Lo(e[n]),e[n]=W(o.slice(0,2),"base16")),o!=null&&++n<8&&e.splice(n,0,W(o.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let i=[n,1];for(n=9-e.length;n>0;n--)i.push("0");e.splice.apply(e,i)}let s=new Uint8Array(t+16);for(n=0;n<e.length;n++){let i=parseInt(e[n],16);s[t++]=i>>8&255,s[t++]=i&255}return s}throw new Error("invalid ip address")},Kl=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let s=[];for(let i=0;i<e;i++)s.push(r[t+i]);return s.join(".")}if(e===16){let s=[];for(let i=0;i<e;i+=2)s.push(n.getUint16(t+i).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Vr={},Co={},Ep=[[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"]];Ep.forEach(r=>{let t=Ap(...r);Co[t.code]=t,Vr[t.name]=t});function Ap(r,t,e,n,s){return{code:r,size:t,name:e,resolvable:!!n,path:!!s}}function J(r){if(typeof r=="number"){if(Co[r]!=null)return Co[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Vr[r]!=null)return Vr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var bw=J("ip4"),ww=J("ip6"),xw=J("ipcidr");function Do(r,t){switch(J(r).code){case 4:case 41:return Sp(t);case 42:return Gl(t);case 6:case 273:case 33:case 132:return jl(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Gl(t);case 421:return Rp(t);case 444:return zl(t);case 445:return zl(t);case 466:return kp(t);default:return W(t,"base16")}}function Oo(r,t){switch(J(r).code){case 4:return ql(t);case 41:return ql(t);case 42:return $l(t);case 6:case 273:case 33:case 132:return Po(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return $l(t);case 421:return Tp(t);case 444:return Np(t);case 445:return _p(t);case 466:return Ip(t);default:return Q(t,"base16")}}var Uo=Object.values(Le).map(r=>r.decoder),Bp=function(){let r=Uo[0].or(Uo[1]);return Uo.slice(2).forEach(t=>r=r.or(t)),r}();function ql(r){if(!Us(r))throw new Error("invalid ip address");return Lo(r)}function Sp(r){let t=Kl(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!Us(t))throw new Error("invalid ip address");return t}function Po(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function jl(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function $l(r){let t=Q(r),e=Uint8Array.from(qt(t.length));return Tt([e,t],e.length+t.length)}function Gl(r){let t=we(r);if(r=r.slice(At(t)),r.length!==t)throw new Error("inconsistent lengths");return W(r)}function Tp(r){let t;r[0]==="Q"||r[0]==="1"?t=Ze(dt.decode(`z${r}`)).bytes:t=Ct.parse(r).multihash.bytes;let e=Uint8Array.from(qt(t.length));return Tt([e,t],e.length+t.length)}function Ip(r){let t=Bp.decode(r),e=Uint8Array.from(qt(t.length));return Tt([e,t],e.length+t.length)}function kp(r){let t=we(r),e=r.slice(At(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+W(e,"base64url")}function Rp(r){let t=we(r),e=r.slice(At(t));if(e.length!==t)throw new Error("inconsistent lengths");return W(e,"base58btc")}function Np(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=fe.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Po(n);return Tt([e,s],e.length+s.length)}function _p(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=fe.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Po(n);return Tt([e,s],e.length+s.length)}function zl(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=W(t,"base32"),s=jl(e);return`${n}:${s}`}function Wl(r){r=Vo(r);let t=[],e=[],n=null,s=r.split("/").slice(1);if(s.length===1&&s[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i<s.length;i++){let o=s[i],a=J(o);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(i++,i>=s.length)throw Zl("invalid address: "+r);if(a.path===!0){n=Vo(s.slice(i).join("/")),t.push([a.code,Oo(a.code,n)]),e.push([a.code,n]);break}let c=Oo(a.code,s[i]);t.push([a.code,c]),e.push([a.code,Do(a.code,c)])}return{string:Yl(e),bytes:Ho(t),tuples:t,stringTuples:e,path:n}}function Mo(r){let t=[],e=[],n=null,s=0;for(;s<r.length;){let i=we(r,s),o=At(i),a=J(i),c=Lp(a,r.slice(s+o));if(c===0){t.push([i]),e.push([i]),s+=o;continue}let f=r.slice(s+o,s+o+c);if(s+=c+o,s>r.length)throw Zl("Invalid address Uint8Array: "+W(r,"base16"));t.push([i,f]);let u=Do(i,f);if(e.push([i,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:Yl(e),tuples:t,stringTuples:e,path:n}}function Yl(r){let t=[];return r.map(e=>{let n=J(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Vo(t.join("/"))}function Ho(r){return Tt(r.map(t=>{let e=J(t[0]),n=Uint8Array.from(qt(e.code));return t.length>1&&t[1]!=null&&(n=Tt([n,t[1]])),n}))}function Lp(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=we(t instanceof Uint8Array?t:Uint8Array.from(t));return e+At(e)}}function Vo(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function Zl(r){return new Error("Error parsing address: "+r)}var Cp=Symbol.for("nodejs.util.inspect.custom"),Fo=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Up=[J("dns").code,J("dns4").code,J("dns6").code,J("dnsaddr").code],Ds=class r{bytes;#t;#e;#r;#n;[Fo]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Mo(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Wl(t)}else if(Jl(t))e=Mo(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,s,i="",o=J("tcp"),a=J("udp"),c=J("ip4"),f=J("ip6"),u=J("dns6"),l=J("ip6zone");for(let[b,m]of this.stringTuples())b===l.code&&(i=`%${m??""}`),Up.includes(b)&&(e=o.name,s=443,n=`${m??""}${i}`,t=b===u.code?6:4),(b===o.code||b===a.code)&&(e=J(b).name,s=parseInt(m??"")),(b===c.code||b===f.code)&&(e=J(b).name,n=`${m??""}${i}`,t=b===f.code?6:4);if(t==null||e==null||n==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:s}}protos(){return this.#e.map(([t])=>Object.assign({},J(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>J(t).name)}tuples(){return this.#e}stringTuples(){return this.#r}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),s=n.lastIndexOf(e);if(s<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,s))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(Ho(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,s])=>{n===Vr.p2p.code&&t.push([n,s]),n===Vr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?W(dt.decode(`z${n}`),"base58btc"):W(Ct.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return ut(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(i=>i.resolvable);if(e==null)return[this];let n=Xl.get(e.name);if(n==null)throw new L(`no available resolver for ${e.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,t)).map(i=>new r(i))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[Cp](){return`Multiaddr(${this.#t})`}};var Xl=new Map;function Jl(r){return!!r?.[Fo]}function Rt(r){return new Ds(r)}function Mt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Os=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function Ps(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new Os(e?.errorMessage,e?.errorCode));let n,s=new Os(e?.errorMessage,e?.errorCode);try{return await Promise.race([r,new Promise((i,o)=>{n=()=>{o(s)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var Ko=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=Mt(),this.haveNext=Mt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Mt(),t}async throw(t){return this.ended=!0,t!=null&&this.haveNext.reject(t),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return await this._push(void 0),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw 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");t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Mt(),await Ps(this.readNext.promise,e?.signal,e)}};function Ql(){return new Ko}var Vs=class extends Error{code;constructor(t,e){super(t),this.code=e}},qo=class extends Vs{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted"}};function tu(r,t){let e=Ql();r.sink(e).catch(async o=>{await e.end(o)}),r.sink=async o=>{for await(let a of o)await e.push(a);await e.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 s=new ee;return{read:async(o,a)=>{a?.signal?.throwIfAborted();let c,f=new Promise((u,l)=>{c=()=>{l(new qo("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(o==null){let{done:l,value:h}=await Promise.race([n.next(),f]);return l===!0?new ee:h}for(;s.byteLength<o;){let{value:l,done:h}=await Promise.race([n.next(),f]);if(h===!0)throw new Vs("unexpected end of input","ERR_UNEXPECTED_EOF");s.append(l)}let u=s.sublist(0,o);return s.consume(o),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(o,a)=>{a?.signal?.throwIfAborted(),o instanceof Uint8Array?await e.push(o,a):await e.push(o.subarray(),a)},unwrap:()=>{if(s.byteLength>0){let o=r.source;r.source=async function*(){t?.yieldBytes===!1?yield s:yield*s,yield*o}()}return r}}}var Ms=class extends Error{code;constructor(t,e){super(t),this.code=e}};function eu(r,t={}){let e=tu(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=At(t.maxDataLength));let n=t?.lengthDecoder??we,s=t?.lengthEncoder??qt;return{read:async o=>{let a=-1,c=new ee;for(;;){c.append(await e.read(1,o));try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ms("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Ms("message length too long","ERR_MSG_DATA_TOO_LONG");return e.read(a,o)},write:async(o,a)=>{await e.write(new ee(s(o.byteLength),o),a)},writeV:async(o,a)=>{let c=new ee(...o.flatMap(f=>[s(f.byteLength),f]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function je(r,t){let e=eu(r,t),n={read:async(s,i)=>{let o=await e.read(i);return s.decode(o)},write:async(s,i,o)=>{await e.write(i.encode(s),o)},writeV:async(s,i,o)=>{await e.writeV(s.map(a=>i.encode(a)),o)},pb:s=>({read:async i=>n.read(s,i),write:async(i,o)=>n.write(i,s,o),writeV:async(i,o)=>n.writeV(i,s,o),unwrap:()=>n}),unwrap:()=>e.unwrap()};return n}var Hs="/libp2p/relay";var ru="circuit-relay-source",nu="circuit-relay-relay";var su=BigInt(131072),zt="/libp2p/circuit/relay/0.2.0/hop",lr="/libp2p/circuit/relay/0.2.0/stop",iu=30*1e3,ou=30*1e3,yn=300,au="ERR_NO_ROUTERS_AVAILABLE",$o="ERR_RELAYED_DIAL",cu="ERR_HOP_REQUEST_FAILED",Fs="ERR_TRANSFER_LIMIT_EXCEEDED";var Z;(function(r){let t;(function(s){s.RESERVE="RESERVE",s.CONNECT="CONNECT",s.STATUS="STATUS"})(t=r.Type||(r.Type={}));let e;(function(s){s[s.RESERVE=0]="RESERVE",s[s.CONNECT=1]="CONNECT",s[s.STATUS=2]="STATUS"})(e||(e={})),function(s){s.codec=()=>nr(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Vt((s,i,o={})=>{o.lengthDelimited!==!1&&i.fork(),s.type!=null&&(i.uint32(8),r.Type.codec().encode(s.type,i)),s.peer!=null&&(i.uint32(18),Mr.codec().encode(s.peer,i)),s.reservation!=null&&(i.uint32(26),Ks.codec().encode(s.reservation,i)),s.limit!=null&&(i.uint32(34),Hr.codec().encode(s.limit,i)),s.status!=null&&(i.uint32(40),H.codec().encode(s.status,i)),o.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let o={},a=i==null?s.len:s.pos+i;for(;s.pos<a;){let c=s.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(s);break;case 2:o.peer=Mr.codec().decode(s,s.uint32());break;case 3:o.reservation=Ks.codec().decode(s,s.uint32());break;case 4:o.limit=Hr.codec().decode(s,s.uint32());break;case 5:o.status=H.codec().decode(s);break;default:s.skipType(c&7);break}}return o})),n),r.encode=s=>Pt(s,r.codec()),r.decode=s=>Ot(s,r.codec())})(Z||(Z={}));var Ht;(function(r){let t;(function(s){s.CONNECT="CONNECT",s.STATUS="STATUS"})(t=r.Type||(r.Type={}));let e;(function(s){s[s.CONNECT=0]="CONNECT",s[s.STATUS=1]="STATUS"})(e||(e={})),function(s){s.codec=()=>nr(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Vt((s,i,o={})=>{o.lengthDelimited!==!1&&i.fork(),s.type!=null&&(i.uint32(8),r.Type.codec().encode(s.type,i)),s.peer!=null&&(i.uint32(18),Mr.codec().encode(s.peer,i)),s.limit!=null&&(i.uint32(26),Hr.codec().encode(s.limit,i)),s.status!=null&&(i.uint32(32),H.codec().encode(s.status,i)),o.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let o={},a=i==null?s.len:s.pos+i;for(;s.pos<a;){let c=s.uint32();switch(c>>>3){case 1:o.type=r.Type.codec().decode(s);break;case 2:o.peer=Mr.codec().decode(s,s.uint32());break;case 3:o.limit=Hr.codec().decode(s,s.uint32());break;case 4:o.status=H.codec().decode(s);break;default:s.skipType(c&7);break}}return o})),n),r.encode=s=>Pt(s,r.codec()),r.decode=s=>Ot(s,r.codec())})(Ht||(Ht={}));var Mr;(function(r){let t;r.codec=()=>(t==null&&(t=Vt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.id!=null&&e.id.byteLength>0&&(n.uint32(10),n.bytes(e.id)),e.addrs!=null)for(let i of e.addrs)n.uint32(18),n.bytes(i);s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={id:new Uint8Array(0),addrs:[]},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:s.id=e.bytes();break;case 2:s.addrs.push(e.bytes());break;default:e.skipType(o&7);break}}return s})),t),r.encode=e=>Pt(e,r.codec()),r.decode=e=>Ot(e,r.codec())})(Mr||(Mr={}));var Ks;(function(r){let t;r.codec=()=>(t==null&&(t=Vt((e,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),e.expire!=null&&e.expire!==0n&&(n.uint32(8),n.uint64(e.expire)),e.addrs!=null)for(let i of e.addrs)n.uint32(18),n.bytes(i);e.voucher!=null&&(n.uint32(26),n.bytes(e.voucher)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={expire:0n,addrs:[]},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:s.expire=e.uint64();break;case 2:s.addrs.push(e.bytes());break;case 3:s.voucher=e.bytes();break;default:e.skipType(o&7);break}}return s})),t),r.encode=e=>Pt(e,r.codec()),r.decode=e=>Ot(e,r.codec())})(Ks||(Ks={}));var Hr;(function(r){let t;r.codec=()=>(t==null&&(t=Vt((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.duration!=null&&(n.uint32(8),n.uint32(e.duration)),e.data!=null&&(n.uint32(16),n.uint64(e.data)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:s.duration=e.uint32();break;case 2:s.data=e.uint64();break;default:e.skipType(o&7);break}}return s})),t),r.encode=e=>Pt(e,r.codec()),r.decode=e=>Ot(e,r.codec())})(Hr||(Hr={}));var H;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(H||(H={}));var Go;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(Go||(Go={}));(function(r){r.codec=()=>nr(Go)})(H||(H={}));var qs;(function(r){let t;r.codec=()=>(t==null&&(t=Vt((e,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),e.relay!=null&&e.relay.byteLength>0&&(n.uint32(10),n.bytes(e.relay)),e.peer!=null&&e.peer.byteLength>0&&(n.uint32(18),n.bytes(e.peer)),e.expiration!=null&&e.expiration!==0n&&(n.uint32(24),n.uint64(e.expiration)),s.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let s={relay:new Uint8Array(0),peer:new Uint8Array(0),expiration:0n},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let o=e.uint32();switch(o>>>3){case 1:s.relay=e.bytes();break;case 2:s.peer=e.bytes();break;case 3:s.expiration=e.uint64();break;default:e.skipType(o&7);break}}return s})),t),r.encode=e=>Pt(e,r.codec()),r.decode=e=>Ot(e,r.codec())})(qs||(qs={}));function lu(r){let t=new globalThis.AbortController;function e(){t.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let i of r){if(i?.aborted===!0){e();break}i?.addEventListener!=null&&i.addEventListener("abort",e)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}let s=t.signal;return s.clear=n,s}async function*uu(r,t,e){let n=t.remaining;for await(let s of r){let i=BigInt(s.byteLength);if(t.remaining-i<0){let o=Number(t.remaining);t.remaining=0n;try{o!==0&&(yield s.subarray(0,o))}catch(a){e.log.error(a)}throw new L(`data limit of ${n} bytes exceeded`,Fs)}t.remaining-=i,yield s}}function fu(r,t,e,n,s){function i(l){r.abort(l),t.abort(l)}let o=[e];n?.duration!=null&&o.push(AbortSignal.timeout(n.duration));let a=lu(o),c=!1,f=!1,u;n?.data!=null&&(u={remaining:n.data}),queueMicrotask(()=>{let l=()=>{t.abort(new L(`duration limit of ${n?.duration} ms exceeded`,Fs))};a.addEventListener("abort",l,{once:!0}),t.sink(u==null?r.source:uu(r.source,u,s)).catch(h=>{s.log.error("error while relaying streams src -> dst",h),i(h)}).finally(()=>{c=!0,f&&(a.removeEventListener("abort",l),a.clear())})}),queueMicrotask(()=>{let l=()=>{r.abort(new L(`duration limit of ${n?.duration} ms exceeded`,Fs))};a.addEventListener("abort",l,{once:!0}),r.sink(u==null?t.source:uu(t.source,u,s)).catch(h=>{s.log.error("error while relaying streams dst -> src",h),i(h)}).finally(()=>{f=!0,c&&(a.removeEventListener("abort",l),a.clear())})})}async function $s(r){let t=new TextEncoder().encode(r),e=await pt.digest(t);return Ct.createV0(e)}function zo(r){let t=r*BigInt(1e3),e=new Date().getTime();return Number(t-BigInt(e))}var bu=ya(gu(),1);var Op=Object.prototype.toString,Pp=r=>Op.call(r)==="[object Error]",Vp=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed"]);function jo(r){return r&&Pp(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:Vp.has(r.message):!1}var Wo=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}},yu=(r,t,e)=>{let n=e.retries-(t-1);return r.attemptNumber=t,r.retriesLeft=n,r};async function Yo(r,t){return new Promise((e,n)=>{t={onFailedAttempt(){},retries:10,shouldRetry:()=>!0,...t};let s=bu.default.operation(t),i=()=>{s.stop(),n(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",i,{once:!0});let o=()=>{t.signal?.removeEventListener("abort",i),s.stop()};s.attempt(async a=>{try{let c=await r(a);o(),e(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof Wo)throw c.originalError;if(c instanceof TypeError&&!jo(c))throw c;if(yu(c,a,t),await t.shouldRetry(c)||(s.stop(),n(c)),await t.onFailedAttempt(c),!s.retry(c))throw s.mainError()}catch(f){yu(f,a,t),o(),n(f)}}})})}var Gs=class extends Nt{contentRouting;timeout;started;bootDelay;log;constructor(t,e){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:advert-service"),this.contentRouting=t.contentRouting,this.bootDelay=e?.bootDelay??ou,this.started=!1}isStarted(){return this.started}start(){this.started||(this.timeout=setTimeout(()=>{this._advertiseService().catch(t=>{this.log.error("could not advertise service",t)})},this.bootDelay),this.started=!0)}stop(){try{clearTimeout(this.timeout)}catch{}this.started=!1}async _advertiseService(){await Yo(async()=>{try{let t=await $s(Hs);await this.contentRouting.provide(t),this.safeDispatchEvent("advert:success",{detail:void 0})}catch(t){if(this.safeDispatchEvent("advert:error",{detail:t}),t.code===au){this.log.error("a content router, such as a DHT, must be provided in order to advertise the relay service",t),this.stop();return}throw this.log.error("could not advertise service",t),t}})}};function Zo(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:t(s)}}};return e}var Ie=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return Zo(this.map.entries(),t=>[Ce(t[0]),t[1]])}forEach(t){this.map.forEach((e,n)=>{t(e,Ce(n),this)})}get(t){return this.map.get(t.toString())}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),e)}keys(){return Zo(this.map.keys(),t=>Ce(t))}values(){return this.map.values()}get size(){return this.map.size}};var zs=class{reservations=new Ie;_started=!1;interval;maxReservations;reservationClearInterval;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;constructor(t={}){this.maxReservations=t.maxReservations??15,this.reservationClearInterval=t.reservationClearInterval??3e5,this.applyDefaultLimit=t.applyDefaultLimit!==!1,this.reservationTtl=t.reservationTtl??72e5,this.defaultDurationLimit=t.defaultDurationLimit??12e4,this.defaultDataLimit=t.defaultDataLimit??su}isStarted(){return this._started}start(){this._started||(this._started=!0,this.interval=setInterval(()=>{let t=new Date().getTime();this.reservations.forEach((e,n)=>{e.expire.getTime()<t&&this.reservations.delete(n)})},this.reservationClearInterval))}stop(){clearInterval(this.interval)}reserve(t,e,n){if(this.reservations.size>=this.maxReservations&&!this.reservations.has(t))return{status:H.RESERVATION_REFUSED};let s=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),this.reservations.set(t,{addr:e,expire:s,limit:i}),{status:H.OK,expire:Math.round(s.getTime()/1e3)}}removeReservation(t){this.reservations.delete(t)}hasReservation(t){return this.reservations.has(t)}get(t){return this.reservations.get(t)}};var js=class r{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:t,peer:e,expiration:n}){this.relay=t,this.peer=e,this.expiration=n}marshal(){return qs.encode({relay:this.relay.toBytes(),peer:this.peer.toBytes(),expiration:BigInt(this.expiration)})}equals(t){return!(!(t instanceof r)||!this.peer.equals(t.peer)||!this.relay.equals(t.relay)||this.expiration!==t.expiration)}};var wu=r=>r.protoCodes().includes(290),qp={maxOutboundStopStreams:yn},Xo=class extends Nt{registrar;peerStore;addressManager;peerId;connectionManager;connectionGater;reservationStore;advertService;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:server"),this.registrar=t.registrar,this.peerStore=t.peerStore,this.addressManager=t.addressManager,this.peerId=t.peerId,this.connectionManager=t.connectionManager,this.connectionGater=t.connectionGater,this.started=!1,this.hopTimeout=e?.hopTimeout??iu,this.shutdownController=new AbortController,this.maxInboundHopStreams=e.maxInboundHopStreams,this.maxOutboundHopStreams=e.maxOutboundHopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??qp.maxOutboundStopStreams,xn(1/0,this.shutdownController.signal),e.advertise!=null&&e.advertise!==!1&&(this.advertService=new Gs(t,e.advertise===!0?void 0:e.advertise),this.advertService.addEventListener("advert:success",()=>{this.safeDispatchEvent("relay:advert:success",{})}),this.advertService.addEventListener("advert:error",n=>{this.safeDispatchEvent("relay:advert:error",{detail:n.detail})})),this.reservationStore=new zs(e.reservations)}isStarted(){return this.started}async start(){this.started||(this.advertService?.start(),await this.registrar.handle(zt,t=>{this.onHop(t).catch(e=>{this.log.error(e)})},{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnTransientConnection:!0}),this.reservationStore.start(),this.started=!0)}async stop(){this.advertService?.stop(),this.reservationStore.stop(),this.shutdownController.abort(),await this.registrar.unhandle(zt),this.started=!1}async onHop({connection:t,stream:e}){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n=Mt(),s=setTimeout(()=>{n.reject("timed out")},this.hopTimeout),i=je(e);try{let o=await Promise.race([i.pb(Z).read(),n.promise]);if(o?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",o.type),await Promise.race([this.handleHopProtocol({connection:t,stream:i,request:o}),n.promise])}catch(o){this.log.error("error while handling hop",o),await i.pb(Z).write({type:Z.Type.STATUS,status:H.MALFORMED_MESSAGE}),e.abort(o)}finally{clearTimeout(s)}}async handleHopProtocol({stream:t,request:e,connection:n}){switch(this.log("received hop message"),e.type){case Z.Type.RESERVE:await this.handleReserve({stream:t,request:e,connection:n});break;case Z.Type.CONNECT:await this.handleConnect({stream:t,request:e,connection:n});break;default:this.log.error("invalid hop request type %s via peer %p",e.type,n.remotePeer),await t.pb(Z).write({type:Z.Type.STATUS,status:H.UNEXPECTED_MESSAGE})}}async handleReserve({stream:t,request:e,connection:n}){let s=t.pb(Z);if(this.log("hop reserve request from %p",n.remotePeer),wu(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await s.write({type:Z.Type.STATUS,status:H.PERMISSION_DENIED});return}if(await this.connectionGater.denyInboundRelayReservation?.(n.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",n.remotePeer),await s.write({type:Z.Type.STATUS,status:H.PERMISSION_DENIED});return}let i=this.reservationStore.reserve(n.remotePeer,n.remoteAddr);if(i.status!==H.OK){await s.write({type:Z.Type.STATUS,status:i.status});return}try{if(i.expire!=null){let o=i.expire*1e3-Date.now();await this.peerStore.merge(n.remotePeer,{tags:{[ru]:{value:1,ttl:o}}})}await s.write({type:Z.Type.STATUS,status:H.OK,reservation:await this.makeReservation(n.remotePeer,BigInt(i.expire??0)),limit:this.reservationStore.get(n.remotePeer)?.limit}),this.log("sent confirmation response to %s",n.remotePeer)}catch(o){this.log.error("failed to send confirmation response to %p",n.remotePeer,o),this.reservationStore.removeReservation(n.remotePeer)}}async makeReservation(t,e){let n=[];for(let i of this.addressManager.getAddresses())i.toString().includes("/p2p-circuit")||n.push(i.bytes);let s=await gn.seal(new js({peer:t,relay:this.peerId,expiration:Number(e)}),this.peerId);return{addrs:n,expire:e,voucher:s.marshal()}}async handleConnect({stream:t,request:e,connection:n}){let s=t.pb(Z);if(wu(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await s.write({type:Z.Type.STATUS,status:H.PERMISSION_DENIED});return}this.log("hop connect request from %p",n.remotePeer);let i;try{if(e.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");e.peer.addrs.forEach(Rt),i=Wr(e.peer.id)}catch(l){this.log.error("invalid hop connect request via peer %p %s",n.remotePeer,l),await s.write({type:Z.Type.STATUS,status:H.MALFORMED_MESSAGE});return}if(!this.reservationStore.hasReservation(i)){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",i,n.remotePeer,H.NO_RESERVATION),await s.write({type:Z.Type.STATUS,status:H.NO_RESERVATION});return}if(await this.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,i)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,i),await s.write({type:Z.Type.STATUS,status:H.PERMISSION_DENIED});return}let o=this.connectionManager.getConnections(i);if(o.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",i,n.remotePeer),await s.write({type:Z.Type.STATUS,status:H.NO_RESERVATION});return}let a=o[0],c=await this.stopHop({connection:a,request:{type:Ht.Type.CONNECT,peer:{id:n.remotePeer.toBytes(),addrs:[]}}});if(c==null){this.log.error("failed to open stream to destination peer %p",a?.remotePeer),await s.write({type:Z.Type.STATUS,status:H.CONNECTION_FAILED});return}await s.write({type:Z.Type.STATUS,status:H.OK});let f=t.unwrap();this.log("connection from %p to %p established - merging streams",n.remotePeer,i);let u=this.reservationStore.get(i)?.limit;fu(f,c,this.shutdownController.signal,u,{log:this.log})}async stopHop({connection:t,request:e}){this.log("starting circuit relay v2 stop request to %s",t.remotePeer);let n=await t.newStream([lr],{maxOutboundStreams:this.maxOutboundStopStreams,runOnTransientConnection:!0}),s=je(n),i=s.pb(Ht);await i.write(e);let o;try{o=await i.read()}catch{this.log.error("error parsing stop message response from %p",t.remotePeer)}if(o==null){this.log.error("could not read response from %p",t.remotePeer),await n.close();return}if(o.status===H.OK)return this.log("stop request to %p was successful",t.remotePeer),s.unwrap();this.log("stop request failed with code %d",o.status),await n.close()}get reservations(){return this.reservationStore.reservations}};function xu(r={}){return t=>new Xo(t,r)}var Ws=class extends Nt{peerId;peerStore;contentRouting;registrar;started;topologyId;log;constructor(t){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.started=!1,this.peerId=t.peerId,this.peerStore=t.peerStore,this.contentRouting=t.contentRouting,this.registrar=t.registrar}isStarted(){return this.started}async start(){this.topologyId=await this.registrar.register(zt,{notifyOnTransient:!0,onConnect:t=>{this.safeDispatchEvent("relay:discover",{detail:t})}}),this.started=!0}afterStart(){this.discover().catch(t=>{this.log.error("error discovering relays",t)})}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async discover(){this.log("searching peer store for relays");let t=await this.peerStore.all({filters:[e=>e.protocols.includes(zt)],orders:[()=>Math.random()<.5?1:-1]});for(let e of t)this.log("found relay peer %p in content peer store",e.id),this.safeDispatchEvent("relay:discover",{detail:e.id});this.log("found %d relay peers in peer store",t.length);try{this.log("searching content routing for relays");let e=await $s(Hs),n=0;for await(let s of this.contentRouting.findProviders(e))if(s.multiaddrs.length>0&&!s.id.equals(this.peerId)){let i=s.id;n++,await this.peerStore.merge(i,{multiaddrs:s.multiaddrs}),this.log("found relay peer %p in content routing",i),this.safeDispatchEvent("relay:discover",{detail:i})}this.log("found %d relay peers in content routing",n)}catch(e){this.log.error("failed when finding relays on the network",e)}}};var Ys=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Fr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Ys(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new Ys(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Qo=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function vu(r={}){return $p(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function $p(r,t){t=t??{};let e=t.onEnd,n=new Fr,s,i,o,a=Mt(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((p,y)=>{i=A=>{i=null,n.push(A);try{p(r(n))}catch(w){y(w)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Mt()})}},f=p=>i!=null?i(p):(n.push(p),s),u=p=>(n=new Fr,i!=null?i({error:p}):(n.push({error:p}),s)),l=p=>{if(o)return s;if(t?.objectMode!==!0&&p?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:p})},h=p=>o?s:(o=!0,p!=null?u(p):f({done:!0})),b=()=>(n=new Fr,h(),{done:!0}),m=p=>(h(p),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:b,throw:m,push:l,end:h,get readableLength(){return n.size},onEmpty:async p=>{let y=p?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let A,w;y!=null&&(A=new Promise((_,x)=>{w=()=>{x(new Qo)},y.addEventListener("abort",w)}));try{await Promise.race([a.promise,A])}finally{w!=null&&y!=null&&y?.removeEventListener("abort",w)}}},e==null)return s;let d=s;return s={[Symbol.asyncIterator](){return this},next(){return d.next()},throw(p){return d.throw(p),e!=null&&(e(p),e=void 0),{done:!0}},return(){return d.return(),e!=null&&(e(),e=void 0),{done:!0}},push:l,end(p){return d.end(p),e!=null&&(e(p),e=void 0),s},get readableLength(){return d.readableLength},onEmpty:p=>d.onEmpty(p)},s}var ta=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function Zs(r,t,e,n){let s=new ta(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(s):new Promise((i,o)=>{let a=f=>{n?.filter?.(f)!==!1&&(r.removeEventListener(t,a),e?.removeEventListener("abort",c),i(f))},c=()=>{r.removeEventListener(t,a),e?.removeEventListener("abort",c),o(s)};r.addEventListener(t,a),e?.addEventListener("abort",c)})}var Xs=class{deferred;signal;where;constructor(t,e){this.signal=e,this.deferred=Mt(),this.where=t,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(new Re)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Gp(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Js=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(t,e,n=0){this.id=Gp(),this.status="queued",this.fn=t,this.priority=n,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,xn(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&this.controller.abort(new Re)}async join(t={}){let e=new Xs(new Error("where").stack,t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await Ps(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.signal?.removeEventListener("abort",this.onAbort)})}};function zp(r,t,e){let n=0,s=r.length;for(;s>0;){let i=Math.trunc(s/2),o=n+i;e(r[o],t)<=0?(n=++o,s-=i+1):s=i}return n}var Qs=class extends Nt{concurrency;queue;pending;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.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 t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){if(this.queue[this.size-1]?.priority>=t.priority){this.queue.push(t);return}let e=zp(this.queue,t,(n,s)=>s.priority-n.priority);this.queue.splice(e,0,t)}async add(t,e){e?.signal?.throwIfAborted();let n=new Js(t,e,e?.priority),s=n.join(e).then(i=>(this.safeDispatchEvent("completed",{detail:i}),i)).catch(i=>{throw this.safeDispatchEvent("error",{detail:i}),i});return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),s}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Re)}),this.clear()}async onEmpty(t){this.size!==0&&await Zs(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await Zs(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Zs(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=vu({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},s=c=>{c.detail!=null&&e.push(c.detail)},i=c=>{n(c.detail)},o=()=>{n()},a=()=>{n(new L("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",s),this.addEventListener("error",i),this.addEventListener("idle",o),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",s),this.removeEventListener("error",i),this.removeEventListener("idle",o),t?.signal?.removeEventListener("abort",a),n()}}};var ti=class extends Qs{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var Wp=60*1e3*10,Yp=60*1e3*5,Zp=30*1e3,ei=class extends Nt{peerId;connectionManager;transportManager;peerStore;events;reserveQueue;reservations;maxDiscoveredRelays;maxReservationQueueLength;reservationCompletionTimeout;started;log;constructor(t,e){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=t.peerId,this.connectionManager=t.connectionManager,this.transportManager=t.transportManager,this.peerStore=t.peerStore,this.events=t.events,this.reservations=new Ie,this.maxDiscoveredRelays=e?.discoverRelays??0,this.maxReservationQueueLength=e?.maxReservationQueueLength??100,this.reservationCompletionTimeout=e?.reservationCompletionTimeout??1e4,this.started=!1,this.reserveQueue=new ti({concurrency:e?.reservationConcurrency??1,metricName:"libp2p_relay_reservation_queue",metrics:t.metrics}),this.events.addEventListener("peer:disconnect",n=>{this.#e(n.detail)})}isStarted(){return this.started}start(){this.started=!0}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:t})=>{clearTimeout(t)}),this.reservations.clear(),this.started=!1}async addRelay(t,e){if(this.peerId.equals(t)){this.log("not trying to use self as relay");return}if(this.reserveQueue.size>this.maxReservationQueueLength){this.log("not adding relay as the queue is full");return}if(this.reserveQueue.has(t)){this.log("relay peer is already in the reservation queue");return}this.log("add relay %p",t),await this.reserveQueue.add(async()=>{try{let n=this.reservations.get(t);if(n!=null){if(zo(n.reservation.expire)>Wp){this.log("already have reservation on relay peer %p and it expires in more than 10 minutes",t);return}clearTimeout(n.timeout),this.reservations.delete(t)}if(e==="discovered"&&[...this.reservations.values()].reduce((u,l)=>(l.type==="discovered"&&u++,u),0)>=this.maxDiscoveredRelays){this.log("already have enough discovered relays");return}let s=AbortSignal.timeout(this.reservationCompletionTimeout),i=await this.connectionManager.openConnection(t,{signal:s});if(i.remoteAddr.protoNames().includes("p2p-circuit")){this.log("not creating reservation over relayed connection");return}let o=await this.#t(i,{signal:s});this.log("created reservation on relay peer %p",t);let a=zo(o.expire),c=Math.min(Math.max(a-Yp,Zp),Math.pow(2,31)-1),f=setTimeout(()=>{this.addRelay(t,e).catch(u=>{this.log.error("could not refresh reservation to relay %p",t,u)})},c);this.reservations.set(t,{timeout:f,reservation:o,type:e}),await this.peerStore.merge(t,{tags:{[nu]:{value:1,ttl:a}}}),await this.transportManager.listen([Rt(`/p2p/${t.toString()}/p2p-circuit`)])}catch(n){this.log.error("could not reserve slot on %p",t,n);let s=this.reservations.get(t);s!=null&&clearTimeout(s.timeout),this.reservations.delete(t)}},{peerId:t})}hasReservation(t){return this.reservations.has(t)}getReservation(t){return this.reservations.get(t)?.reservation}async#t(t,e){e.signal?.throwIfAborted(),this.log("requesting reservation from %p",t.remotePeer);let n=await t.newStream(zt,e),i=je(n).pb(Z);await i.write({type:Z.Type.RESERVE},e);let o;try{o=await i.read(e)}catch(c){throw this.log.error("error parsing reserve message response from %p because",t.remotePeer,c),n.abort(c),c}finally{await n.close()}if(o.status===H.OK&&o.reservation!=null){let c=!1,f=t.remoteAddr.bytes;for(let u of o.reservation.addrs)if(ut(f,u)){c=!0;break}return c||o.reservation.addrs.push(f),o.reservation}let a=`reservation failed with status ${o.status??"undefined"}`;throw this.log.error(a),new Error(a)}#e(t){let e=this.reservations.get(t);e!=null&&(this.log("connection to relay %p closed, removing reservation from local store",t),clearTimeout(e.timeout),this.reservations.delete(t),this.safeDispatchEvent("relay:removed",{detail:t}),this.reservations.size<this.maxDiscoveredRelays&&(this.log("not enough relays %d/%d",this.reservations.size,this.maxDiscoveredRelays),this.safeDispatchEvent("relay:not-enough-relays",{})))}};function ea(r){let{stream:t,remoteAddr:e,logger:n}=r,s=n.forComponent("libp2p:stream:converter"),i=!1,o=!1,a=t.close.bind(t);t.close=async h=>{await a(h),l(!0)};let c=t.abort.bind(t);t.abort=h=>{c(h),l(!0)};let f=t.sink.bind(t);t.sink=async h=>{try{await f(h)}catch(b){b.type!=="aborted"&&s.error("%s error in sink",e,b)}finally{o=!0,l()}};let u={log:s,sink:t.sink,source:async function*(){try{for await(let h of t.source)h instanceof Uint8Array?yield h:yield*h}finally{i=!0,l()}}(),remoteAddr:e,timeline:{open:Date.now(),close:void 0},close:t.close,abort:t.abort};function l(h){h===!0&&(i=!0,o=!0),i&&o&&u.timeline.close==null&&(u.timeline.close=Date.now())}return u}var Xp=B("dns4"),Jp=B("dns6"),Qp=B("dnsaddr"),fr=at(B("dns"),Qp,Xp,Jp),si=at(B("ip4"),B("ip6")),Kr=at(U(si,B("tcp")),U(fr,B("tcp"))),ii=U(si,B("udp")),t0=U(ii,B("utp")),e0=U(ii,B("quic")),r0=U(ii,B("quic-v1")),ra=at(U(Kr,B("ws")),U(fr,B("ws"))),ri=at(U(ra,B("p2p")),ra),na=at(U(Kr,B("wss")),U(fr,B("wss")),U(Kr,B("tls"),B("ws")),U(fr,B("tls"),B("ws"))),ni=at(U(na,B("p2p")),na),sa=at(U(Kr,B("http")),U(si,B("http")),U(fr,B("http"))),ia=at(U(Kr,B("https")),U(si,B("https")),U(fr,B("https"))),Eu=U(ii,B("webrtc-direct"),B("certhash")),Su=at(U(Eu,B("p2p")),Eu),Au=U(r0,B("webtransport"),B("certhash"),B("certhash")),Tu=at(U(Au,B("p2p")),Au),Iu=at(U(ri,B("p2p-webrtc-star"),B("p2p")),U(ni,B("p2p-webrtc-star"),B("p2p")),U(ri,B("p2p-webrtc-star")),U(ni,B("p2p-webrtc-star"))),Dv=at(U(ri,B("p2p-websocket-star"),B("p2p")),U(ni,B("p2p-websocket-star"),B("p2p")),U(ri,B("p2p-websocket-star")),U(ni,B("p2p-websocket-star"))),ku=at(U(sa,B("p2p-webrtc-direct"),B("p2p")),U(ia,B("p2p-webrtc-direct"),B("p2p")),U(sa,B("p2p-webrtc-direct")),U(ia,B("p2p-webrtc-direct"))),hr=at(ra,na,sa,ia,Iu,ku,Kr,t0,e0,fr,Su,Tu),Ov=at(U(hr,B("p2p-stardust"),B("p2p")),U(hr,B("p2p-stardust"))),We=at(U(hr,B("p2p")),Iu,ku,Su,Tu,B("p2p")),Bu=at(U(We,B("p2p-circuit"),We),U(We,B("p2p-circuit")),U(B("p2p-circuit"),We),U(hr,B("p2p-circuit")),U(B("p2p-circuit"),hr),B("p2p-circuit")),Ru=()=>at(U(Bu,Ru),Bu),ke=Ru(),Pv=at(U(ke,We,ke),U(We,ke),U(ke,We),ke,We);var Vv=at(U(ke,B("webrtc"),B("p2p")),U(ke,B("webrtc")),U(hr,B("webrtc"),B("p2p")),U(hr,B("webrtc")),B("webrtc"));function Nu(r){function t(e){let n;try{n=Rt(e)}catch{return!1}let s=r(n.protoNames());return s===null?!1:s===!0||s===!1?s:s.length===0}return t}function U(...r){function t(e){if(e.length<r.length)return null;let n=e;return r.some(s=>(n=typeof s=="function"?s().partialMatch(e):s.partialMatch(e),Array.isArray(n)&&(e=n),n===null)),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:Nu(t),partialMatch:t}}function at(...r){function t(n){let s=null;return r.some(i=>{let o=typeof i=="function"?i().partialMatch(n):i.partialMatch(n);return o!=null?(s=o,!0):!1}),s}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:Nu(t),partialMatch:t}}function B(r){let t=r;function e(s){let i;try{i=Rt(s)}catch{return!1}let o=i.protoNames();return o.length===1&&o[0]===t}function n(s){return s.length===0?null:s[0]===t?s.slice(1):null}return{toString:function(){return t},matches:e,partialMatch:n}}var oa=class extends Nt{connectionManager;relayStore;listeningAddrs;log;constructor(t){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=t.connectionManager,this.relayStore=t.relayStore,this.listeningAddrs=new Ie,this.relayStore.addEventListener("relay:removed",this._onRemoveRelayPeer)}_onRemoveRelayPeer=t=>{this.#t(t.detail)};async listen(t){this.log("listen on %a",t);let e=t.decapsulate("/p2p-circuit"),n=await this.connectionManager.openConnection(e);if(!this.relayStore.hasReservation(n.remotePeer)){this.log("making reservation on peer %p",n.remotePeer),await this.relayStore.addRelay(n.remotePeer,"configured");return}let s=this.relayStore.getReservation(n.remotePeer);if(s==null)throw new L("Did not have reservation after making reservation","ERR_NO_RESERVATION");if(this.listeningAddrs.has(n.remotePeer)){this.log("already listening on relay %p",n.remotePeer);return}this.listeningAddrs.set(n.remotePeer,s.addrs.map(i=>Rt(i).encapsulate("/p2p-circuit"))),this.safeDispatchEvent("listening",{})}getAddrs(){return[...this.listeningAddrs.values()].flat()}async close(){}#t(t){let e=this.listeningAddrs.has(t);this.log("relay peer removed %p - had reservation",t,e),this.listeningAddrs.delete(t),e&&(this.log.trace("removing relay event listener for peer %p",t),this.relayStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),this.safeDispatchEvent("close",{}))}};function _u(r){return new oa(r)}var s0=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(Rt)}catch{return!1}return!0},aa={maxInboundStopStreams:yn,maxOutboundStopStreams:yn,stopTimeout:3e4},oi=class{discovery;registrar;peerStore;connectionManager;transportManager;peerId;upgrader;addressManager;connectionGater;reservationStore;logger;maxInboundStopStreams;maxOutboundStopStreams;stopTimeout;started;log;constructor(t,e){this.log=t.logger.forComponent("libp2p:circuit-relay:transport"),this.registrar=t.registrar,this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.transportManager=t.transportManager,this.logger=t.logger,this.peerId=t.peerId,this.upgrader=t.upgrader,this.addressManager=t.addressManager,this.connectionGater=t.connectionGater,this.maxInboundStopStreams=e.maxInboundStopStreams??aa.maxInboundStopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??aa.maxOutboundStopStreams,this.stopTimeout=e.stopTimeout??aa.stopTimeout,e.discoverRelays!=null&&e.discoverRelays>0&&(this.discovery=new Ws(t),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(s=>{this.log.error("could not add discovered relay %p",n.detail,s)})})),this.reservationStore=new ei(t,e),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.discover().catch(n=>{this.log.error("could not discover relays",n)})}),this.started=!1}isStarted(){return this.started}async start(){this.reservationStore.start(),await this.registrar.handle(lr,t=>{this.onStop(t).catch(e=>{this.log.error("error while handling STOP protocol",e),t.stream.abort(e)})},{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnTransientConnection:!0}),await this.discovery?.start(),this.started=!0}afterStart(){this.discovery?.afterStart()}async stop(){this.discovery?.stop(),this.reservationStore.stop(),await this.registrar.unhandle(lr),this.started=!1}[xa]=!0;[Symbol.toStringTag]="libp2p/circuit-relay-v2";async dial(t,e={}){if(t.protoCodes().filter(m=>m===290).length!==1){let m="Invalid circuit relay address";throw this.log.error(m,t),new L(m,$o)}let n=t.toString().split("/p2p-circuit"),s=Rt(n[0]),i=Rt(n[n.length-1]),o=s.getPeerId(),a=i.getPeerId();if(o==null||a==null){let m=`Circuit relay dial to ${t.toString()} failed as address did not have peer ids`;throw this.log.error(m),new L(m,$o)}let c=Ce(o),f=Ce(a),u=!1,h=this.connectionManager.getConnections(c)[0];h==null&&(await this.peerStore.merge(c,{multiaddrs:[s]}),h=await this.connectionManager.openConnection(c,e),u=!0);let b;try{return b=await h.newStream(zt),await this.connectV2({stream:b,connection:h,destinationPeer:f,destinationAddr:i,relayAddr:s,ma:t,disconnectOnFailure:u})}catch(m){throw this.log.error("circuit relay dial to destination %p via relay %p failed",f,c,m),b?.abort(m),u&&await h.close(),m}}async connectV2({stream:t,connection:e,destinationPeer:n,destinationAddr:s,relayAddr:i,ma:o,disconnectOnFailure:a}){try{let c=je(t),f=c.pb(Z);await f.write({type:Z.Type.CONNECT,peer:{id:n.toBytes(),addrs:[Rt(s).bytes]}});let u=await f.read();if(u.status!==H.OK)throw new L(`failed to connect via relay with status ${u?.status?.toString()??"undefined"}`,cu);let l=ea({stream:c.unwrap(),remoteAddr:o,localAddr:i.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`),logger:this.logger});return this.log("new outbound transient connection %a",l.remoteAddr),await this.upgrader.upgradeOutbound(l,{transient:!0})}catch(c){throw this.log.error(`Circuit relay dial to destination ${n.toString()} via relay ${e.remotePeer.toString()} failed`,c),a&&await e.close(),c}}createListener(t){return _u({connectionManager:this.connectionManager,relayStore:this.reservationStore,logger:this.logger})}filter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>ke.matches(e))}async onStop({connection:t,stream:e}){if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(u){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on",u)}let n=AbortSignal.timeout(this.stopTimeout),s=je(e).pb(Ht),i=await s.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,i.type),i?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await s.write({type:Ht.Type.STATUS,status:H.MALFORMED_MESSAGE},{signal:n}),await e.close();return}if(i.type!==Ht.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:Ht.Type.STATUS,status:H.UNEXPECTED_MESSAGE},{signal:n}),await e.close();return}if(!s0(i)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:Ht.Type.STATUS,status:H.MALFORMED_MESSAGE},{signal:n}),await e.close();return}let o=Wr(i.peer.id);if(await this.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,o)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await s.write({type:Ht.Type.STATUS,status:H.PERMISSION_DENIED},{signal:n}),await e.close();return}this.log.trace("sending success response to %p",t.remotePeer),await s.write({type:Ht.Type.STATUS,status:H.OK},{signal:n});let a=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${o.toString()}`),c=this.addressManager.getAddresses()[0],f=ea({stream:s.unwrap().unwrap(),remoteAddr:a,localAddr:c,logger:this.logger});this.log("new inbound transient connection %a",f.remoteAddr),await this.upgrader.upgradeInbound(f,{transient:!0}),this.log("%s connection %a upgraded","inbound",f.remoteAddr)}};function Lu(r={}){return t=>new oi(t,r)}return zu(i0);})();
8
8
  /*! Bundled license information:
9
9
 
10
10
  pvtsutils/build/index.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@libp2p/circuit-relay-v2",
3
- "version": "1.0.13-2370d1c39",
3
+ "version": "1.0.13-9891ecd73",
4
4
  "description": "Implementation of Circuit Relay v2",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/transport-circuit-relay-v2#readme",
@@ -51,36 +51,36 @@
51
51
  "dep-check": "aegir dep-check"
52
52
  },
53
53
  "dependencies": {
54
- "@libp2p/interface": "1.1.2-2370d1c39",
55
- "@libp2p/interface-internal": "1.0.7-2370d1c39",
56
- "@libp2p/peer-collections": "5.1.5-2370d1c39",
57
- "@libp2p/peer-id": "4.0.5-2370d1c39",
58
- "@libp2p/peer-record": "7.0.7-2370d1c39",
59
- "@libp2p/utils": "5.2.3-2370d1c39",
54
+ "@libp2p/interface": "1.1.2-9891ecd73",
55
+ "@libp2p/interface-internal": "1.0.7-9891ecd73",
56
+ "@libp2p/peer-collections": "5.1.5-9891ecd73",
57
+ "@libp2p/peer-id": "4.0.5-9891ecd73",
58
+ "@libp2p/peer-record": "7.0.7-9891ecd73",
59
+ "@libp2p/utils": "5.2.3-9891ecd73",
60
60
  "@multiformats/mafmt": "^12.1.6",
61
- "@multiformats/multiaddr": "^12.1.10",
61
+ "@multiformats/multiaddr": "^12.1.14",
62
62
  "any-signal": "^4.1.1",
63
- "it-protobuf-stream": "^1.1.1",
63
+ "it-protobuf-stream": "^1.1.2",
64
64
  "it-stream-types": "^2.0.1",
65
- "multiformats": "^13.0.0",
65
+ "multiformats": "^13.0.1",
66
66
  "p-defer": "^4.0.0",
67
- "p-retry": "^6.1.0",
68
- "protons-runtime": "^5.0.0",
69
- "uint8arraylist": "^2.4.7",
70
- "uint8arrays": "^5.0.0"
67
+ "p-retry": "^6.2.0",
68
+ "protons-runtime": "^5.4.0",
69
+ "uint8arraylist": "^2.4.8",
70
+ "uint8arrays": "^5.0.1"
71
71
  },
72
72
  "devDependencies": {
73
- "@libp2p/interface-compliance-tests": "5.2.0-2370d1c39",
74
- "@libp2p/logger": "4.0.5-2370d1c39",
75
- "@libp2p/peer-id-factory": "4.0.5-2370d1c39",
76
- "aegir": "^42.0.0",
73
+ "@libp2p/interface-compliance-tests": "5.2.0-9891ecd73",
74
+ "@libp2p/logger": "4.0.5-9891ecd73",
75
+ "@libp2p/peer-id-factory": "4.0.5-9891ecd73",
76
+ "aegir": "^42.2.3",
77
77
  "delay": "^6.0.0",
78
78
  "it-drain": "^3.0.5",
79
79
  "it-pair": "^2.0.6",
80
- "it-pushable": "^3.2.1",
81
- "it-to-buffer": "^4.0.3",
80
+ "it-pushable": "^3.2.3",
81
+ "it-to-buffer": "^4.0.5",
82
82
  "p-wait-for": "^5.0.2",
83
- "protons": "^7.3.0",
83
+ "protons": "^7.5.0",
84
84
  "race-signal": "^1.0.2",
85
85
  "sinon": "^17.0.1",
86
86
  "sinon-ts": "^2.0.0"