@libp2p/circuit-relay-v2 3.1.3-98b43045c → 3.1.3-b02ea9b6e
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/index.min.js +1 -1
- package/package.json +10 -10
package/dist/index.min.js
CHANGED
@@ -3,7 +3,7 @@
|
|
3
3
|
`).map(s=>` ${s}`).join(`
|
4
4
|
`));let e=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return t.length?`${e} :
|
5
5
|
${t.join(`
|
6
|
-
`)}`:`${e} :`}};Ul=Ke;k.Constructed=Ul;Ke.NAME="CONSTRUCTED";var ls=class extends _t{fromBER(t,e,n){return e}toBER(t){return te}};ls.override="EndOfContentValueBlock";var Dl,us=class extends bt{constructor(t={}){super(t,ls),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Dl=us;k.EndOfContent=Dl;us.NAME=rn;var Ol,Br=class extends bt{constructor(t={}){super(t,_t),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}`}};Ol=Br;k.Null=Ol;Br.NAME="NULL";var fs=class extends _e(_t){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=z.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=z.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,sa.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};fs.NAME="BooleanValueBlock";var Ml,hs=class extends bt{constructor(t={}){super(t,fs),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}`}};Ml=hs;k.Boolean=Ml;hs.NAME="BOOLEAN";var ds=class extends _e(ce){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=ce.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===rn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(o!==Cl)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?ce.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};ds.NAME="OctetStringValueBlock";var Pl,ps=class r extends bt{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},ds),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=Ks(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} : ${z.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 z.BufferSourceConverter.concat(t)}};Pl=ps;k.OctetString=Pl;ps.NAME=Cl;var ms=class extends _e(ce){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=ce.prototype.fromBER.call(this,t,e,n),s===-1)return s;for(let a of this.value){let c=a.constructor.NAME;if(c===rn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Nl)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let h=a.valueBlock;if(this.unusedBits>0&&h.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=h.unusedBits}return s}let i=z.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=Ks(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 ce.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return te;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}}};ms.NAME="BitStringValueBlock";var Vl,_r=class extends bt{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},ms),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)}`}}};Vl=_r;k.BitString=Vl;_r.NAME=Nl;var Hl;function Vp(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,h=0,f=c<o?o:c,u=0;for(let g=f;g>=0;g--,u++){switch(!0){case u<a.length:h=i[o-u]+a[c-u]+e[0];break;default:h=i[o-u]+e[0]}switch(e[0]=h/10,!0){case u>=i.length:i=rs(new Uint8Array([h%10]),i);break;default:i[o-u]=h%10}}return e[0]>0&&(i=rs(e,i)),i}function kl(r){if(r>=tn.length)for(let t=tn.length;t<=r;t++){let e=new Uint8Array([0]),n=tn[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=rs(e,n)),tn.push(n)}return tn[r]}function Hp(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,h,f=0;for(let u=c;u>=0;u--,f++)switch(h=i[o-f]-a[c-f]-e,!0){case h<0:e=1,i[o-f]=h+10;break;default:e=0,i[o-f]=h}if(e>0)for(let u=o-c+1;u>=0;u--,f++)if(h=i[o-f]-e,h<0)e=1,i[o-f]=h+10;else{e=0,i[o-f]=h;break}return i.slice()}var nn=class extends _e(_t){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=sa.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(_l(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 h=0;h<8;h++){if((s&1)===1)switch(n){case t:e=Hp(kl(n),e),o="-";break;default:e=Vp(e,kl(n))}n++,s>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(o+=Tl.charAt(e[c]));return a===!1&&(o+=Tl.charAt(0)),o}};Hl=nn;nn.NAME="IntegerValueBlock";Object.defineProperty(Hl.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Fl,wt=class r extends bt{constructor(t={}){super(t,nn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return ns(),BigInt(this.valueBlock.toString())}static fromBigInt(t){ns();let e=BigInt(t),n=new en,s=e.toString(16).replace(/^-/,""),i=new Uint8Array(z.Convert.FromHex(s));if(e<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let h=BigInt(`0x${z.Convert.ToHex(a)}`)+e,f=z.BufferSourceConverter.toUint8Array(z.Convert.FromHex(h.toString(16)));f[0]|=128,n.write(f)}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()}`}};Fl=wt;k.Integer=Fl;wt.NAME="INTEGER";var Kl,gs=class extends wt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Kl=gs;k.Enumerated=Kl;gs.NAME="ENUMERATED";var sn=class extends _e(_t){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=z.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=ir(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){ns();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",te;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=z.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}}};sn.NAME="sidBlock";var ys=class extends _t{constructor({value:t=Tr,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let s=e;for(;n>0;){let i=new sn;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,te;e.push(s)}return ia(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 sn;if(s>Number.MAX_SAFE_INTEGER){ns();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}};ys.NAME="ObjectIdentifierValueBlock";var ql,Ir=class extends bt{constructor(t={}){super(t,ys),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()}}};ql=Ir;k.ObjectIdentifier=ql;Ir.NAME="OBJECT IDENTIFIER";var on=class extends _e(Ee){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let s=z.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=ir(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",te;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=z.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};on.NAME="relativeSidBlock";var bs=class extends _t{constructor({value:t=Tr,...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.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,te;n.push(i)}return ia(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 on;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}};bs.NAME="RelativeObjectIdentifierValueBlock";var zl,ws=class extends bt{constructor(t={}){super(t,bs),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()}}};zl=ws;k.RelativeObjectIdentifier=zl;ws.NAME="RelativeObjectIdentifier";var $l,Se=class extends Ke{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};$l=Se;k.Sequence=$l;Se.NAME="SEQUENCE";var Gl,xs=class extends Ke{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Gl=xs;k.Set=Gl;xs.NAME="SET";var vs=class extends _e(_t){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=Tr}toJSON(){return{...super.toJSON(),value:this.value}}};vs.NAME="StringValueBlock";var Es=class extends vs{};Es.NAME="SimpleStringValueBlock";var Ct=class extends os{constructor({...t}={}){super(t,Es)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,z.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}};Ct.NAME="SIMPLE STRING";var Ss=class extends Ct{fromBuffer(t){this.valueBlock.valueHexView=z.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=z.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=z.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(z.Convert.FromUtf8String(t)),this.valueBlock.value=t}};Ss.NAME="Utf8StringValueBlock";var Wl,Ae=class extends Ss{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Wl=Ae;k.Utf8String=Wl;Ae.NAME="UTF8String";var As=class extends Ct{fromBuffer(t){this.valueBlock.value=z.Convert.ToUtf16String(t),this.valueBlock.valueHexView=z.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(z.Convert.FromUtf16String(t))}};As.NAME="BmpStringValueBlock";var Zl,Bs=class extends As{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Zl=Bs;k.BmpString=Zl;Bs.NAME="BMPString";var _s=class extends Ct{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}};_s.NAME="UniversalStringValueBlock";var jl,Is=class extends _s{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};jl=Is;k.UniversalString=jl;Is.NAME="UniversalString";var Yl,Ts=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Yl=Ts;k.NumericString=Yl;Ts.NAME="NumericString";var Xl,ks=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Xl=ks;k.PrintableString=Xl;ks.NAME="PrintableString";var Jl,Cs=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Jl=Cs;k.TeletexString=Jl;Cs.NAME="TeletexString";var Ql,Ns=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Ql=Ns;k.VideotexString=Ql;Ns.NAME="VideotexString";var tu,Ls=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};tu=Ls;k.IA5String=tu;Ls.NAME="IA5String";var eu,Rs=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};eu=Rs;k.GraphicString=eu;Rs.NAME="GraphicString";var ru,an=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};ru=an;k.VisibleString=ru;an.NAME="VisibleString";var nu,Us=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};nu=Us;k.GeneralString=nu;Us.NAME="GeneralString";var su,Ds=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};su=Ds;k.CharacterString=su;Ds.NAME="CharacterString";var iu,cn=class extends an{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,z.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]=Vt(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=Vt(this.month,2),e[2]=Vt(this.day,2),e[3]=Vt(this.hour,2),e[4]=Vt(this.minute,2),e[5]=Vt(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}}};iu=cn;k.UTCTime=iu;cn.NAME="UTCTime";var ou,Os=class extends cn{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 u=new Number(t[t.length-1]);if(isNaN(u.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 u=1,g=n.indexOf("+"),l="";if(g===-1&&(g=n.indexOf("-"),u=-1),g!==-1){if(l=n.substring(g+1),n=n.substring(0,g),l.length!==2&&l.length!==4)throw new Error("Wrong input string for conversion");let d=parseInt(l.substring(0,2),10);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");if(a=u*d,l.length===4){if(d=parseInt(l.substring(2,4),10),isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");c=u*d}}}let h=n.indexOf(".");if(h===-1&&(h=n.indexOf(",")),h!==-1){let u=new Number(`0${n.substring(h)}`);if(isNaN(u.valueOf()))throw new Error("Wrong input string for conversion");i=u.valueOf(),s=n.substring(0,h)}else s=n;switch(!0){case s.length===8:if(o=/(\d{4})(\d{2})(\d{2})/ig,h!==-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,h!==-1){let u=60*i;this.minute=Math.floor(u),u=60*(u-this.minute),this.second=Math.floor(u),u=1e3*(u-this.second),this.millisecond=Math.floor(u)}break;case s.length===12:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,h!==-1){let u=60*i;this.second=Math.floor(u),u=1e3*(u-this.second),this.millisecond=Math.floor(u)}break;case s.length===14:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,h!==-1){let u=1e3*i;this.millisecond=Math.floor(u)}break;default:throw new Error("Wrong input string for conversion")}let f=o.exec(s);if(f===null)throw new Error("Wrong input string for conversion");for(let u=1;u<f.length;u++)switch(u){case 1:this.year=parseInt(f[u],10);break;case 2:this.month=parseInt(f[u],10);break;case 3:this.day=parseInt(f[u],10);break;case 4:this.hour=parseInt(f[u],10)+a;break;case 5:this.minute=parseInt(f[u],10)+c;break;case 6:this.second=parseInt(f[u],10);break;default:throw new Error("Wrong input string for conversion")}if(e===!1){let u=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=u.getUTCFullYear(),this.month=u.getUTCMonth(),this.day=u.getUTCDay(),this.hour=u.getUTCHours(),this.minute=u.getUTCMinutes(),this.second=u.getUTCSeconds(),this.millisecond=u.getUTCMilliseconds()}}toString(t="iso"){if(t==="iso"){let e=[];return e.push(Vt(this.year,4)),e.push(Vt(this.month,2)),e.push(Vt(this.day,2)),e.push(Vt(this.hour,2)),e.push(Vt(this.minute,2)),e.push(Vt(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(Vt(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};ou=Os;k.GeneralizedTime=ou;Os.NAME="GeneralizedTime";var au,Ms=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};au=Ms;k.DATE=au;Ms.NAME="DATE";var cu,Ps=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};cu=Ps;k.TimeOfDay=cu;Ps.NAME="TimeOfDay";var lu,Vs=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};lu=Vs;k.DateTime=lu;Vs.NAME="DateTime";var uu,Hs=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};uu=Hs;k.Duration=uu;Hs.NAME="Duration";var fu,Fs=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};fu=Fs;k.TIME=fu;Fs.NAME="TIME";function lt(r,t="utf8"){let e=Wn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var ln=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},qs=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var hu={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new qs("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var qe=hu;async function du(r){let t=await qe.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 Kp(t);return{privateKey:e[0],publicKey:e[1]}}async function pu(r,t){let e=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await qe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function mu(r,t,e){let n=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return qe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function Kp(r){if(r.privateKey==null||r.publicKey==null)throw new Et("Private and public key are required");return Promise.all([qe.get().subtle.exportKey("jwk",r.privateKey),qe.get().subtle.exportKey("jwk",r.publicKey)])}function ca(r){if(r.kty!=="RSA")throw new Et("invalid key type");if(r.n==null)throw new Et("invalid key modulus");return G(r.n,"base64url").length*8}var kr=class{type="RSA";_key;_raw;_multihash;constructor(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=un.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return pt.createV1(114,this._multihash)}toString(){return tt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:mt(this.raw,t.raw)}verify(t,e){return mu(this._key,e,t)}},fn=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=un.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:mt(this.raw,t.raw)}sign(t){return pu(this._key,t)}};var zs=8192,la=18;function gu(r){let{result:t}=aa(r),e=t.valueBlock.value;return{n:le(e[1]),e:le(e[2]),d:le(e[3]),p:le(e[4]),q:le(e[5]),dp:le(e[6]),dq:le(e[7]),qi:le(e[8]),kty:"RSA",alg:"RS256"}}function qp(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 Et("JWK was missing components");let e=new Se({value:[new wt({value:0}),wt.fromBigInt(ue(G(r.n,"base64url"))),wt.fromBigInt(ue(G(r.e,"base64url"))),wt.fromBigInt(ue(G(r.d,"base64url"))),wt.fromBigInt(ue(G(r.p,"base64url"))),wt.fromBigInt(ue(G(r.q,"base64url"))),wt.fromBigInt(ue(G(r.dp,"base64url"))),wt.fromBigInt(ue(G(r.dq,"base64url"))),wt.fromBigInt(ue(G(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function yu(r){let{result:t}=aa(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:le(e[0]),e:le(e[1])}}function ua(r){if(r.n==null||r.e==null)throw new Et("JWK was missing components");let e=new Se({value:[new Se({value:[new Ir({value:"1.2.840.113549.1.1.1"}),new Br]}),new _r({valueHex:new Se({value:[wt.fromBigInt(ue(G(r.n,"base64url"))),wt.fromBigInt(ue(G(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function le(r){let t=r.valueBlock.valueHexView;for(;t[0]===0;)t=t.subarray(1);return lt(t,"base64url")}function ue(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(""))}function bu(r){let t=gu(r);return wu(t)}function fa(r){let t=yu(r);if(ca(t)>zs)throw new fr("Key size is too large");let e=Qn(ae.encode({Type:ft.RSA,Data:r})),n=Zt(la,e);return new kr(t,n)}function wu(r){if(ca(r)>zs)throw new Et("Key size is too large");let t=vu(r),e=Qn(ae.encode({Type:ft.RSA,Data:ua(t.publicKey)})),n=Zt(la,e);return new fn(t.privateKey,new kr(t.publicKey,n))}async function xu(r){if(r>zs)throw new Et("Key size is too large");let t=await du(r),e=Qn(ae.encode({Type:ft.RSA,Data:ua(t.publicKey)})),n=Zt(la,e);return new fn(t.privateKey,new kr(t.publicKey,n))}function vu(r){if(r==null)throw new Et("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var zp=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]),ze=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),$e=new Uint32Array(64),ha=class extends xr{constructor(){super(64,32,8,!1),this.A=ze[0]|0,this.B=ze[1]|0,this.C=ze[2]|0,this.D=ze[3]|0,this.E=ze[4]|0,this.F=ze[5]|0,this.G=ze[6]|0,this.H=ze[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 u=0;u<16;u++,e+=4)$e[u]=t.getUint32(e,!1);for(let u=16;u<64;u++){let g=$e[u-15],l=$e[u-2],d=jt(g,7)^jt(g,18)^g>>>3,p=jt(l,17)^jt(l,19)^l>>>10;$e[u]=p+$e[u-7]+d+$e[u-16]|0}let{A:n,B:s,C:i,D:o,E:a,F:c,G:h,H:f}=this;for(let u=0;u<64;u++){let g=jt(a,6)^jt(a,11)^jt(a,25),l=f+g+Fc(a,c,h)+zp[u]+$e[u]|0,p=(jt(n,2)^jt(n,13)^jt(n,22))+Kc(n,s,i)|0;f=h,h=c,c=a,a=o+l|0,o=i,i=s,s=n,n=l+p|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,h=h+this.G|0,f=f+this.H|0,this.set(n,s,i,o,a,c,h,f)}roundClean(){$e.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Eu=Ln(()=>new ha);var $s=class extends wr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Pc(t);let n=Gr(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let s=this.blockLen,i=new Uint8Array(s);i.set(n.length>s?t.create().update(n).digest():n);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=t.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),i.fill(0)}update(t){return br(this),this.iHash.update(t),this}digestInto(t){br(this),yr(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:s,destroyed:i,blockLen:o,outputLen:a}=this;return t=t,t.finished=s,t.destroyed=i,t.blockLen=o,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},da=(r,t,e)=>new $s(r,t).update(e).digest();da.create=(r,t)=>new $s(r,t);function Su(r){r.lowS!==void 0&&Yt("lowS",r.lowS),r.prehash!==void 0&&Yt("prehash",r.prehash)}function $p(r){let t=jr(r);oe(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("invalid 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("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:Gp,hexToBytes:Wp}=Mn,Ie={Err:class extends Error{constructor(t=""){super(t)}},_tlv:{encode:(r,t)=>{let{Err:e}=Ie;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,s=Xe(n);if(s.length/2&128)throw new e("tlv.encode: long form length too big");let i=n>127?Xe(s.length/2|128):"";return Xe(r)+i+s+t},decode(r,t){let{Err:e}=Ie,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let s=t[n++],i=!!(s&128),o=0;if(!i)o=s;else{let c=s&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let h=t.subarray(n,n+c);if(h.length!==c)throw new e("tlv.decode: length bytes not complete");if(h[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let f of h)o=o<<8|f;if(n+=c,o<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+o);if(a.length!==o)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+o)}}},_int:{encode(r){let{Err:t}=Ie;if(r<Te)throw new t("integer: negative integers are not allowed");let e=Xe(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=Ie;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Gp(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Ie,s=typeof r=="string"?Wp(r):r;vr(s);let{v:i,l:o}=n.decode(48,s);if(o.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:h,l:f}=n.decode(2,c);if(f.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(h)}},hexFromSig(r){let{_tlv:t,_int:e}=Ie,n=t.encode(2,e.encode(r.r)),s=t.encode(2,e.encode(r.s)),i=n+s;return t.encode(48,i)}},Te=BigInt(0),gt=BigInt(1),Vb=BigInt(2),Au=BigInt(3),Hb=BigInt(4);function Zp(r){let t=$p(r),{Fp:e}=t,n=Oe(t.n,t.nBitLength),s=t.toBytes||((p,y,b)=>{let w=y.toAffine();return we(Uint8Array.from([4]),e.toBytes(w.x),e.toBytes(w.y))}),i=t.fromBytes||(p=>{let y=p.subarray(1),b=e.fromBytes(y.subarray(0,e.BYTES)),w=e.fromBytes(y.subarray(e.BYTES,2*e.BYTES));return{x:b,y:w}});function o(p){let{a:y,b}=t,w=e.sqr(p),m=e.mul(w,p);return e.add(e.add(m,e.mul(p,y)),b)}if(!e.eql(e.sqr(t.Gy),o(t.Gx)))throw new Error("bad generator point: equation left != right");function a(p){return Wr(p,gt,t.n)}function c(p){let{allowedPrivateKeyLengths:y,nByteLength:b,wrapPrivateKey:w,n:m}=t;if(y&&typeof p!="bigint"){if(Re(p)&&(p=ye(p)),typeof p!="string"||!y.includes(p.length))throw new Error("invalid private key");p=p.padStart(b*2,"0")}let E;try{E=typeof p=="bigint"?p:be(ot("private key",p,b))}catch{throw new Error("invalid private key, expected hex or "+b+" bytes, got "+typeof p)}return w&&(E=J(E,m)),Rt("private key",E,gt,m),E}function h(p){if(!(p instanceof g))throw new Error("ProjectivePoint expected")}let f=tr((p,y)=>{let{px:b,py:w,pz:m}=p;if(e.eql(m,e.ONE))return{x:b,y:w};let E=p.is0();y==null&&(y=E?e.ONE:e.inv(m));let A=e.mul(b,y),_=e.mul(w,y),x=e.mul(m,y);if(E)return{x:e.ZERO,y:e.ZERO};if(!e.eql(x,e.ONE))throw new Error("invZ was invalid");return{x:A,y:_}}),u=tr(p=>{if(p.is0()){if(t.allowInfinityPoint&&!e.is0(p.py))return;throw new Error("bad point: ZERO")}let{x:y,y:b}=p.toAffine();if(!e.isValid(y)||!e.isValid(b))throw new Error("bad point: x or y not FE");let w=e.sqr(b),m=o(y);if(!e.eql(w,m))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(y,b,w){if(this.px=y,this.py=b,this.pz=w,y==null||!e.isValid(y))throw new Error("x required");if(b==null||!e.isValid(b))throw new Error("y required");if(w==null||!e.isValid(w))throw new Error("z required");Object.freeze(this)}static fromAffine(y){let{x:b,y:w}=y||{};if(!y||!e.isValid(b)||!e.isValid(w))throw new Error("invalid affine point");if(y instanceof g)throw new Error("projective point not allowed");let m=E=>e.eql(E,e.ZERO);return m(b)&&m(w)?g.ZERO:new g(b,w,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(y){let b=e.invertBatch(y.map(w=>w.pz));return y.map((w,m)=>w.toAffine(b[m])).map(g.fromAffine)}static fromHex(y){let b=g.fromAffine(i(ot("pointHex",y)));return b.assertValidity(),b}static fromPrivateKey(y){return g.BASE.multiply(c(y))}static msm(y,b){return Fn(g,n,y,b)}_setWindowSize(y){d.setWindowSize(this,y)}assertValidity(){u(this)}hasEvenY(){let{y}=this.toAffine();if(e.isOdd)return!e.isOdd(y);throw new Error("Field doesn't support isOdd")}equals(y){h(y);let{px:b,py:w,pz:m}=this,{px:E,py:A,pz:_}=y,x=e.eql(e.mul(b,_),e.mul(E,m)),I=e.eql(e.mul(w,_),e.mul(A,m));return x&&I}negate(){return new g(this.px,e.neg(this.py),this.pz)}double(){let{a:y,b}=t,w=e.mul(b,Au),{px:m,py:E,pz:A}=this,_=e.ZERO,x=e.ZERO,I=e.ZERO,C=e.mul(m,m),j=e.mul(E,E),V=e.mul(A,A),P=e.mul(m,E);return P=e.add(P,P),I=e.mul(m,A),I=e.add(I,I),_=e.mul(y,I),x=e.mul(w,V),x=e.add(_,x),_=e.sub(j,x),x=e.add(j,x),x=e.mul(_,x),_=e.mul(P,_),I=e.mul(w,I),V=e.mul(y,V),P=e.sub(C,V),P=e.mul(y,P),P=e.add(P,I),I=e.add(C,C),C=e.add(I,C),C=e.add(C,V),C=e.mul(C,P),x=e.add(x,C),V=e.mul(E,A),V=e.add(V,V),C=e.mul(V,P),_=e.sub(_,C),I=e.mul(V,j),I=e.add(I,I),I=e.add(I,I),new g(_,x,I)}add(y){h(y);let{px:b,py:w,pz:m}=this,{px:E,py:A,pz:_}=y,x=e.ZERO,I=e.ZERO,C=e.ZERO,j=t.a,V=e.mul(t.b,Au),P=e.mul(b,E),R=e.mul(w,A),T=e.mul(m,_),L=e.add(b,w),S=e.add(E,A);L=e.mul(L,S),S=e.add(P,R),L=e.sub(L,S),S=e.add(b,m);let v=e.add(E,_);return S=e.mul(S,v),v=e.add(P,T),S=e.sub(S,v),v=e.add(w,m),x=e.add(A,_),v=e.mul(v,x),x=e.add(R,T),v=e.sub(v,x),C=e.mul(j,S),x=e.mul(V,T),C=e.add(x,C),x=e.sub(R,C),C=e.add(R,C),I=e.mul(x,C),R=e.add(P,P),R=e.add(R,P),T=e.mul(j,T),S=e.mul(V,S),R=e.add(R,T),T=e.sub(P,T),T=e.mul(j,T),S=e.add(S,T),P=e.mul(R,S),I=e.add(I,P),P=e.mul(v,S),x=e.mul(L,x),x=e.sub(x,P),P=e.mul(L,R),C=e.mul(v,C),C=e.add(C,P),new g(x,I,C)}subtract(y){return this.add(y.negate())}is0(){return this.equals(g.ZERO)}wNAF(y){return d.wNAFCached(this,y,g.normalizeZ)}multiplyUnsafe(y){let{endo:b,n:w}=t;Rt("scalar",y,Te,w);let m=g.ZERO;if(y===Te)return m;if(this.is0()||y===gt)return this;if(!b||d.hasPrecomputes(this))return d.wNAFCachedUnsafe(this,y,g.normalizeZ);let{k1neg:E,k1:A,k2neg:_,k2:x}=b.splitScalar(y),I=m,C=m,j=this;for(;A>Te||x>Te;)A>&&(I=I.add(j)),x>&&(C=C.add(j)),j=j.double(),A>>=gt,x>>=gt;return E&&(I=I.negate()),_&&(C=C.negate()),C=new g(e.mul(C.px,b.beta),C.py,C.pz),I.add(C)}multiply(y){let{endo:b,n:w}=t;Rt("scalar",y,gt,w);let m,E;if(b){let{k1neg:A,k1:_,k2neg:x,k2:I}=b.splitScalar(y),{p:C,f:j}=this.wNAF(_),{p:V,f:P}=this.wNAF(I);C=d.constTimeNegate(A,C),V=d.constTimeNegate(x,V),V=new g(e.mul(V.px,b.beta),V.py,V.pz),m=C.add(V),E=j.add(P)}else{let{p:A,f:_}=this.wNAF(y);m=A,E=_}return g.normalizeZ([m,E])[0]}multiplyAndAddUnsafe(y,b,w){let m=g.BASE,E=(_,x)=>x===Te||x===gt||!_.equals(m)?_.multiplyUnsafe(x):_.multiply(x),A=E(this,b).add(E(y,w));return A.is0()?void 0:A}toAffine(y){return f(this,y)}isTorsionFree(){let{h:y,isTorsionFree:b}=t;if(y===gt)return!0;if(b)return b(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:y,clearCofactor:b}=t;return y===gt?this:b?b(g,this):this.multiplyUnsafe(t.h)}toRawBytes(y=!0){return Yt("isCompressed",y),this.assertValidity(),s(g,this,y)}toHex(y=!0){return Yt("isCompressed",y),ye(this.toRawBytes(y))}}g.BASE=new g(t.Gx,t.Gy,e.ONE),g.ZERO=new g(e.ZERO,e.ONE,e.ZERO);let l=t.nBitLength,d=Hn(g,t.endo?Math.ceil(l/2):l);return{CURVE:t,ProjectivePoint:g,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function jp(r){let t=jr(r);return oe(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Bu(r){let t=jp(r),{Fp:e,n}=t,s=e.BYTES+1,i=2*e.BYTES+1;function o(T){return J(T,n)}function a(T){return Pn(T,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:f,isWithinCurveOrder:u}=Zp({...t,toBytes(T,L,S){let v=L.toAffine(),B=e.toBytes(v.x),N=we;return Yt("isCompressed",S),S?N(Uint8Array.from([L.hasEvenY()?2:3]),B):N(Uint8Array.from([4]),B,e.toBytes(v.y))},fromBytes(T){let L=T.length,S=T[0],v=T.subarray(1);if(L===s&&(S===2||S===3)){let B=be(v);if(!Wr(B,gt,e.ORDER))throw new Error("Point is not on curve");let N=f(B),U;try{U=e.sqrt(N)}catch($){let O=$ instanceof Error?": "+$.message:"";throw new Error("Point is not on curve"+O)}let D=(U>)===gt;return(S&1)===1!==D&&(U=e.neg(U)),{x:B,y:U}}else if(L===i&&S===4){let B=e.fromBytes(v.subarray(0,e.BYTES)),N=e.fromBytes(v.subarray(e.BYTES,2*e.BYTES));return{x:B,y:N}}else{let B=s,N=i;throw new Error("invalid Point, expected length of "+B+", or uncompressed "+N+", got "+L)}}}),g=T=>ye(De(T,t.nByteLength));function l(T){let L=n>>gt;return T>L}function d(T){return l(T)?o(-T):T}let p=(T,L,S)=>be(T.slice(L,S));class y{constructor(L,S,v){this.r=L,this.s=S,this.recovery=v,this.assertValidity()}static fromCompact(L){let S=t.nByteLength;return L=ot("compactSignature",L,S*2),new y(p(L,0,S),p(L,S,2*S))}static fromDER(L){let{r:S,s:v}=Ie.toSig(ot("DER",L));return new y(S,v)}assertValidity(){Rt("r",this.r,gt,n),Rt("s",this.s,gt,n)}addRecoveryBit(L){return new y(this.r,this.s,L)}recoverPublicKey(L){let{r:S,s:v,recovery:B}=this,N=_(ot("msgHash",L));if(B==null||![0,1,2,3].includes(B))throw new Error("recovery id invalid");let U=B===2||B===3?S+t.n:S;if(U>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let D=B&1?"03":"02",H=c.fromHex(D+g(U)),$=a(U),O=o(-N*$),Y=o(v*$),rt=c.BASE.multiplyAndAddUnsafe(H,O,Y);if(!rt)throw new Error("point at infinify");return rt.assertValidity(),rt}hasHighS(){return l(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Je(this.toDERHex())}toDERHex(){return Ie.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Je(this.toCompactHex())}toCompactHex(){return g(this.r)+g(this.s)}}let b={isValidPrivateKey(T){try{return h(T),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{let T=po(t.n);return Xc(t.randomBytes(T),t.n)},precompute(T=8,L=c.BASE){return L._setWindowSize(T),L.multiply(BigInt(3)),L}};function w(T,L=!0){return c.fromPrivateKey(T).toRawBytes(L)}function m(T){let L=Re(T),S=typeof T=="string",v=(L||S)&&T.length;return L?v===s||v===i:S?v===2*s||v===2*i:T instanceof c}function E(T,L,S=!0){if(m(T))throw new Error("first arg must be private key");if(!m(L))throw new Error("second arg must be public key");return c.fromHex(L).multiply(h(T)).toRawBytes(S)}let A=t.bits2int||function(T){if(T.length>8192)throw new Error("input is too large");let L=be(T),S=T.length*8-t.nBitLength;return S>0?L>>BigInt(S):L},_=t.bits2int_modN||function(T){return o(A(T))},x=Zr(t.nBitLength);function I(T){return Rt("num < 2^"+t.nBitLength,T,Te,x),De(T,t.nByteLength)}function C(T,L,S=j){if(["recovered","canonical"].some(dt=>dt in S))throw new Error("sign() legacy options not supported");let{hash:v,randomBytes:B}=t,{lowS:N,prehash:U,extraEntropy:D}=S;N==null&&(N=!0),T=ot("msgHash",T),Su(S),U&&(T=ot("prehashed msgHash",v(T)));let H=_(T),$=h(L),O=[I($),I(H)];if(D!=null&&D!==!1){let dt=D===!0?B(e.BYTES):D;O.push(ot("extraEntropy",dt))}let Y=we(...O),rt=H;function ht(dt){let yt=A(dt);if(!u(yt))return;let vt=a(yt),Nt=c.BASE.multiply(yt).toAffine(),Tt=o(Nt.x);if(Tt===Te)return;let se=o(vt*o(rt+Tt*$));if(se===Te)return;let fe=(Nt.x===Tt?0:2)|Number(Nt.y>),Hr=se;return N&&l(se)&&(Hr=d(se),fe^=1),new y(Tt,Hr,fe)}return{seed:Y,k2sig:ht}}let j={lowS:t.lowS,prehash:!1},V={lowS:t.lowS,prehash:!1};function P(T,L,S=j){let{seed:v,k2sig:B}=C(T,L,S),N=t;return lo(N.hash.outputLen,N.nByteLength,N.hmac)(v,B)}c.BASE._setWindowSize(8);function R(T,L,S,v=V){let B=T;L=ot("msgHash",L),S=ot("publicKey",S);let{lowS:N,prehash:U,format:D}=v;if(Su(v),"strict"in v)throw new Error("options.strict was renamed to lowS");if(D!==void 0&&D!=="compact"&&D!=="der")throw new Error("format must be compact or der");let H=typeof B=="string"||Re(B),$=!H&&!D&&typeof B=="object"&&B!==null&&typeof B.r=="bigint"&&typeof B.s=="bigint";if(!H&&!$)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let O,Y;try{if($&&(O=new y(B.r,B.s)),H){try{D!=="compact"&&(O=y.fromDER(B))}catch(fe){if(!(fe instanceof Ie.Err))throw fe}!O&&D!=="der"&&(O=y.fromCompact(B))}Y=c.fromHex(S)}catch{return!1}if(!O||N&&O.hasHighS())return!1;U&&(L=t.hash(L));let{r:rt,s:ht}=O,dt=_(L),yt=a(ht),vt=o(dt*yt),Nt=o(rt*yt),Tt=c.BASE.multiplyAndAddUnsafe(Y,vt,Nt)?.toAffine();return Tt?o(Tt.x)===rt:!1}return{CURVE:t,getPublicKey:w,getSharedSecret:E,sign:P,verify:R,ProjectivePoint:c,Signature:y,utils:b}}function Yp(r){return{hash:r,hmac:(t,...e)=>da(r,t,ro(...e)),randomBytes:Rn}}function _u(r,t){let e=n=>Bu({...r,...Yp(n)});return Object.freeze({...e(t),create:e})}var ku=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Iu=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Xp=BigInt(1),pa=BigInt(2),Tu=(r,t)=>(r+t/pa)/t;function Jp(r){let t=ku,e=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),h=r*r*r%t,f=h*h*r%t,u=it(f,e,t)*f%t,g=it(u,e,t)*f%t,l=it(g,pa,t)*h%t,d=it(l,s,t)*l%t,p=it(d,i,t)*d%t,y=it(p,a,t)*p%t,b=it(y,c,t)*y%t,w=it(b,a,t)*p%t,m=it(w,e,t)*f%t,E=it(m,o,t)*d%t,A=it(E,n,t)*h%t,_=it(A,pa,t);if(!ma.eql(ma.sqr(_),r))throw new Error("Cannot find square root");return _}var ma=Oe(ku,void 0,void 0,{sqrt:Jp}),or=_u({a:BigInt(0),b:BigInt(7),Fp:ma,n:Iu,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Iu,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Xp*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=e,o=BigInt("0x100000000000000000000000000000000"),a=Tu(i*r,t),c=Tu(-n*r,t),h=J(r-a*e-c*s,t),f=J(-a*n-c*i,t),u=h>o,g=f>o;if(u&&(h=t-h),g&&(f=t-f),h>o||f>o)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:u,k1:h,k2neg:g,k2:f}}}},Eu),jb=BigInt(0);var Yb=or.ProjectivePoint;function Ft(r,t){t==null&&(t=r.reduce((s,i)=>s+i.length,0));let e=Dt(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return e}function Cu(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Nu(r,t,e){let n=Er.digest(e instanceof Uint8Array?e:e.subarray());if(Cu(n))return n.then(({digest:s})=>or.verify(t,s,r)).catch(s=>{throw new ln(String(s))});try{return or.verify(t,n.digest,r)}catch(s){throw new ln(String(s))}}var Gs=class{type="secp256k1";raw;_key;constructor(t){this._key=Ru(t),this.raw=Lu(this._key)}toMultihash(){return me.digest(Me(this))}toCID(){return pt.createV1(114,this.toMultihash())}toString(){return tt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:mt(this.raw,t.raw)}verify(t,e){return Nu(this._key,e,t)}};function ga(r){return new Gs(r)}function Lu(r){return or.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Ru(r){try{return or.ProjectivePoint.fromHex(r),r}catch(t){throw new fr(String(t))}}function Uu(r){let{Type:t,Data:e}=ae.decode(r),n=e??new Uint8Array;switch(t){case ft.RSA:return fa(n);case ft.Ed25519:return vo(n);case ft.secp256k1:return ga(n);default:throw new hr}}function Du(r){let{Type:t,Data:e}=ae.decode(r.digest),n=e??new Uint8Array;switch(t){case ft.Ed25519:return vo(n);case ft.secp256k1:return ga(n);default:throw new hr}}function Me(r){return ae.encode({Type:ft[r.type],Data:r.raw})}var Ou=Symbol.for("nodejs.util.inspect.custom"),Qp=114,hn=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[zi]=!0;toString(){return this.string==null&&(this.string=tt.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return pt.createV1(Qp,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return mt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return mt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Ou](){return`PeerId(${this.toString()})`}},Ws=class extends hn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Zs=class extends hn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},js=class extends hn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},t0=2336,Ys=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=me.digest(G(this.url))}[Ou](){return`PeerId(${this.url})`}[zi]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return pt.createV1(t0,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=lt(t)),t.toString()===this.toString())}};function ya(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=zt(tt.decode(`z${r}`));else{if(t==null)throw new Et('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=zt(t.decode(r))}return dn(e)}function dn(r){if(r0(r))return new Ws({multihash:r});if(e0(r))try{let t=Du(r);if(t.type==="Ed25519")return new Zs({multihash:r,publicKey:t});if(t.type==="secp256k1")return new js({multihash:r,publicKey:t})}catch{let e=lt(r.digest);return new Ys(new URL(e))}throw new Tn("Supplied PeerID Multihash is invalid")}function e0(r){return r.code===me.code}function r0(r){return r.code===Er.code}var Pu=Symbol.for("@achingbrain/uint8arraylist");function Mu(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 Xs(r){return!!r?.[Pu]}var ee=class r{bufs;length;[Pu]=!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(Xs(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(Xs(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=Mu(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Mu(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(Xs(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 Ft(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:Ft(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 h=t>=a&&t<c,f=e>a&&e<=c;if(h&&f){if(t===a&&e===c){n.push(o);break}let u=t-a;n.push(o.subarray(u,u+(e-t)));break}if(h){if(t===0){n.push(o);continue}n.push(o.subarray(t-a));continue}if(f){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(!Xs(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 u=0;u<i;u++)o[u]=-1;for(let u=0;u<s;u++)o[n[u]]=u;let a=o,c=this.byteLength-n.byteLength,h=n.byteLength-1,f;for(let u=e;u<=c;u+=f){f=0;for(let g=h;g>=0;g--){let l=this.get(u+g);if(n[g]!==l){f=Math.max(1,g-a[l]);break}}if(f===0)return u}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=Dt(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=at(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=at(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=at(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=Dt(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=at(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=at(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=at(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=at(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=at(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(!mt(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 pn;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((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,s={})=>{let i={publicKey:at(0),payloadType:at(0),payload:at(0),signature:at(0)},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let a=e.uint32();switch(a>>>3){case 1:{i.publicKey=e.bytes();break}case 2:{i.payloadType=e.bytes();break}case 3:{i.payload=e.bytes();break}case 5:{i.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Ot(e,r.codec(),n)})(pn||(pn={}));var Js=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var mn=class r{static createFromProtobuf=async t=>{let e=pn.decode(t),n=Uu(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e)=>{if(e==null)throw new Error("Missing private key");let n=t.domain,s=t.codec,i=t.marshal(),o=Vu(n,s,i),a=await e.sign(o.subarray());return new r({publicKey:e.publicKey,payloadType:s,payload:i,signature:a})};static openAndCertify=async(t,e)=>{let n=await r.createFromProtobuf(t);if(!await n.validate(e))throw new Js("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(t){let{publicKey:e,payloadType:n,payload:s,signature:i}=t;this.publicKey=e,this.payloadType=n,this.payload=s,this.signature=i}marshal(){return this.marshaled==null&&(this.marshaled=pn.encode({publicKey:Me(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return mt(this.marshal(),t.marshal())}async validate(t){let e=Vu(t,this.payloadType,this.payload);return this.publicKey.verify(e.subarray(),this.signature)}},Vu=(r,t,e)=>{let n=G(r),s=$t(n.byteLength),i=$t(t.length),o=$t(e.length);return new ee(s,n,i,t,o,e)};var Qs=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",h=2**(8*s)-1;for(;;){let f=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let g=Number.parseInt(u,t);if(!Number.isNaN(g))return g});if(f===void 0)break;if(i*=t,i+=f,i>h||(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 Hu=45,n0=15,Cr=new Qs;function ba(r){if(!(r.length>n0))return Cr.new(r).parseWith(()=>Cr.readIPv4Addr())}function wa(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Hu))return Cr.new(r).parseWith(()=>Cr.readIPv6Addr())}function ti(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Hu))return Cr.new(r).parseWith(()=>Cr.readIPAddr())}var Ix=parseInt("0xFFFF",16),Tx=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function ei(r){return!!ba(r)}function ri(r){return!!wa(r)}function ni(r){return!!ti(r)}var qu=ei,c0=ri,xa=function(r){let t=0;if(r=r.toString().trim(),qu(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(c0(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=qu(e[n]),o;i&&(o=xa(e[n]),e[n]=lt(o.slice(0,2),"base16")),o!=null&&++n<8&&e.splice(n,0,lt(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")},zu=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 Nr={},va={},u0=[[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"],[481,-1,"http-path"],[777,-1,"memory"]];u0.forEach(r=>{let t=f0(...r);va[t.code]=t,Nr[t.name]=t});function f0(r,t,e,n,s){return{code:r,size:t,name:e,resolvable:!!n,path:!!s}}function et(r){if(typeof r=="number"){if(va[r]!=null)return va[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Nr[r]!=null)return Nr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var f1=et("ip4"),h1=et("ip6"),d1=et("ipcidr");function Ba(r,t){switch(et(r).code){case 4:case 41:return d0(t);case 42:return Aa(t);case 6:case 273:case 33:case 132:return Wu(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Aa(t);case 421:return y0(t);case 444:return Gu(t);case 445:return Gu(t);case 466:return g0(t);case 481:return globalThis.encodeURIComponent(Aa(t));default:return lt(t,"base16")}}function _a(r,t){switch(et(r).code){case 4:return $u(t);case 41:return $u(t);case 42:return Sa(t);case 6:case 273:case 33:case 132:return Ia(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Sa(t);case 421:return p0(t);case 444:return b0(t);case 445:return w0(t);case 466:return m0(t);case 481:return Sa(globalThis.decodeURIComponent(t));default:return G(t,"base16")}}var Ea=Object.values(Yr).map(r=>r.decoder),h0=function(){let r=Ea[0].or(Ea[1]);return Ea.slice(2).forEach(t=>r=r.or(t)),r}();function $u(r){if(!ni(r))throw new Error("invalid ip address");return xa(r)}function d0(r){let t=zu(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!ni(t))throw new Error("invalid ip address");return t}function Ia(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Wu(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Sa(r){let t=G(r),e=Uint8Array.from($t(t.length));return Ft([e,t],e.length+t.length)}function Aa(r){let t=xe(r);if(r=r.slice(At(t)),r.length!==t)throw new Error("inconsistent lengths");return lt(r)}function p0(r){let t;r[0]==="Q"||r[0]==="1"?t=zt(tt.decode(`z${r}`)).bytes:t=pt.parse(r).multihash.bytes;let e=Uint8Array.from($t(t.length));return Ft([e,t],e.length+t.length)}function m0(r){let t=h0.decode(r),e=Uint8Array.from($t(t.length));return Ft([e,t],e.length+t.length)}function g0(r){let t=xe(r),e=r.slice(At(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+lt(e,"base64url")}function y0(r){let t=xe(r),e=r.slice(At(t));if(e.length!==t)throw new Error("inconsistent lengths");return lt(e,"base58btc")}function b0(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=pe.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=Ia(n);return Ft([e,s],e.length+s.length)}function w0(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=pe.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=Ia(n);return Ft([e,s],e.length+s.length)}function Gu(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=lt(t,"base32"),s=Wu(e);return`${n}:${s}`}function Zu(r){r=Ta(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=et(o);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(i++,i>=s.length)throw Yu("invalid address: "+r);if(a.path===!0){n=Ta(s.slice(i).join("/")),t.push([a.code,_a(a.code,n)]),e.push([a.code,n]);break}let c=_a(a.code,s[i]);t.push([a.code,c]),e.push([a.code,Ba(a.code,c)])}return{string:ju(e),bytes:Ca(t),tuples:t,stringTuples:e,path:n}}function ka(r){let t=[],e=[],n=null,s=0;for(;s<r.length;){let i=xe(r,s),o=At(i),a=et(i),c=x0(a,r.slice(s+o));if(c===0){t.push([i]),e.push([i]),s+=o;continue}let h=r.slice(s+o,s+o+c);if(s+=c+o,s>r.length)throw Yu("Invalid address Uint8Array: "+lt(r,"base16"));t.push([i,h]);let f=Ba(i,h);if(e.push([i,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:ju(e),tuples:t,stringTuples:e,path:n}}function ju(r){let t=[];return r.map(e=>{let n=et(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Ta(t.join("/"))}function Ca(r){return Ft(r.map(t=>{let e=et(t[0]),n=Uint8Array.from($t(e.code));return t.length>1&&t[1]!=null&&(n=Ft([n,t[1]])),n}))}function x0(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=xe(t instanceof Uint8Array?t:Uint8Array.from(t));return e+At(e)}}function Ta(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function Yu(r){return new Error("Error parsing address: "+r)}var v0=Symbol.for("nodejs.util.inspect.custom"),La=Symbol.for("@multiformats/js-multiaddr/multiaddr"),E0=[et("dns").code,et("dns4").code,et("dns6").code,et("dnsaddr").code],Na=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},si=class r{bytes;#t;#e;#r;#n;[La]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=ka(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Zu(t)}else if(Ju(t))e=ka(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=et("tcp"),a=et("udp"),c=et("ip4"),h=et("ip6"),f=et("dns6"),u=et("ip6zone");for(let[l,d]of this.stringTuples())l===u.code&&(i=`%${d??""}`),E0.includes(l)&&(e=o.name,s=443,n=`${d??""}${i}`,t=l===f.code?6:4),(l===o.code||l===a.code)&&(e=et(l).name,s=parseInt(d??"")),(l===c.code||l===h.code)&&(e=et(l).name,n=`${d??""}${i}`,t=l===h.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({},et(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>et(t).name)}tuples(){return this.#e.map(([t,e])=>e==null?[t]:[t,e])}stringTuples(){return this.#r.map(([t,e])=>e==null?[t]:[t,e])}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(Ca(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,s])=>{n===Nr.p2p.code&&t.push([n,s]),n===Nr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?lt(tt.decode(`z${n}`),"base58btc"):lt(pt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return mt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(i=>i.resolvable);if(e==null)return[this];let n=Xu.get(e.name);if(n==null)throw new Na(`no available resolver for ${e.name}`);return(await n(this,t)).map(i=>xt(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)}[v0](){return`Multiaddr(${this.#t})`}};var Xu=new Map;function Ju(r){return!!r?.[La]}function xt(r){return new si(r)}function re(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var ii=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function oi(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new ii(e?.errorMessage,e?.errorCode,e?.errorName));let n,s=new ii(e?.errorMessage,e?.errorCode,e?.errorName);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 Ra=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=re(),this.haveNext=re()}[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=re(),t}async throw(t){return this.ended=!0,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return 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");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=re(),await oi(this.readNext.promise,e?.signal,e)}};function Qu(){return new Ra}var ai=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Ua=class extends Error{code;constructor(t,e){super(t),this.code=e}},Da=class extends Ua{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function tf(r,t){let e=Qu();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,h=new Promise((f,u)=>{c=()=>{u(new Da("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(o==null){let{done:u,value:g}=await Promise.race([n.next(),h]);return u===!0?new ee:g}for(;s.byteLength<o;){let{value:u,done:g}=await Promise.race([n.next(),h]);if(g===!0)throw new ai("unexpected end of input");s.append(u)}let f=s.sublist(0,o);return s.consume(o),f}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 ci=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},li=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ui=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function ef(r,t={}){let e=tf(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=At(t.maxDataLength));let n=t?.lengthDecoder??xe,s=t?.lengthEncoder??$t;return{read:async o=>{let a=-1,c=new ee;for(;;){c.append(await e.read(1,o));try{a=n(c)}catch(h){if(h instanceof RangeError)continue;throw h}if(a<0)throw new ci("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new ui("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new li("message length 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(h=>[s(h.byteLength),h]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Ge(r,t){let e=ef(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 Oa=1e3,rf=60*Oa,fi=290,nf=15,sf=2*60*rf,of=1,hi=2e3,af=100,Ma="circuit-relay-source",gn=`${$i}-circuit-relay`,Pa=`${$i}-circuit-relay-source`,cf=2*rf,lf=BigInt(1<<17),Wt="/libp2p/circuit/relay/0.2.0/hop",ar="/libp2p/circuit/relay/0.2.0/stop",uf=30*Oa,n2=30*Oa,yn=300,ff=4096,hf=.001;var X;(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=()=>sr(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Pt((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),Lr.codec().encode(s.peer,i)),s.reservation!=null&&(i.uint32(26),di.codec().encode(s.reservation,i)),s.limit!=null&&(i.uint32(34),Rr.codec().encode(s.limit,i)),s.status!=null&&(i.uint32(40),K.codec().encode(s.status,i)),o.lengthDelimited!==!1&&i.ldelim()},(s,i,o={})=>{let a={},c=i==null?s.len:s.pos+i;for(;s.pos<c;){let h=s.uint32();switch(h>>>3){case 1:{a.type=r.Type.codec().decode(s);break}case 2:{a.peer=Lr.codec().decode(s,s.uint32(),{limits:o.limits?.peer});break}case 3:{a.reservation=di.codec().decode(s,s.uint32(),{limits:o.limits?.reservation});break}case 4:{a.limit=Rr.codec().decode(s,s.uint32(),{limits:o.limits?.limit});break}case 5:{a.status=K.codec().decode(s);break}default:{s.skipType(h&7);break}}}return a})),n),r.encode=s=>Mt(s,r.codec()),r.decode=(s,i)=>Ot(s,r.codec(),i)})(X||(X={}));var Kt;(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=()=>sr(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Pt((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),Lr.codec().encode(s.peer,i)),s.limit!=null&&(i.uint32(26),Rr.codec().encode(s.limit,i)),s.status!=null&&(i.uint32(32),K.codec().encode(s.status,i)),o.lengthDelimited!==!1&&i.ldelim()},(s,i,o={})=>{let a={},c=i==null?s.len:s.pos+i;for(;s.pos<c;){let h=s.uint32();switch(h>>>3){case 1:{a.type=r.Type.codec().decode(s);break}case 2:{a.peer=Lr.codec().decode(s,s.uint32(),{limits:o.limits?.peer});break}case 3:{a.limit=Rr.codec().decode(s,s.uint32(),{limits:o.limits?.limit});break}case 4:{a.status=K.codec().decode(s);break}default:{s.skipType(h&7);break}}}return a})),n),r.encode=s=>Mt(s,r.codec()),r.decode=(s,i)=>Ot(s,r.codec(),i)})(Kt||(Kt={}));var Lr;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((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,s={})=>{let i={id:at(0),addrs:[]},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let a=e.uint32();switch(a>>>3){case 1:{i.id=e.bytes();break}case 2:{if(s.limits?.addrs!=null&&i.addrs.length===s.limits.addrs)throw new Qr('Decode error - map field "addrs" had too many elements');i.addrs.push(e.bytes());break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Ot(e,r.codec(),n)})(Lr||(Lr={}));var di;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((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),pi.codec().encode(e.voucher,n)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let i={expire:0n,addrs:[]},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let a=e.uint32();switch(a>>>3){case 1:{i.expire=e.uint64();break}case 2:{if(s.limits?.addrs!=null&&i.addrs.length===s.limits.addrs)throw new Qr('Decode error - map field "addrs" had too many elements');i.addrs.push(e.bytes());break}case 3:{i.voucher=pi.codec().decode(e,e.uint32(),{limits:s.limits?.voucher});break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Ot(e,r.codec(),n)})(di||(di={}));var Rr;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((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,s={})=>{let i={},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let a=e.uint32();switch(a>>>3){case 1:{i.duration=e.uint32();break}case 2:{i.data=e.uint64();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Ot(e,r.codec(),n)})(Rr||(Rr={}));var K;(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"})(K||(K={}));var Va;(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"})(Va||(Va={}));(function(r){r.codec=()=>sr(Va)})(K||(K={}));var Ur;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((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,s={})=>{let i={relay:at(0),peer:at(0),expiration:0n},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let a=e.uint32();switch(a>>>3){case 1:{i.relay=e.bytes();break}case 2:{i.peer=e.bytes();break}case 3:{i.expiration=e.uint64();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Ot(e,r.codec(),n)})(Ur||(Ur={}));var pi;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((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&&(n.uint32(26),Ur.codec().encode(e.payload,n)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let i={publicKey:at(0),payloadType:at(0),signature:at(0)},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let a=e.uint32();switch(a>>>3){case 1:{i.publicKey=e.bytes();break}case 2:{i.payloadType=e.bytes();break}case 3:{i.payload=Ur.codec().decode(e,e.uint32(),{limits:s.limits?.payload});break}case 5:{i.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Ot(e,r.codec(),n)})(pi||(pi={}));var S0=r=>r.toString().split("/").slice(1),Dr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),F=r=>({match:t=>Dr(e=>e===r).match(t),pattern:r}),cr=()=>({match:r=>Dr(t=>typeof t=="string").match(r),pattern:"{string}"}),bn=()=>({match:r=>Dr(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),Q=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{tt.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),wn=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Mo.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),W=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),It=(...r)=>({match:t=>{let e;for(let n of r){let s=n.match(t);s!==!1&&(e==null||s.length<e.length)&&(e=s)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),q=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function nt(...r){function t(s){let i=S0(s);for(let o of r){let a=o.match(i);if(a===!1)return!1;i=a}return i}function e(s){return t(s)!==!1}function n(s){let i=t(s);return i===!1?!1:i.length===0}return{matchers:r,matches:e,exactMatch:n}}var gi=q(F("dns4"),cr()),yi=q(F("dns6"),cr()),bi=q(F("dnsaddr"),cr()),Fa=q(F("dns"),cr()),d2=nt(gi,W(Q())),p2=nt(yi,W(Q())),m2=nt(bi,W(Q())),g2=nt(It(Fa,bi,gi,yi),W(Q())),df=q(F("ip4"),Dr(ei)),pf=q(F("ip6"),Dr(ri)),Ka=It(df,pf),ke=It(Ka,Fa,gi,yi,bi),y2=nt(It(Ka,q(It(Fa,bi,gi,yi),W(Q())))),b2=nt(df),w2=nt(pf),x2=nt(Ka),qa=q(ke,F("tcp"),bn()),xn=q(ke,F("udp"),bn()),v2=nt(q(qa,W(Q()))),E2=nt(xn),za=q(xn,F("quic"),W(Q())),wi=q(xn,F("quic-v1"),W(Q())),A0=It(za,wi),S2=nt(za),A2=nt(wi),Ha=It(ke,qa,xn,za,wi),mf=It(q(Ha,F("ws"),W(Q()))),B2=nt(mf),gf=It(q(Ha,F("wss"),W(Q())),q(Ha,F("tls"),W(q(F("sni"),cr())),F("ws"),W(Q()))),_2=nt(gf),yf=q(xn,F("webrtc-direct"),W(wn()),W(wn()),W(Q())),I2=nt(yf),bf=q(wi,F("webtransport"),W(wn()),W(wn()),W(Q())),T2=nt(bf),mi=It(mf,gf,q(qa,W(Q())),q(A0,W(Q())),q(ke,W(Q())),yf,bf,Q()),wf=nt(mi),B0=q(mi,F("p2p-circuit"),Q()),xi=nt(B0),_0=It(q(mi,F("p2p-circuit"),F("webrtc"),W(Q())),q(mi,F("webrtc"),W(Q())),q(F("webrtc"),W(Q()))),k2=nt(_0),I0=It(q(ke,F("tcp"),bn(),F("http"),W(Q())),q(ke,F("http"),W(Q()))),C2=nt(I0),T0=It(q(ke,F("tcp"),It(q(F("443"),F("http")),q(bn(),F("https"))),W(Q())),q(ke,F("tls"),F("http"),W(Q())),q(ke,F("https"),W(Q()))),N2=nt(T0),k0=It(q(F("memory"),cr(),W(Q()))),L2=nt(k0);function vi(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}var Ei=class extends Error{constructor(t="Transfer limit error"){super(t),this.name="TransferLimitError"}},vn=class extends Error{constructor(t="Duration limit error"){super(t),this.name="DurationLimitError"}},En=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},Si=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},Ai=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};async function*xf(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 Ei(`data limit of ${n} bytes exceeded`)}t.remaining-=i,yield s}}function vf(r,t,e,n,s){function i(u){r.abort(u),t.abort(u)}let o=[e,n.signal];n.limit?.duration!=null&&(s.log("limiting relayed connection duration to %dms",n.limit.duration),o.push(AbortSignal.timeout(n.limit.duration)));let a=vi(o),c=!1,h=!1,f;n.limit?.data!=null&&(f={remaining:n.limit.data}),queueMicrotask(()=>{let u=()=>{s.log("relayed connection reached time limit"),t.abort(new vn(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",u,{once:!0}),t.sink(f==null?r.source:xf(r.source,f,s)).catch(g=>{s.log.error("error while relaying streams src -> dst",g),i(g)}).finally(()=>{c=!0,h&&(a.removeEventListener("abort",u),a.clear())})}),queueMicrotask(()=>{let u=()=>{s.log("relayed connection reached time limit"),r.abort(new vn(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",u,{once:!0}),r.sink(f==null?t.source:xf(t.source,f,s)).catch(g=>{s.log.error("error while relaying streams dst -> src",g),i(g)}).finally(()=>{h=!0,c&&(a.removeEventListener("abort",u),a.clear())})})}function $a(r){let t=r*BigInt(1e3),e=new Date().getTime();return Number(t-BigInt(e))}var Sn=class{expires;bytes;constructor(t){t?.duration!=null&&t?.duration!==0&&(this.expires=Date.now()+t.duration*1e3),this.bytes=t?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(t){this.bytes!=null&&(this.bytes-=BigInt(t.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let t={};if(this.bytes!=null){let e=this;Object.defineProperty(t,"bytes",{get(){return e.bytes}})}if(this.expires!=null){let e=this;Object.defineProperty(t,"seconds",{get(){return Math.round(((e.expires??0)-Date.now())/1e3)}})}return t}},Bi=nt(q(wf.matchers[0],F("p2p-circuit"))),_i=nt(F("p2p-circuit"));function Ii(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 We=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return Ii(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return Ii(this.map.values(),t=>t.key)}values(){return Ii(this.map.values(),t=>t.value)}get size(){return this.map.size}};var Ga=64,ne=class{fp;h;seed;constructor(t,e,n,s=2){if(s>Ga)throw new TypeError("Invalid Fingerprint Size");let i=e.hashV(t,n),o=at(s);for(let a=0;a<o.length;a++)o[a]=i[a];o.length===0&&(o[0]=7),this.fp=o,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?mt(this.fp,t.fp):!1}};function lr(r,t){return Math.floor(Math.random()*(t-r))+r}var ur=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof ne))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof ne))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof ne))throw new TypeError("Invalid Fingerprint");let e=lr(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof ne))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Wa={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Bf={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},_f=new globalThis.TextEncoder;function C0(r,t){let e=Wa[t],n=Bf[t];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(t,n*e);return n}function N0(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Wa[t],s=Bf[t],i=r;for(;i.length>0;){let o=_f.encodeInto(i,e);i=i.slice(o.read);for(let a=0;a<o.written;a++)s^=BigInt(e[a]),s=BigInt.asUintN(t,s*n)}return s}function Za(r,{size:t=32,utf8Buffer:e}={}){if(!Wa[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return N0(r,t,e);r=_f.encode(r)}return C0(r,t)}var L0=pc(Af(),1);var Bn={hash:r=>Number(Za(r,{size:32})),hashV:(r,t)=>R0(Bn.hash(r,t))};function R0(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),G(t,"base16")}var U0=500,_n=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??Bn,this.seed=t.seed??lr(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=G(t));let e=new ne(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new ur(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new ur(this.bucketSize)),this.buckets[n].add(e)||this.buckets[s].add(e))return this.count++,!0;let i=[n,s],o=i[lr(0,i.length-1)];this.buckets[o]==null&&(this.buckets[o]=new ur(this.bucketSize));for(let a=0;a<U0;a++){let c=this.buckets[o].swap(e);if(c!=null&&(o=(o^c.hash())%this.filterSize,this.buckets[o]==null&&(this.buckets[o]=new ur(this.bucketSize)),this.buckets[o].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=G(t));let e=new ne(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.has(e)??!1;if(s)return s;let i=(n^e.hash())%this.filterSize;return this.buckets[i]?.has(e)??!1}remove(t){typeof t=="string"&&(t=G(t));let e=new ne(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.remove(e)??!1;if(s)return this.count--,s;let i=(n^e.hash())%this.filterSize,o=this.buckets[i]?.remove(e)??!1;return o&&this.count--,o}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},D0={1:.5,2:.84,4:.95,8:.98};function O0(r=.001){return r>.002?2:r>1e-5?4:8}function If(r,t=.001){let e=O0(t),n=D0[e],s=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Ga);return{filterSize:s,bucketSize:e,fingerprintSize:i}}var ki=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??Bn,this.seed=t.seed??lr(0,Math.pow(2,10)),this.filterSeries=[new _n({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=G(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new _n({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=G(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=G(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function Or(r,t=.001,e){return new ki({...If(r,t),...e??{}})}var Ci=class{filter;constructor(t,e){this.filter=Or(t,e)}has(t){return this.filter.has(t.toMultihash().bytes)}add(t){this.filter.add(t.toMultihash().bytes)}remove(t){this.filter.remove?.(t.toMultihash().bytes)}};function ja(r,t=.001){return new Ci(r,t)}var Ya=class extends We{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Xa(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Ya({name:t,metrics:e}):n=new We,n}var Ja=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};function Tf(r,t){let e=new Ja(t?.errorMessage,t?.errorCode,t?.errorName),n=new AbortController,s=()=>{n.abort(e)},i=AbortSignal.timeout(r);i.addEventListener("abort",s);let o=n.signal;return o.reset=a=>{i?.removeEventListener("abort",s),i=AbortSignal.timeout(a??r),i.addEventListener("abort",()=>{n.abort(e)})},o.clear=()=>{i?.removeEventListener("abort",s),i=void 0},o}var Ni=class{reservations;maxReservations;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:circuit-relay:server:reservation-store"),this.maxReservations=e.maxReservations??nf,this.applyDefaultLimit=e.applyDefaultLimit!==!1,this.reservationTtl=e.reservationTtl??sf,this.defaultDurationLimit=e.defaultDurationLimit??cf,this.defaultDataLimit=e.defaultDataLimit??lf,this.reservations=Xa({metrics:t.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(t,e,n){let s=this.reservations.get(t);if(this.reservations.size>=this.maxReservations&&s==null)return{status:K.RESERVATION_REFUSED};let i=new Date(Date.now()+this.reservationTtl),o;return this.applyDefaultLimit&&(o=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),s!=null?(this.log("refreshing reservation for client %p",t),s.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",t),s={addr:e,expiry:i,limit:o,signal:Tf(this.reservationTtl)}),this.reservations.set(t,s),s.signal.addEventListener("abort",()=>{this.reservations.delete(t)}),{status:K.OK,expire:Math.round(i.getTime()/1e3)}}removeReservation(t){this.reservations.delete(t)}get(t){return this.reservations.get(t)}clear(){this.reservations.clear()}};var Li=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 Ur.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,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 kf=r=>r.protoCodes().includes(fi),M0={maxOutboundStopStreams:yn},Qa=class extends qt{registrar;peerStore;addressManager;peerId;privateKey;connectionManager;connectionGater;reservationStore;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.privateKey=t.privateKey,this.connectionManager=t.connectionManager,this.connectionGater=t.connectionGater,this.started=!1,this.hopTimeout=e?.hopTimeout??uf,this.maxInboundHopStreams=e.maxInboundHopStreams,this.maxOutboundHopStreams=e.maxOutboundHopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??M0.maxOutboundStopStreams,this.reservationStore=new Ni(t,e.reservations),this.shutdownController=new AbortController,Lt(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.registrar.handle(Wt,t=>{this.onHop(t).catch(e=>{this.log.error(e)})},{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.registrar.unhandle(Wt),this.started=!1}async onHop({connection:t,stream:e}){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n={signal:AbortSignal.timeout(this.hopTimeout)},s=Ge(e);try{let i=await s.pb(X).read(n);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:t,stream:s,request:i},n)}catch(i){this.log.error("error while handling hop",i),await s.pb(X).write({type:X.Type.STATUS,status:K.MALFORMED_MESSAGE},n),e.abort(i)}}async handleHopProtocol({stream:t,request:e,connection:n},s){switch(this.log("received hop message"),e.type){case X.Type.RESERVE:await this.handleReserve({stream:t,request:e,connection:n},s);break;case X.Type.CONNECT:await this.handleConnect({stream:t,request:e,connection:n},s);break;default:this.log.error("invalid hop request type %s via peer %p",e.type,n.remotePeer),await t.pb(X).write({type:X.Type.STATUS,status:K.UNEXPECTED_MESSAGE})}}async handleReserve({stream:t,connection:e},n){let s=t.pb(X);if(this.log("hop reserve request from %p",e.remotePeer),kf(e.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",e.remotePeer),await s.write({type:X.Type.STATUS,status:K.PERMISSION_DENIED},n);return}if(await this.connectionGater.denyInboundRelayReservation?.(e.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",e.remotePeer),await s.write({type:X.Type.STATUS,status:K.PERMISSION_DENIED},n);return}let i=this.reservationStore.reserve(e.remotePeer,e.remoteAddr);try{if(i.status!==K.OK){await s.write({type:X.Type.STATUS,status:i.status},n);return}if(i.expire!=null){let o=i.expire*1e3-Date.now();await this.peerStore.merge(e.remotePeer,{tags:{[Ma]:{value:1,ttl:o},[Pa]:{value:1,ttl:o}}})}await s.write({type:X.Type.STATUS,status:K.OK,reservation:await this.makeReservation(e.remotePeer,BigInt(i.expire??0)),limit:this.reservationStore.get(e.remotePeer)?.limit},n),this.log("sent confirmation response to %s",e.remotePeer)}catch(o){this.log.error("failed to send confirmation response to %p - %e",e.remotePeer,o),this.reservationStore.removeReservation(e.remotePeer);try{await this.peerStore.merge(e.remotePeer,{tags:{[Ma]:void 0,[Pa]:void 0}})}catch(a){this.log.error("failed to untag relay source peer %p - %e",e.remotePeer,a)}}}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 mn.seal(new Li({peer:t,relay:this.peerId,expiration:e}),this.privateKey);return{addrs:n,expire:e,voucher:{publicKey:Me(s.publicKey),payloadType:s.payloadType,payload:{peer:t.toMultihash().bytes,relay:this.peerId.toMultihash().bytes,expiration:e},signature:s.signature}}}async handleConnect({stream:t,request:e,connection:n},s){let i=t.pb(X);if(kf(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await i.write({type:X.Type.STATUS,status:K.PERMISSION_DENIED},s);return}this.log("hop connect request from %p",n.remotePeer);let o;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(xt),o=dn(zt(e.peer.id))}catch(g){this.log.error("invalid hop connect request via peer %p %s",n.remotePeer,g),await i.write({type:X.Type.STATUS,status:K.MALFORMED_MESSAGE},s);return}let a=this.reservationStore.get(o);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",o,n.remotePeer,K.NO_RESERVATION),await i.write({type:X.Type.STATUS,status:K.NO_RESERVATION},s);return}if(await this.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,o)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,o),await i.write({type:X.Type.STATUS,status:K.PERMISSION_DENIED},s);return}let c=this.connectionManager.getConnections(o);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",o,n.remotePeer),await i.write({type:X.Type.STATUS,status:K.NO_RESERVATION},s);return}let h=c[0],f=await this.stopHop({connection:h,request:{type:Kt.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},s);if(f==null){this.log.error("failed to open stream to destination peer %p",h?.remotePeer),await i.write({type:X.Type.STATUS,status:K.CONNECTION_FAILED},s);return}await i.write({type:X.Type.STATUS,status:K.OK,limit:a?.limit},s);let u=t.unwrap();this.log("connection from %p to %p established - merging streams",n.remotePeer,o),vf(u,f,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:t,request:e},n){this.log("starting circuit relay v2 stop request to %s",t.remotePeer);let s=await t.newStream([ar],{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),i=Ge(s),o=i.pb(Kt);await o.write(e,n);let a;try{a=await o.read(n)}catch{this.log.error("error parsing stop message response from %p",t.remotePeer)}if(a==null){this.log.error("could not read response from %p",t.remotePeer),await s.close(n);return}if(a.status===K.OK)return this.log("stop request to %p was successful",t.remotePeer),i.unwrap();this.log("stop request failed with code %d",a.status),await s.close(n)}get reservations(){return this.reservationStore.reservations}};function Cf(r={}){return t=>new Qa(t,r)}function P0(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var Nf=P0;function V0(r){return r[Symbol.asyncIterator]!=null}function Lf(r){return r?.then!=null}function H0(r,t){let e=0;if(V0(r))return async function*(){for await(let c of r){let h=t(c,e++);Lf(h)&&await h,yield c}}();let n=Nf(r),{value:s,done:i}=n.next();if(i===!0)return function*(){}();if(typeof t(s,e++)?.then=="function")return async function*(){yield s;for await(let c of n){let h=t(c,e++);Lf(h)&&await h,yield c}}();let a=t;return function*(){yield s;for(let c of n)a(c,e++),yield c}()}var Rf=H0;var Ri=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}},Mr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Ri(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 Ri(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 tc=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Pr(r={}){return F0(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 F0(r,t){t=t??{};let e=t.onEnd,n=new Mr,s,i,o,a=re(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((y,b)=>{i=w=>{i=null,n.push(w);try{y(r(n))}catch(m){b(m)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=re()})}},h=y=>i!=null?i(y):(n.push(y),s),f=y=>(n=new Mr,i!=null?i({error:y}):(n.push({error:y}),s)),u=y=>{if(o)return s;if(t?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return h({done:!1,value:y})},g=y=>o?s:(o=!0,y!=null?f(y):h({done:!0})),l=()=>(n=new Mr,g(),{done:!0}),d=y=>(g(y),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:l,throw:d,push:u,end:g,get readableLength(){return n.size},onEmpty:async y=>{let b=y?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let w,m;b!=null&&(w=new Promise((E,A)=>{m=()=>{A(new tc)},b.addEventListener("abort",m)}));try{await Promise.race([a.promise,w])}finally{m!=null&&b!=null&&b?.removeEventListener("abort",m)}}},e==null)return s;let p=s;return s={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(y){return p.throw(y),e!=null&&(e(y),e=void 0),{done:!0}},return(){return p.return(),e!=null&&(e(),e=void 0),{done:!0}},push:u,end(y){return p.end(y),e!=null&&(e(y),e=void 0),s},get readableLength(){return p.readableLength},onEmpty:y=>p.onEmpty(y)},s}function K0(r){return r[Symbol.asyncIterator]!=null}function q0(...r){let t=[];for(let e of r)K0(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=Pr({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let s of n)e.push(s)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var Uf=q0;function Df(r,...t){if(r==null)throw new Error("Empty pipeline");if(ec(r)){let n=r;r=()=>n.source}else if(Mf(r)||Of(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&ec(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)ec(e[n])&&(e[n]=$0(e[n]));return z0(...e)}var z0=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Of=r=>r?.[Symbol.asyncIterator]!=null,Mf=r=>r?.[Symbol.iterator]!=null,ec=r=>r==null?!1:r.sink!=null&&r.source!=null,$0=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Pr({objectMode:!0});e.then(()=>{n.end()},o=>{n.end(o)});let s,i=r.source;if(Of(i))s=async function*(){yield*i,n.end()};else if(Mf(i))s=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Uf(n,s())}return r.source};function rc(r){let{stream:t,remoteAddr:e,logger:n,onDataRead:s,onDataWrite:i}=r,o=n.forComponent("libp2p:stream:converter"),a=!1,c=!1,h=t.close.bind(t);t.close=async d=>{await h(d),l(!0)};let f=t.abort.bind(t);t.abort=d=>{f(d),l(!0)};let u=t.sink.bind(t);t.sink=async d=>{try{await u(Df(d,p=>Rf(p,y=>i?.(y))))}catch(p){p.type!=="aborted"&&o.error("%s error in sink",e,p)}finally{c=!0,l()}};let g={log:o,sink:t.sink,source:async function*(){try{for await(let d of t.source)s?.(d),yield d}finally{a=!0,l()}}(),remoteAddr:e,timeline:{open:Date.now(),close:void 0},close:t.close,abort:t.abort};function l(d){d===!0&&(a=!0,c=!0),a&&c&&g.timeline.close==null&&(g.timeline.close=Date.now())}return g}var Ze=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var nc=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 Ui(r,t,e,n){let s=new nc(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(s):new Promise((i,o)=>{function a(){e?.removeEventListener("abort",f),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,h)}let c=u=>{try{if(n?.filter?.(u)===!1)return}catch(g){a(),o(g);return}a(),i(u)},h=u=>{a(),o(u.detail)},f=()=>{a(),o(s)};e?.addEventListener("abort",f),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,h)})}var Di=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var Oi=class{deferred;signal;constructor(t){this.signal=t,this.deferred=re(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new he)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function G0(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Mi=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=G0(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,Lt(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 he),this.cleanup())}async join(t={}){let e=new Oi(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 oi(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.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var Pi=class extends qt{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??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.sort=t.sort,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){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Di;let n=new Mi(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new he)}),this.clear()}async onEmpty(t){this.size!==0&&await Ui(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await Ui(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Ui(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=Pr({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 he("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 Vr=class extends Pi{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var Vi=class extends qt{peerStore;registrar;connectionManager;randomWalk;started;running;topologyId;log;discoveryController;filter;queue;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.started=!1,this.running=!1,this.peerStore=t.peerStore,this.registrar=t.registrar,this.connectionManager=t.connectionManager,this.randomWalk=t.randomWalk,this.filter=e.filter,this.discoveryController=new AbortController,Lt(1/0,this.discoveryController.signal)}isStarted(){return this.started}async start(){this.topologyId=await this.registrar.register(Wt,{filter:this.filter,onConnect:t=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",t,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:t})}}),this.started=!0}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.discoveryController?.abort(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,Lt(1/0,this.discoveryController.signal),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let t=await this.peerStore.all({filters:[n=>n.protocols.includes(Wt)],orders:[()=>Math.random()<.5?1:-1,(n,s)=>{let i=Pf(n),o=Pf(s);return i>o?-1:o>i?1:0}]});for(let n of t)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",t.length);let e=this.queue=new Vr({concurrency:5});this.log("start random walk");for await(let n of this.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),e.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(s=>s.toString()));continue}e.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await e.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,e.size,e.running),e.add(async()=>{let s=vi([this.discoveryController.signal,AbortSignal.timeout(5e3)]);Lt(1/0,s);try{await this.connectionManager.openConnection(n.id,{signal:s})}finally{s.clear()}},{peerId:n.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to random peer %p",n.id,s)})}this.log("stop random walk"),await e.onIdle()}).catch(t=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network",t)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort()}};function Pf(r){let t=r.metadata.get("last-dial-success");return t==null?0:new Date(lt(t)).getTime()}var sc=class extends qt{connectionManager;reservationStore;discovery;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=t.connectionManager,this.reservationStore=t.relayStore,this.listeningAddrs=[],this.listenTimeout=e.listenTimeout??hi,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=t=>{this.log("relay removed %p our relay %p",t.detail.relay,this.relay,this.relay?.equals(t.detail.relay)),this.relay?.equals(t.detail.relay)===!0&&(this.log("relay peer removed %p",t.detail.relay),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=t=>{let{relay:e,details:n}=t.detail;n.type!=="configured"&&n.id===this.reservationId&&(this.log("relay peer added %p",e),this.relay=e,this.listeningAddrs=n.reservation.addrs.map(s=>xt(s).encapsulate("/p2p-circuit")),this.safeDispatchEvent("listening"))};async listen(t){if(this.log("listen on %a",t),_i.exactMatch(t))this.reservationId=this.reservationStore.reserveRelay();else if(Bi.exactMatch(t)){let e=AbortSignal.timeout(this.listenTimeout);Lt(1/0,e);let n=t.decapsulate("/p2p-circuit"),s=await this.connectionManager.openConnection(n,{signal:e});if(!this.reservationStore.hasReservation(s.remotePeer)){this.log("making reservation on peer %p",s.remotePeer);let i=await this.reservationStore.addRelay(s.remotePeer,"configured");this.log("made reservation on peer %p",s.remotePeer),this.relay=i.relay,this.listeningAddrs=i.details.reservation.addrs.map(o=>xt(o).encapsulate("/p2p-circuit")),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}}else throw new je(`Could not listen on p2p-circuit address "${t}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};function Vf(r){return new sc(r)}var Hf="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Ff=(r=21)=>{let t="",e=crypto.getRandomValues(new Uint8Array(r));for(;r--;)t+=Hf[e[r]&63];return t};var W0=60*1e3*10,Z0=60*1e3*5,j0=30*1e3,Hi=class extends qt{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(t,e){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=t.peerId,this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.reservations=new We,this.pendingReservations=[],this.maxReservationQueueLength=e?.maxReservationQueueLength??af,this.reservationCompletionTimeout=e?.reservationCompletionTimeout??hi,this.started=!1,this.relayFilter=Or(100),this.reserveQueue=new Vr({concurrency:e?.reservationConcurrency??of,metricName:"libp2p_relay_reservation_queue",metrics:t.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(i=>i.connection===n.detail.id)!=null&&this.#e(n.detail.remotePeer).catch(i=>{this.log("could not remove relay %p - %e",n.detail,i)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let t=await this.peerStore.all({filters:[e=>e.tags.has(gn)]});this.log("removing tag from %d old relays",t.length),await Promise.all(t.map(async e=>{await this.peerStore.merge(e.id,{tags:{[gn]:void 0}})})),this.log("redialing %d old relays",t.length),await Promise.all(t.map(async e=>this.addRelay(e.id,"discovered"))),this.#r()}).catch(t=>{this.log.error(t)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:t})=>{clearTimeout(t)}),this.reservations.clear(),this.started=!1}reserveRelay(){let t=Ff();return this.pendingReservations.push(t),this.#r(),t}async addRelay(t,e){if(this.peerId.equals(t))throw this.log.trace("not trying to use self as relay"),new je("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new Ai("The reservation queue is full");let n=this.reserveQueue.find(t);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",t),n.join();if(this.relayFilter.has(t.toMultihash().bytes))throw new je("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",t),this.reserveQueue.add(async()=>{let s=Date.now();try{let i=this.reservations.get(t);if(i!=null){let d=this.connectionManager.getConnections(t),p=!1;if(d.length===0&&this.log("already have relay reservation with %p but we are no longer connected",t),d.map(y=>y.id).includes(i.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",t),p=!0),p&&$a(i.reservation.expire)>W0)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",t),{relay:t,details:i};await this.#e(t)}if(e==="discovered"&&this.pendingReservations.length===0)throw new En("Not making reservation on discovered relay because we do not need any more relays");let o=AbortSignal.timeout(this.reservationCompletionTimeout);Lt(1/0,o);let a=await this.connectionManager.openConnection(t,{signal:o});if(xi.matches(a.remoteAddr))throw new Si("not creating reservation over relayed connection");let c=await this.#t(a,{signal:o}),h=$a(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",t,new Date(Date.now()+h).toString());let f=Math.min(Math.max(h-Z0,j0),Math.pow(2,31)-1),u=setTimeout(()=>{this.log("refresh reservation to relay %p",t),this.addRelay(t,e).catch(async d=>{this.log.error("could not refresh reservation to relay %p - %e",t,d),await this.#e(t)}).catch(d=>{this.log.error("could not remove expired reservation to relay %p - %e",t,d)})},f),g;if(e==="discovered"){let d=this.pendingReservations.pop();if(d==null)throw new En("Made reservation on relay but did not need any more discovered relays");g={timeout:u,reservation:c,type:e,connection:a.id,id:d}}else g={timeout:u,reservation:c,type:e,connection:a.id};this.reservations.set(t,g),await this.peerStore.merge(t,{tags:{[gn]:{value:1,ttl:h}}}),this.#r();let l={relay:t,details:g};return this.safeDispatchEvent("relay:created-reservation",{detail:l}),l}catch(i){throw e==="discovered"&&i.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",t,Date.now()-s,i),(i.name==="DialError"||i.name==="UnsupportedProtocolError")&&this.relayFilter.add(t.toMultihash().bytes),this.#e(t).catch(o=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",t,o)}),i}},{peerId:t})}hasReservation(t){return this.reservations.has(t)}getReservation(t){return this.reservations.get(t)?.reservation}reservationCount(t){return t==null?this.reservations.size:[...this.reservations.values()].reduce((e,n)=>(n.type===t&&e++,e),0)}cancelReservations(){[...this.reservations.values()].forEach(t=>{clearTimeout(t.timeout)}),this.reservations.clear()}async#t(t,e){e.signal?.throwIfAborted(),this.log("requesting reservation from %p",t.remotePeer);let n=await t.newStream(Wt,e),i=Ge(n).pb(X);this.log.trace("send RESERVE to %p",t.remotePeer),await i.write({type:X.Type.RESERVE},e);let o;try{this.log.trace("reading response from %p",t.remotePeer),o=await i.read(e)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(e)}if(this.log.trace("read response %o",o),o.status===K.OK&&o.reservation!=null){let c=new Set;c.add(t.remoteAddr.toString());for(let h of o.reservation.addrs){let f=xt(h);f.getPeerId()==null&&(f=f.encapsulate(`/p2p/${t.remotePeer}`)),f=xt(f.toString().replace(`/p2p/${t.remotePeer}/p2p/${t.remotePeer}`,`/p2p/${t.remotePeer}`)),c.add(f.toString())}return o.reservation.addrs=[...c].map(h=>xt(h).bytes),o.reservation}let a=`reservation failed with status ${o.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#e(t){let e=this.reservations.get(t);e!=null&&(this.log("removing relay reservation with %p from local store",t),clearTimeout(e.timeout),this.reservations.delete(t),e.type==="discovered"&&this.pendingReservations.push(e.id),await this.peerStore.merge(t,{tags:{[gn]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:t,details:e}}),this.#r())}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=Or(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var Y0=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(xt)}catch{return!1}return!0},ic={maxInboundStopStreams:yn,maxOutboundStopStreams:yn,stopTimeout:3e4},Fi=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??ic.maxInboundStopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??ic.maxOutboundStopStreams,this.stopTimeout=e.stopTimeout??ic.stopTimeout,this.discovery=new Vi(t,{filter:e.discoveryFilter??ja(ff,hf)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(s=>{s.name!=="HadEnoughRelaysError"&&s.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p",n.detail,s)})}),this.reservationStore=new Hi(t,e),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[xc]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[vc](){return this.discovery!=null?["@libp2p/identify"]:[]}[gc]=!0;isStarted(){return this.started}async start(){await this.registrar.handle(ar,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,runOnLimitedConnection:!0}),await bc(this.discovery,this.reservationStore),this.started=!0}async stop(){await wc(this.discovery,this.reservationStore),await this.registrar.unhandle(ar),this.started=!1}async dial(t,e){if(t.protoCodes().filter(l=>l===fi).length!==1){let l="Invalid circuit relay address";throw this.log.error(l,t),new Fr(l)}let n=t.toString().split("/p2p-circuit"),s=xt(n[0]),i=xt(n[n.length-1]),o=s.getPeerId(),a=i.getPeerId();if(o==null||a==null){let l=`ircuit relay dial to ${t.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${l}`),new Fr(`C${l}`)}let c=ya(o),h=ya(a),u=this.connectionManager.getConnections(c)[0];u==null?(await this.peerStore.merge(c,{multiaddrs:[s]}),e.onProgress?.(new Ze("circuit-relay:open-connection")),u=await this.connectionManager.openConnection(c,e)):e.onProgress?.(new Ze("circuit-relay:reuse-connection"));let g;try{e.onProgress?.(new Ze("circuit-relay:open-hop-stream")),g=await u.newStream(Wt,e);let l=Ge(g),d=l.pb(X);e.onProgress?.(new Ze("circuit-relay:write-connect-message")),await d.write({type:X.Type.CONNECT,peer:{id:h.toMultihash().bytes,addrs:[xt(i).bytes]}},e),e.onProgress?.(new Ze("circuit-relay:read-connect-response"));let p=await d.read(e);if(p.status!==K.OK)throw new kn(`failed to connect via relay with status ${p?.status?.toString()??"undefined"}`);let y=new Sn(p.limit),b=rc({stream:l.unwrap(),remoteAddr:t,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`),logger:this.logger,onDataRead:y.onData,onDataWrite:y.onData});return this.log("new outbound relayed connection %a",b.remoteAddr),await this.upgrader.upgradeOutbound(b,{...e,limits:y.getLimits()})}catch(l){throw this.log.error("circuit relay dial to destination %p via relay %p failed",h,c,l),g?.abort(l),l}}createListener(t){return Vf({connectionManager:this.connectionManager,relayStore:this.reservationStore,logger:this.logger})}listenFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>Bi.exactMatch(e)||_i.exactMatch(e))}dialFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>xi.exactMatch(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=Ge(e).pb(Kt),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:Kt.Type.STATUS,status:K.MALFORMED_MESSAGE},{signal:n}),await e.close();return}if(i.type!==Kt.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:Kt.Type.STATUS,status:K.UNEXPECTED_MESSAGE},{signal:n}),await e.close();return}if(!Y0(i)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:Kt.Type.STATUS,status:K.MALFORMED_MESSAGE},{signal:n}),await e.close();return}let o=dn(zt(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:Kt.Type.STATUS,status:K.PERMISSION_DENIED},{signal:n}),await e.close();return}this.log.trace("sending success response to %p",t.remotePeer),await s.write({type:Kt.Type.STATUS,status:K.OK},{signal:n});let a=new Sn(i.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${o.toString()}`),h=this.addressManager.getAddresses()[0],f=rc({stream:s.unwrap().unwrap(),remoteAddr:c,localAddr:h,logger:this.logger,onDataRead:a.onData,onDataWrite:a.onData});this.log("new inbound relayed connection %a",f.remoteAddr),await this.upgrader.upgradeInbound(f,{limits:a.getLimits()}),this.log("%s connection %a upgraded","inbound",f.remoteAddr)}};function Kf(r={}){return t=>new Fi(t,r)}return rh(X0);})();
|
6
|
+
`)}`:`${e} :`}};Ul=Ke;k.Constructed=Ul;Ke.NAME="CONSTRUCTED";var ls=class extends _t{fromBER(t,e,n){return e}toBER(t){return te}};ls.override="EndOfContentValueBlock";var Dl,us=class extends bt{constructor(t={}){super(t,ls),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Dl=us;k.EndOfContent=Dl;us.NAME=rn;var Ol,Br=class extends bt{constructor(t={}){super(t,_t),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}`}};Ol=Br;k.Null=Ol;Br.NAME="NULL";var fs=class extends _e(_t){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=z.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=z.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,sa.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};fs.NAME="BooleanValueBlock";var Ml,hs=class extends bt{constructor(t={}){super(t,fs),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}`}};Ml=hs;k.Boolean=Ml;hs.NAME="BOOLEAN";var ds=class extends _e(ce){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=ce.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===rn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(o!==Cl)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?ce.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};ds.NAME="OctetStringValueBlock";var Pl,ps=class r extends bt{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},ds),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=Ks(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} : ${z.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 z.BufferSourceConverter.concat(t)}};Pl=ps;k.OctetString=Pl;ps.NAME=Cl;var ms=class extends _e(ce){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=ce.prototype.fromBER.call(this,t,e,n),s===-1)return s;for(let a of this.value){let c=a.constructor.NAME;if(c===rn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Nl)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let h=a.valueBlock;if(this.unusedBits>0&&h.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=h.unusedBits}return s}let i=z.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=Ks(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 ce.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return te;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}}};ms.NAME="BitStringValueBlock";var Vl,_r=class extends bt{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},ms),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)}`}}};Vl=_r;k.BitString=Vl;_r.NAME=Nl;var Hl;function Vp(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,h=0,f=c<o?o:c,u=0;for(let g=f;g>=0;g--,u++){switch(!0){case u<a.length:h=i[o-u]+a[c-u]+e[0];break;default:h=i[o-u]+e[0]}switch(e[0]=h/10,!0){case u>=i.length:i=rs(new Uint8Array([h%10]),i);break;default:i[o-u]=h%10}}return e[0]>0&&(i=rs(e,i)),i}function kl(r){if(r>=tn.length)for(let t=tn.length;t<=r;t++){let e=new Uint8Array([0]),n=tn[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=rs(e,n)),tn.push(n)}return tn[r]}function Hp(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,h,f=0;for(let u=c;u>=0;u--,f++)switch(h=i[o-f]-a[c-f]-e,!0){case h<0:e=1,i[o-f]=h+10;break;default:e=0,i[o-f]=h}if(e>0)for(let u=o-c+1;u>=0;u--,f++)if(h=i[o-f]-e,h<0)e=1,i[o-f]=h+10;else{e=0,i[o-f]=h;break}return i.slice()}var nn=class extends _e(_t){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=sa.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(_l(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 h=0;h<8;h++){if((s&1)===1)switch(n){case t:e=Hp(kl(n),e),o="-";break;default:e=Vp(e,kl(n))}n++,s>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(o+=Tl.charAt(e[c]));return a===!1&&(o+=Tl.charAt(0)),o}};Hl=nn;nn.NAME="IntegerValueBlock";Object.defineProperty(Hl.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Fl,wt=class r extends bt{constructor(t={}){super(t,nn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return ns(),BigInt(this.valueBlock.toString())}static fromBigInt(t){ns();let e=BigInt(t),n=new en,s=e.toString(16).replace(/^-/,""),i=new Uint8Array(z.Convert.FromHex(s));if(e<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let h=BigInt(`0x${z.Convert.ToHex(a)}`)+e,f=z.BufferSourceConverter.toUint8Array(z.Convert.FromHex(h.toString(16)));f[0]|=128,n.write(f)}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()}`}};Fl=wt;k.Integer=Fl;wt.NAME="INTEGER";var Kl,gs=class extends wt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Kl=gs;k.Enumerated=Kl;gs.NAME="ENUMERATED";var sn=class extends _e(_t){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=z.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=ir(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){ns();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",te;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=z.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}}};sn.NAME="sidBlock";var ys=class extends _t{constructor({value:t=Tr,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let s=e;for(;n>0;){let i=new sn;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,te;e.push(s)}return ia(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 sn;if(s>Number.MAX_SAFE_INTEGER){ns();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}};ys.NAME="ObjectIdentifierValueBlock";var ql,Ir=class extends bt{constructor(t={}){super(t,ys),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()}}};ql=Ir;k.ObjectIdentifier=ql;Ir.NAME="OBJECT IDENTIFIER";var on=class extends _e(Ee){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let s=z.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=ir(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",te;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=z.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};on.NAME="relativeSidBlock";var bs=class extends _t{constructor({value:t=Tr,...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.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,te;n.push(i)}return ia(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 on;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}};bs.NAME="RelativeObjectIdentifierValueBlock";var zl,ws=class extends bt{constructor(t={}){super(t,bs),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()}}};zl=ws;k.RelativeObjectIdentifier=zl;ws.NAME="RelativeObjectIdentifier";var $l,Se=class extends Ke{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};$l=Se;k.Sequence=$l;Se.NAME="SEQUENCE";var Gl,xs=class extends Ke{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Gl=xs;k.Set=Gl;xs.NAME="SET";var vs=class extends _e(_t){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=Tr}toJSON(){return{...super.toJSON(),value:this.value}}};vs.NAME="StringValueBlock";var Es=class extends vs{};Es.NAME="SimpleStringValueBlock";var Ct=class extends os{constructor({...t}={}){super(t,Es)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,z.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}};Ct.NAME="SIMPLE STRING";var Ss=class extends Ct{fromBuffer(t){this.valueBlock.valueHexView=z.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=z.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=z.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(z.Convert.FromUtf8String(t)),this.valueBlock.value=t}};Ss.NAME="Utf8StringValueBlock";var Wl,Ae=class extends Ss{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Wl=Ae;k.Utf8String=Wl;Ae.NAME="UTF8String";var As=class extends Ct{fromBuffer(t){this.valueBlock.value=z.Convert.ToUtf16String(t),this.valueBlock.valueHexView=z.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(z.Convert.FromUtf16String(t))}};As.NAME="BmpStringValueBlock";var Zl,Bs=class extends As{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Zl=Bs;k.BmpString=Zl;Bs.NAME="BMPString";var _s=class extends Ct{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}};_s.NAME="UniversalStringValueBlock";var jl,Is=class extends _s{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};jl=Is;k.UniversalString=jl;Is.NAME="UniversalString";var Yl,Ts=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Yl=Ts;k.NumericString=Yl;Ts.NAME="NumericString";var Xl,ks=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Xl=ks;k.PrintableString=Xl;ks.NAME="PrintableString";var Jl,Cs=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Jl=Cs;k.TeletexString=Jl;Cs.NAME="TeletexString";var Ql,Ns=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Ql=Ns;k.VideotexString=Ql;Ns.NAME="VideotexString";var tu,Ls=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};tu=Ls;k.IA5String=tu;Ls.NAME="IA5String";var eu,Rs=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};eu=Rs;k.GraphicString=eu;Rs.NAME="GraphicString";var ru,an=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};ru=an;k.VisibleString=ru;an.NAME="VisibleString";var nu,Us=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};nu=Us;k.GeneralString=nu;Us.NAME="GeneralString";var su,Ds=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};su=Ds;k.CharacterString=su;Ds.NAME="CharacterString";var iu,cn=class extends an{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,z.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]=Vt(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=Vt(this.month,2),e[2]=Vt(this.day,2),e[3]=Vt(this.hour,2),e[4]=Vt(this.minute,2),e[5]=Vt(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}}};iu=cn;k.UTCTime=iu;cn.NAME="UTCTime";var ou,Os=class extends cn{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 u=new Number(t[t.length-1]);if(isNaN(u.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 u=1,g=n.indexOf("+"),l="";if(g===-1&&(g=n.indexOf("-"),u=-1),g!==-1){if(l=n.substring(g+1),n=n.substring(0,g),l.length!==2&&l.length!==4)throw new Error("Wrong input string for conversion");let d=parseInt(l.substring(0,2),10);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");if(a=u*d,l.length===4){if(d=parseInt(l.substring(2,4),10),isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");c=u*d}}}let h=n.indexOf(".");if(h===-1&&(h=n.indexOf(",")),h!==-1){let u=new Number(`0${n.substring(h)}`);if(isNaN(u.valueOf()))throw new Error("Wrong input string for conversion");i=u.valueOf(),s=n.substring(0,h)}else s=n;switch(!0){case s.length===8:if(o=/(\d{4})(\d{2})(\d{2})/ig,h!==-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,h!==-1){let u=60*i;this.minute=Math.floor(u),u=60*(u-this.minute),this.second=Math.floor(u),u=1e3*(u-this.second),this.millisecond=Math.floor(u)}break;case s.length===12:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,h!==-1){let u=60*i;this.second=Math.floor(u),u=1e3*(u-this.second),this.millisecond=Math.floor(u)}break;case s.length===14:if(o=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,h!==-1){let u=1e3*i;this.millisecond=Math.floor(u)}break;default:throw new Error("Wrong input string for conversion")}let f=o.exec(s);if(f===null)throw new Error("Wrong input string for conversion");for(let u=1;u<f.length;u++)switch(u){case 1:this.year=parseInt(f[u],10);break;case 2:this.month=parseInt(f[u],10);break;case 3:this.day=parseInt(f[u],10);break;case 4:this.hour=parseInt(f[u],10)+a;break;case 5:this.minute=parseInt(f[u],10)+c;break;case 6:this.second=parseInt(f[u],10);break;default:throw new Error("Wrong input string for conversion")}if(e===!1){let u=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=u.getUTCFullYear(),this.month=u.getUTCMonth(),this.day=u.getUTCDay(),this.hour=u.getUTCHours(),this.minute=u.getUTCMinutes(),this.second=u.getUTCSeconds(),this.millisecond=u.getUTCMilliseconds()}}toString(t="iso"){if(t==="iso"){let e=[];return e.push(Vt(this.year,4)),e.push(Vt(this.month,2)),e.push(Vt(this.day,2)),e.push(Vt(this.hour,2)),e.push(Vt(this.minute,2)),e.push(Vt(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(Vt(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};ou=Os;k.GeneralizedTime=ou;Os.NAME="GeneralizedTime";var au,Ms=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};au=Ms;k.DATE=au;Ms.NAME="DATE";var cu,Ps=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};cu=Ps;k.TimeOfDay=cu;Ps.NAME="TimeOfDay";var lu,Vs=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};lu=Vs;k.DateTime=lu;Vs.NAME="DateTime";var uu,Hs=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};uu=Hs;k.Duration=uu;Hs.NAME="Duration";var fu,Fs=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};fu=Fs;k.TIME=fu;Fs.NAME="TIME";function lt(r,t="utf8"){let e=Wn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var ln=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},qs=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var hu={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new qs("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var qe=hu;async function du(r){let t=await qe.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 Kp(t);return{privateKey:e[0],publicKey:e[1]}}async function pu(r,t){let e=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await qe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function mu(r,t,e){let n=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return qe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function Kp(r){if(r.privateKey==null||r.publicKey==null)throw new Et("Private and public key are required");return Promise.all([qe.get().subtle.exportKey("jwk",r.privateKey),qe.get().subtle.exportKey("jwk",r.publicKey)])}function ca(r){if(r.kty!=="RSA")throw new Et("invalid key type");if(r.n==null)throw new Et("invalid key modulus");return G(r.n,"base64url").length*8}var kr=class{type="RSA";_key;_raw;_multihash;constructor(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=un.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return pt.createV1(114,this._multihash)}toString(){return tt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:mt(this.raw,t.raw)}verify(t,e){return mu(this._key,e,t)}},fn=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=un.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:mt(this.raw,t.raw)}sign(t){return pu(this._key,t)}};var zs=8192,la=18;function gu(r){let{result:t}=aa(r),e=t.valueBlock.value;return{n:le(e[1]),e:le(e[2]),d:le(e[3]),p:le(e[4]),q:le(e[5]),dp:le(e[6]),dq:le(e[7]),qi:le(e[8]),kty:"RSA",alg:"RS256"}}function qp(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 Et("JWK was missing components");let e=new Se({value:[new wt({value:0}),wt.fromBigInt(ue(G(r.n,"base64url"))),wt.fromBigInt(ue(G(r.e,"base64url"))),wt.fromBigInt(ue(G(r.d,"base64url"))),wt.fromBigInt(ue(G(r.p,"base64url"))),wt.fromBigInt(ue(G(r.q,"base64url"))),wt.fromBigInt(ue(G(r.dp,"base64url"))),wt.fromBigInt(ue(G(r.dq,"base64url"))),wt.fromBigInt(ue(G(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function yu(r){let{result:t}=aa(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:le(e[0]),e:le(e[1])}}function ua(r){if(r.n==null||r.e==null)throw new Et("JWK was missing components");let e=new Se({value:[new Se({value:[new Ir({value:"1.2.840.113549.1.1.1"}),new Br]}),new _r({valueHex:new Se({value:[wt.fromBigInt(ue(G(r.n,"base64url"))),wt.fromBigInt(ue(G(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function le(r){let t=r.valueBlock.valueHexView;for(;t[0]===0;)t=t.subarray(1);return lt(t,"base64url")}function ue(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(""))}function bu(r){let t=gu(r);return wu(t)}function fa(r){let t=yu(r);if(ca(t)>zs)throw new fr("Key size is too large");let e=Qn(ae.encode({Type:ft.RSA,Data:r})),n=Zt(la,e);return new kr(t,n)}function wu(r){if(ca(r)>zs)throw new Et("Key size is too large");let t=vu(r),e=Qn(ae.encode({Type:ft.RSA,Data:ua(t.publicKey)})),n=Zt(la,e);return new fn(t.privateKey,new kr(t.publicKey,n))}async function xu(r){if(r>zs)throw new Et("Key size is too large");let t=await du(r),e=Qn(ae.encode({Type:ft.RSA,Data:ua(t.publicKey)})),n=Zt(la,e);return new fn(t.privateKey,new kr(t.publicKey,n))}function vu(r){if(r==null)throw new Et("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var zp=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]),ze=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),$e=new Uint32Array(64),ha=class extends xr{constructor(){super(64,32,8,!1),this.A=ze[0]|0,this.B=ze[1]|0,this.C=ze[2]|0,this.D=ze[3]|0,this.E=ze[4]|0,this.F=ze[5]|0,this.G=ze[6]|0,this.H=ze[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 u=0;u<16;u++,e+=4)$e[u]=t.getUint32(e,!1);for(let u=16;u<64;u++){let g=$e[u-15],l=$e[u-2],d=jt(g,7)^jt(g,18)^g>>>3,p=jt(l,17)^jt(l,19)^l>>>10;$e[u]=p+$e[u-7]+d+$e[u-16]|0}let{A:n,B:s,C:i,D:o,E:a,F:c,G:h,H:f}=this;for(let u=0;u<64;u++){let g=jt(a,6)^jt(a,11)^jt(a,25),l=f+g+Fc(a,c,h)+zp[u]+$e[u]|0,p=(jt(n,2)^jt(n,13)^jt(n,22))+Kc(n,s,i)|0;f=h,h=c,c=a,a=o+l|0,o=i,i=s,s=n,n=l+p|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,h=h+this.G|0,f=f+this.H|0,this.set(n,s,i,o,a,c,h,f)}roundClean(){$e.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Eu=Ln(()=>new ha);var $s=class extends wr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Pc(t);let n=Gr(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let s=this.blockLen,i=new Uint8Array(s);i.set(n.length>s?t.create().update(n).digest():n);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=t.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),i.fill(0)}update(t){return br(this),this.iHash.update(t),this}digestInto(t){br(this),yr(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:s,destroyed:i,blockLen:o,outputLen:a}=this;return t=t,t.finished=s,t.destroyed=i,t.blockLen=o,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},da=(r,t,e)=>new $s(r,t).update(e).digest();da.create=(r,t)=>new $s(r,t);function Su(r){r.lowS!==void 0&&Yt("lowS",r.lowS),r.prehash!==void 0&&Yt("prehash",r.prehash)}function $p(r){let t=jr(r);oe(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("invalid 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("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:Gp,hexToBytes:Wp}=Mn,Ie={Err:class extends Error{constructor(t=""){super(t)}},_tlv:{encode:(r,t)=>{let{Err:e}=Ie;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,s=Xe(n);if(s.length/2&128)throw new e("tlv.encode: long form length too big");let i=n>127?Xe(s.length/2|128):"";return Xe(r)+i+s+t},decode(r,t){let{Err:e}=Ie,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let s=t[n++],i=!!(s&128),o=0;if(!i)o=s;else{let c=s&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let h=t.subarray(n,n+c);if(h.length!==c)throw new e("tlv.decode: length bytes not complete");if(h[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let f of h)o=o<<8|f;if(n+=c,o<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+o);if(a.length!==o)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+o)}}},_int:{encode(r){let{Err:t}=Ie;if(r<Te)throw new t("integer: negative integers are not allowed");let e=Xe(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=Ie;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Gp(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Ie,s=typeof r=="string"?Wp(r):r;vr(s);let{v:i,l:o}=n.decode(48,s);if(o.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:h,l:f}=n.decode(2,c);if(f.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(h)}},hexFromSig(r){let{_tlv:t,_int:e}=Ie,n=t.encode(2,e.encode(r.r)),s=t.encode(2,e.encode(r.s)),i=n+s;return t.encode(48,i)}},Te=BigInt(0),gt=BigInt(1),Vb=BigInt(2),Au=BigInt(3),Hb=BigInt(4);function Zp(r){let t=$p(r),{Fp:e}=t,n=Oe(t.n,t.nBitLength),s=t.toBytes||((p,y,b)=>{let w=y.toAffine();return we(Uint8Array.from([4]),e.toBytes(w.x),e.toBytes(w.y))}),i=t.fromBytes||(p=>{let y=p.subarray(1),b=e.fromBytes(y.subarray(0,e.BYTES)),w=e.fromBytes(y.subarray(e.BYTES,2*e.BYTES));return{x:b,y:w}});function o(p){let{a:y,b}=t,w=e.sqr(p),m=e.mul(w,p);return e.add(e.add(m,e.mul(p,y)),b)}if(!e.eql(e.sqr(t.Gy),o(t.Gx)))throw new Error("bad generator point: equation left != right");function a(p){return Wr(p,gt,t.n)}function c(p){let{allowedPrivateKeyLengths:y,nByteLength:b,wrapPrivateKey:w,n:m}=t;if(y&&typeof p!="bigint"){if(Re(p)&&(p=ye(p)),typeof p!="string"||!y.includes(p.length))throw new Error("invalid private key");p=p.padStart(b*2,"0")}let E;try{E=typeof p=="bigint"?p:be(ot("private key",p,b))}catch{throw new Error("invalid private key, expected hex or "+b+" bytes, got "+typeof p)}return w&&(E=J(E,m)),Rt("private key",E,gt,m),E}function h(p){if(!(p instanceof g))throw new Error("ProjectivePoint expected")}let f=tr((p,y)=>{let{px:b,py:w,pz:m}=p;if(e.eql(m,e.ONE))return{x:b,y:w};let E=p.is0();y==null&&(y=E?e.ONE:e.inv(m));let A=e.mul(b,y),_=e.mul(w,y),x=e.mul(m,y);if(E)return{x:e.ZERO,y:e.ZERO};if(!e.eql(x,e.ONE))throw new Error("invZ was invalid");return{x:A,y:_}}),u=tr(p=>{if(p.is0()){if(t.allowInfinityPoint&&!e.is0(p.py))return;throw new Error("bad point: ZERO")}let{x:y,y:b}=p.toAffine();if(!e.isValid(y)||!e.isValid(b))throw new Error("bad point: x or y not FE");let w=e.sqr(b),m=o(y);if(!e.eql(w,m))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(y,b,w){if(this.px=y,this.py=b,this.pz=w,y==null||!e.isValid(y))throw new Error("x required");if(b==null||!e.isValid(b))throw new Error("y required");if(w==null||!e.isValid(w))throw new Error("z required");Object.freeze(this)}static fromAffine(y){let{x:b,y:w}=y||{};if(!y||!e.isValid(b)||!e.isValid(w))throw new Error("invalid affine point");if(y instanceof g)throw new Error("projective point not allowed");let m=E=>e.eql(E,e.ZERO);return m(b)&&m(w)?g.ZERO:new g(b,w,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(y){let b=e.invertBatch(y.map(w=>w.pz));return y.map((w,m)=>w.toAffine(b[m])).map(g.fromAffine)}static fromHex(y){let b=g.fromAffine(i(ot("pointHex",y)));return b.assertValidity(),b}static fromPrivateKey(y){return g.BASE.multiply(c(y))}static msm(y,b){return Fn(g,n,y,b)}_setWindowSize(y){d.setWindowSize(this,y)}assertValidity(){u(this)}hasEvenY(){let{y}=this.toAffine();if(e.isOdd)return!e.isOdd(y);throw new Error("Field doesn't support isOdd")}equals(y){h(y);let{px:b,py:w,pz:m}=this,{px:E,py:A,pz:_}=y,x=e.eql(e.mul(b,_),e.mul(E,m)),I=e.eql(e.mul(w,_),e.mul(A,m));return x&&I}negate(){return new g(this.px,e.neg(this.py),this.pz)}double(){let{a:y,b}=t,w=e.mul(b,Au),{px:m,py:E,pz:A}=this,_=e.ZERO,x=e.ZERO,I=e.ZERO,C=e.mul(m,m),j=e.mul(E,E),V=e.mul(A,A),P=e.mul(m,E);return P=e.add(P,P),I=e.mul(m,A),I=e.add(I,I),_=e.mul(y,I),x=e.mul(w,V),x=e.add(_,x),_=e.sub(j,x),x=e.add(j,x),x=e.mul(_,x),_=e.mul(P,_),I=e.mul(w,I),V=e.mul(y,V),P=e.sub(C,V),P=e.mul(y,P),P=e.add(P,I),I=e.add(C,C),C=e.add(I,C),C=e.add(C,V),C=e.mul(C,P),x=e.add(x,C),V=e.mul(E,A),V=e.add(V,V),C=e.mul(V,P),_=e.sub(_,C),I=e.mul(V,j),I=e.add(I,I),I=e.add(I,I),new g(_,x,I)}add(y){h(y);let{px:b,py:w,pz:m}=this,{px:E,py:A,pz:_}=y,x=e.ZERO,I=e.ZERO,C=e.ZERO,j=t.a,V=e.mul(t.b,Au),P=e.mul(b,E),R=e.mul(w,A),T=e.mul(m,_),L=e.add(b,w),S=e.add(E,A);L=e.mul(L,S),S=e.add(P,R),L=e.sub(L,S),S=e.add(b,m);let v=e.add(E,_);return S=e.mul(S,v),v=e.add(P,T),S=e.sub(S,v),v=e.add(w,m),x=e.add(A,_),v=e.mul(v,x),x=e.add(R,T),v=e.sub(v,x),C=e.mul(j,S),x=e.mul(V,T),C=e.add(x,C),x=e.sub(R,C),C=e.add(R,C),I=e.mul(x,C),R=e.add(P,P),R=e.add(R,P),T=e.mul(j,T),S=e.mul(V,S),R=e.add(R,T),T=e.sub(P,T),T=e.mul(j,T),S=e.add(S,T),P=e.mul(R,S),I=e.add(I,P),P=e.mul(v,S),x=e.mul(L,x),x=e.sub(x,P),P=e.mul(L,R),C=e.mul(v,C),C=e.add(C,P),new g(x,I,C)}subtract(y){return this.add(y.negate())}is0(){return this.equals(g.ZERO)}wNAF(y){return d.wNAFCached(this,y,g.normalizeZ)}multiplyUnsafe(y){let{endo:b,n:w}=t;Rt("scalar",y,Te,w);let m=g.ZERO;if(y===Te)return m;if(this.is0()||y===gt)return this;if(!b||d.hasPrecomputes(this))return d.wNAFCachedUnsafe(this,y,g.normalizeZ);let{k1neg:E,k1:A,k2neg:_,k2:x}=b.splitScalar(y),I=m,C=m,j=this;for(;A>Te||x>Te;)A>&&(I=I.add(j)),x>&&(C=C.add(j)),j=j.double(),A>>=gt,x>>=gt;return E&&(I=I.negate()),_&&(C=C.negate()),C=new g(e.mul(C.px,b.beta),C.py,C.pz),I.add(C)}multiply(y){let{endo:b,n:w}=t;Rt("scalar",y,gt,w);let m,E;if(b){let{k1neg:A,k1:_,k2neg:x,k2:I}=b.splitScalar(y),{p:C,f:j}=this.wNAF(_),{p:V,f:P}=this.wNAF(I);C=d.constTimeNegate(A,C),V=d.constTimeNegate(x,V),V=new g(e.mul(V.px,b.beta),V.py,V.pz),m=C.add(V),E=j.add(P)}else{let{p:A,f:_}=this.wNAF(y);m=A,E=_}return g.normalizeZ([m,E])[0]}multiplyAndAddUnsafe(y,b,w){let m=g.BASE,E=(_,x)=>x===Te||x===gt||!_.equals(m)?_.multiplyUnsafe(x):_.multiply(x),A=E(this,b).add(E(y,w));return A.is0()?void 0:A}toAffine(y){return f(this,y)}isTorsionFree(){let{h:y,isTorsionFree:b}=t;if(y===gt)return!0;if(b)return b(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:y,clearCofactor:b}=t;return y===gt?this:b?b(g,this):this.multiplyUnsafe(t.h)}toRawBytes(y=!0){return Yt("isCompressed",y),this.assertValidity(),s(g,this,y)}toHex(y=!0){return Yt("isCompressed",y),ye(this.toRawBytes(y))}}g.BASE=new g(t.Gx,t.Gy,e.ONE),g.ZERO=new g(e.ZERO,e.ONE,e.ZERO);let l=t.nBitLength,d=Hn(g,t.endo?Math.ceil(l/2):l);return{CURVE:t,ProjectivePoint:g,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function jp(r){let t=jr(r);return oe(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Bu(r){let t=jp(r),{Fp:e,n}=t,s=e.BYTES+1,i=2*e.BYTES+1;function o(T){return J(T,n)}function a(T){return Pn(T,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:f,isWithinCurveOrder:u}=Zp({...t,toBytes(T,L,S){let v=L.toAffine(),B=e.toBytes(v.x),N=we;return Yt("isCompressed",S),S?N(Uint8Array.from([L.hasEvenY()?2:3]),B):N(Uint8Array.from([4]),B,e.toBytes(v.y))},fromBytes(T){let L=T.length,S=T[0],v=T.subarray(1);if(L===s&&(S===2||S===3)){let B=be(v);if(!Wr(B,gt,e.ORDER))throw new Error("Point is not on curve");let N=f(B),U;try{U=e.sqrt(N)}catch($){let O=$ instanceof Error?": "+$.message:"";throw new Error("Point is not on curve"+O)}let D=(U>)===gt;return(S&1)===1!==D&&(U=e.neg(U)),{x:B,y:U}}else if(L===i&&S===4){let B=e.fromBytes(v.subarray(0,e.BYTES)),N=e.fromBytes(v.subarray(e.BYTES,2*e.BYTES));return{x:B,y:N}}else{let B=s,N=i;throw new Error("invalid Point, expected length of "+B+", or uncompressed "+N+", got "+L)}}}),g=T=>ye(De(T,t.nByteLength));function l(T){let L=n>>gt;return T>L}function d(T){return l(T)?o(-T):T}let p=(T,L,S)=>be(T.slice(L,S));class y{constructor(L,S,v){this.r=L,this.s=S,this.recovery=v,this.assertValidity()}static fromCompact(L){let S=t.nByteLength;return L=ot("compactSignature",L,S*2),new y(p(L,0,S),p(L,S,2*S))}static fromDER(L){let{r:S,s:v}=Ie.toSig(ot("DER",L));return new y(S,v)}assertValidity(){Rt("r",this.r,gt,n),Rt("s",this.s,gt,n)}addRecoveryBit(L){return new y(this.r,this.s,L)}recoverPublicKey(L){let{r:S,s:v,recovery:B}=this,N=_(ot("msgHash",L));if(B==null||![0,1,2,3].includes(B))throw new Error("recovery id invalid");let U=B===2||B===3?S+t.n:S;if(U>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let D=B&1?"03":"02",H=c.fromHex(D+g(U)),$=a(U),O=o(-N*$),Y=o(v*$),rt=c.BASE.multiplyAndAddUnsafe(H,O,Y);if(!rt)throw new Error("point at infinify");return rt.assertValidity(),rt}hasHighS(){return l(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Je(this.toDERHex())}toDERHex(){return Ie.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Je(this.toCompactHex())}toCompactHex(){return g(this.r)+g(this.s)}}let b={isValidPrivateKey(T){try{return h(T),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{let T=po(t.n);return Xc(t.randomBytes(T),t.n)},precompute(T=8,L=c.BASE){return L._setWindowSize(T),L.multiply(BigInt(3)),L}};function w(T,L=!0){return c.fromPrivateKey(T).toRawBytes(L)}function m(T){let L=Re(T),S=typeof T=="string",v=(L||S)&&T.length;return L?v===s||v===i:S?v===2*s||v===2*i:T instanceof c}function E(T,L,S=!0){if(m(T))throw new Error("first arg must be private key");if(!m(L))throw new Error("second arg must be public key");return c.fromHex(L).multiply(h(T)).toRawBytes(S)}let A=t.bits2int||function(T){if(T.length>8192)throw new Error("input is too large");let L=be(T),S=T.length*8-t.nBitLength;return S>0?L>>BigInt(S):L},_=t.bits2int_modN||function(T){return o(A(T))},x=Zr(t.nBitLength);function I(T){return Rt("num < 2^"+t.nBitLength,T,Te,x),De(T,t.nByteLength)}function C(T,L,S=j){if(["recovered","canonical"].some(dt=>dt in S))throw new Error("sign() legacy options not supported");let{hash:v,randomBytes:B}=t,{lowS:N,prehash:U,extraEntropy:D}=S;N==null&&(N=!0),T=ot("msgHash",T),Su(S),U&&(T=ot("prehashed msgHash",v(T)));let H=_(T),$=h(L),O=[I($),I(H)];if(D!=null&&D!==!1){let dt=D===!0?B(e.BYTES):D;O.push(ot("extraEntropy",dt))}let Y=we(...O),rt=H;function ht(dt){let yt=A(dt);if(!u(yt))return;let vt=a(yt),Nt=c.BASE.multiply(yt).toAffine(),Tt=o(Nt.x);if(Tt===Te)return;let se=o(vt*o(rt+Tt*$));if(se===Te)return;let fe=(Nt.x===Tt?0:2)|Number(Nt.y>),Hr=se;return N&&l(se)&&(Hr=d(se),fe^=1),new y(Tt,Hr,fe)}return{seed:Y,k2sig:ht}}let j={lowS:t.lowS,prehash:!1},V={lowS:t.lowS,prehash:!1};function P(T,L,S=j){let{seed:v,k2sig:B}=C(T,L,S),N=t;return lo(N.hash.outputLen,N.nByteLength,N.hmac)(v,B)}c.BASE._setWindowSize(8);function R(T,L,S,v=V){let B=T;L=ot("msgHash",L),S=ot("publicKey",S);let{lowS:N,prehash:U,format:D}=v;if(Su(v),"strict"in v)throw new Error("options.strict was renamed to lowS");if(D!==void 0&&D!=="compact"&&D!=="der")throw new Error("format must be compact or der");let H=typeof B=="string"||Re(B),$=!H&&!D&&typeof B=="object"&&B!==null&&typeof B.r=="bigint"&&typeof B.s=="bigint";if(!H&&!$)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let O,Y;try{if($&&(O=new y(B.r,B.s)),H){try{D!=="compact"&&(O=y.fromDER(B))}catch(fe){if(!(fe instanceof Ie.Err))throw fe}!O&&D!=="der"&&(O=y.fromCompact(B))}Y=c.fromHex(S)}catch{return!1}if(!O||N&&O.hasHighS())return!1;U&&(L=t.hash(L));let{r:rt,s:ht}=O,dt=_(L),yt=a(ht),vt=o(dt*yt),Nt=o(rt*yt),Tt=c.BASE.multiplyAndAddUnsafe(Y,vt,Nt)?.toAffine();return Tt?o(Tt.x)===rt:!1}return{CURVE:t,getPublicKey:w,getSharedSecret:E,sign:P,verify:R,ProjectivePoint:c,Signature:y,utils:b}}function Yp(r){return{hash:r,hmac:(t,...e)=>da(r,t,ro(...e)),randomBytes:Rn}}function _u(r,t){let e=n=>Bu({...r,...Yp(n)});return Object.freeze({...e(t),create:e})}var ku=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Iu=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Xp=BigInt(1),pa=BigInt(2),Tu=(r,t)=>(r+t/pa)/t;function Jp(r){let t=ku,e=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),h=r*r*r%t,f=h*h*r%t,u=it(f,e,t)*f%t,g=it(u,e,t)*f%t,l=it(g,pa,t)*h%t,d=it(l,s,t)*l%t,p=it(d,i,t)*d%t,y=it(p,a,t)*p%t,b=it(y,c,t)*y%t,w=it(b,a,t)*p%t,m=it(w,e,t)*f%t,E=it(m,o,t)*d%t,A=it(E,n,t)*h%t,_=it(A,pa,t);if(!ma.eql(ma.sqr(_),r))throw new Error("Cannot find square root");return _}var ma=Oe(ku,void 0,void 0,{sqrt:Jp}),or=_u({a:BigInt(0),b:BigInt(7),Fp:ma,n:Iu,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Iu,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Xp*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=e,o=BigInt("0x100000000000000000000000000000000"),a=Tu(i*r,t),c=Tu(-n*r,t),h=J(r-a*e-c*s,t),f=J(-a*n-c*i,t),u=h>o,g=f>o;if(u&&(h=t-h),g&&(f=t-f),h>o||f>o)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:u,k1:h,k2neg:g,k2:f}}}},Eu),jb=BigInt(0);var Yb=or.ProjectivePoint;function Ft(r,t){t==null&&(t=r.reduce((s,i)=>s+i.length,0));let e=Dt(t),n=0;for(let s of r)e.set(s,n),n+=s.length;return e}function Cu(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Nu(r,t,e){let n=Er.digest(e instanceof Uint8Array?e:e.subarray());if(Cu(n))return n.then(({digest:s})=>or.verify(t,s,r)).catch(s=>{throw new ln(String(s))});try{return or.verify(t,n.digest,r)}catch(s){throw new ln(String(s))}}var Gs=class{type="secp256k1";raw;_key;constructor(t){this._key=Ru(t),this.raw=Lu(this._key)}toMultihash(){return me.digest(Me(this))}toCID(){return pt.createV1(114,this.toMultihash())}toString(){return tt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:mt(this.raw,t.raw)}verify(t,e){return Nu(this._key,e,t)}};function ga(r){return new Gs(r)}function Lu(r){return or.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Ru(r){try{return or.ProjectivePoint.fromHex(r),r}catch(t){throw new fr(String(t))}}function Uu(r){let{Type:t,Data:e}=ae.decode(r),n=e??new Uint8Array;switch(t){case ft.RSA:return fa(n);case ft.Ed25519:return vo(n);case ft.secp256k1:return ga(n);default:throw new hr}}function Du(r){let{Type:t,Data:e}=ae.decode(r.digest),n=e??new Uint8Array;switch(t){case ft.Ed25519:return vo(n);case ft.secp256k1:return ga(n);default:throw new hr}}function Me(r){return ae.encode({Type:ft[r.type],Data:r.raw})}var Ou=Symbol.for("nodejs.util.inspect.custom"),Qp=114,hn=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[zi]=!0;toString(){return this.string==null&&(this.string=tt.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return pt.createV1(Qp,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return mt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return mt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Ou](){return`PeerId(${this.toString()})`}},Ws=class extends hn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Zs=class extends hn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},js=class extends hn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},t0=2336,Ys=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=me.digest(G(this.url))}[Ou](){return`PeerId(${this.url})`}[zi]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return pt.createV1(t0,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=lt(t)),t.toString()===this.toString())}};function ya(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=zt(tt.decode(`z${r}`));else{if(t==null)throw new Et('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=zt(t.decode(r))}return dn(e)}function dn(r){if(r0(r))return new Ws({multihash:r});if(e0(r))try{let t=Du(r);if(t.type==="Ed25519")return new Zs({multihash:r,publicKey:t});if(t.type==="secp256k1")return new js({multihash:r,publicKey:t})}catch{let e=lt(r.digest);return new Ys(new URL(e))}throw new Tn("Supplied PeerID Multihash is invalid")}function e0(r){return r.code===me.code}function r0(r){return r.code===Er.code}var Pu=Symbol.for("@achingbrain/uint8arraylist");function Mu(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 Xs(r){return!!r?.[Pu]}var ee=class r{bufs;length;[Pu]=!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(Xs(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(Xs(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=Mu(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Mu(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(Xs(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 Ft(n,s)}subarray(t,e){let{bufs:n,length:s}=this._subList(t,e);return n.length===1?n[0]:Ft(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 h=t>=a&&t<c,f=e>a&&e<=c;if(h&&f){if(t===a&&e===c){n.push(o);break}let u=t-a;n.push(o.subarray(u,u+(e-t)));break}if(h){if(t===0){n.push(o);continue}n.push(o.subarray(t-a));continue}if(f){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(!Xs(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 u=0;u<i;u++)o[u]=-1;for(let u=0;u<s;u++)o[n[u]]=u;let a=o,c=this.byteLength-n.byteLength,h=n.byteLength-1,f;for(let u=e;u<=c;u+=f){f=0;for(let g=h;g>=0;g--){let l=this.get(u+g);if(n[g]!==l){f=Math.max(1,g-a[l]);break}}if(f===0)return u}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=Dt(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=at(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=at(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=at(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=Dt(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=at(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=at(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=at(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=at(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=at(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(!mt(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 pn;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((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,s={})=>{let i={publicKey:at(0),payloadType:at(0),payload:at(0),signature:at(0)},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let a=e.uint32();switch(a>>>3){case 1:{i.publicKey=e.bytes();break}case 2:{i.payloadType=e.bytes();break}case 3:{i.payload=e.bytes();break}case 5:{i.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Ot(e,r.codec(),n)})(pn||(pn={}));var Js=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var mn=class r{static createFromProtobuf=async t=>{let e=pn.decode(t),n=Uu(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e)=>{if(e==null)throw new Error("Missing private key");let n=t.domain,s=t.codec,i=t.marshal(),o=Vu(n,s,i),a=await e.sign(o.subarray());return new r({publicKey:e.publicKey,payloadType:s,payload:i,signature:a})};static openAndCertify=async(t,e)=>{let n=await r.createFromProtobuf(t);if(!await n.validate(e))throw new Js("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(t){let{publicKey:e,payloadType:n,payload:s,signature:i}=t;this.publicKey=e,this.payloadType=n,this.payload=s,this.signature=i}marshal(){return this.marshaled==null&&(this.marshaled=pn.encode({publicKey:Me(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return mt(this.marshal(),t.marshal())}async validate(t){let e=Vu(t,this.payloadType,this.payload);return this.publicKey.verify(e.subarray(),this.signature)}},Vu=(r,t,e)=>{let n=G(r),s=$t(n.byteLength),i=$t(t.length),o=$t(e.length);return new ee(s,n,i,t,o,e)};var Qs=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",h=2**(8*s)-1;for(;;){let f=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let g=Number.parseInt(u,t);if(!Number.isNaN(g))return g});if(f===void 0)break;if(i*=t,i+=f,i>h||(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 Hu=45,n0=15,Cr=new Qs;function ba(r){if(!(r.length>n0))return Cr.new(r).parseWith(()=>Cr.readIPv4Addr())}function wa(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Hu))return Cr.new(r).parseWith(()=>Cr.readIPv6Addr())}function ti(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Hu))return Cr.new(r).parseWith(()=>Cr.readIPAddr())}var Ix=parseInt("0xFFFF",16),Tx=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function ei(r){return!!ba(r)}function ri(r){return!!wa(r)}function ni(r){return!!ti(r)}var qu=ei,c0=ri,xa=function(r){let t=0;if(r=r.toString().trim(),qu(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(c0(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=qu(e[n]),o;i&&(o=xa(e[n]),e[n]=lt(o.slice(0,2),"base16")),o!=null&&++n<8&&e.splice(n,0,lt(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")},zu=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 Nr={},va={},u0=[[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"],[481,-1,"http-path"],[777,-1,"memory"]];u0.forEach(r=>{let t=f0(...r);va[t.code]=t,Nr[t.name]=t});function f0(r,t,e,n,s){return{code:r,size:t,name:e,resolvable:!!n,path:!!s}}function et(r){if(typeof r=="number"){if(va[r]!=null)return va[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Nr[r]!=null)return Nr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var f1=et("ip4"),h1=et("ip6"),d1=et("ipcidr");function Ba(r,t){switch(et(r).code){case 4:case 41:return d0(t);case 42:return Aa(t);case 6:case 273:case 33:case 132:return Wu(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Aa(t);case 421:return y0(t);case 444:return Gu(t);case 445:return Gu(t);case 466:return g0(t);case 481:return globalThis.encodeURIComponent(Aa(t));default:return lt(t,"base16")}}function _a(r,t){switch(et(r).code){case 4:return $u(t);case 41:return $u(t);case 42:return Sa(t);case 6:case 273:case 33:case 132:return Ia(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Sa(t);case 421:return p0(t);case 444:return b0(t);case 445:return w0(t);case 466:return m0(t);case 481:return Sa(globalThis.decodeURIComponent(t));default:return G(t,"base16")}}var Ea=Object.values(Yr).map(r=>r.decoder),h0=function(){let r=Ea[0].or(Ea[1]);return Ea.slice(2).forEach(t=>r=r.or(t)),r}();function $u(r){if(!ni(r))throw new Error("invalid ip address");return xa(r)}function d0(r){let t=zu(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!ni(t))throw new Error("invalid ip address");return t}function Ia(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Wu(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Sa(r){let t=G(r),e=Uint8Array.from($t(t.length));return Ft([e,t],e.length+t.length)}function Aa(r){let t=xe(r);if(r=r.slice(At(t)),r.length!==t)throw new Error("inconsistent lengths");return lt(r)}function p0(r){let t;r[0]==="Q"||r[0]==="1"?t=zt(tt.decode(`z${r}`)).bytes:t=pt.parse(r).multihash.bytes;let e=Uint8Array.from($t(t.length));return Ft([e,t],e.length+t.length)}function m0(r){let t=h0.decode(r),e=Uint8Array.from($t(t.length));return Ft([e,t],e.length+t.length)}function g0(r){let t=xe(r),e=r.slice(At(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+lt(e,"base64url")}function y0(r){let t=xe(r),e=r.slice(At(t));if(e.length!==t)throw new Error("inconsistent lengths");return lt(e,"base58btc")}function b0(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=pe.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=Ia(n);return Ft([e,s],e.length+s.length)}function w0(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=pe.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=Ia(n);return Ft([e,s],e.length+s.length)}function Gu(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=lt(t,"base32"),s=Wu(e);return`${n}:${s}`}function Zu(r){r=Ta(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=et(o);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(i++,i>=s.length)throw Yu("invalid address: "+r);if(a.path===!0){n=Ta(s.slice(i).join("/")),t.push([a.code,_a(a.code,n)]),e.push([a.code,n]);break}let c=_a(a.code,s[i]);t.push([a.code,c]),e.push([a.code,Ba(a.code,c)])}return{string:ju(e),bytes:Ca(t),tuples:t,stringTuples:e,path:n}}function ka(r){let t=[],e=[],n=null,s=0;for(;s<r.length;){let i=xe(r,s),o=At(i),a=et(i),c=x0(a,r.slice(s+o));if(c===0){t.push([i]),e.push([i]),s+=o;continue}let h=r.slice(s+o,s+o+c);if(s+=c+o,s>r.length)throw Yu("Invalid address Uint8Array: "+lt(r,"base16"));t.push([i,h]);let f=Ba(i,h);if(e.push([i,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:ju(e),tuples:t,stringTuples:e,path:n}}function ju(r){let t=[];return r.map(e=>{let n=et(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Ta(t.join("/"))}function Ca(r){return Ft(r.map(t=>{let e=et(t[0]),n=Uint8Array.from($t(e.code));return t.length>1&&t[1]!=null&&(n=Ft([n,t[1]])),n}))}function x0(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=xe(t instanceof Uint8Array?t:Uint8Array.from(t));return e+At(e)}}function Ta(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function Yu(r){return new Error("Error parsing address: "+r)}var v0=Symbol.for("nodejs.util.inspect.custom"),La=Symbol.for("@multiformats/js-multiaddr/multiaddr"),E0=[et("dns").code,et("dns4").code,et("dns6").code,et("dnsaddr").code],Na=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},si=class r{bytes;#t;#e;#r;#n;[La]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=ka(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Zu(t)}else if(Ju(t))e=ka(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=et("tcp"),a=et("udp"),c=et("ip4"),h=et("ip6"),f=et("dns6"),u=et("ip6zone");for(let[l,d]of this.stringTuples())l===u.code&&(i=`%${d??""}`),E0.includes(l)&&(e=o.name,s=443,n=`${d??""}${i}`,t=l===f.code?6:4),(l===o.code||l===a.code)&&(e=et(l).name,s=parseInt(d??"")),(l===c.code||l===h.code)&&(e=et(l).name,n=`${d??""}${i}`,t=l===h.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({},et(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>et(t).name)}tuples(){return this.#e.map(([t,e])=>e==null?[t]:[t,e])}stringTuples(){return this.#r.map(([t,e])=>e==null?[t]:[t,e])}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(Ca(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,s])=>{n===Nr.p2p.code&&t.push([n,s]),n===Nr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?lt(tt.decode(`z${n}`),"base58btc"):lt(pt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return mt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(i=>i.resolvable);if(e==null)return[this];let n=Xu.get(e.name);if(n==null)throw new Na(`no available resolver for ${e.name}`);return(await n(this,t)).map(i=>xt(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)}[v0](){return`Multiaddr(${this.#t})`}};var Xu=new Map;function Ju(r){return!!r?.[La]}function xt(r){return new si(r)}function re(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var ii=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function oi(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new ii(e?.errorMessage,e?.errorCode,e?.errorName));let n,s=new ii(e?.errorMessage,e?.errorCode,e?.errorName);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 Ra=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=re(),this.haveNext=re()}[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=re(),t}async throw(t){return this.ended=!0,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return 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");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=re(),await oi(this.readNext.promise,e?.signal,e)}};function Qu(){return new Ra}var ai=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Ua=class extends Error{code;constructor(t,e){super(t),this.code=e}},Da=class extends Ua{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function tf(r,t){let e=Qu();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,h=new Promise((f,u)=>{c=()=>{u(new Da("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(o==null){let{done:u,value:g}=await Promise.race([n.next(),h]);return u===!0?new ee:g}for(;s.byteLength<o;){let{value:u,done:g}=await Promise.race([n.next(),h]);if(g===!0)throw new ai("unexpected end of input");s.append(u)}let f=s.sublist(0,o);return s.consume(o),f}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 ci=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},li=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ui=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function ef(r,t={}){let e=tf(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=At(t.maxDataLength));let n=t?.lengthDecoder??xe,s=t?.lengthEncoder??$t;return{read:async o=>{let a=-1,c=new ee;for(;;){c.append(await e.read(1,o));try{a=n(c)}catch(h){if(h instanceof RangeError)continue;throw h}if(a<0)throw new ci("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new ui("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new li("message length 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(h=>[s(h.byteLength),h]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Ge(r,t){let e=ef(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 Oa=1e3,rf=60*Oa,fi=290,nf=15,sf=2*60*rf,of=1,hi=2e3,af=100,Ma="circuit-relay-source",gn=`${$i}-circuit-relay`,Pa=`${$i}-circuit-relay-source`,cf=2*rf,lf=BigInt(1<<17),Wt="/libp2p/circuit/relay/0.2.0/hop",ar="/libp2p/circuit/relay/0.2.0/stop",uf=30*Oa,n2=30*Oa,yn=300,ff=4096,hf=.001;var X;(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=()=>sr(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Pt((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),Lr.codec().encode(s.peer,i)),s.reservation!=null&&(i.uint32(26),di.codec().encode(s.reservation,i)),s.limit!=null&&(i.uint32(34),Rr.codec().encode(s.limit,i)),s.status!=null&&(i.uint32(40),K.codec().encode(s.status,i)),o.lengthDelimited!==!1&&i.ldelim()},(s,i,o={})=>{let a={},c=i==null?s.len:s.pos+i;for(;s.pos<c;){let h=s.uint32();switch(h>>>3){case 1:{a.type=r.Type.codec().decode(s);break}case 2:{a.peer=Lr.codec().decode(s,s.uint32(),{limits:o.limits?.peer});break}case 3:{a.reservation=di.codec().decode(s,s.uint32(),{limits:o.limits?.reservation});break}case 4:{a.limit=Rr.codec().decode(s,s.uint32(),{limits:o.limits?.limit});break}case 5:{a.status=K.codec().decode(s);break}default:{s.skipType(h&7);break}}}return a})),n),r.encode=s=>Mt(s,r.codec()),r.decode=(s,i)=>Ot(s,r.codec(),i)})(X||(X={}));var Kt;(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=()=>sr(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Pt((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),Lr.codec().encode(s.peer,i)),s.limit!=null&&(i.uint32(26),Rr.codec().encode(s.limit,i)),s.status!=null&&(i.uint32(32),K.codec().encode(s.status,i)),o.lengthDelimited!==!1&&i.ldelim()},(s,i,o={})=>{let a={},c=i==null?s.len:s.pos+i;for(;s.pos<c;){let h=s.uint32();switch(h>>>3){case 1:{a.type=r.Type.codec().decode(s);break}case 2:{a.peer=Lr.codec().decode(s,s.uint32(),{limits:o.limits?.peer});break}case 3:{a.limit=Rr.codec().decode(s,s.uint32(),{limits:o.limits?.limit});break}case 4:{a.status=K.codec().decode(s);break}default:{s.skipType(h&7);break}}}return a})),n),r.encode=s=>Mt(s,r.codec()),r.decode=(s,i)=>Ot(s,r.codec(),i)})(Kt||(Kt={}));var Lr;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((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,s={})=>{let i={id:at(0),addrs:[]},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let a=e.uint32();switch(a>>>3){case 1:{i.id=e.bytes();break}case 2:{if(s.limits?.addrs!=null&&i.addrs.length===s.limits.addrs)throw new Qr('Decode error - map field "addrs" had too many elements');i.addrs.push(e.bytes());break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Ot(e,r.codec(),n)})(Lr||(Lr={}));var di;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((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),pi.codec().encode(e.voucher,n)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let i={expire:0n,addrs:[]},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let a=e.uint32();switch(a>>>3){case 1:{i.expire=e.uint64();break}case 2:{if(s.limits?.addrs!=null&&i.addrs.length===s.limits.addrs)throw new Qr('Decode error - map field "addrs" had too many elements');i.addrs.push(e.bytes());break}case 3:{i.voucher=pi.codec().decode(e,e.uint32(),{limits:s.limits?.voucher});break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Ot(e,r.codec(),n)})(di||(di={}));var Rr;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((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,s={})=>{let i={},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let a=e.uint32();switch(a>>>3){case 1:{i.duration=e.uint32();break}case 2:{i.data=e.uint64();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Ot(e,r.codec(),n)})(Rr||(Rr={}));var K;(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"})(K||(K={}));var Va;(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"})(Va||(Va={}));(function(r){r.codec=()=>sr(Va)})(K||(K={}));var Ur;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((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,s={})=>{let i={relay:at(0),peer:at(0),expiration:0n},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let a=e.uint32();switch(a>>>3){case 1:{i.relay=e.bytes();break}case 2:{i.peer=e.bytes();break}case 3:{i.expiration=e.uint64();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Ot(e,r.codec(),n)})(Ur||(Ur={}));var pi;(function(r){let t;r.codec=()=>(t==null&&(t=Pt((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&&(n.uint32(26),Ur.codec().encode(e.payload,n)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),s.lengthDelimited!==!1&&n.ldelim()},(e,n,s={})=>{let i={publicKey:at(0),payloadType:at(0),signature:at(0)},o=n==null?e.len:e.pos+n;for(;e.pos<o;){let a=e.uint32();switch(a>>>3){case 1:{i.publicKey=e.bytes();break}case 2:{i.payloadType=e.bytes();break}case 3:{i.payload=Ur.codec().decode(e,e.uint32(),{limits:s.limits?.payload});break}case 5:{i.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>Mt(e,r.codec()),r.decode=(e,n)=>Ot(e,r.codec(),n)})(pi||(pi={}));var S0=r=>r.toString().split("/").slice(1),Dr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),F=r=>({match:t=>Dr(e=>e===r).match(t),pattern:r}),cr=()=>({match:r=>Dr(t=>typeof t=="string").match(r),pattern:"{string}"}),bn=()=>({match:r=>Dr(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),Q=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{tt.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),wn=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Mo.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),W=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),It=(...r)=>({match:t=>{let e;for(let n of r){let s=n.match(t);s!==!1&&(e==null||s.length<e.length)&&(e=s)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),q=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function nt(...r){function t(s){let i=S0(s);for(let o of r){let a=o.match(i);if(a===!1)return!1;i=a}return i}function e(s){return t(s)!==!1}function n(s){let i=t(s);return i===!1?!1:i.length===0}return{matchers:r,matches:e,exactMatch:n}}var gi=q(F("dns4"),cr()),yi=q(F("dns6"),cr()),bi=q(F("dnsaddr"),cr()),Fa=q(F("dns"),cr()),d2=nt(gi,W(Q())),p2=nt(yi,W(Q())),m2=nt(bi,W(Q())),g2=nt(It(Fa,bi,gi,yi),W(Q())),df=q(F("ip4"),Dr(ei)),pf=q(F("ip6"),Dr(ri)),Ka=It(df,pf),ke=It(Ka,Fa,gi,yi,bi),y2=nt(It(Ka,q(It(Fa,bi,gi,yi),W(Q())))),b2=nt(df),w2=nt(pf),x2=nt(Ka),qa=q(ke,F("tcp"),bn()),xn=q(ke,F("udp"),bn()),v2=nt(q(qa,W(Q()))),E2=nt(xn),za=q(xn,F("quic"),W(Q())),wi=q(xn,F("quic-v1"),W(Q())),A0=It(za,wi),S2=nt(za),A2=nt(wi),Ha=It(ke,qa,xn,za,wi),mf=It(q(Ha,F("ws"),W(Q()))),B2=nt(mf),gf=It(q(Ha,F("wss"),W(Q())),q(Ha,F("tls"),W(q(F("sni"),cr())),F("ws"),W(Q()))),_2=nt(gf),yf=q(xn,F("webrtc-direct"),W(wn()),W(wn()),W(Q())),I2=nt(yf),bf=q(wi,F("webtransport"),W(wn()),W(wn()),W(Q())),T2=nt(bf),mi=It(mf,gf,q(qa,W(Q())),q(A0,W(Q())),q(ke,W(Q())),yf,bf,Q()),wf=nt(mi),B0=q(mi,F("p2p-circuit"),Q()),xi=nt(B0),_0=It(q(mi,F("p2p-circuit"),F("webrtc"),W(Q())),q(mi,F("webrtc"),W(Q())),q(F("webrtc"),W(Q()))),k2=nt(_0),I0=It(q(ke,F("tcp"),bn(),F("http"),W(Q())),q(ke,F("http"),W(Q()))),C2=nt(I0),T0=It(q(ke,F("tcp"),It(q(F("443"),F("http")),q(bn(),F("https"))),W(Q())),q(ke,F("tls"),F("http"),W(Q())),q(ke,F("https"),W(Q()))),N2=nt(T0),k0=It(q(F("memory"),cr(),W(Q()))),L2=nt(k0);function vi(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}var Ei=class extends Error{constructor(t="Transfer limit error"){super(t),this.name="TransferLimitError"}},vn=class extends Error{constructor(t="Duration limit error"){super(t),this.name="DurationLimitError"}},En=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},Si=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},Ai=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};async function*xf(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 Ei(`data limit of ${n} bytes exceeded`)}t.remaining-=i,yield s}}function vf(r,t,e,n,s){function i(u){r.abort(u),t.abort(u)}let o=[e,n.signal];n.limit?.duration!=null&&(s.log("limiting relayed connection duration to %dms",n.limit.duration),o.push(AbortSignal.timeout(n.limit.duration)));let a=vi(o),c=!1,h=!1,f;n.limit?.data!=null&&(f={remaining:n.limit.data}),queueMicrotask(()=>{let u=()=>{s.log("relayed connection reached time limit"),t.abort(new vn(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",u,{once:!0}),t.sink(f==null?r.source:xf(r.source,f,s)).catch(g=>{s.log.error("error while relaying streams src -> dst",g),i(g)}).finally(()=>{c=!0,h&&(a.removeEventListener("abort",u),a.clear())})}),queueMicrotask(()=>{let u=()=>{s.log("relayed connection reached time limit"),r.abort(new vn(`duration limit of ${n.limit?.duration} ms exceeded`))};a.addEventListener("abort",u,{once:!0}),r.sink(f==null?t.source:xf(t.source,f,s)).catch(g=>{s.log.error("error while relaying streams dst -> src",g),i(g)}).finally(()=>{h=!0,c&&(a.removeEventListener("abort",u),a.clear())})})}function $a(r){let t=r*BigInt(1e3),e=new Date().getTime();return Number(t-BigInt(e))}var Sn=class{expires;bytes;constructor(t){t?.duration!=null&&t?.duration!==0&&(this.expires=Date.now()+t.duration*1e3),this.bytes=t?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(t){this.bytes!=null&&(this.bytes-=BigInt(t.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let t={};if(this.bytes!=null){let e=this;Object.defineProperty(t,"bytes",{get(){return e.bytes}})}if(this.expires!=null){let e=this;Object.defineProperty(t,"seconds",{get(){return Math.round(((e.expires??0)-Date.now())/1e3)}})}return t}},Bi=nt(q(wf.matchers[0],F("p2p-circuit"))),_i=nt(F("p2p-circuit"));function Ii(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 We=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return Ii(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return Ii(this.map.values(),t=>t.key)}values(){return Ii(this.map.values(),t=>t.value)}get size(){return this.map.size}};var Ga=64,ne=class{fp;h;seed;constructor(t,e,n,s=2){if(s>Ga)throw new TypeError("Invalid Fingerprint Size");let i=e.hashV(t,n),o=at(s);for(let a=0;a<o.length;a++)o[a]=i[a];o.length===0&&(o[0]=7),this.fp=o,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?mt(this.fp,t.fp):!1}};function lr(r,t){return Math.floor(Math.random()*(t-r))+r}var ur=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof ne))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof ne))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof ne))throw new TypeError("Invalid Fingerprint");let e=lr(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof ne))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Wa={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Bf={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},_f=new globalThis.TextEncoder;function C0(r,t){let e=Wa[t],n=Bf[t];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(t,n*e);return n}function N0(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Wa[t],s=Bf[t],i=r;for(;i.length>0;){let o=_f.encodeInto(i,e);i=i.slice(o.read);for(let a=0;a<o.written;a++)s^=BigInt(e[a]),s=BigInt.asUintN(t,s*n)}return s}function Za(r,{size:t=32,utf8Buffer:e}={}){if(!Wa[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return N0(r,t,e);r=_f.encode(r)}return C0(r,t)}var L0=pc(Af(),1);var Bn={hash:r=>Number(Za(r,{size:32})),hashV:(r,t)=>R0(Bn.hash(r,t))};function R0(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),G(t,"base16")}var U0=500,_n=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??Bn,this.seed=t.seed??lr(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=G(t));let e=new ne(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new ur(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new ur(this.bucketSize)),this.buckets[n].add(e)||this.buckets[s].add(e))return this.count++,!0;let i=[n,s],o=i[lr(0,i.length-1)];this.buckets[o]==null&&(this.buckets[o]=new ur(this.bucketSize));for(let a=0;a<U0;a++){let c=this.buckets[o].swap(e);if(c!=null&&(o=(o^c.hash())%this.filterSize,this.buckets[o]==null&&(this.buckets[o]=new ur(this.bucketSize)),this.buckets[o].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=G(t));let e=new ne(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.has(e)??!1;if(s)return s;let i=(n^e.hash())%this.filterSize;return this.buckets[i]?.has(e)??!1}remove(t){typeof t=="string"&&(t=G(t));let e=new ne(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,s=this.buckets[n]?.remove(e)??!1;if(s)return this.count--,s;let i=(n^e.hash())%this.filterSize,o=this.buckets[i]?.remove(e)??!1;return o&&this.count--,o}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},D0={1:.5,2:.84,4:.95,8:.98};function O0(r=.001){return r>.002?2:r>1e-5?4:8}function If(r,t=.001){let e=O0(t),n=D0[e],s=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Ga);return{filterSize:s,bucketSize:e,fingerprintSize:i}}var ki=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??Bn,this.seed=t.seed??lr(0,Math.pow(2,10)),this.filterSeries=[new _n({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=G(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new _n({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=G(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=G(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function Or(r,t=.001,e){return new ki({...If(r,t),...e??{}})}var Ci=class{filter;constructor(t,e){this.filter=Or(t,e)}has(t){return this.filter.has(t.toMultihash().bytes)}add(t){this.filter.add(t.toMultihash().bytes)}remove(t){this.filter.remove?.(t.toMultihash().bytes)}};function ja(r,t=.001){return new Ci(r,t)}var Ya=class extends We{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Xa(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Ya({name:t,metrics:e}):n=new We,n}var Ja=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};function Tf(r,t){let e=new Ja(t?.errorMessage,t?.errorCode,t?.errorName),n=new AbortController,s=()=>{n.abort(e)},i=AbortSignal.timeout(r);i.addEventListener("abort",s);let o=n.signal;return o.reset=a=>{i?.removeEventListener("abort",s),i=AbortSignal.timeout(a??r),i.addEventListener("abort",()=>{n.abort(e)})},o.clear=()=>{i?.removeEventListener("abort",s),i=void 0},o}var Ni=class{reservations;maxReservations;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:circuit-relay:server:reservation-store"),this.maxReservations=e.maxReservations??nf,this.applyDefaultLimit=e.applyDefaultLimit!==!1,this.reservationTtl=e.reservationTtl??sf,this.defaultDurationLimit=e.defaultDurationLimit??cf,this.defaultDataLimit=e.defaultDataLimit??lf,this.reservations=Xa({metrics:t.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(t,e,n){let s=this.reservations.get(t);if(this.reservations.size>=this.maxReservations&&s==null)return{status:K.RESERVATION_REFUSED};let i=new Date(Date.now()+this.reservationTtl),o;return this.applyDefaultLimit&&(o=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),s!=null?(this.log("refreshing reservation for client %p",t),s.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",t),s={addr:e,expiry:i,limit:o,signal:Tf(this.reservationTtl)}),this.reservations.set(t,s),s.signal.addEventListener("abort",()=>{this.reservations.delete(t)}),{status:K.OK,expire:Math.round(i.getTime()/1e3)}}removeReservation(t){this.reservations.delete(t)}get(t){return this.reservations.get(t)}clear(){this.reservations.clear()}};var Li=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 Ur.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,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 kf=r=>r.protoCodes().includes(fi),M0={maxOutboundStopStreams:yn},Qa=class extends qt{registrar;peerStore;addressManager;peerId;privateKey;connectionManager;connectionGater;reservationStore;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.privateKey=t.privateKey,this.connectionManager=t.connectionManager,this.connectionGater=t.connectionGater,this.started=!1,this.hopTimeout=e?.hopTimeout??uf,this.maxInboundHopStreams=e.maxInboundHopStreams,this.maxOutboundHopStreams=e.maxOutboundHopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??M0.maxOutboundStopStreams,this.reservationStore=new Ni(t,e.reservations),this.shutdownController=new AbortController,Lt(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.registrar.handle(Wt,t=>{this.onHop(t).catch(e=>{this.log.error(e)})},{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.registrar.unhandle(Wt),this.started=!1}async onHop({connection:t,stream:e}){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n={signal:AbortSignal.timeout(this.hopTimeout)},s=Ge(e);try{let i=await s.pb(X).read(n);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:t,stream:s,request:i},n)}catch(i){this.log.error("error while handling hop",i),await s.pb(X).write({type:X.Type.STATUS,status:K.MALFORMED_MESSAGE},n),e.abort(i)}}async handleHopProtocol({stream:t,request:e,connection:n},s){switch(this.log("received hop message"),e.type){case X.Type.RESERVE:await this.handleReserve({stream:t,request:e,connection:n},s);break;case X.Type.CONNECT:await this.handleConnect({stream:t,request:e,connection:n},s);break;default:this.log.error("invalid hop request type %s via peer %p",e.type,n.remotePeer),await t.pb(X).write({type:X.Type.STATUS,status:K.UNEXPECTED_MESSAGE})}}async handleReserve({stream:t,connection:e},n){let s=t.pb(X);if(this.log("hop reserve request from %p",e.remotePeer),kf(e.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",e.remotePeer),await s.write({type:X.Type.STATUS,status:K.PERMISSION_DENIED},n);return}if(await this.connectionGater.denyInboundRelayReservation?.(e.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",e.remotePeer),await s.write({type:X.Type.STATUS,status:K.PERMISSION_DENIED},n);return}let i=this.reservationStore.reserve(e.remotePeer,e.remoteAddr);try{if(i.status!==K.OK){await s.write({type:X.Type.STATUS,status:i.status},n);return}if(i.expire!=null){let o=i.expire*1e3-Date.now();await this.peerStore.merge(e.remotePeer,{tags:{[Ma]:{value:1,ttl:o},[Pa]:{value:1,ttl:o}}})}await s.write({type:X.Type.STATUS,status:K.OK,reservation:await this.makeReservation(e.remotePeer,BigInt(i.expire??0)),limit:this.reservationStore.get(e.remotePeer)?.limit},n),this.log("sent confirmation response to %s",e.remotePeer)}catch(o){this.log.error("failed to send confirmation response to %p - %e",e.remotePeer,o),this.reservationStore.removeReservation(e.remotePeer);try{await this.peerStore.merge(e.remotePeer,{tags:{[Ma]:void 0,[Pa]:void 0}})}catch(a){this.log.error("failed to untag relay source peer %p - %e",e.remotePeer,a)}}}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 mn.seal(new Li({peer:t,relay:this.peerId,expiration:e}),this.privateKey);return{addrs:n,expire:e,voucher:{publicKey:Me(s.publicKey),payloadType:s.payloadType,payload:{peer:t.toMultihash().bytes,relay:this.peerId.toMultihash().bytes,expiration:e},signature:s.signature}}}async handleConnect({stream:t,request:e,connection:n},s){let i=t.pb(X);if(kf(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await i.write({type:X.Type.STATUS,status:K.PERMISSION_DENIED},s);return}this.log("hop connect request from %p",n.remotePeer);let o;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(xt),o=dn(zt(e.peer.id))}catch(g){this.log.error("invalid hop connect request via peer %p %s",n.remotePeer,g),await i.write({type:X.Type.STATUS,status:K.MALFORMED_MESSAGE},s);return}let a=this.reservationStore.get(o);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",o,n.remotePeer,K.NO_RESERVATION),await i.write({type:X.Type.STATUS,status:K.NO_RESERVATION},s);return}if(await this.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,o)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,o),await i.write({type:X.Type.STATUS,status:K.PERMISSION_DENIED},s);return}let c=this.connectionManager.getConnections(o);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",o,n.remotePeer),await i.write({type:X.Type.STATUS,status:K.NO_RESERVATION},s);return}let h=c[0],f=await this.stopHop({connection:h,request:{type:Kt.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},s);if(f==null){this.log.error("failed to open stream to destination peer %p",h?.remotePeer),await i.write({type:X.Type.STATUS,status:K.CONNECTION_FAILED},s);return}await i.write({type:X.Type.STATUS,status:K.OK,limit:a?.limit},s);let u=t.unwrap();this.log("connection from %p to %p established - merging streams",n.remotePeer,o),vf(u,f,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:t,request:e},n){this.log("starting circuit relay v2 stop request to %s",t.remotePeer);let s=await t.newStream([ar],{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),i=Ge(s),o=i.pb(Kt);await o.write(e,n);let a;try{a=await o.read(n)}catch{this.log.error("error parsing stop message response from %p",t.remotePeer)}if(a==null){this.log.error("could not read response from %p",t.remotePeer),await s.close(n);return}if(a.status===K.OK)return this.log("stop request to %p was successful",t.remotePeer),i.unwrap();this.log("stop request failed with code %d",a.status),await s.close(n)}get reservations(){return this.reservationStore.reservations}};function Cf(r={}){return t=>new Qa(t,r)}function P0(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var Nf=P0;function V0(r){return r[Symbol.asyncIterator]!=null}function Lf(r){return r?.then!=null}function H0(r,t){let e=0;if(V0(r))return async function*(){for await(let c of r){let h=t(c,e++);Lf(h)&&await h,yield c}}();let n=Nf(r),{value:s,done:i}=n.next();if(i===!0)return function*(){}();if(typeof t(s,e++)?.then=="function")return async function*(){yield s;for await(let c of n){let h=t(c,e++);Lf(h)&&await h,yield c}}();let a=t;return function*(){yield s;for(let c of n)a(c,e++),yield c}()}var Rf=H0;var Ri=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}},Mr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Ri(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 Ri(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 tc=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Pr(r={}){return F0(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 F0(r,t){t=t??{};let e=t.onEnd,n=new Mr,s,i,o,a=re(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((y,b)=>{i=w=>{i=null,n.push(w);try{y(r(n))}catch(m){b(m)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=re()})}},h=y=>i!=null?i(y):(n.push(y),s),f=y=>(n=new Mr,i!=null?i({error:y}):(n.push({error:y}),s)),u=y=>{if(o)return s;if(t?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return h({done:!1,value:y})},g=y=>o?s:(o=!0,y!=null?f(y):h({done:!0})),l=()=>(n=new Mr,g(),{done:!0}),d=y=>(g(y),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:l,throw:d,push:u,end:g,get readableLength(){return n.size},onEmpty:async y=>{let b=y?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let w,m;b!=null&&(w=new Promise((E,A)=>{m=()=>{A(new tc)},b.addEventListener("abort",m)}));try{await Promise.race([a.promise,w])}finally{m!=null&&b!=null&&b?.removeEventListener("abort",m)}}},e==null)return s;let p=s;return s={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(y){return p.throw(y),e!=null&&(e(y),e=void 0),{done:!0}},return(){return p.return(),e!=null&&(e(),e=void 0),{done:!0}},push:u,end(y){return p.end(y),e!=null&&(e(y),e=void 0),s},get readableLength(){return p.readableLength},onEmpty:y=>p.onEmpty(y)},s}function K0(r){return r[Symbol.asyncIterator]!=null}function q0(...r){let t=[];for(let e of r)K0(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=Pr({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let s of n)e.push(s)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var Uf=q0;function Df(r,...t){if(r==null)throw new Error("Empty pipeline");if(ec(r)){let n=r;r=()=>n.source}else if(Mf(r)||Of(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&ec(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)ec(e[n])&&(e[n]=$0(e[n]));return z0(...e)}var z0=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Of=r=>r?.[Symbol.asyncIterator]!=null,Mf=r=>r?.[Symbol.iterator]!=null,ec=r=>r==null?!1:r.sink!=null&&r.source!=null,$0=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Pr({objectMode:!0});e.then(()=>{n.end()},o=>{n.end(o)});let s,i=r.source;if(Of(i))s=async function*(){yield*i,n.end()};else if(Mf(i))s=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Uf(n,s())}return r.source};function rc(r){let{stream:t,remoteAddr:e,logger:n,onDataRead:s,onDataWrite:i}=r,o=n.forComponent("libp2p:stream:converter"),a=!1,c=!1,h=t.close.bind(t);t.close=async d=>{await h(d),l(!0)};let f=t.abort.bind(t);t.abort=d=>{f(d),l(!0)};let u=t.sink.bind(t);t.sink=async d=>{try{await u(Df(d,p=>Rf(p,y=>i?.(y))))}catch(p){p.type!=="aborted"&&o.error("%s error in sink",e,p)}finally{c=!0,l()}};let g={log:o,sink:t.sink,source:async function*(){try{for await(let d of t.source)s?.(d),yield d}finally{a=!0,l()}}(),remoteAddr:e,timeline:{open:Date.now(),close:void 0},close:t.close,abort:t.abort};function l(d){d===!0&&(a=!0,c=!0),a&&c&&g.timeline.close==null&&(g.timeline.close=Date.now())}return g}var Ze=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var nc=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 Ui(r,t,e,n){let s=new nc(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(s):new Promise((i,o)=>{function a(){e?.removeEventListener("abort",f),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,h)}let c=u=>{try{if(n?.filter?.(u)===!1)return}catch(g){a(),o(g);return}a(),i(u)},h=u=>{a(),o(u.detail)},f=()=>{a(),o(s)};e?.addEventListener("abort",f),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,h)})}var Di=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var Oi=class{deferred;signal;constructor(t){this.signal=t,this.deferred=re(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new he)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function G0(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Mi=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=G0(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,Lt(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 he),this.cleanup())}async join(t={}){let e=new Oi(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 oi(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.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var Pi=class extends qt{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??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.sort=t.sort,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){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Di;let n=new Mi(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new he)}),this.clear()}async onEmpty(t){this.size!==0&&await Ui(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await Ui(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Ui(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=Pr({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 he("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 Vr=class extends Pi{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var Vi=class extends qt{peerStore;registrar;connectionManager;randomWalk;started;running;topologyId;log;discoveryController;filter;queue;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.started=!1,this.running=!1,this.peerStore=t.peerStore,this.registrar=t.registrar,this.connectionManager=t.connectionManager,this.randomWalk=t.randomWalk,this.filter=e.filter,this.discoveryController=new AbortController,Lt(1/0,this.discoveryController.signal)}isStarted(){return this.started}async start(){this.topologyId=await this.registrar.register(Wt,{filter:this.filter,onConnect:t=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",t,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:t})}}),this.started=!0}stop(){this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.discoveryController?.abort(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,Lt(1/0,this.discoveryController.signal),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let t=await this.peerStore.all({filters:[n=>n.protocols.includes(Wt)],orders:[()=>Math.random()<.5?1:-1,(n,s)=>{let i=Pf(n),o=Pf(s);return i>o?-1:o>i?1:0}]});for(let n of t)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",t.length);let e=this.queue=new Vr({concurrency:5});this.log("start random walk");for await(let n of this.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),e.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(s=>s.toString()));continue}e.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await e.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,e.size,e.running),e.add(async()=>{let s=vi([this.discoveryController.signal,AbortSignal.timeout(5e3)]);Lt(1/0,s);try{await this.connectionManager.openConnection(n.id,{signal:s})}finally{s.clear()}},{peerId:n.id,signal:this.discoveryController.signal}).catch(s=>{this.log.error("error opening connection to random peer %p",n.id,s)})}this.log("stop random walk"),await e.onIdle()}).catch(t=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network",t)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort()}};function Pf(r){let t=r.metadata.get("last-dial-success");return t==null?0:new Date(lt(t)).getTime()}var sc=class extends qt{connectionManager;reservationStore;discovery;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(t,e={}){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=t.connectionManager,this.reservationStore=t.relayStore,this.listeningAddrs=[],this.listenTimeout=e.listenTimeout??hi,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=t=>{this.log("relay removed %p our relay %p",t.detail.relay,this.relay,this.relay?.equals(t.detail.relay)),this.relay?.equals(t.detail.relay)===!0&&(this.log("relay peer removed %p",t.detail.relay),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=t=>{let{relay:e,details:n}=t.detail;n.type!=="configured"&&n.id===this.reservationId&&(this.log("relay peer added %p",e),this.relay=e,this.listeningAddrs=n.reservation.addrs.map(s=>xt(s).encapsulate("/p2p-circuit")),this.safeDispatchEvent("listening"))};async listen(t){if(this.log("listen on %a",t),_i.exactMatch(t))this.reservationId=this.reservationStore.reserveRelay();else if(Bi.exactMatch(t)){let e=AbortSignal.timeout(this.listenTimeout);Lt(1/0,e);let n=t.decapsulate("/p2p-circuit"),s=await this.connectionManager.openConnection(n,{signal:e});if(!this.reservationStore.hasReservation(s.remotePeer)){this.log("making reservation on peer %p",s.remotePeer);let i=await this.reservationStore.addRelay(s.remotePeer,"configured");this.log("made reservation on peer %p",s.remotePeer),this.relay=i.relay,this.listeningAddrs=i.details.reservation.addrs.map(o=>xt(o).encapsulate("/p2p-circuit")),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}}else throw new je(`Could not listen on p2p-circuit address "${t}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};function Vf(r){return new sc(r)}var Hf="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Ff=(r=21)=>{let t="",e=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)t+=Hf[e[r]&63];return t};var W0=60*1e3*10,Z0=60*1e3*5,j0=30*1e3,Hi=class extends qt{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(t,e){super(),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=t.peerId,this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.reservations=new We,this.pendingReservations=[],this.maxReservationQueueLength=e?.maxReservationQueueLength??af,this.reservationCompletionTimeout=e?.reservationCompletionTimeout??hi,this.started=!1,this.relayFilter=Or(100),this.reserveQueue=new Vr({concurrency:e?.reservationConcurrency??of,metricName:"libp2p_relay_reservation_queue",metrics:t.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(i=>i.connection===n.detail.id)!=null&&this.#e(n.detail.remotePeer).catch(i=>{this.log("could not remove relay %p - %e",n.detail,i)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let t=await this.peerStore.all({filters:[e=>e.tags.has(gn)]});this.log("removing tag from %d old relays",t.length),await Promise.all(t.map(async e=>{await this.peerStore.merge(e.id,{tags:{[gn]:void 0}})})),this.log("redialing %d old relays",t.length),await Promise.all(t.map(async e=>this.addRelay(e.id,"discovered"))),this.#r()}).catch(t=>{this.log.error(t)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:t})=>{clearTimeout(t)}),this.reservations.clear(),this.started=!1}reserveRelay(){let t=Ff();return this.pendingReservations.push(t),this.#r(),t}async addRelay(t,e){if(this.peerId.equals(t))throw this.log.trace("not trying to use self as relay"),new je("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new Ai("The reservation queue is full");let n=this.reserveQueue.find(t);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",t),n.join();if(this.relayFilter.has(t.toMultihash().bytes))throw new je("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",t),this.reserveQueue.add(async()=>{let s=Date.now();try{let i=this.reservations.get(t);if(i!=null){let d=this.connectionManager.getConnections(t),p=!1;if(d.length===0&&this.log("already have relay reservation with %p but we are no longer connected",t),d.map(y=>y.id).includes(i.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",t),p=!0),p&&$a(i.reservation.expire)>W0)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",t),{relay:t,details:i};await this.#e(t)}if(e==="discovered"&&this.pendingReservations.length===0)throw new En("Not making reservation on discovered relay because we do not need any more relays");let o=AbortSignal.timeout(this.reservationCompletionTimeout);Lt(1/0,o);let a=await this.connectionManager.openConnection(t,{signal:o});if(xi.matches(a.remoteAddr))throw new Si("not creating reservation over relayed connection");let c=await this.#t(a,{signal:o}),h=$a(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",t,new Date(Date.now()+h).toString());let f=Math.min(Math.max(h-Z0,j0),Math.pow(2,31)-1),u=setTimeout(()=>{this.log("refresh reservation to relay %p",t),this.addRelay(t,e).catch(async d=>{this.log.error("could not refresh reservation to relay %p - %e",t,d),await this.#e(t)}).catch(d=>{this.log.error("could not remove expired reservation to relay %p - %e",t,d)})},f),g;if(e==="discovered"){let d=this.pendingReservations.pop();if(d==null)throw new En("Made reservation on relay but did not need any more discovered relays");g={timeout:u,reservation:c,type:e,connection:a.id,id:d}}else g={timeout:u,reservation:c,type:e,connection:a.id};this.reservations.set(t,g),await this.peerStore.merge(t,{tags:{[gn]:{value:1,ttl:h}}}),this.#r();let l={relay:t,details:g};return this.safeDispatchEvent("relay:created-reservation",{detail:l}),l}catch(i){throw e==="discovered"&&i.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",t,Date.now()-s,i),(i.name==="DialError"||i.name==="UnsupportedProtocolError")&&this.relayFilter.add(t.toMultihash().bytes),this.#e(t).catch(o=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",t,o)}),i}},{peerId:t})}hasReservation(t){return this.reservations.has(t)}getReservation(t){return this.reservations.get(t)?.reservation}reservationCount(t){return t==null?this.reservations.size:[...this.reservations.values()].reduce((e,n)=>(n.type===t&&e++,e),0)}cancelReservations(){[...this.reservations.values()].forEach(t=>{clearTimeout(t.timeout)}),this.reservations.clear()}async#t(t,e){e.signal?.throwIfAborted(),this.log("requesting reservation from %p",t.remotePeer);let n=await t.newStream(Wt,e),i=Ge(n).pb(X);this.log.trace("send RESERVE to %p",t.remotePeer),await i.write({type:X.Type.RESERVE},e);let o;try{this.log.trace("reading response from %p",t.remotePeer),o=await i.read(e)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(e)}if(this.log.trace("read response %o",o),o.status===K.OK&&o.reservation!=null){let c=new Set;c.add(t.remoteAddr.toString());for(let h of o.reservation.addrs){let f=xt(h);f.getPeerId()==null&&(f=f.encapsulate(`/p2p/${t.remotePeer}`)),f=xt(f.toString().replace(`/p2p/${t.remotePeer}/p2p/${t.remotePeer}`,`/p2p/${t.remotePeer}`)),c.add(f.toString())}return o.reservation.addrs=[...c].map(h=>xt(h).bytes),o.reservation}let a=`reservation failed with status ${o.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#e(t){let e=this.reservations.get(t);e!=null&&(this.log("removing relay reservation with %p from local store",t),clearTimeout(e.timeout),this.reservations.delete(t),e.type==="discovered"&&this.pendingReservations.push(e.id),await this.peerStore.merge(t,{tags:{[gn]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:t,details:e}}),this.#r())}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=Or(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var Y0=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(xt)}catch{return!1}return!0},ic={maxInboundStopStreams:yn,maxOutboundStopStreams:yn,stopTimeout:3e4},Fi=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??ic.maxInboundStopStreams,this.maxOutboundStopStreams=e.maxOutboundStopStreams??ic.maxOutboundStopStreams,this.stopTimeout=e.stopTimeout??ic.stopTimeout,this.discovery=new Vi(t,{filter:e.discoveryFilter??ja(ff,hf)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(s=>{s.name!=="HadEnoughRelaysError"&&s.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p",n.detail,s)})}),this.reservationStore=new Hi(t,e),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[xc]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[vc](){return this.discovery!=null?["@libp2p/identify"]:[]}[gc]=!0;isStarted(){return this.started}async start(){await this.registrar.handle(ar,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,runOnLimitedConnection:!0}),await bc(this.discovery,this.reservationStore),this.started=!0}async stop(){await wc(this.discovery,this.reservationStore),await this.registrar.unhandle(ar),this.started=!1}async dial(t,e){if(t.protoCodes().filter(l=>l===fi).length!==1){let l="Invalid circuit relay address";throw this.log.error(l,t),new Fr(l)}let n=t.toString().split("/p2p-circuit"),s=xt(n[0]),i=xt(n[n.length-1]),o=s.getPeerId(),a=i.getPeerId();if(o==null||a==null){let l=`ircuit relay dial to ${t.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${l}`),new Fr(`C${l}`)}let c=ya(o),h=ya(a),u=this.connectionManager.getConnections(c)[0];u==null?(await this.peerStore.merge(c,{multiaddrs:[s]}),e.onProgress?.(new Ze("circuit-relay:open-connection")),u=await this.connectionManager.openConnection(c,e)):e.onProgress?.(new Ze("circuit-relay:reuse-connection"));let g;try{e.onProgress?.(new Ze("circuit-relay:open-hop-stream")),g=await u.newStream(Wt,e);let l=Ge(g),d=l.pb(X);e.onProgress?.(new Ze("circuit-relay:write-connect-message")),await d.write({type:X.Type.CONNECT,peer:{id:h.toMultihash().bytes,addrs:[xt(i).bytes]}},e),e.onProgress?.(new Ze("circuit-relay:read-connect-response"));let p=await d.read(e);if(p.status!==K.OK)throw new kn(`failed to connect via relay with status ${p?.status?.toString()??"undefined"}`);let y=new Sn(p.limit),b=rc({stream:l.unwrap(),remoteAddr:t,localAddr:s.encapsulate(`/p2p-circuit/p2p/${this.peerId.toString()}`),logger:this.logger,onDataRead:y.onData,onDataWrite:y.onData});return this.log("new outbound relayed connection %a",b.remoteAddr),await this.upgrader.upgradeOutbound(b,{...e,limits:y.getLimits()})}catch(l){throw this.log.error("circuit relay dial to destination %p via relay %p failed",h,c,l),g?.abort(l),l}}createListener(t){return Vf({connectionManager:this.connectionManager,relayStore:this.reservationStore,logger:this.logger})}listenFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>Bi.exactMatch(e)||_i.exactMatch(e))}dialFilter(t){return t=Array.isArray(t)?t:[t],t.filter(e=>xi.exactMatch(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=Ge(e).pb(Kt),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:Kt.Type.STATUS,status:K.MALFORMED_MESSAGE},{signal:n}),await e.close();return}if(i.type!==Kt.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:Kt.Type.STATUS,status:K.UNEXPECTED_MESSAGE},{signal:n}),await e.close();return}if(!Y0(i)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await s.write({type:Kt.Type.STATUS,status:K.MALFORMED_MESSAGE},{signal:n}),await e.close();return}let o=dn(zt(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:Kt.Type.STATUS,status:K.PERMISSION_DENIED},{signal:n}),await e.close();return}this.log.trace("sending success response to %p",t.remotePeer),await s.write({type:Kt.Type.STATUS,status:K.OK},{signal:n});let a=new Sn(i.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${o.toString()}`),h=this.addressManager.getAddresses()[0],f=rc({stream:s.unwrap().unwrap(),remoteAddr:c,localAddr:h,logger:this.logger,onDataRead:a.onData,onDataWrite:a.onData});this.log("new inbound relayed connection %a",f.remoteAddr),await this.upgrader.upgradeInbound(f,{limits:a.getLimits()}),this.log("%s connection %a upgraded","inbound",f.remoteAddr)}};function Kf(r={}){return t=>new Fi(t,r)}return rh(X0);})();
|
7
7
|
/*! Bundled license information:
|
8
8
|
|
9
9
|
pvtsutils/build/index.js:
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@libp2p/circuit-relay-v2",
|
3
|
-
"version": "3.1.3-
|
3
|
+
"version": "3.1.3-b02ea9b6e",
|
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",
|
@@ -52,13 +52,13 @@
|
|
52
52
|
"doc-check": "aegir doc-check"
|
53
53
|
},
|
54
54
|
"dependencies": {
|
55
|
-
"@libp2p/crypto": "5.0.7-
|
56
|
-
"@libp2p/interface": "2.2.1-
|
57
|
-
"@libp2p/interface-internal": "2.1.1-
|
58
|
-
"@libp2p/peer-collections": "6.0.12-
|
59
|
-
"@libp2p/peer-id": "5.0.8-
|
60
|
-
"@libp2p/peer-record": "8.0.12-
|
61
|
-
"@libp2p/utils": "6.2.1-
|
55
|
+
"@libp2p/crypto": "5.0.7-b02ea9b6e",
|
56
|
+
"@libp2p/interface": "2.2.1-b02ea9b6e",
|
57
|
+
"@libp2p/interface-internal": "2.1.1-b02ea9b6e",
|
58
|
+
"@libp2p/peer-collections": "6.0.12-b02ea9b6e",
|
59
|
+
"@libp2p/peer-id": "5.0.8-b02ea9b6e",
|
60
|
+
"@libp2p/peer-record": "8.0.12-b02ea9b6e",
|
61
|
+
"@libp2p/utils": "6.2.1-b02ea9b6e",
|
62
62
|
"@multiformats/multiaddr": "^12.2.3",
|
63
63
|
"@multiformats/multiaddr-matcher": "^1.3.0",
|
64
64
|
"any-signal": "^4.1.1",
|
@@ -73,8 +73,8 @@
|
|
73
73
|
"uint8arrays": "^5.1.0"
|
74
74
|
},
|
75
75
|
"devDependencies": {
|
76
|
-
"@libp2p/interface-compliance-tests": "6.1.11-
|
77
|
-
"@libp2p/logger": "5.1.4-
|
76
|
+
"@libp2p/interface-compliance-tests": "6.1.11-b02ea9b6e",
|
77
|
+
"@libp2p/logger": "5.1.4-b02ea9b6e",
|
78
78
|
"aegir": "^44.0.1",
|
79
79
|
"delay": "^6.0.0",
|
80
80
|
"it-drain": "^3.0.7",
|