@libp2p/identify 1.0.12-e1db332a4 → 1.0.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +1 -1
- package/dist/typedoc-urls.json +12 -0
- package/package.json +18 -18
package/dist/index.min.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
`));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
|
|
5
5
|
${e.join(`
|
|
6
6
|
`)}`:`${t} :`}};oc=Pt;I.Constructed=oc;Pt.NAME="CONSTRUCTED";var Mn=class extends Be{fromBER(e,t,n){return t}toBER(e){return je}};Mn.override="EndOfContentValueBlock";var ic,Hn=class extends be{constructor(e={}){super(e,Mn),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};ic=Hn;I.EndOfContent=ic;Hn.NAME=qr;var ac,Ot=class extends be{constructor(e={}){super(e,Be),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let s=new Uint8Array(n);s[0]=5,s[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};ac=Ot;I.Null=ac;Ot.NAME="NULL";var Fn=class extends vt(Be){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=M.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let s=M.BufferSourceConverter.toUint8Array(e);return xt(this,s,t,n)?(this.valueHexView=s.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Wo.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Fn.NAME="BooleanValueBlock";var cc,Kn=class extends be{constructor(e={}){super(e,Fn),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};cc=Kn;I.Boolean=cc;Kn.NAME="BOOLEAN";var qn=class extends vt(et){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let s=0;if(this.isConstructed){if(this.isHexOnly=!1,s=et.prototype.fromBER.call(this,e,t,n),s===-1)return s;for(let o=0;o<this.value.length;o++){let i=this.value[o].constructor.NAME;if(i===qr){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==tc)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,s=super.fromBER(e,t,n),this.blockLength=n;return s}toBER(e,t){return this.isConstructed?et.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};qn.NAME="OctetStringValueBlock";var lc,bt=class r extends be{constructor({idBlock:e={},lenBlock:t={},...n}={}){var s,o;(s=n.isConstructed)!==null&&s!==void 0||(n.isConstructed=!!(!((o=n.value)===null||o===void 0)&&o.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},qn),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let o=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(o.byteLength){let i=ys(o,0,o.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?Pt.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${M.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return M.BufferSourceConverter.concat(e)}};lc=bt;I.OctetString=lc;bt.NAME=tc;var $n=class extends vt(et){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let s=-1;if(this.isConstructed){if(s=et.prototype.fromBER.call(this,e,t,n),s===-1)return s;for(let a of this.value){let c=a.constructor.NAME;if(c===qr){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==rc)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let f=a.valueBlock;if(this.unusedBits>0&&f.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=f.unusedBits}return s}let o=M.BufferSourceConverter.toUint8Array(e);if(!xt(this,o,t,n))return-1;let i=o.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=ys(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return et.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return je;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}}};$n.NAME="BitStringValueBlock";var uc,Er=class extends be{constructor({idBlock:e={},lenBlock:t={},...n}={}){var s,o;(s=n.isConstructed)!==null&&s!==void 0||(n.isConstructed=!!(!((o=n.value)===null||o===void 0)&&o.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},$n),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Pt.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let s of t)e.push(s.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};uc=Er;I.BitString=uc;Er.NAME=rc;var fc;function Qh(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),s=new Uint8Array(e),o=n.slice(0),i=o.length-1,a=s.slice(0),c=a.length-1,f=0,u=c<i?i:c,l=0;for(let d=u;d>=0;d--,l++){switch(!0){case l<a.length:f=o[i-l]+a[c-l]+t[0];break;default:f=o[i-l]+t[0]}switch(t[0]=f/10,!0){case l>=o.length:o=Cn(new Uint8Array([f%10]),o);break;default:o[i-l]=f%10}}return t[0]>0&&(o=Cn(t,o)),o}function ec(r){if(r>=Fr.length)for(let e=Fr.length;e<=r;e++){let t=new Uint8Array([0]),n=Fr[e-1].slice(0);for(let s=n.length-1;s>=0;s--){let o=new Uint8Array([(n[s]<<1)+t[0]]);t[0]=o[0]/10,n[s]=o[0]%10}t[0]>0&&(n=Cn(t,n)),Fr.push(n)}return Fr[r]}function ed(r,e){let t=0,n=new Uint8Array(r),s=new Uint8Array(e),o=n.slice(0),i=o.length-1,a=s.slice(0),c=a.length-1,f,u=0;for(let l=c;l>=0;l--,u++)switch(f=o[i-u]-a[c-u]-t,!0){case f<0:t=1,o[i-u]=f+10;break;default:t=0,o[i-u]=f}if(t>0)for(let l=i-c+1;l>=0;l--,u++)if(f=o[i-u]-t,f<0)t=1,o[i-u]=f+10;else{t=0,o[i-u]=f;break}return o.slice()}var $r=class extends vt(Be){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=Wo.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Ja(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,s=0){let o=this.fromBER(e,t,n);if(o===-1)return o;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):s!==0&&i.length<s&&(s-i.length>1&&(s=i.length+1),this.valueHexView=i.subarray(s-i.length)),o}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let s=super.fromBER(e,t,n);return s===-1||this.setValueHex(),s}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,s,o=this.valueHexView,i="",a=!1;for(let c=o.byteLength-1;c>=0;c--){s=o[c];for(let f=0;f<8;f++){if((s&1)===1)switch(n){case e:t=ed(ec(n),t),i="-";break;default:t=Qh(t,ec(n))}n++,s>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=Qa.charAt(t[c]));return a===!1&&(i+=Qa.charAt(0)),i}};fc=$r;$r.NAME="IntegerValueBlock";Object.defineProperty(fc.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var hc,ce=class r extends be{constructor(e={}){super(e,$r),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Ln(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Ln();let t=BigInt(e),n=new Kr,s=t.toString(16).replace(/^-/,""),o=new Uint8Array(M.Convert.FromHex(s));if(t<0){let a=new Uint8Array(o.length+(o[0]&128?1:0));a[0]|=128;let f=BigInt(`0x${M.Convert.ToHex(a)}`)+t,u=M.BufferSourceConverter.toUint8Array(M.Convert.FromHex(f.toString(16)));u[0]|=128,n.write(u)}else o[0]&128&&n.write(new Uint8Array([0])),n.write(o);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};hc=ce;I.Integer=hc;ce.NAME="INTEGER";var dc,Gn=class extends ce{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};dc=Gn;I.Enumerated=dc;Gn.NAME="ENUMERATED";var Gr=class extends vt(Be){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let s=M.BufferSourceConverter.toUint8Array(e);if(!xt(this,s,t,n))return-1;let o=s.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=o[a]&127,this.blockLength++,!!(o[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,o[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=Xt(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Ln();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let s=0;s<n.length;s++)n[s]=parseInt(t.slice(s*7,s*7+7),2)+(s+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let s=this.valueHexView,o=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)o[i]=s[i]|128;return o[this.blockLength-1]=s[this.blockLength-1],o.buffer}let t=Ut(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",je;let n=new Uint8Array(t.byteLength);if(!e){let s=new Uint8Array(t),o=t.byteLength-1;for(let i=0;i<o;i++)n[i]=s[i]|128;n[o]=s[o]}return n}toString(){let e="";if(this.isHexOnly)e=M.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Gr.NAME="sidBlock";var zn=class extends Be{constructor({value:e=Br,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let s=t;for(;n>0;){let o=new Gr;if(s=o.fromBER(e,s,n),s===-1)return this.blockLength=0,this.error=o.error,s;this.value.length===0&&(o.isFirstSid=!0),this.blockLength+=o.blockLength,n-=o.blockLength,this.value.push(o)}return s}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let s=this.value[n].toBER(e);if(s.byteLength===0)return this.error=this.value[n].error,je;t.push(s)}return Yo(t)}fromString(e){this.value=[];let t=0,n=0,s="",o=!1;do if(n=e.indexOf(".",t),n===-1?s=e.substring(t):s=e.substring(t,n),t=n+1,o){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(s,10);if(isNaN(c))return;i.valueDec=c+a,o=!1}else{let i=new Gr;if(s>Number.MAX_SAFE_INTEGER){Ln();let a=BigInt(s);i.valueBigInt=a}else if(i.valueDec=parseInt(s,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,o=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let s=this.value[n].toString();n!==0&&(e=`${e}.`),t?(s=`{${s}}`,this.value[n].isFirstSid?e=`2.{${s} - 80}`:e+=s):e+=s}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};zn.NAME="ObjectIdentifierValueBlock";var pc,ze=class extends be{constructor(e={}){super(e,zn),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};pc=ze;I.ObjectIdentifier=pc;ze.NAME="OBJECT IDENTIFIER";var zr=class extends vt(yt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let s=M.BufferSourceConverter.toUint8Array(e);if(!xt(this,s,t,n))return-1;let o=s.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=o[a]&127,this.blockLength++,!!(o[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,o[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=Xt(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let s=this.valueHexView,o=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)o[i]=s[i]|128;return o[this.blockLength-1]=s[this.blockLength-1],o.buffer}let t=Ut(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",je;let n=new Uint8Array(t.byteLength);if(!e){let s=new Uint8Array(t),o=t.byteLength-1;for(let i=0;i<o;i++)n[i]=s[i]|128;n[o]=s[o]}return n.buffer}toString(){let e="";return this.isHexOnly?e=M.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};zr.NAME="relativeSidBlock";var jn=class extends Be{constructor({value:e=Br,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let s=t;for(;n>0;){let o=new zr;if(s=o.fromBER(e,s,n),s===-1)return this.blockLength=0,this.error=o.error,s;this.blockLength+=o.blockLength,n-=o.blockLength,this.value.push(o)}return s}toBER(e,t){let n=[];for(let s=0;s<this.value.length;s++){let o=this.value[s].toBER(e);if(o.byteLength===0)return this.error=this.value[s].error,je;n.push(o)}return Yo(n)}fromString(e){this.value=[];let t=0,n=0,s="";do{n=e.indexOf(".",t),n===-1?s=e.substring(t):s=e.substring(t,n),t=n+1;let o=new zr;if(o.valueDec=parseInt(s,10),isNaN(o.valueDec))return!0;this.value.push(o)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let s=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(s=`{${s}}`),e+=s}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};jn.NAME="RelativeObjectIdentifierValueBlock";var gc,Wn=class extends be{constructor(e={}){super(e,jn),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};gc=Wn;I.RelativeObjectIdentifier=gc;Wn.NAME="RelativeObjectIdentifier";var mc,pe=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};mc=pe;I.Sequence=mc;pe.NAME="SEQUENCE";var yc,Yn=class extends Pt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};yc=Yn;I.Set=yc;Yn.NAME="SET";var Zn=class extends vt(Be){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Br}toJSON(){return{...super.toJSON(),value:this.value}}};Zn.NAME="StringValueBlock";var Jn=class extends Zn{};Jn.NAME="SimpleStringValueBlock";var Se=class extends On{constructor({...e}={}){super(e,Jn)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,M.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);this.valueBlock.value=e}};Se.NAME="SIMPLE STRING";var Xn=class extends Se{fromBuffer(e){this.valueBlock.valueHexView=M.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=M.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=M.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(M.Convert.FromUtf8String(e)),this.valueBlock.value=e}};Xn.NAME="Utf8StringValueBlock";var bc,wt=class extends Xn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};bc=wt;I.Utf8String=bc;wt.NAME="UTF8String";var Qn=class extends Se{fromBuffer(e){this.valueBlock.value=M.Convert.ToUtf16String(e),this.valueBlock.valueHexView=M.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(M.Convert.FromUtf16String(e))}};Qn.NAME="BmpStringValueBlock";var wc,es=class extends Qn{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};wc=es;I.BmpString=wc;es.NAME="BMPString";var ts=class extends Se{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);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(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let s=0;s<t;s++){let o=Ut(e.charCodeAt(s),8),i=new Uint8Array(o);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[s*4+c+a]=i[c]}this.valueBlock.value=e}};ts.NAME="UniversalStringValueBlock";var xc,rs=class extends ts{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};xc=rs;I.UniversalString=xc;rs.NAME="UniversalString";var vc,ns=class extends Se{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};vc=ns;I.NumericString=vc;ns.NAME="NumericString";var Ec,ss=class extends Se{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Ec=ss;I.PrintableString=Ec;ss.NAME="PrintableString";var Bc,os=class extends Se{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Bc=os;I.TeletexString=Bc;os.NAME="TeletexString";var Ac,is=class extends Se{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Ac=is;I.VideotexString=Ac;is.NAME="VideotexString";var Ic,as=class extends Se{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Ic=as;I.IA5String=Ic;as.NAME="IA5String";var Sc,cs=class extends Se{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Sc=cs;I.GraphicString=Sc;cs.NAME="GraphicString";var kc,jr=class extends Se{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};kc=jr;I.VisibleString=kc;jr.NAME="VisibleString";var Nc,ls=class extends Se{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Nc=ls;I.GeneralString=Nc;ls.NAME="GeneralString";var Rc,us=class extends Se{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Rc=us;I.CharacterString=Rc;us.NAME="CharacterString";var Tc,Wr=class extends jr{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let s=0;s<e.length;s++)this.valueBlock.valueHexView[s]=e.charCodeAt(s)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,M.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let 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(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=Ne(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=Ne(this.month,2),t[2]=Ne(this.day,2),t[3]=Ne(this.hour,2),t[4]=Ne(this.minute,2),t[5]=Ne(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};Tc=Wr;I.UTCTime=Tc;Wr.NAME="UTCTime";var _c,fs=class extends Wr{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",s="",o=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let l=new Number(e[e.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let l=1,d=n.indexOf("+"),b="";if(d===-1&&(d=n.indexOf("-"),l=-1),d!==-1){if(b=n.substring(d+1),n=n.substring(0,d),b.length!==2&&b.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(b.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*p,b.length===4){if(p=parseInt(b.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=l*p}}}let f=n.indexOf(".");if(f===-1&&(f=n.indexOf(",")),f!==-1){let l=new Number(`0${n.substring(f)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");o=l.valueOf(),s=n.substring(0,f)}else s=n;switch(!0){case s.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,f!==-1)throw new Error("Wrong input string for conversion");break;case s.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,f!==-1){let l=60*o;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case s.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,f!==-1){let l=60*o;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case s.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,f!==-1){let l=1e3*o;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let u=i.exec(s);if(u===null)throw new Error("Wrong input string for conversion");for(let l=1;l<u.length;l++)switch(l){case 1:this.year=parseInt(u[l],10);break;case 2:this.month=parseInt(u[l],10);break;case 3:this.day=parseInt(u[l],10);break;case 4:this.hour=parseInt(u[l],10)+a;break;case 5:this.minute=parseInt(u[l],10)+c;break;case 6:this.second=parseInt(u[l],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(Ne(this.year,4)),t.push(Ne(this.month,2)),t.push(Ne(this.day,2)),t.push(Ne(this.hour,2)),t.push(Ne(this.minute,2)),t.push(Ne(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(Ne(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};_c=fs;I.GeneralizedTime=_c;fs.NAME="GeneralizedTime";var Cc,hs=class extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Cc=hs;I.DATE=Cc;hs.NAME="DATE";var Lc,ds=class extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Lc=ds;I.TimeOfDay=Lc;ds.NAME="TimeOfDay";var Uc,ps=class extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Uc=ps;I.DateTime=Uc;ps.NAME="DateTime";var Pc,gs=class extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Pc=gs;I.Duration=Pc;gs.NAME="Duration";var Oc,ms=class extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Oc=ms;I.TIME=Oc;ms.NAME="TIME";function rd(r){let{result:e}=Ar(r),t=e.valueBlock.value;return{n:K(tt(t[1].toBigInt()),"base64url"),e:K(tt(t[2].toBigInt()),"base64url"),d:K(tt(t[3].toBigInt()),"base64url"),p:K(tt(t[4].toBigInt()),"base64url"),q:K(tt(t[5].toBigInt()),"base64url"),dp:K(tt(t[6].toBigInt()),"base64url"),dq:K(tt(t[7].toBigInt()),"base64url"),qi:K(tt(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function nd(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 C("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new pe({value:[new ce({value:0}),ce.fromBigInt(rt(F(r.n,"base64url"))),ce.fromBigInt(rt(F(r.e,"base64url"))),ce.fromBigInt(rt(F(r.d,"base64url"))),ce.fromBigInt(rt(F(r.p,"base64url"))),ce.fromBigInt(rt(F(r.q,"base64url"))),ce.fromBigInt(rt(F(r.dp,"base64url"))),ce.fromBigInt(rt(F(r.dq,"base64url"))),ce.fromBigInt(rt(F(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function sd(r){let{result:e}=Ar(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:K(tt(t[0].toBigInt()),"base64url"),e:K(tt(t[1].toBigInt()),"base64url")}}function od(r){if(r.n==null||r.e==null)throw new C("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new pe({value:[new pe({value:[new ze({value:"1.2.840.113549.1.1.1"}),new Ot]}),new Er({valueHex:new pe({value:[ce.fromBigInt(rt(F(r.n,"base64url"))),ce.fromBigInt(rt(F(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function tt(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),s=0,o=0;for(;s<t;)n[s]=parseInt(e.slice(o,o+2),16),s+=1,o+=2;return n}function rt(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}var id=16,Jo=32,Xo=1e4;async function ad(r,e){let t=Ie.get(),s=new pe({value:[new ce({value:0}),new pe({value:[new ze({value:"1.2.840.113549.1.1.1"}),new Ot]}),new bt({valueHex:r.marshal()})]}).toBER(),o=new Uint8Array(s,0,s.byteLength),i=Jt(id),a=await zo(gr,e,i,{c:Xo,dkLen:Jo}),c=Jt(16),f=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),u=await t.subtle.encrypt({name:"AES-CBC",iv:c},f,o),l=new pe({value:[new bt({valueHex:i}),new ce({value:Xo}),new ce({value:Jo}),new pe({value:[new ze({value:"1.2.840.113549.2.11"}),new Ot]})]}),d=new pe({value:[new ze({value:"1.2.840.113549.1.5.13"}),new pe({value:[new pe({value:[new ze({value:"1.2.840.113549.1.5.12"}),l]}),new pe({value:[new ze({value:"2.16.840.1.101.3.4.1.42"}),new bt({valueHex:c})]})]})]}),p=new pe({value:[d,new bt({valueHex:u})]}).toBER(),h=new Uint8Array(p,0,p.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...K(h,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
|
|
7
|
-
`)}async function cd(r,e){let t=Ie.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let s=F(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:o}=Ar(s),{iv:i,salt:a,iterations:c,keySize:f,cipherText:u}=ld(o),l=await zo(gr,e,a,{c,dkLen:f}),d=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),b=Yr(await t.subtle.decrypt({name:"AES-CBC",iv:i},d,u)),{result:p}=Ar(b);n=Vc(p)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let s=F(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:o}=Ar(s);n=Vc(o)}else throw new C("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return Qo(n)}function ld(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new C("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new C("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let o=n.valueBlock.value[1],i=Yr(o.valueBlock.value[0].getValue()),a=Xo,c=Jo;if(o.valueBlock.value.length===3)a=Number(o.valueBlock.value[1].toBigInt()),c=Number(o.valueBlock.value[2].toBigInt());else if(o.valueBlock.value.length===2)throw new C("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let f=e.valueBlock.value[1].valueBlock.value[1],u=f.valueBlock.value[0].toString();if(u!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(u!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new C("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let l=Yr(f.valueBlock.value[1].getValue());return{cipherText:Yr(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function Vc(r){return Yr(r.valueBlock.value[2].getValue())}function Yr(r){return new Uint8Array(r,0,r.byteLength)}async function Dc(r){let e=await Ie.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await Fc(e);return{privateKey:t[0],publicKey:t[1]}}async function ei(r){let t=[await Ie.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await ud(r)],n=await Fc({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function Mc(r,e){let t=await Ie.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ie.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Hc(r,e,t){let n=await Ie.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ie.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function Fc(r){if(r.privateKey==null||r.publicKey==null)throw new C("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Ie.get().subtle.exportKey("jwk",r.privateKey),Ie.get().subtle.exportKey("jwk",r.publicKey)])}async function ud(r){return Ie.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function bs(r){if(r.kty!=="RSA")throw new C("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new C("invalid key modulus","ERR_INVALID_KEY_MODULUS");return F(r.n,"base64url").length*8}var Jr=8192,Zr=class{_key;constructor(e){this._key=e}verify(e,t){return Hc(this._key,t,e)}marshal(){return Vt.jwkToPkix(this._key)}get bytes(){return Xe.encode({Type:X.RSA,Data:this.marshal()}).subarray()}equals(e){return de(this.bytes,e.bytes)}hash(){let e=ye.digest(this.bytes);return Ce(e)?e.then(({bytes:t})=>t):e.bytes}},Ir=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return Jt(16)}sign(e){return Mc(this._key,e)}get public(){if(this._publicKey==null)throw new C("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Zr(this._publicKey)}marshal(){return Vt.jwkToPkcs1(this._key)}get bytes(){return Qe.encode({Type:X.RSA,Data:this.marshal()}).subarray()}equals(e){return de(this.bytes,e.bytes)}hash(){let e=ye.digest(this.bytes);return Ce(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return K(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return Vt.exportToPem(this,e);if(t==="libp2p-key")return br(this.bytes,e);throw new C(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function Qo(r){let e=Vt.pkcs1ToJwk(r);if(bs(e)>Jr)throw new C("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await ei(e);return new Ir(t.privateKey,t.publicKey)}function hd(r){let e=Vt.pkixToJwk(r);if(bs(e)>Jr)throw new C("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Zr(e)}async function dd(r){if(bs(r)>Jr)throw new C("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await ei(r);return new Ir(e.privateKey,e.publicKey)}async function pd(r){if(r>Jr)throw new C("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Dc(r);return new Ir(e.privateKey,e.publicKey)}var ii={};he(ii,{Secp256k1PrivateKey:()=>Qr,Secp256k1PublicKey:()=>Xr,generateKeyPair:()=>Rd,unmarshalSecp256k1PrivateKey:()=>kd,unmarshalSecp256k1PublicKey:()=>Nd});var gd=(r,e,t)=>r&e^~r&t,md=(r,e,t)=>r&e^r&t^e&t,yd=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]),Dt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Mt=new Uint32Array(64),ri=class extends pr{constructor(){super(64,32,8,!1),this.A=Dt[0]|0,this.B=Dt[1]|0,this.C=Dt[2]|0,this.D=Dt[3]|0,this.E=Dt[4]|0,this.F=Dt[5]|0,this.G=Dt[6]|0,this.H=Dt[7]|0}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let l=0;l<16;l++,t+=4)Mt[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let d=Mt[l-15],b=Mt[l-2],p=Me(d,7)^Me(d,18)^d>>>3,h=Me(b,17)^Me(b,19)^b>>>10;Mt[l]=h+Mt[l-7]+p+Mt[l-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:f,H:u}=this;for(let l=0;l<64;l++){let d=Me(a,6)^Me(a,11)^Me(a,25),b=u+d+gd(a,c,f)+yd[l]+Mt[l]|0,h=(Me(n,2)^Me(n,13)^Me(n,22))+md(n,s,o)|0;u=f,f=c,c=a,a=i+b|0,i=o,o=s,s=n,n=b+h|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(n,s,o,i,a,c,f,u)}roundClean(){Mt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Kc=pn(()=>new ri);function bd(r){let e=Or(r);Je(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:s}=e;if(t){if(!n.eql(s,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:wd,hexToBytes:xd}=yn,Qt={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=Qt;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:wd(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Qt,t=typeof r=="string"?xd(r):r;if(!He(t))throw new Error("ui8a expected");let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:s,l:o}=Qt._parseInt(t.subarray(2)),{d:i,l:a}=Qt._parseInt(o);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:s,s:i}},hexFromSig(r){let e=f=>Number.parseInt(f[0],16)&8?"00"+f:f,t=f=>{let u=f.toString(16);return u.length&1?`0${u}`:u},n=e(t(r.s)),s=e(t(r.r)),o=n.length/2,i=s.length/2,a=t(o),c=t(i);return`30${t(i+o+4)}02${c}${s}02${a}${n}`}},Et=BigInt(0),Pe=BigInt(1),Vm=BigInt(2),qc=BigInt(3),Dm=BigInt(4);function vd(r){let e=bd(r),{Fp:t}=e,n=e.toBytes||((p,h,m)=>{let y=h.toAffine();return ht(Uint8Array.from([4]),t.toBytes(y.x),t.toBytes(y.y))}),s=e.fromBytes||(p=>{let h=p.subarray(1),m=t.fromBytes(h.subarray(0,t.BYTES)),y=t.fromBytes(h.subarray(t.BYTES,2*t.BYTES));return{x:m,y}});function o(p){let{a:h,b:m}=e,y=t.sqr(p),B=t.mul(y,p);return t.add(t.add(B,t.mul(p,h)),m)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function i(p){return typeof p=="bigint"&&Et<p&&p<e.n}function a(p){if(!i(p))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(p){let{allowedPrivateKeyLengths:h,nByteLength:m,wrapPrivateKey:y,n:B}=e;if(h&&typeof p!="bigint"){if(He(p)&&(p=ut(p)),typeof p!="string"||!h.includes(p.length))throw new Error("Invalid key");p=p.padStart(m*2,"0")}let w;try{w=typeof p=="bigint"?p:ft(te("private key",p,m))}catch{throw new Error(`private key must be ${m} bytes, hex or bigint, not ${typeof p}`)}return y&&(w=Y(w,B)),a(w),w}let f=new Map;function u(p){if(!(p instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(h,m,y){if(this.px=h,this.py=m,this.pz=y,h==null||!t.isValid(h))throw new Error("x required");if(m==null||!t.isValid(m))throw new Error("y required");if(y==null||!t.isValid(y))throw new Error("z required")}static fromAffine(h){let{x:m,y}=h||{};if(!h||!t.isValid(m)||!t.isValid(y))throw new Error("invalid affine point");if(h instanceof l)throw new Error("projective point not allowed");let B=w=>t.eql(w,t.ZERO);return B(m)&&B(y)?l.ZERO:new l(m,y,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let m=t.invertBatch(h.map(y=>y.pz));return h.map((y,B)=>y.toAffine(m[B])).map(l.fromAffine)}static fromHex(h){let m=l.fromAffine(s(te("pointHex",h)));return m.assertValidity(),m}static fromPrivateKey(h){return l.BASE.multiply(c(h))}_setWindowSize(h){this._WINDOW_SIZE=h,f.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:h,y:m}=this.toAffine();if(!t.isValid(h)||!t.isValid(m))throw new Error("bad point: x or y not FE");let y=t.sqr(m),B=o(h);if(!t.eql(y,B))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:h}=this.toAffine();if(t.isOdd)return!t.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){u(h);let{px:m,py:y,pz:B}=this,{px:w,py:T,pz:x}=h,A=t.eql(t.mul(m,x),t.mul(w,B)),N=t.eql(t.mul(y,x),t.mul(T,B));return A&&N}negate(){return new l(this.px,t.neg(this.py),this.pz)}double(){let{a:h,b:m}=e,y=t.mul(m,qc),{px:B,py:w,pz:T}=this,x=t.ZERO,A=t.ZERO,N=t.ZERO,R=t.mul(B,B),G=t.mul(w,w),q=t.mul(T,T),P=t.mul(B,w);return P=t.add(P,P),N=t.mul(B,T),N=t.add(N,N),x=t.mul(h,N),A=t.mul(y,q),A=t.add(x,A),x=t.sub(G,A),A=t.add(G,A),A=t.mul(x,A),x=t.mul(P,x),N=t.mul(y,N),q=t.mul(h,q),P=t.sub(R,q),P=t.mul(h,P),P=t.add(P,N),N=t.add(R,R),R=t.add(N,R),R=t.add(R,q),R=t.mul(R,P),A=t.add(A,R),q=t.mul(w,T),q=t.add(q,q),R=t.mul(q,P),x=t.sub(x,R),N=t.mul(q,G),N=t.add(N,N),N=t.add(N,N),new l(x,A,N)}add(h){u(h);let{px:m,py:y,pz:B}=this,{px:w,py:T,pz:x}=h,A=t.ZERO,N=t.ZERO,R=t.ZERO,G=e.a,q=t.mul(e.b,qc),P=t.mul(m,w),ie=t.mul(y,T),re=t.mul(B,x),_e=t.add(m,y),v=t.add(w,T);_e=t.mul(_e,v),v=t.add(P,ie),_e=t.sub(_e,v),v=t.add(m,B);let k=t.add(w,x);return v=t.mul(v,k),k=t.add(P,re),v=t.sub(v,k),k=t.add(y,B),A=t.add(T,x),k=t.mul(k,A),A=t.add(ie,re),k=t.sub(k,A),R=t.mul(G,v),A=t.mul(q,re),R=t.add(A,R),A=t.sub(ie,R),R=t.add(ie,R),N=t.mul(A,R),ie=t.add(P,P),ie=t.add(ie,P),re=t.mul(G,re),v=t.mul(q,v),ie=t.add(ie,re),re=t.sub(P,re),re=t.mul(G,re),v=t.add(v,re),P=t.mul(ie,v),N=t.add(N,P),P=t.mul(k,v),A=t.mul(_e,A),A=t.sub(A,P),P=t.mul(_e,ie),R=t.mul(k,R),R=t.add(R,P),new l(A,N,R)}subtract(h){return this.add(h.negate())}is0(){return this.equals(l.ZERO)}wNAF(h){return b.wNAFCached(this,f,h,m=>{let y=t.invertBatch(m.map(B=>B.pz));return m.map((B,w)=>B.toAffine(y[w])).map(l.fromAffine)})}multiplyUnsafe(h){let m=l.ZERO;if(h===Et)return m;if(a(h),h===Pe)return this;let{endo:y}=e;if(!y)return b.unsafeLadder(this,h);let{k1neg:B,k1:w,k2neg:T,k2:x}=y.splitScalar(h),A=m,N=m,R=this;for(;w>Et||x>Et;)w&Pe&&(A=A.add(R)),x&Pe&&(N=N.add(R)),R=R.double(),w>>=Pe,x>>=Pe;return B&&(A=A.negate()),T&&(N=N.negate()),N=new l(t.mul(N.px,y.beta),N.py,N.pz),A.add(N)}multiply(h){a(h);let m=h,y,B,{endo:w}=e;if(w){let{k1neg:T,k1:x,k2neg:A,k2:N}=w.splitScalar(m),{p:R,f:G}=this.wNAF(x),{p:q,f:P}=this.wNAF(N);R=b.constTimeNegate(T,R),q=b.constTimeNegate(A,q),q=new l(t.mul(q.px,w.beta),q.py,q.pz),y=R.add(q),B=G.add(P)}else{let{p:T,f:x}=this.wNAF(m);y=T,B=x}return l.normalizeZ([y,B])[0]}multiplyAndAddUnsafe(h,m,y){let B=l.BASE,w=(x,A)=>A===Et||A===Pe||!x.equals(B)?x.multiplyUnsafe(A):x.multiply(A),T=w(this,m).add(w(h,y));return T.is0()?void 0:T}toAffine(h){let{px:m,py:y,pz:B}=this,w=this.is0();h==null&&(h=w?t.ONE:t.inv(B));let T=t.mul(m,h),x=t.mul(y,h),A=t.mul(B,h);if(w)return{x:t.ZERO,y:t.ZERO};if(!t.eql(A,t.ONE))throw new Error("invZ was invalid");return{x:T,y:x}}isTorsionFree(){let{h,isTorsionFree:m}=e;if(h===Pe)return!0;if(m)return m(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:m}=e;return h===Pe?this:m?m(l,this):this.multiplyUnsafe(e.h)}toRawBytes(h=!0){return this.assertValidity(),n(l,this,h)}toHex(h=!0){return ut(this.toRawBytes(h))}}l.BASE=new l(e.Gx,e.Gy,t.ONE),l.ZERO=new l(t.ZERO,t.ONE,t.ZERO);let d=e.nBitLength,b=xn(l,e.endo?Math.ceil(d/2):d);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:i}}function Ed(r){let e=Or(r);return Je(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function $c(r){let e=Ed(r),{Fp:t,n}=e,s=t.BYTES+1,o=2*t.BYTES+1;function i(v){return Et<v&&v<t.ORDER}function a(v){return Y(v,n)}function c(v){return bn(v,n)}let{ProjectivePoint:f,normPrivateKeyToScalar:u,weierstrassEquation:l,isWithinCurveOrder:d}=vd({...e,toBytes(v,k,O){let E=k.toAffine(),g=t.toBytes(E.x),S=ht;return O?S(Uint8Array.from([k.hasEvenY()?2:3]),g):S(Uint8Array.from([4]),g,t.toBytes(E.y))},fromBytes(v){let k=v.length,O=v[0],E=v.subarray(1);if(k===s&&(O===2||O===3)){let g=ft(E);if(!i(g))throw new Error("Point is not on curve");let S=l(g),_=t.sqrt(S),L=(_&Pe)===Pe;return(O&1)===1!==L&&(_=t.neg(_)),{x:g,y:_}}else if(k===o&&O===4){let g=t.fromBytes(E.subarray(0,t.BYTES)),S=t.fromBytes(E.subarray(t.BYTES,2*t.BYTES));return{x:g,y:S}}else throw new Error(`Point of length ${k} was invalid. Expected ${s} compressed bytes or ${o} uncompressed bytes`)}}),b=v=>ut(Ct(v,e.nByteLength));function p(v){let k=n>>Pe;return v>k}function h(v){return p(v)?a(-v):v}let m=(v,k,O)=>ft(v.slice(k,O));class y{constructor(k,O,E){this.r=k,this.s=O,this.recovery=E,this.assertValidity()}static fromCompact(k){let O=e.nByteLength;return k=te("compactSignature",k,O*2),new y(m(k,0,O),m(k,O,2*O))}static fromDER(k){let{r:O,s:E}=Qt.toSig(te("DER",k));return new y(O,E)}assertValidity(){if(!d(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!d(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(k){return new y(this.r,this.s,k)}recoverPublicKey(k){let{r:O,s:E,recovery:g}=this,S=N(te("msgHash",k));if(g==null||![0,1,2,3].includes(g))throw new Error("recovery id invalid");let _=g===2||g===3?O+e.n:O;if(_>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let L=g&1?"03":"02",V=f.fromHex(L+b(_)),D=c(_),W=a(-S*D),H=a(E*D),$=f.BASE.multiplyAndAddUnsafe(V,W,H);if(!$)throw new Error("point at infinify");return $.assertValidity(),$}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return Gt(this.toDERHex())}toDERHex(){return Qt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Gt(this.toCompactHex())}toCompactHex(){return b(this.r)+b(this.s)}}let B={isValidPrivateKey(v){try{return u(v),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let v=xo(e.n);return Ta(e.randomBytes(v),e.n)},precompute(v=8,k=f.BASE){return k._setWindowSize(v),k.multiply(BigInt(3)),k}};function w(v,k=!0){return f.fromPrivateKey(v).toRawBytes(k)}function T(v){let k=He(v),O=typeof v=="string",E=(k||O)&&v.length;return k?E===s||E===o:O?E===2*s||E===2*o:v instanceof f}function x(v,k,O=!0){if(T(v))throw new Error("first arg must be private key");if(!T(k))throw new Error("second arg must be public key");return f.fromHex(k).multiply(u(v)).toRawBytes(O)}let A=e.bits2int||function(v){let k=ft(v),O=v.length*8-e.nBitLength;return O>0?k>>BigInt(O):k},N=e.bits2int_modN||function(v){return a(A(v))},R=Pr(e.nBitLength);function G(v){if(typeof v!="bigint")throw new Error("bigint expected");if(!(Et<=v&&v<R))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Ct(v,e.nByteLength)}function q(v,k,O=P){if(["recovered","canonical"].some(Q=>Q in O))throw new Error("sign() legacy options not supported");let{hash:E,randomBytes:g}=e,{lowS:S,prehash:_,extraEntropy:L}=O;S==null&&(S=!0),v=te("msgHash",v),_&&(v=te("prehashed msgHash",E(v)));let V=N(v),D=u(k),W=[G(D),G(V)];if(L!=null){let Q=L===!0?g(t.BYTES):L;W.push(te("extraEntropy",Q))}let H=ht(...W),$=V;function ae(Q){let ge=A(Q);if(!d(ge))return;let me=c(ge),le=f.BASE.multiply(ge).toAffine(),we=a(le.x);if(we===Et)return;let ot=a(me*a($+we*D));if(ot===Et)return;let Kt=(le.x===we?0:2)|Number(le.y&Pe),Rr=ot;return S&&p(ot)&&(Rr=h(ot),Kt^=1),new y(we,Rr,Kt)}return{seed:H,k2sig:ae}}let P={lowS:e.lowS,prehash:!1},ie={lowS:e.lowS,prehash:!1};function re(v,k,O=P){let{seed:E,k2sig:g}=q(v,k,O),S=e;return mo(S.hash.outputLen,S.nByteLength,S.hmac)(E,g)}f.BASE._setWindowSize(8);function _e(v,k,O,E=ie){let g=v;if(k=te("msgHash",k),O=te("publicKey",O),"strict"in E)throw new Error("options.strict was renamed to lowS");let{lowS:S,prehash:_}=E,L,V;try{if(typeof g=="string"||He(g))try{L=y.fromDER(g)}catch(le){if(!(le instanceof Qt.Err))throw le;L=y.fromCompact(g)}else if(typeof g=="object"&&typeof g.r=="bigint"&&typeof g.s=="bigint"){let{r:le,s:we}=g;L=new y(le,we)}else throw new Error("PARSE");V=f.fromHex(O)}catch(le){if(le.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(S&&L.hasHighS())return!1;_&&(k=e.hash(k));let{r:D,s:W}=L,H=N(k),$=c(W),ae=a(H*$),Q=a(D*$),ge=f.BASE.multiplyAndAddUnsafe(V,ae,Q)?.toAffine();return ge?a(ge.x)===D:!1}return{CURVE:e,getPublicKey:w,getSharedSecret:x,sign:re,verify:_e,ProjectivePoint:f,Signature:y,utils:B}}function Bd(r){return{hash:r,hmac:(e,...t)=>Hr(r,e,dn(...t)),randomBytes:dr}}function Gc(r,e){let t=n=>$c({...r,...Bd(n)});return Object.freeze({...t(e),create:t})}var Wc=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),zc=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ad=BigInt(1),ni=BigInt(2),jc=(r,e)=>(r+e/ni)/e;function Id(r){let e=Wc,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=r*r*r%e,u=f*f*r%e,l=J(u,t,e)*u%e,d=J(l,t,e)*u%e,b=J(d,ni,e)*f%e,p=J(b,s,e)*b%e,h=J(p,o,e)*p%e,m=J(h,a,e)*h%e,y=J(m,c,e)*m%e,B=J(y,a,e)*h%e,w=J(B,t,e)*u%e,T=J(w,i,e)*p%e,x=J(T,n,e)*f%e,A=J(x,ni,e);if(!si.eql(si.sqr(A),r))throw new Error("Cannot find square root");return A}var si=wn(Wc,void 0,void 0,{sqrt:Id}),We=Gc({a:BigInt(0),b:BigInt(7),Fp:si,n:zc,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=zc,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Ad*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=t,i=BigInt("0x100000000000000000000000000000000"),a=jc(o*r,e),c=jc(-n*r,e),f=Y(r-a*t-c*s,e),u=Y(-a*n-c*o,e),l=f>i,d=u>i;if(l&&(f=e-f),d&&(u=e-u),f>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:f,k2neg:d,k2:u}}}},Kc),jm=BigInt(0);var Wm=We.ProjectivePoint;function Yc(){return We.utils.randomPrivateKey()}function Zc(r,e){let t=ye.digest(e instanceof Uint8Array?e:e.subarray());if(Ce(t))return t.then(({digest:n})=>We.sign(n,r).toDERRawBytes()).catch(n=>{throw new C(String(n),"ERR_INVALID_INPUT")});try{return We.sign(t.digest,r).toDERRawBytes()}catch(n){throw new C(String(n),"ERR_INVALID_INPUT")}}function Jc(r,e,t){let n=ye.digest(t instanceof Uint8Array?t:t.subarray());if(Ce(n))return n.then(({digest:s})=>We.verify(e,s,r)).catch(s=>{throw new C(String(s),"ERR_INVALID_INPUT")});try{return We.verify(e,n.digest,r)}catch(s){throw new C(String(s),"ERR_INVALID_INPUT")}}function Xc(r){return We.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Qc(r){try{We.getPublicKey(r,!0)}catch(e){throw new C(String(e),"ERR_INVALID_PRIVATE_KEY")}}function oi(r){try{We.ProjectivePoint.fromHex(r)}catch(e){throw new C(String(e),"ERR_INVALID_PUBLIC_KEY")}}function el(r){try{return We.getPublicKey(r,!0)}catch(e){throw new C(String(e),"ERR_INVALID_PRIVATE_KEY")}}var Xr=class{_key;constructor(e){oi(e),this._key=e}verify(e,t){return Jc(this._key,t,e)}marshal(){return Xc(this._key)}get bytes(){return Xe.encode({Type:X.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return de(this.bytes,e.bytes)}async hash(){let e=ye.digest(this.bytes),t;return Ce(e)?{bytes:t}=await e:t=e.bytes,t}},Qr=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??el(e),Qc(this._key),oi(this._publicKey)}sign(e){return Zc(this._key,e)}get public(){return new Xr(this._publicKey)}marshal(){return this._key}get bytes(){return Qe.encode({Type:X.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return de(this.bytes,e.bytes)}hash(){let e=ye.digest(this.bytes);return Ce(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return K(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return br(this.bytes,e);throw new C(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function kd(r){return new Qr(r)}function Nd(r){return new Xr(r)}async function Rd(){let r=Yc();return new Qr(r)}var er={rsa:ti,ed25519:Go,secp256k1:ii};function tl(r){let e=Object.keys(er).join(" / ");return new C(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function rl(r){let e=Xe.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case X.RSA:return er.rsa.unmarshalRsaPublicKey(t);case X.Ed25519:return er.ed25519.unmarshalEd25519PublicKey(t);case X.Secp256k1:return er.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw tl(e.Type??"unknown")}}async function nl(r){let e=Qe.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case X.RSA:return er.rsa.unmarshalRsaPrivateKey(t);case X.Ed25519:return er.ed25519.unmarshalEd25519PrivateKey(t);case X.Secp256k1:return er.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw tl(e.Type??"RSA")}}var ol=Symbol.for("@achingbrain/uint8arraylist");function sl(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function ws(r){return!!r?.[ol]}var Ye=class r{bufs;length;[ol]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(ws(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(ws(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=sl(this.bufs,e);return t.buf[t.index]}set(e,t){let n=sl(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(ws(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return Ae(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Ae(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=[...n],o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let f=e>=a&&e<c,u=t>a&&t<=c;if(f&&u){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(f){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!ws(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let l=0;l<o;l++)i[l]=-1;for(let l=0;l<s;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let l=t;l<=c;l+=u){u=0;for(let d=f;d>=0;d--){let b=this.get(l+d);if(n[d]!==b){u=Math.max(1,d-a[b]);break}}if(u===0)return l}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=ke(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=ct(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=ct(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=ct(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=ke(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=ct(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=ct(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=ct(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=ct(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=ct(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!de(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}};var il={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var en;(function(r){let e;r.codec=()=>(e==null&&(e=Ge((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},o=n==null?t.len:t.pos+n;for(;t.pos<o;){let i=t.uint32();switch(i>>>3){case 1:s.publicKey=t.bytes();break;case 2:s.payloadType=t.bytes();break;case 3:s.payload=t.bytes();break;case 5:s.signature=t.bytes();break;default:t.skipType(i&7);break}}return s})),e),r.encode=t=>$e(t,r.codec()),r.decode=t=>qe(t,r.codec())})(en||(en={}));var Ht=class r{static createFromProtobuf=async e=>{let t=en.decode(e),n=await Ur(t.publicKey);return new r({peerId:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t.privateKey==null)throw new Error("Missing private key");let n=e.domain,s=e.codec,o=e.marshal(),i=al(n,s,o),c=await(await nl(t.privateKey)).sign(i.subarray());return new r({peerId:t,payloadType:s,payload:o,signature:c})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new C("envelope signature is not valid for the given domain",il.ERR_SIGNATURE_NOT_VALID);return n};peerId;payloadType;payload;signature;marshaled;constructor(e){let{peerId:t,payloadType:n,payload:s,signature:o}=e;this.peerId=t,this.payloadType=n,this.payload=s,this.signature=o}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=en.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return de(this.marshal(),e.marshal())}async validate(e){let t=al(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return rl(this.peerId.publicKey).verify(t.subarray(),this.signature)}},al=(r,e,t)=>{let n=F(r),s=Le(n.byteLength),o=Le(e.length),i=Le(t.length);return new Ye(s,n,o,e,i,t)};function cl(r,e){let t=(n,s)=>n.toString().localeCompare(s.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,s)=>e[s].equals(n)))}var xs=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(o*=e,o+=u,o>f||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var ll=45,Td=15,Sr=new xs;function ai(r){if(!(r.length>Td))return Sr.new(r).parseWith(()=>Sr.readIPv4Addr())}function ci(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>ll))return Sr.new(r).parseWith(()=>Sr.readIPv6Addr())}function vs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>ll))return Sr.new(r).parseWith(()=>Sr.readIPAddr())}var Uy=parseInt("0xFFFF",16),Py=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Es(r){return!!ai(r)}function Bs(r){return!!ci(r)}function As(r){return!!vs(r)}var hl=Es,Pd=Bs,li=function(r){let e=0;if(r=r.toString().trim(),hl(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(Pd(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=hl(t[n]),i;o&&(i=li(t[n]),t[n]=K(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,K(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){let o=parseInt(t[n],16);s[e++]=o>>8&255,s[e++]=o&255}return s}throw new Error("invalid ip address")},dl=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let s=[];for(let o=0;o<t;o++)s.push(r[e+o]);return s.join(".")}if(t===16){let s=[];for(let o=0;o<t;o+=2)s.push(n.getUint16(e+o).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var kr={},ui={},Vd=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,-1,"memory"]];Vd.forEach(r=>{let e=Dd(...r);ui[e.code]=e,kr[e.name]=e});function Dd(r,e,t,n,s){return{code:r,size:e,name:t,resolvable:!!n,path:!!s}}function j(r){if(typeof r=="number"){if(ui[r]!=null)return ui[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(kr[r]!=null)return kr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var bb=j("ip4"),wb=j("ip6"),xb=j("ipcidr");function hi(r,e){switch(j(r).code){case 4:case 41:return Hd(e);case 42:return ml(e);case 6:case 273:case 33:case 132:return bl(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ml(e);case 421:return $d(e);case 444:return yl(e);case 445:return yl(e);case 466:return qd(e);default:return K(e,"base16")}}function di(r,e){switch(j(r).code){case 4:return pl(e);case 41:return pl(e);case 42:return gl(e);case 6:case 273:case 33:case 132:return pi(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return gl(e);case 421:return Fd(e);case 444:return Gd(e);case 445:return zd(e);case 466:return Kd(e);default:return F(e,"base16")}}var fi=Object.values(St).map(r=>r.decoder),Md=function(){let r=fi[0].or(fi[1]);return fi.slice(2).forEach(e=>r=r.or(e)),r}();function pl(r){if(!As(r))throw new Error("invalid ip address");return li(r)}function Hd(r){let e=dl(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!As(e))throw new Error("invalid ip address");return e}function pi(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function bl(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function gl(r){let e=F(r),t=Uint8Array.from(Le(e.length));return Ae([t,e],t.length+e.length)}function ml(r){let e=gt(r);if(r=r.slice(ve(e)),r.length!==e)throw new Error("inconsistent lengths");return K(r)}function Fd(r){let e;r[0]==="Q"||r[0]==="1"?e=qt(ne.decode(`z${r}`)).bytes:e=De.parse(r).multihash.bytes;let t=Uint8Array.from(Le(e.length));return Ae([t,e],t.length+e.length)}function Kd(r){let e=Md.decode(r),t=Uint8Array.from(Le(e.length));return Ae([t,e],t.length+e.length)}function qd(r){let e=gt(r),t=r.slice(ve(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+K(t,"base64url")}function $d(r){let e=gt(r),t=r.slice(ve(e));if(t.length!==e)throw new Error("inconsistent lengths");return K(t,"base58btc")}function Gd(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=at.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=pi(n);return Ae([t,s],t.length+s.length)}function zd(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=at.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=pi(n);return Ae([t,s],t.length+s.length)}function yl(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=K(e,"base32"),s=bl(t);return`${n}:${s}`}function wl(r){r=gi(r);let e=[],t=[],n=null,s=r.split("/").slice(1);if(s.length===1&&s[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let o=0;o<s.length;o++){let i=s[o],a=j(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(o++,o>=s.length)throw vl("invalid address: "+r);if(a.path===!0){n=gi(s.slice(o).join("/")),e.push([a.code,di(a.code,n)]),t.push([a.code,n]);break}let c=di(a.code,s[o]);e.push([a.code,c]),t.push([a.code,hi(a.code,c)])}return{string:xl(t),bytes:yi(e),tuples:e,stringTuples:t,path:n}}function mi(r){let e=[],t=[],n=null,s=0;for(;s<r.length;){let o=gt(r,s),i=ve(o),a=j(o),c=jd(a,r.slice(s+i));if(c===0){e.push([o]),t.push([o]),s+=i;continue}let f=r.slice(s+i,s+i+c);if(s+=c+i,s>r.length)throw vl("Invalid address Uint8Array: "+K(r,"base16"));e.push([o,f]);let u=hi(o,f);if(t.push([o,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:xl(t),tuples:e,stringTuples:t,path:n}}function xl(r){let e=[];return r.map(t=>{let n=j(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),gi(e.join("/"))}function yi(r){return Ae(r.map(e=>{let t=j(e[0]),n=Uint8Array.from(Le(t.code));return e.length>1&&e[1]!=null&&(n=Ae([n,e[1]])),n}))}function jd(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=gt(e instanceof Uint8Array?e:Uint8Array.from(e));return t+ve(t)}}function gi(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function vl(r){return new Error("Error parsing address: "+r)}var Wd=Symbol.for("nodejs.util.inspect.custom"),bi=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Yd=[j("dns").code,j("dns4").code,j("dns6").code,j("dnsaddr").code],Is=class r{bytes;#e;#t;#r;#n;[bi]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=mi(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=wl(e)}else if(Bl(e))t=mi(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#r=t.stringTuples,this.#n=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,s,o="",i=j("tcp"),a=j("udp"),c=j("ip4"),f=j("ip6"),u=j("dns6"),l=j("ip6zone");for(let[b,p]of this.stringTuples())b===l.code&&(o=`%${p??""}`),Yd.includes(b)&&(t=i.name,s=443,n=`${p??""}${o}`,e=b===u.code?6:4),(b===i.code||b===a.code)&&(t=j(b).name,s=parseInt(p??"")),(b===c.code||b===f.code)&&(t=j(b).name,n=`${p??""}${o}`,e=b===f.code?6:4);if(e==null||t==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:e,host:n,transport:t,port:s}}protos(){return this.#t.map(([e])=>Object.assign({},j(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>j(e).name)}tuples(){return this.#t}stringTuples(){return this.#r}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,s))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(yi(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,s])=>{n===kr.p2p.code&&e.push([n,s]),n===kr["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?K(ne.decode(`z${n}`),"base58btc"):K(De.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(e){return de(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let n=El.get(t.name);if(n==null)throw new C(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(o=>new r(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[Wd](){return`Multiaddr(${this.#e})`}};var El=new Map;function Bl(r){return!!r?.[bi]}function Ft(r){return new Is(r)}var Al="libp2p-peer-record",Il=Uint8Array.from([3,1]);var tn;(function(r){let e;(function(n){let s;n.codec=()=>(s==null&&(s=Ge((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(o.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(o,i)=>{let a={multiaddr:new Uint8Array(0)},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let f=o.uint32();switch(f>>>3){case 1:a.multiaddr=o.bytes();break;default:o.skipType(f&7);break}}return a})),s),n.encode=o=>$e(o,n.codec()),n.decode=o=>qe(o,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ge((n,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(s.uint32(10),s.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(s.uint32(16),s.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)s.uint32(26),r.AddressInfo.codec().encode(i,s);o.lengthDelimited!==!1&&s.ldelim()},(n,s)=>{let o={peerId:new Uint8Array(0),seq:0n,addresses:[]},i=s==null?n.len:n.pos+s;for(;n.pos<i;){let a=n.uint32();switch(a>>>3){case 1:o.peerId=n.bytes();break;case 2:o.seq=n.uint64();break;case 3:o.addresses.push(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return o})),t),r.encode=n=>$e(n,r.codec()),r.decode=n=>qe(n,r.codec())})(tn||(tn={}));var Bt=class r{static createFromProtobuf=e=>{let t=tn.decode(e),n=ao(t.peerId),s=(t.addresses??[]).map(i=>Ft(i.multiaddr)),o=t.seq;return new r({peerId:n,multiaddrs:s,seqNumber:o})};static DOMAIN=Al;static CODEC=Il;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:s}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=s??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=tn.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!cl(this.multiaddrs,e.multiaddrs))}};var Zd=r=>r.toString().split("/").slice(1),rn=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),se=r=>({match:e=>rn(t=>t===r).match(e),pattern:r}),Ns=()=>({match:r=>rn(e=>typeof e=="string").match(r),pattern:"{string}"}),Sl=()=>({match:r=>rn(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Oe=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ne.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Ss=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Ys.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),nt=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),st=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),oe=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function fe(...r){function e(s){let o=Zd(s);for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matches:t,exactMatch:n}}var xi=oe(se("dns4"),Ns()),vi=oe(se("dns6"),Ns()),Ei=oe(se("dnsaddr"),Ns()),kl=oe(se("dns"),Ns()),aw=fe(xi),cw=fe(vi),lw=fe(Ei),uw=fe(st(kl,Ei,xi,vi)),Nl=oe(se("ip4"),rn(Es)),Rl=oe(se("ip6"),rn(Bs)),Tl=st(Nl,Rl),nn=st(Tl,kl,xi,vi,Ei),_l=fe(nn),fw=fe(Nl),hw=fe(Rl),dw=fe(Tl),Rs=oe(nn,se("tcp"),Sl()),sn=oe(nn,se("udp"),Sl()),Jd=st(Rs,sn),pw=fe(Rs),gw=fe(sn),Bi=oe(sn,se("quic")),Ts=oe(sn,se("quic-v1")),Xd=st(Bi,Ts),mw=fe(Bi),yw=fe(Ts),wi=st(nn,Rs,sn,Bi,Ts),Cl=st(oe(wi,se("ws"),nt(Oe()))),bw=fe(Cl),Ll=st(oe(wi,se("wss"),nt(Oe())),oe(wi,se("tls"),se("ws"),nt(Oe()))),ww=fe(Ll),Ul=oe(Jd,se("webrtc-direct"),Ss(),nt(Ss()),nt(Oe())),xw=fe(Ul),Pl=oe(Ts,se("webtransport"),Ss(),Ss(),nt(Oe())),vw=fe(Pl),ks=st(Cl,Ll,oe(Rs,nt(Oe())),oe(Xd,nt(Oe())),oe(nn,nt(Oe())),Ul,Pl,Oe()),Ew=fe(ks),Qd=oe(ks,se("p2p-circuit"),Oe()),Bw=fe(Qd),e0=st(oe(ks,se("p2p-circuit"),se("webrtc"),Oe()),oe(ks,se("webrtc"),nt(Oe())),se("webrtc")),Aw=fe(e0);function Nr(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var _s=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Ol(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new _s(t?.errorMessage,t?.errorCode));let n,s=new _s(t?.errorMessage,t?.errorCode);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Ai=class{needNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.needNext=Nr(),this.haveNext=Nr()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("Have next but next was undefined");let e=this.nextResult;return this.nextResult=void 0,this.needNext.resolve(),this.needNext=Nr(),e}async throw(e){return this.ended=!0,e!=null&&this.haveNext.reject(e),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");this.nextResult!=null&&await this.needNext.promise,e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Nr(),await Ol(this.needNext.promise,t?.signal,t)}};function Vl(){return new Ai}var Cs=class extends Error{code;constructor(e,t){super(e),this.code=t}},Ii=class extends Cs{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function Dl(r,e){let t=Vl();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let s=new Ye;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,f=new Promise((u,l)=>{c=()=>{l(new Ii("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:d}=await Promise.race([n.next(),f]);return l===!0?new Ye:d}for(;s.byteLength<i;){let{value:l,done:d}=await Promise.race([n.next(),f]);if(d===!0)throw new Cs("unexpected end of input","ERR_UNEXPECTED_EOF");s.append(l)}let u=s.sublist(0,i);return s.consume(i),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(s.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield s:yield*s,yield*i}()}return r}}}var Ls=class extends Error{code;constructor(e,t){super(e),this.code=t}};function Ml(r,e={}){let t=Dl(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=ve(e.maxDataLength));let n=e?.lengthDecoder??gt,s=e?.lengthEncoder??Le;return{read:async i=>{let a=-1,c=new Ye;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Ls("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Ls("message length too long","ERR_MSG_DATA_TOO_LONG");return t.read(a,i)},write:async(i,a)=>{await t.write(new Ye(s(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new Ye(...i.flatMap(f=>[s(f.byteLength),f]));await t.write(c,a)},unwrap:()=>t.unwrap()}}function on(r,e){let t=Ml(r,e),n={read:async(s,o)=>{let i=await t.read(o);return s.decode(i)},write:async(s,o,i)=>{await t.write(o.encode(s),i)},writeV:async(s,o,i)=>{await t.writeV(s.map(a=>o.encode(a)),i)},pb:s=>({read:async o=>n.read(s,o),write:async(o,i)=>n.write(o,s,i),writeV:async(o,i)=>n.writeV(o,s,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var Kl=Di(Fl(),1),Si=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,Us=(0,Kl.default)(),ql=Si&&!Us,$l=Us&&!Si,Gl=Us&&Si,zl=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!Us,jl=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,Fw=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+"_"+"ENV"]==="test",Wl=typeof navigator<"u"&&navigator.product==="ReactNative";var tr;(function(r){let e;r.codec=()=>(e==null&&(e=Ge((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let o of t.listenAddrs)n.uint32(18),n.bytes(o);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let o of t.protocols)n.uint32(26),n.string(o);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={listenAddrs:[],protocols:[]},o=n==null?t.len:t.pos+n;for(;t.pos<o;){let i=t.uint32();switch(i>>>3){case 5:s.protocolVersion=t.string();break;case 6:s.agentVersion=t.string();break;case 1:s.publicKey=t.bytes();break;case 2:s.listenAddrs.push(t.bytes());break;case 4:s.observedAddr=t.bytes();break;case 3:s.protocols.push(t.string());break;case 8:s.signedPeerRecord=t.bytes();break;default:t.skipType(i&7);break}}return s})),e),r.encode=t=>$e(t,r.codec()),r.decode=t=>qe(t,r.codec())})(tr||(tr={}));var ki=1024*8,Ve={protocolPrefix:"ipfs",timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1,maxObservedAddresses:10,maxIdentifyMessageSize:8192,runOnConnectionOpen:!0,runOnTransientConnection:!0},Ps=class{identifyProtocolStr;identifyPushProtocolStr;host;started;timeout;peerId;peerStore;registrar;connectionManager;addressManager;maxInboundStreams;maxOutboundStreams;maxPushIncomingStreams;maxPushOutgoingStreams;maxIdentifyMessageSize;maxObservedAddresses;events;runOnTransientConnection;log;constructor(e,t={}){this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.events=e.events,this.log=e.logger.forComponent("libp2p:identify"),this.identifyProtocolStr=`/${t.protocolPrefix??Ve.protocolPrefix}/${Ki}/${$i}`,this.identifyPushProtocolStr=`/${t.protocolPrefix??Ve.protocolPrefix}/${qi}/${Gi}`,this.timeout=t.timeout??Ve.timeout,this.maxInboundStreams=t.maxInboundStreams??Ve.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??Ve.maxOutboundStreams,this.maxPushIncomingStreams=t.maxPushIncomingStreams??Ve.maxPushIncomingStreams,this.maxPushOutgoingStreams=t.maxPushOutgoingStreams??Ve.maxPushOutgoingStreams,this.maxIdentifyMessageSize=t.maxIdentifyMessageSize??Ve.maxIdentifyMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??Ve.maxObservedAddresses,this.runOnTransientConnection=t.runOnTransientConnection??Ve.runOnTransientConnection,this.host={protocolVersion:`${t.protocolPrefix??Ve.protocolPrefix}/${Fi}`,agentVersion:t.agentVersion??`${e.nodeInfo.name}/${e.nodeInfo.version}`},(t.runOnConnectionOpen??Ve.runOnConnectionOpen)&&e.events.addEventListener("connection:open",n=>{let s=n.detail;this.identify(s).catch(o=>{this.log.error("error during identify trigged by connection:open",o)})}),e.events.addEventListener("self:peer:update",n=>{this.push().catch(s=>{this.log.error(s)})}),this.host.agentVersion===`${e.nodeInfo.name}/${e.nodeInfo.version}`&&(zl||$l?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(ql||jl||Gl||Wl)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:F(this.host.agentVersion),ProtocolVersion:F(this.host.protocolVersion)}}),await this.registrar.handle(this.identifyProtocolStr,e=>{this._handleIdentify(e).catch(t=>{this.log.error(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}),await this.registrar.handle(this.identifyPushProtocolStr,e=>{this._handlePush(e).catch(t=>{this.log.error(t)})},{maxInboundStreams:this.maxPushIncomingStreams,maxOutboundStreams:this.maxPushOutgoingStreams,runOnTransientConnection:this.runOnTransientConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.identifyProtocolStr),await this.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async pushToConnections(e){let t=this.addressManager.getAddresses().map(u=>u.decapsulateCode(j("p2p").code)),n=new Bt({peerId:this.peerId,multiaddrs:t}),s=await Ht.seal(n,this.peerId),o=this.registrar.getProtocols(),i=await this.peerStore.get(this.peerId),a=K(i.metadata.get("AgentVersion")??F(this.host.agentVersion)),c=K(i.metadata.get("ProtocolVersion")??F(this.host.protocolVersion)),f=e.map(async u=>{let l,d=AbortSignal.timeout(this.timeout);cn(1/0,d);try{l=await u.newStream(this.identifyPushProtocolStr,{signal:d,runOnTransientConnection:this.runOnTransientConnection}),await on(l,{maxDataLength:this.maxIdentifyMessageSize??ki}).pb(tr).write({listenAddrs:t.map(p=>p.bytes),signedPeerRecord:s.marshal(),protocols:o,agentVersion:a,protocolVersion:c},{signal:d}),await l.close({signal:d})}catch(b){this.log.error("could not push identify update to peer",b),l?.abort(b)}});await Promise.all(f)}async push(){if(!this.isStarted())return;let e=[];await Promise.all(this.connectionManager.getConnections().map(async t=>{try{if(!(await this.peerStore.get(t.remotePeer)).protocols.includes(this.identifyPushProtocolStr))return;e.push(t)}catch(n){if(n.code!==ji)throw n}})),await this.pushToConnections(e)}async _identify(e,t={}){let n;if(t.signal==null){let s=AbortSignal.timeout(this.timeout);cn(1/0,s),t={...t,signal:s}}try{n=await e.newStream(this.identifyProtocolStr,{...t,runOnTransientConnection:this.runOnTransientConnection});let o=await on(n,{maxDataLength:this.maxIdentifyMessageSize??ki}).pb(tr).read(t);return await n.close(t),o}catch(s){throw this.log.error("error while reading identify message",s),n?.abort(s),s}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:s,protocols:o,observedAddr:i}=n;if(s==null)throw new C("public key was missing from identify message","ERR_MISSING_PUBLIC_KEY");let a=await Ur(s);if(!e.remotePeer.equals(a))throw new C("identified peer does not match the expected peer","ERR_INVALID_PEER");if(this.peerId.equals(a))throw new C("identified peer is our own peer id?","ERR_INVALID_PEER");let c=r0(i);return this.log("identify completed for peer %p and protocols %o",a,o),this.log("our observed address is %a",c),c!=null&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(this.log("storing our observed address %a",c),this.addressManager.addObservedAddr(c)),this.#e(e,n)}async _handleIdentify(e){let{connection:t,stream:n}=e,s=AbortSignal.timeout(this.timeout);cn(1/0,s);try{let o=this.peerId.publicKey??new Uint8Array(0),i=await this.peerStore.get(this.peerId),a=this.addressManager.getAddresses().map(l=>l.decapsulateCode(j("p2p").code)),c=i.peerRecordEnvelope;if(a.length>0&&c==null){let l=new Bt({peerId:this.peerId,multiaddrs:a});c=(await Ht.seal(l,this.peerId)).marshal().subarray()}let f=t.remoteAddr.bytes;_l.matches(t.remoteAddr)||(f=void 0),await on(n).pb(tr).write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:o,listenAddrs:a.map(l=>l.bytes),signedPeerRecord:c,observedAddr:f,protocols:i.protocols},{signal:s}),await n.close({signal:s})}catch(o){this.log.error("could not respond to identify request",o),n.abort(o)}}async _handlePush(e){let{connection:t,stream:n}=e;try{if(this.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");let s={signal:AbortSignal.timeout(this.timeout)},i=await on(n,{maxDataLength:this.maxIdentifyMessageSize??ki}).pb(tr).read(s);await n.close(s),await this.#e(t,i)}catch(s){this.log.error("received invalid message",s),n.abort(s);return}this.log("handled push from %p",t.remotePeer)}async#e(e,t){if(this.log("received identify from %p",e.remotePeer),t==null)throw new C("message was null or undefined","ERR_INVALID_MESSAGE");let n={};if(t.listenAddrs.length>0&&(n.addresses=t.listenAddrs.map(i=>({isCertified:!1,multiaddr:Ft(i)}))),t.protocols.length>0&&(n.protocols=t.protocols),t.publicKey!=null&&(n.publicKey=t.publicKey,!(await Ur(t.publicKey)).equals(e.remotePeer)))throw new C("public key did not match remote PeerId","ERR_INVALID_PUBLIC_KEY");let s;if(t.signedPeerRecord!=null){this.log("received signedPeerRecord from %p",e.remotePeer);let i=t.signedPeerRecord,a=await Ht.openAndCertify(i,Bt.DOMAIN),c=Bt.createFromProtobuf(a.payload);if(!c.peerId.equals(a.peerId))throw new C("signing key does not match PeerId in the PeerRecord","ERR_INVALID_SIGNING_KEY");if(!e.remotePeer.equals(c.peerId))throw new C("signing key does not match remote PeerId","ERR_INVALID_PEER_RECORD_KEY");let f;try{f=await this.peerStore.get(c.peerId)}catch(u){if(u.code!=="ERR_NOT_FOUND")throw u}if(f!=null&&(n.metadata=f.metadata,f.peerRecordEnvelope!=null)){let u=await Ht.createFromProtobuf(f.peerRecordEnvelope),l=Bt.createFromProtobuf(u.payload);l.seqNumber>=c.seqNumber&&(this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",l.seqNumber,c.seqNumber),c=l,i=f.peerRecordEnvelope)}n.peerRecordEnvelope=i,n.addresses=c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u})),s={seq:c.seqNumber,addresses:c.multiaddrs}}else this.log("%p did not send a signed peer record",e.remotePeer);if(this.log("patching %p with",e.remotePeer,n),await this.peerStore.patch(e.remotePeer,n),t.agentVersion!=null||t.protocolVersion!=null){let i={};t.agentVersion!=null&&(i.AgentVersion=F(t.agentVersion)),t.protocolVersion!=null&&(i.ProtocolVersion=F(t.protocolVersion)),this.log("merging %p metadata",e.remotePeer,i),await this.peerStore.merge(e.remotePeer,{metadata:i})}let o={peerId:e.remotePeer,protocolVersion:t.protocolVersion,agentVersion:t.agentVersion,publicKey:t.publicKey,listenAddrs:t.listenAddrs.map(i=>Ft(i)),observedAddr:t.observedAddr==null?void 0:Ft(t.observedAddr),protocols:t.protocols,signedPeerRecord:s,connection:e};return this.events.safeDispatchEvent("peer:identify",{detail:o}),o}};function r0(r){if(r!=null&&r.length>0)try{return Ft(r)}catch{}}var n0={IDENTIFY:Mi,IDENTIFY_PUSH:Hi};function s0(r={}){return e=>new Ps(e,r)}return cu(o0);})();
|
|
7
|
+
`)}async function cd(r,e){let t=Ie.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let s=F(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:o}=Ar(s),{iv:i,salt:a,iterations:c,keySize:f,cipherText:u}=ld(o),l=await zo(gr,e,a,{c,dkLen:f}),d=await t.subtle.importKey("raw",l,"AES-CBC",!1,["decrypt"]),b=Yr(await t.subtle.decrypt({name:"AES-CBC",iv:i},d,u)),{result:p}=Ar(b);n=Vc(p)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let s=F(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:o}=Ar(s);n=Vc(o)}else throw new C("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return Qo(n)}function ld(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new C("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new C("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let o=n.valueBlock.value[1],i=Yr(o.valueBlock.value[0].getValue()),a=Xo,c=Jo;if(o.valueBlock.value.length===3)a=Number(o.valueBlock.value[1].toBigInt()),c=Number(o.valueBlock.value[2].toBigInt());else if(o.valueBlock.value.length===2)throw new C("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let f=e.valueBlock.value[1].valueBlock.value[1],u=f.valueBlock.value[0].toString();if(u!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(u!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new C("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let l=Yr(f.valueBlock.value[1].getValue());return{cipherText:Yr(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:l}}function Vc(r){return Yr(r.valueBlock.value[2].getValue())}function Yr(r){return new Uint8Array(r,0,r.byteLength)}async function Dc(r){let e=await Ie.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await Fc(e);return{privateKey:t[0],publicKey:t[1]}}async function ei(r){let t=[await Ie.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await ud(r)],n=await Fc({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function Mc(r,e){let t=await Ie.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ie.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Hc(r,e,t){let n=await Ie.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ie.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function Fc(r){if(r.privateKey==null||r.publicKey==null)throw new C("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Ie.get().subtle.exportKey("jwk",r.privateKey),Ie.get().subtle.exportKey("jwk",r.publicKey)])}async function ud(r){return Ie.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function bs(r){if(r.kty!=="RSA")throw new C("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new C("invalid key modulus","ERR_INVALID_KEY_MODULUS");return F(r.n,"base64url").length*8}var Jr=8192,Zr=class{_key;constructor(e){this._key=e}verify(e,t){return Hc(this._key,t,e)}marshal(){return Vt.jwkToPkix(this._key)}get bytes(){return Xe.encode({Type:X.RSA,Data:this.marshal()}).subarray()}equals(e){return de(this.bytes,e.bytes)}hash(){let e=ye.digest(this.bytes);return Ce(e)?e.then(({bytes:t})=>t):e.bytes}},Ir=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return Jt(16)}sign(e){return Mc(this._key,e)}get public(){if(this._publicKey==null)throw new C("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Zr(this._publicKey)}marshal(){return Vt.jwkToPkcs1(this._key)}get bytes(){return Qe.encode({Type:X.RSA,Data:this.marshal()}).subarray()}equals(e){return de(this.bytes,e.bytes)}hash(){let e=ye.digest(this.bytes);return Ce(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return K(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return Vt.exportToPem(this,e);if(t==="libp2p-key")return br(this.bytes,e);throw new C(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function Qo(r){let e=Vt.pkcs1ToJwk(r);if(bs(e)>Jr)throw new C("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await ei(e);return new Ir(t.privateKey,t.publicKey)}function hd(r){let e=Vt.pkixToJwk(r);if(bs(e)>Jr)throw new C("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Zr(e)}async function dd(r){if(bs(r)>Jr)throw new C("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await ei(r);return new Ir(e.privateKey,e.publicKey)}async function pd(r){if(r>Jr)throw new C("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Dc(r);return new Ir(e.privateKey,e.publicKey)}var ii={};he(ii,{Secp256k1PrivateKey:()=>Qr,Secp256k1PublicKey:()=>Xr,generateKeyPair:()=>Rd,unmarshalSecp256k1PrivateKey:()=>kd,unmarshalSecp256k1PublicKey:()=>Nd});var gd=(r,e,t)=>r&e^~r&t,md=(r,e,t)=>r&e^r&t^e&t,yd=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]),Dt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Mt=new Uint32Array(64),ri=class extends pr{constructor(){super(64,32,8,!1),this.A=Dt[0]|0,this.B=Dt[1]|0,this.C=Dt[2]|0,this.D=Dt[3]|0,this.E=Dt[4]|0,this.F=Dt[5]|0,this.G=Dt[6]|0,this.H=Dt[7]|0}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let l=0;l<16;l++,t+=4)Mt[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let d=Mt[l-15],b=Mt[l-2],p=Me(d,7)^Me(d,18)^d>>>3,h=Me(b,17)^Me(b,19)^b>>>10;Mt[l]=h+Mt[l-7]+p+Mt[l-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:f,H:u}=this;for(let l=0;l<64;l++){let d=Me(a,6)^Me(a,11)^Me(a,25),b=u+d+gd(a,c,f)+yd[l]+Mt[l]|0,h=(Me(n,2)^Me(n,13)^Me(n,22))+md(n,s,o)|0;u=f,f=c,c=a,a=i+b|0,i=o,o=s,s=n,n=b+h|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(n,s,o,i,a,c,f,u)}roundClean(){Mt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Kc=pn(()=>new ri);function bd(r){let e=Or(r);Je(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:s}=e;if(t){if(!n.eql(s,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:wd,hexToBytes:xd}=yn,Qt={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=Qt;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:wd(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Qt,t=typeof r=="string"?xd(r):r;if(!He(t))throw new Error("ui8a expected");let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:s,l:o}=Qt._parseInt(t.subarray(2)),{d:i,l:a}=Qt._parseInt(o);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:s,s:i}},hexFromSig(r){let e=f=>Number.parseInt(f[0],16)&8?"00"+f:f,t=f=>{let u=f.toString(16);return u.length&1?`0${u}`:u},n=e(t(r.s)),s=e(t(r.r)),o=n.length/2,i=s.length/2,a=t(o),c=t(i);return`30${t(i+o+4)}02${c}${s}02${a}${n}`}},Et=BigInt(0),Pe=BigInt(1),Vm=BigInt(2),qc=BigInt(3),Dm=BigInt(4);function vd(r){let e=bd(r),{Fp:t}=e,n=e.toBytes||((p,h,m)=>{let y=h.toAffine();return ht(Uint8Array.from([4]),t.toBytes(y.x),t.toBytes(y.y))}),s=e.fromBytes||(p=>{let h=p.subarray(1),m=t.fromBytes(h.subarray(0,t.BYTES)),y=t.fromBytes(h.subarray(t.BYTES,2*t.BYTES));return{x:m,y}});function o(p){let{a:h,b:m}=e,y=t.sqr(p),B=t.mul(y,p);return t.add(t.add(B,t.mul(p,h)),m)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function i(p){return typeof p=="bigint"&&Et<p&&p<e.n}function a(p){if(!i(p))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(p){let{allowedPrivateKeyLengths:h,nByteLength:m,wrapPrivateKey:y,n:B}=e;if(h&&typeof p!="bigint"){if(He(p)&&(p=ut(p)),typeof p!="string"||!h.includes(p.length))throw new Error("Invalid key");p=p.padStart(m*2,"0")}let w;try{w=typeof p=="bigint"?p:ft(te("private key",p,m))}catch{throw new Error(`private key must be ${m} bytes, hex or bigint, not ${typeof p}`)}return y&&(w=Y(w,B)),a(w),w}let f=new Map;function u(p){if(!(p instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(h,m,y){if(this.px=h,this.py=m,this.pz=y,h==null||!t.isValid(h))throw new Error("x required");if(m==null||!t.isValid(m))throw new Error("y required");if(y==null||!t.isValid(y))throw new Error("z required")}static fromAffine(h){let{x:m,y}=h||{};if(!h||!t.isValid(m)||!t.isValid(y))throw new Error("invalid affine point");if(h instanceof l)throw new Error("projective point not allowed");let B=w=>t.eql(w,t.ZERO);return B(m)&&B(y)?l.ZERO:new l(m,y,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let m=t.invertBatch(h.map(y=>y.pz));return h.map((y,B)=>y.toAffine(m[B])).map(l.fromAffine)}static fromHex(h){let m=l.fromAffine(s(te("pointHex",h)));return m.assertValidity(),m}static fromPrivateKey(h){return l.BASE.multiply(c(h))}_setWindowSize(h){this._WINDOW_SIZE=h,f.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:h,y:m}=this.toAffine();if(!t.isValid(h)||!t.isValid(m))throw new Error("bad point: x or y not FE");let y=t.sqr(m),B=o(h);if(!t.eql(y,B))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:h}=this.toAffine();if(t.isOdd)return!t.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){u(h);let{px:m,py:y,pz:B}=this,{px:w,py:T,pz:x}=h,A=t.eql(t.mul(m,x),t.mul(w,B)),N=t.eql(t.mul(y,x),t.mul(T,B));return A&&N}negate(){return new l(this.px,t.neg(this.py),this.pz)}double(){let{a:h,b:m}=e,y=t.mul(m,qc),{px:B,py:w,pz:T}=this,x=t.ZERO,A=t.ZERO,N=t.ZERO,R=t.mul(B,B),G=t.mul(w,w),q=t.mul(T,T),P=t.mul(B,w);return P=t.add(P,P),N=t.mul(B,T),N=t.add(N,N),x=t.mul(h,N),A=t.mul(y,q),A=t.add(x,A),x=t.sub(G,A),A=t.add(G,A),A=t.mul(x,A),x=t.mul(P,x),N=t.mul(y,N),q=t.mul(h,q),P=t.sub(R,q),P=t.mul(h,P),P=t.add(P,N),N=t.add(R,R),R=t.add(N,R),R=t.add(R,q),R=t.mul(R,P),A=t.add(A,R),q=t.mul(w,T),q=t.add(q,q),R=t.mul(q,P),x=t.sub(x,R),N=t.mul(q,G),N=t.add(N,N),N=t.add(N,N),new l(x,A,N)}add(h){u(h);let{px:m,py:y,pz:B}=this,{px:w,py:T,pz:x}=h,A=t.ZERO,N=t.ZERO,R=t.ZERO,G=e.a,q=t.mul(e.b,qc),P=t.mul(m,w),ie=t.mul(y,T),re=t.mul(B,x),_e=t.add(m,y),v=t.add(w,T);_e=t.mul(_e,v),v=t.add(P,ie),_e=t.sub(_e,v),v=t.add(m,B);let k=t.add(w,x);return v=t.mul(v,k),k=t.add(P,re),v=t.sub(v,k),k=t.add(y,B),A=t.add(T,x),k=t.mul(k,A),A=t.add(ie,re),k=t.sub(k,A),R=t.mul(G,v),A=t.mul(q,re),R=t.add(A,R),A=t.sub(ie,R),R=t.add(ie,R),N=t.mul(A,R),ie=t.add(P,P),ie=t.add(ie,P),re=t.mul(G,re),v=t.mul(q,v),ie=t.add(ie,re),re=t.sub(P,re),re=t.mul(G,re),v=t.add(v,re),P=t.mul(ie,v),N=t.add(N,P),P=t.mul(k,v),A=t.mul(_e,A),A=t.sub(A,P),P=t.mul(_e,ie),R=t.mul(k,R),R=t.add(R,P),new l(A,N,R)}subtract(h){return this.add(h.negate())}is0(){return this.equals(l.ZERO)}wNAF(h){return b.wNAFCached(this,f,h,m=>{let y=t.invertBatch(m.map(B=>B.pz));return m.map((B,w)=>B.toAffine(y[w])).map(l.fromAffine)})}multiplyUnsafe(h){let m=l.ZERO;if(h===Et)return m;if(a(h),h===Pe)return this;let{endo:y}=e;if(!y)return b.unsafeLadder(this,h);let{k1neg:B,k1:w,k2neg:T,k2:x}=y.splitScalar(h),A=m,N=m,R=this;for(;w>Et||x>Et;)w&Pe&&(A=A.add(R)),x&Pe&&(N=N.add(R)),R=R.double(),w>>=Pe,x>>=Pe;return B&&(A=A.negate()),T&&(N=N.negate()),N=new l(t.mul(N.px,y.beta),N.py,N.pz),A.add(N)}multiply(h){a(h);let m=h,y,B,{endo:w}=e;if(w){let{k1neg:T,k1:x,k2neg:A,k2:N}=w.splitScalar(m),{p:R,f:G}=this.wNAF(x),{p:q,f:P}=this.wNAF(N);R=b.constTimeNegate(T,R),q=b.constTimeNegate(A,q),q=new l(t.mul(q.px,w.beta),q.py,q.pz),y=R.add(q),B=G.add(P)}else{let{p:T,f:x}=this.wNAF(m);y=T,B=x}return l.normalizeZ([y,B])[0]}multiplyAndAddUnsafe(h,m,y){let B=l.BASE,w=(x,A)=>A===Et||A===Pe||!x.equals(B)?x.multiplyUnsafe(A):x.multiply(A),T=w(this,m).add(w(h,y));return T.is0()?void 0:T}toAffine(h){let{px:m,py:y,pz:B}=this,w=this.is0();h==null&&(h=w?t.ONE:t.inv(B));let T=t.mul(m,h),x=t.mul(y,h),A=t.mul(B,h);if(w)return{x:t.ZERO,y:t.ZERO};if(!t.eql(A,t.ONE))throw new Error("invZ was invalid");return{x:T,y:x}}isTorsionFree(){let{h,isTorsionFree:m}=e;if(h===Pe)return!0;if(m)return m(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:m}=e;return h===Pe?this:m?m(l,this):this.multiplyUnsafe(e.h)}toRawBytes(h=!0){return this.assertValidity(),n(l,this,h)}toHex(h=!0){return ut(this.toRawBytes(h))}}l.BASE=new l(e.Gx,e.Gy,t.ONE),l.ZERO=new l(t.ZERO,t.ONE,t.ZERO);let d=e.nBitLength,b=xn(l,e.endo?Math.ceil(d/2):d);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:i}}function Ed(r){let e=Or(r);return Je(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function $c(r){let e=Ed(r),{Fp:t,n}=e,s=t.BYTES+1,o=2*t.BYTES+1;function i(v){return Et<v&&v<t.ORDER}function a(v){return Y(v,n)}function c(v){return bn(v,n)}let{ProjectivePoint:f,normPrivateKeyToScalar:u,weierstrassEquation:l,isWithinCurveOrder:d}=vd({...e,toBytes(v,k,O){let E=k.toAffine(),g=t.toBytes(E.x),S=ht;return O?S(Uint8Array.from([k.hasEvenY()?2:3]),g):S(Uint8Array.from([4]),g,t.toBytes(E.y))},fromBytes(v){let k=v.length,O=v[0],E=v.subarray(1);if(k===s&&(O===2||O===3)){let g=ft(E);if(!i(g))throw new Error("Point is not on curve");let S=l(g),_=t.sqrt(S),L=(_&Pe)===Pe;return(O&1)===1!==L&&(_=t.neg(_)),{x:g,y:_}}else if(k===o&&O===4){let g=t.fromBytes(E.subarray(0,t.BYTES)),S=t.fromBytes(E.subarray(t.BYTES,2*t.BYTES));return{x:g,y:S}}else throw new Error(`Point of length ${k} was invalid. Expected ${s} compressed bytes or ${o} uncompressed bytes`)}}),b=v=>ut(Ct(v,e.nByteLength));function p(v){let k=n>>Pe;return v>k}function h(v){return p(v)?a(-v):v}let m=(v,k,O)=>ft(v.slice(k,O));class y{constructor(k,O,E){this.r=k,this.s=O,this.recovery=E,this.assertValidity()}static fromCompact(k){let O=e.nByteLength;return k=te("compactSignature",k,O*2),new y(m(k,0,O),m(k,O,2*O))}static fromDER(k){let{r:O,s:E}=Qt.toSig(te("DER",k));return new y(O,E)}assertValidity(){if(!d(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!d(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(k){return new y(this.r,this.s,k)}recoverPublicKey(k){let{r:O,s:E,recovery:g}=this,S=N(te("msgHash",k));if(g==null||![0,1,2,3].includes(g))throw new Error("recovery id invalid");let _=g===2||g===3?O+e.n:O;if(_>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let L=g&1?"03":"02",V=f.fromHex(L+b(_)),D=c(_),W=a(-S*D),H=a(E*D),$=f.BASE.multiplyAndAddUnsafe(V,W,H);if(!$)throw new Error("point at infinify");return $.assertValidity(),$}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return Gt(this.toDERHex())}toDERHex(){return Qt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Gt(this.toCompactHex())}toCompactHex(){return b(this.r)+b(this.s)}}let B={isValidPrivateKey(v){try{return u(v),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let v=xo(e.n);return Ta(e.randomBytes(v),e.n)},precompute(v=8,k=f.BASE){return k._setWindowSize(v),k.multiply(BigInt(3)),k}};function w(v,k=!0){return f.fromPrivateKey(v).toRawBytes(k)}function T(v){let k=He(v),O=typeof v=="string",E=(k||O)&&v.length;return k?E===s||E===o:O?E===2*s||E===2*o:v instanceof f}function x(v,k,O=!0){if(T(v))throw new Error("first arg must be private key");if(!T(k))throw new Error("second arg must be public key");return f.fromHex(k).multiply(u(v)).toRawBytes(O)}let A=e.bits2int||function(v){let k=ft(v),O=v.length*8-e.nBitLength;return O>0?k>>BigInt(O):k},N=e.bits2int_modN||function(v){return a(A(v))},R=Pr(e.nBitLength);function G(v){if(typeof v!="bigint")throw new Error("bigint expected");if(!(Et<=v&&v<R))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Ct(v,e.nByteLength)}function q(v,k,O=P){if(["recovered","canonical"].some(Q=>Q in O))throw new Error("sign() legacy options not supported");let{hash:E,randomBytes:g}=e,{lowS:S,prehash:_,extraEntropy:L}=O;S==null&&(S=!0),v=te("msgHash",v),_&&(v=te("prehashed msgHash",E(v)));let V=N(v),D=u(k),W=[G(D),G(V)];if(L!=null){let Q=L===!0?g(t.BYTES):L;W.push(te("extraEntropy",Q))}let H=ht(...W),$=V;function ae(Q){let ge=A(Q);if(!d(ge))return;let me=c(ge),le=f.BASE.multiply(ge).toAffine(),we=a(le.x);if(we===Et)return;let ot=a(me*a($+we*D));if(ot===Et)return;let Kt=(le.x===we?0:2)|Number(le.y&Pe),Rr=ot;return S&&p(ot)&&(Rr=h(ot),Kt^=1),new y(we,Rr,Kt)}return{seed:H,k2sig:ae}}let P={lowS:e.lowS,prehash:!1},ie={lowS:e.lowS,prehash:!1};function re(v,k,O=P){let{seed:E,k2sig:g}=q(v,k,O),S=e;return mo(S.hash.outputLen,S.nByteLength,S.hmac)(E,g)}f.BASE._setWindowSize(8);function _e(v,k,O,E=ie){let g=v;if(k=te("msgHash",k),O=te("publicKey",O),"strict"in E)throw new Error("options.strict was renamed to lowS");let{lowS:S,prehash:_}=E,L,V;try{if(typeof g=="string"||He(g))try{L=y.fromDER(g)}catch(le){if(!(le instanceof Qt.Err))throw le;L=y.fromCompact(g)}else if(typeof g=="object"&&typeof g.r=="bigint"&&typeof g.s=="bigint"){let{r:le,s:we}=g;L=new y(le,we)}else throw new Error("PARSE");V=f.fromHex(O)}catch(le){if(le.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(S&&L.hasHighS())return!1;_&&(k=e.hash(k));let{r:D,s:W}=L,H=N(k),$=c(W),ae=a(H*$),Q=a(D*$),ge=f.BASE.multiplyAndAddUnsafe(V,ae,Q)?.toAffine();return ge?a(ge.x)===D:!1}return{CURVE:e,getPublicKey:w,getSharedSecret:x,sign:re,verify:_e,ProjectivePoint:f,Signature:y,utils:B}}function Bd(r){return{hash:r,hmac:(e,...t)=>Hr(r,e,dn(...t)),randomBytes:dr}}function Gc(r,e){let t=n=>$c({...r,...Bd(n)});return Object.freeze({...t(e),create:t})}var Wc=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),zc=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ad=BigInt(1),ni=BigInt(2),jc=(r,e)=>(r+e/ni)/e;function Id(r){let e=Wc,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=r*r*r%e,u=f*f*r%e,l=J(u,t,e)*u%e,d=J(l,t,e)*u%e,b=J(d,ni,e)*f%e,p=J(b,s,e)*b%e,h=J(p,o,e)*p%e,m=J(h,a,e)*h%e,y=J(m,c,e)*m%e,B=J(y,a,e)*h%e,w=J(B,t,e)*u%e,T=J(w,i,e)*p%e,x=J(T,n,e)*f%e,A=J(x,ni,e);if(!si.eql(si.sqr(A),r))throw new Error("Cannot find square root");return A}var si=wn(Wc,void 0,void 0,{sqrt:Id}),We=Gc({a:BigInt(0),b:BigInt(7),Fp:si,n:zc,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=zc,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Ad*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=t,i=BigInt("0x100000000000000000000000000000000"),a=jc(o*r,e),c=jc(-n*r,e),f=Y(r-a*t-c*s,e),u=Y(-a*n-c*o,e),l=f>i,d=u>i;if(l&&(f=e-f),d&&(u=e-u),f>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:l,k1:f,k2neg:d,k2:u}}}},Kc),jm=BigInt(0);var Wm=We.ProjectivePoint;function Yc(){return We.utils.randomPrivateKey()}function Zc(r,e){let t=ye.digest(e instanceof Uint8Array?e:e.subarray());if(Ce(t))return t.then(({digest:n})=>We.sign(n,r).toDERRawBytes()).catch(n=>{throw new C(String(n),"ERR_INVALID_INPUT")});try{return We.sign(t.digest,r).toDERRawBytes()}catch(n){throw new C(String(n),"ERR_INVALID_INPUT")}}function Jc(r,e,t){let n=ye.digest(t instanceof Uint8Array?t:t.subarray());if(Ce(n))return n.then(({digest:s})=>We.verify(e,s,r)).catch(s=>{throw new C(String(s),"ERR_INVALID_INPUT")});try{return We.verify(e,n.digest,r)}catch(s){throw new C(String(s),"ERR_INVALID_INPUT")}}function Xc(r){return We.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Qc(r){try{We.getPublicKey(r,!0)}catch(e){throw new C(String(e),"ERR_INVALID_PRIVATE_KEY")}}function oi(r){try{We.ProjectivePoint.fromHex(r)}catch(e){throw new C(String(e),"ERR_INVALID_PUBLIC_KEY")}}function el(r){try{return We.getPublicKey(r,!0)}catch(e){throw new C(String(e),"ERR_INVALID_PRIVATE_KEY")}}var Xr=class{_key;constructor(e){oi(e),this._key=e}verify(e,t){return Jc(this._key,t,e)}marshal(){return Xc(this._key)}get bytes(){return Xe.encode({Type:X.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return de(this.bytes,e.bytes)}async hash(){let e=ye.digest(this.bytes),t;return Ce(e)?{bytes:t}=await e:t=e.bytes,t}},Qr=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??el(e),Qc(this._key),oi(this._publicKey)}sign(e){return Zc(this._key,e)}get public(){return new Xr(this._publicKey)}marshal(){return this._key}get bytes(){return Qe.encode({Type:X.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return de(this.bytes,e.bytes)}hash(){let e=ye.digest(this.bytes);return Ce(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return K(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return br(this.bytes,e);throw new C(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function kd(r){return new Qr(r)}function Nd(r){return new Xr(r)}async function Rd(){let r=Yc();return new Qr(r)}var er={rsa:ti,ed25519:Go,secp256k1:ii};function tl(r){let e=Object.keys(er).join(" / ");return new C(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function rl(r){let e=Xe.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case X.RSA:return er.rsa.unmarshalRsaPublicKey(t);case X.Ed25519:return er.ed25519.unmarshalEd25519PublicKey(t);case X.Secp256k1:return er.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw tl(e.Type??"unknown")}}async function nl(r){let e=Qe.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case X.RSA:return er.rsa.unmarshalRsaPrivateKey(t);case X.Ed25519:return er.ed25519.unmarshalEd25519PrivateKey(t);case X.Secp256k1:return er.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw tl(e.Type??"RSA")}}var ol=Symbol.for("@achingbrain/uint8arraylist");function sl(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function ws(r){return!!r?.[ol]}var Ye=class r{bufs;length;[ol]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(ws(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(ws(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=sl(this.bufs,e);return t.buf[t.index]}set(e,t){let n=sl(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(ws(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return Ae(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Ae(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=[...n],o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let f=e>=a&&e<c,u=t>a&&t<=c;if(f&&u){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(f){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!ws(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let l=0;l<o;l++)i[l]=-1;for(let l=0;l<s;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let l=t;l<=c;l+=u){u=0;for(let d=f;d>=0;d--){let b=this.get(l+d);if(n[d]!==b){u=Math.max(1,d-a[b]);break}}if(u===0)return l}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=ke(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=ct(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=ct(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=ct(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=ke(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=ct(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=ct(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=ct(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=ct(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=ct(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!de(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}};var il={ERR_SIGNATURE_NOT_VALID:"ERR_SIGNATURE_NOT_VALID"};var en;(function(r){let e;r.codec=()=>(e==null&&(e=Ge((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},o=n==null?t.len:t.pos+n;for(;t.pos<o;){let i=t.uint32();switch(i>>>3){case 1:s.publicKey=t.bytes();break;case 2:s.payloadType=t.bytes();break;case 3:s.payload=t.bytes();break;case 5:s.signature=t.bytes();break;default:t.skipType(i&7);break}}return s})),e),r.encode=t=>$e(t,r.codec()),r.decode=t=>qe(t,r.codec())})(en||(en={}));var Ht=class r{static createFromProtobuf=async e=>{let t=en.decode(e),n=await Ur(t.publicKey);return new r({peerId:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t.privateKey==null)throw new Error("Missing private key");let n=e.domain,s=e.codec,o=e.marshal(),i=al(n,s,o),c=await(await nl(t.privateKey)).sign(i.subarray());return new r({peerId:t,payloadType:s,payload:o,signature:c})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new C("envelope signature is not valid for the given domain",il.ERR_SIGNATURE_NOT_VALID);return n};peerId;payloadType;payload;signature;marshaled;constructor(e){let{peerId:t,payloadType:n,payload:s,signature:o}=e;this.peerId=t,this.payloadType=n,this.payload=s,this.signature=o}marshal(){if(this.peerId.publicKey==null)throw new Error("Missing public key");return this.marshaled==null&&(this.marshaled=en.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return de(this.marshal(),e.marshal())}async validate(e){let t=al(e,this.payloadType,this.payload);if(this.peerId.publicKey==null)throw new Error("Missing public key");return rl(this.peerId.publicKey).verify(t.subarray(),this.signature)}},al=(r,e,t)=>{let n=F(r),s=Le(n.byteLength),o=Le(e.length),i=Le(t.length);return new Ye(s,n,o,e,i,t)};function cl(r,e){let t=(n,s)=>n.toString().localeCompare(s.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,s)=>e[s].equals(n)))}var xs=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(o*=e,o+=u,o>f||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var ll=45,Td=15,Sr=new xs;function ai(r){if(!(r.length>Td))return Sr.new(r).parseWith(()=>Sr.readIPv4Addr())}function ci(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>ll))return Sr.new(r).parseWith(()=>Sr.readIPv6Addr())}function vs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>ll))return Sr.new(r).parseWith(()=>Sr.readIPAddr())}var Uy=parseInt("0xFFFF",16),Py=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Es(r){return!!ai(r)}function Bs(r){return!!ci(r)}function As(r){return!!vs(r)}var hl=Es,Pd=Bs,li=function(r){let e=0;if(r=r.toString().trim(),hl(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(Pd(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=hl(t[n]),i;o&&(i=li(t[n]),t[n]=K(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,K(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){let o=parseInt(t[n],16);s[e++]=o>>8&255,s[e++]=o&255}return s}throw new Error("invalid ip address")},dl=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let s=[];for(let o=0;o<t;o++)s.push(r[e+o]);return s.join(".")}if(t===16){let s=[];for(let o=0;o<t;o+=2)s.push(n.getUint16(e+o).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var kr={},ui={},Vd=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,-1,"memory"]];Vd.forEach(r=>{let e=Dd(...r);ui[e.code]=e,kr[e.name]=e});function Dd(r,e,t,n,s){return{code:r,size:e,name:t,resolvable:!!n,path:!!s}}function j(r){if(typeof r=="number"){if(ui[r]!=null)return ui[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(kr[r]!=null)return kr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var bb=j("ip4"),wb=j("ip6"),xb=j("ipcidr");function hi(r,e){switch(j(r).code){case 4:case 41:return Hd(e);case 42:return ml(e);case 6:case 273:case 33:case 132:return bl(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ml(e);case 421:return $d(e);case 444:return yl(e);case 445:return yl(e);case 466:return qd(e);default:return K(e,"base16")}}function di(r,e){switch(j(r).code){case 4:return pl(e);case 41:return pl(e);case 42:return gl(e);case 6:case 273:case 33:case 132:return pi(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return gl(e);case 421:return Fd(e);case 444:return Gd(e);case 445:return zd(e);case 466:return Kd(e);default:return F(e,"base16")}}var fi=Object.values(St).map(r=>r.decoder),Md=function(){let r=fi[0].or(fi[1]);return fi.slice(2).forEach(e=>r=r.or(e)),r}();function pl(r){if(!As(r))throw new Error("invalid ip address");return li(r)}function Hd(r){let e=dl(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!As(e))throw new Error("invalid ip address");return e}function pi(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function bl(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function gl(r){let e=F(r),t=Uint8Array.from(Le(e.length));return Ae([t,e],t.length+e.length)}function ml(r){let e=gt(r);if(r=r.slice(ve(e)),r.length!==e)throw new Error("inconsistent lengths");return K(r)}function Fd(r){let e;r[0]==="Q"||r[0]==="1"?e=qt(ne.decode(`z${r}`)).bytes:e=De.parse(r).multihash.bytes;let t=Uint8Array.from(Le(e.length));return Ae([t,e],t.length+e.length)}function Kd(r){let e=Md.decode(r),t=Uint8Array.from(Le(e.length));return Ae([t,e],t.length+e.length)}function qd(r){let e=gt(r),t=r.slice(ve(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+K(t,"base64url")}function $d(r){let e=gt(r),t=r.slice(ve(e));if(t.length!==e)throw new Error("inconsistent lengths");return K(t,"base58btc")}function Gd(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=at.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=pi(n);return Ae([t,s],t.length+s.length)}function zd(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=at.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=pi(n);return Ae([t,s],t.length+s.length)}function yl(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=K(e,"base32"),s=bl(t);return`${n}:${s}`}function wl(r){r=gi(r);let e=[],t=[],n=null,s=r.split("/").slice(1);if(s.length===1&&s[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let o=0;o<s.length;o++){let i=s[o],a=j(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(o++,o>=s.length)throw vl("invalid address: "+r);if(a.path===!0){n=gi(s.slice(o).join("/")),e.push([a.code,di(a.code,n)]),t.push([a.code,n]);break}let c=di(a.code,s[o]);e.push([a.code,c]),t.push([a.code,hi(a.code,c)])}return{string:xl(t),bytes:yi(e),tuples:e,stringTuples:t,path:n}}function mi(r){let e=[],t=[],n=null,s=0;for(;s<r.length;){let o=gt(r,s),i=ve(o),a=j(o),c=jd(a,r.slice(s+i));if(c===0){e.push([o]),t.push([o]),s+=i;continue}let f=r.slice(s+i,s+i+c);if(s+=c+i,s>r.length)throw vl("Invalid address Uint8Array: "+K(r,"base16"));e.push([o,f]);let u=hi(o,f);if(t.push([o,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:xl(t),tuples:e,stringTuples:t,path:n}}function xl(r){let e=[];return r.map(t=>{let n=j(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),gi(e.join("/"))}function yi(r){return Ae(r.map(e=>{let t=j(e[0]),n=Uint8Array.from(Le(t.code));return e.length>1&&e[1]!=null&&(n=Ae([n,e[1]])),n}))}function jd(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=gt(e instanceof Uint8Array?e:Uint8Array.from(e));return t+ve(t)}}function gi(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function vl(r){return new Error("Error parsing address: "+r)}var Wd=Symbol.for("nodejs.util.inspect.custom"),bi=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Yd=[j("dns").code,j("dns4").code,j("dns6").code,j("dnsaddr").code],Is=class r{bytes;#e;#t;#r;#n;[bi]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=mi(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=wl(e)}else if(Bl(e))t=mi(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#r=t.stringTuples,this.#n=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,s,o="",i=j("tcp"),a=j("udp"),c=j("ip4"),f=j("ip6"),u=j("dns6"),l=j("ip6zone");for(let[b,p]of this.stringTuples())b===l.code&&(o=`%${p??""}`),Yd.includes(b)&&(t=i.name,s=443,n=`${p??""}${o}`,e=b===u.code?6:4),(b===i.code||b===a.code)&&(t=j(b).name,s=parseInt(p??"")),(b===c.code||b===f.code)&&(t=j(b).name,n=`${p??""}${o}`,e=b===f.code?6:4);if(e==null||t==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:e,host:n,transport:t,port:s}}protos(){return this.#t.map(([e])=>Object.assign({},j(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>j(e).name)}tuples(){return this.#t}stringTuples(){return this.#r}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,s))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(yi(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,s])=>{n===kr.p2p.code&&e.push([n,s]),n===kr["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?K(ne.decode(`z${n}`),"base58btc"):K(De.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(e){return de(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let n=El.get(t.name);if(n==null)throw new C(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(o=>new r(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[Wd](){return`Multiaddr(${this.#e})`}};var El=new Map;function Bl(r){return!!r?.[bi]}function Ft(r){return new Is(r)}var Al="libp2p-peer-record",Il=Uint8Array.from([3,1]);var tn;(function(r){let e;(function(n){let s;n.codec=()=>(s==null&&(s=Ge((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(o.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(o,i)=>{let a={multiaddr:new Uint8Array(0)},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let f=o.uint32();switch(f>>>3){case 1:a.multiaddr=o.bytes();break;default:o.skipType(f&7);break}}return a})),s),n.encode=o=>$e(o,n.codec()),n.decode=o=>qe(o,n.codec())})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ge((n,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(s.uint32(10),s.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(s.uint32(16),s.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)s.uint32(26),r.AddressInfo.codec().encode(i,s);o.lengthDelimited!==!1&&s.ldelim()},(n,s)=>{let o={peerId:new Uint8Array(0),seq:0n,addresses:[]},i=s==null?n.len:n.pos+s;for(;n.pos<i;){let a=n.uint32();switch(a>>>3){case 1:o.peerId=n.bytes();break;case 2:o.seq=n.uint64();break;case 3:o.addresses.push(r.AddressInfo.codec().decode(n,n.uint32()));break;default:n.skipType(a&7);break}}return o})),t),r.encode=n=>$e(n,r.codec()),r.decode=n=>qe(n,r.codec())})(tn||(tn={}));var Bt=class r{static createFromProtobuf=e=>{let t=tn.decode(e),n=ao(t.peerId),s=(t.addresses??[]).map(i=>Ft(i.multiaddr)),o=t.seq;return new r({peerId:n,multiaddrs:s,seqNumber:o})};static DOMAIN=Al;static CODEC=Il;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:s}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=s??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=tn.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!cl(this.multiaddrs,e.multiaddrs))}};var Zd=r=>r.toString().split("/").slice(1),rn=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),se=r=>({match:e=>rn(t=>t===r).match(e),pattern:r}),Ns=()=>({match:r=>rn(e=>typeof e=="string").match(r),pattern:"{string}"}),Sl=()=>({match:r=>rn(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Oe=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ne.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Ss=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Ys.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),nt=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),st=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),oe=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function fe(...r){function e(s){let o=Zd(s);for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matches:t,exactMatch:n}}var xi=oe(se("dns4"),Ns()),vi=oe(se("dns6"),Ns()),Ei=oe(se("dnsaddr"),Ns()),kl=oe(se("dns"),Ns()),aw=fe(xi),cw=fe(vi),lw=fe(Ei),uw=fe(st(kl,Ei,xi,vi)),Nl=oe(se("ip4"),rn(Es)),Rl=oe(se("ip6"),rn(Bs)),Tl=st(Nl,Rl),nn=st(Tl,kl,xi,vi,Ei),_l=fe(nn),fw=fe(Nl),hw=fe(Rl),dw=fe(Tl),Rs=oe(nn,se("tcp"),Sl()),sn=oe(nn,se("udp"),Sl()),Jd=st(Rs,sn),pw=fe(Rs),gw=fe(sn),Bi=oe(sn,se("quic")),Ts=oe(sn,se("quic-v1")),Xd=st(Bi,Ts),mw=fe(Bi),yw=fe(Ts),wi=st(nn,Rs,sn,Bi,Ts),Cl=st(oe(wi,se("ws"),nt(Oe()))),bw=fe(Cl),Ll=st(oe(wi,se("wss"),nt(Oe())),oe(wi,se("tls"),se("ws"),nt(Oe()))),ww=fe(Ll),Ul=oe(Jd,se("webrtc-direct"),Ss(),nt(Ss()),nt(Oe())),xw=fe(Ul),Pl=oe(Ts,se("webtransport"),Ss(),Ss(),nt(Oe())),vw=fe(Pl),ks=st(Cl,Ll,oe(Rs,nt(Oe())),oe(Xd,nt(Oe())),oe(nn,nt(Oe())),Ul,Pl,Oe()),Ew=fe(ks),Qd=oe(ks,se("p2p-circuit"),Oe()),Bw=fe(Qd),e0=st(oe(ks,se("p2p-circuit"),se("webrtc"),Oe()),oe(ks,se("webrtc"),nt(Oe())),se("webrtc")),Aw=fe(e0);function Nr(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var _s=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Ol(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new _s(t?.errorMessage,t?.errorCode));let n,s=new _s(t?.errorMessage,t?.errorCode);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Ai=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=Nr(),this.haveNext=Nr()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Nr(),e}async throw(e){return this.ended=!0,e!=null&&this.haveNext.reject(e),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");if(this.nextResult!=null&&(await this.readNext.promise,this.nextResult!=null))throw new Error("NeedNext promise resolved but nextResult was not consumed");e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Nr(),await Ol(this.readNext.promise,t?.signal,t)}};function Vl(){return new Ai}var Cs=class extends Error{code;constructor(e,t){super(e),this.code=t}},Ii=class extends Cs{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted"}};function Dl(r,e){let t=Vl();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let s=new Ye;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,f=new Promise((u,l)=>{c=()=>{l(new Ii("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:l,value:d}=await Promise.race([n.next(),f]);return l===!0?new Ye:d}for(;s.byteLength<i;){let{value:l,done:d}=await Promise.race([n.next(),f]);if(d===!0)throw new Cs("unexpected end of input","ERR_UNEXPECTED_EOF");s.append(l)}let u=s.sublist(0,i);return s.consume(i),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(s.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield s:yield*s,yield*i}()}return r}}}var Ls=class extends Error{code;constructor(e,t){super(e),this.code=t}};function Ml(r,e={}){let t=Dl(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=ve(e.maxDataLength));let n=e?.lengthDecoder??gt,s=e?.lengthEncoder??Le;return{read:async i=>{let a=-1,c=new Ye;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Ls("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Ls("message length too long","ERR_MSG_DATA_TOO_LONG");return t.read(a,i)},write:async(i,a)=>{await t.write(new Ye(s(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new Ye(...i.flatMap(f=>[s(f.byteLength),f]));await t.write(c,a)},unwrap:()=>t.unwrap()}}function on(r,e){let t=Ml(r,e),n={read:async(s,o)=>{let i=await t.read(o);return s.decode(i)},write:async(s,o,i)=>{await t.write(o.encode(s),i)},writeV:async(s,o,i)=>{await t.writeV(s.map(a=>o.encode(a)),i)},pb:s=>({read:async o=>n.read(s,o),write:async(o,i)=>n.write(o,s,i),writeV:async(o,i)=>n.writeV(o,s,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var Kl=Di(Fl(),1),Si=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,Us=(0,Kl.default)(),ql=Si&&!Us,$l=Us&&!Si,Gl=Us&&Si,zl=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!Us,jl=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,Fw=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+"_"+"ENV"]==="test",Wl=typeof navigator<"u"&&navigator.product==="ReactNative";var tr;(function(r){let e;r.codec=()=>(e==null&&(e=Ge((t,n,s={})=>{if(s.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let o of t.listenAddrs)n.uint32(18),n.bytes(o);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let o of t.protocols)n.uint32(26),n.string(o);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),s.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let s={listenAddrs:[],protocols:[]},o=n==null?t.len:t.pos+n;for(;t.pos<o;){let i=t.uint32();switch(i>>>3){case 5:s.protocolVersion=t.string();break;case 6:s.agentVersion=t.string();break;case 1:s.publicKey=t.bytes();break;case 2:s.listenAddrs.push(t.bytes());break;case 4:s.observedAddr=t.bytes();break;case 3:s.protocols.push(t.string());break;case 8:s.signedPeerRecord=t.bytes();break;default:t.skipType(i&7);break}}return s})),e),r.encode=t=>$e(t,r.codec()),r.decode=t=>qe(t,r.codec())})(tr||(tr={}));var ki=1024*8,Ve={protocolPrefix:"ipfs",timeout:6e4,maxInboundStreams:1,maxOutboundStreams:1,maxPushIncomingStreams:1,maxPushOutgoingStreams:1,maxObservedAddresses:10,maxIdentifyMessageSize:8192,runOnConnectionOpen:!0,runOnTransientConnection:!0},Ps=class{identifyProtocolStr;identifyPushProtocolStr;host;started;timeout;peerId;peerStore;registrar;connectionManager;addressManager;maxInboundStreams;maxOutboundStreams;maxPushIncomingStreams;maxPushOutgoingStreams;maxIdentifyMessageSize;maxObservedAddresses;events;runOnTransientConnection;log;constructor(e,t={}){this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.events=e.events,this.log=e.logger.forComponent("libp2p:identify"),this.identifyProtocolStr=`/${t.protocolPrefix??Ve.protocolPrefix}/${Ki}/${$i}`,this.identifyPushProtocolStr=`/${t.protocolPrefix??Ve.protocolPrefix}/${qi}/${Gi}`,this.timeout=t.timeout??Ve.timeout,this.maxInboundStreams=t.maxInboundStreams??Ve.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??Ve.maxOutboundStreams,this.maxPushIncomingStreams=t.maxPushIncomingStreams??Ve.maxPushIncomingStreams,this.maxPushOutgoingStreams=t.maxPushOutgoingStreams??Ve.maxPushOutgoingStreams,this.maxIdentifyMessageSize=t.maxIdentifyMessageSize??Ve.maxIdentifyMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??Ve.maxObservedAddresses,this.runOnTransientConnection=t.runOnTransientConnection??Ve.runOnTransientConnection,this.host={protocolVersion:`${t.protocolPrefix??Ve.protocolPrefix}/${Fi}`,agentVersion:t.agentVersion??`${e.nodeInfo.name}/${e.nodeInfo.version}`},(t.runOnConnectionOpen??Ve.runOnConnectionOpen)&&e.events.addEventListener("connection:open",n=>{let s=n.detail;this.identify(s).catch(o=>{this.log.error("error during identify trigged by connection:open",o)})}),e.events.addEventListener("self:peer:update",n=>{this.push().catch(s=>{this.log.error(s)})}),this.host.agentVersion===`${e.nodeInfo.name}/${e.nodeInfo.version}`&&(zl||$l?this.host.agentVersion+=` UserAgent=${globalThis.process.version}`:(ql||jl||Gl||Wl)&&(this.host.agentVersion+=` UserAgent=${globalThis.navigator.userAgent}`))}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:F(this.host.agentVersion),ProtocolVersion:F(this.host.protocolVersion)}}),await this.registrar.handle(this.identifyProtocolStr,e=>{this._handleIdentify(e).catch(t=>{this.log.error(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}),await this.registrar.handle(this.identifyPushProtocolStr,e=>{this._handlePush(e).catch(t=>{this.log.error(t)})},{maxInboundStreams:this.maxPushIncomingStreams,maxOutboundStreams:this.maxPushOutgoingStreams,runOnTransientConnection:this.runOnTransientConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.identifyProtocolStr),await this.registrar.unhandle(this.identifyPushProtocolStr),this.started=!1}async pushToConnections(e){let t=this.addressManager.getAddresses().map(u=>u.decapsulateCode(j("p2p").code)),n=new Bt({peerId:this.peerId,multiaddrs:t}),s=await Ht.seal(n,this.peerId),o=this.registrar.getProtocols(),i=await this.peerStore.get(this.peerId),a=K(i.metadata.get("AgentVersion")??F(this.host.agentVersion)),c=K(i.metadata.get("ProtocolVersion")??F(this.host.protocolVersion)),f=e.map(async u=>{let l,d=AbortSignal.timeout(this.timeout);cn(1/0,d);try{l=await u.newStream(this.identifyPushProtocolStr,{signal:d,runOnTransientConnection:this.runOnTransientConnection}),await on(l,{maxDataLength:this.maxIdentifyMessageSize??ki}).pb(tr).write({listenAddrs:t.map(p=>p.bytes),signedPeerRecord:s.marshal(),protocols:o,agentVersion:a,protocolVersion:c},{signal:d}),await l.close({signal:d})}catch(b){this.log.error("could not push identify update to peer",b),l?.abort(b)}});await Promise.all(f)}async push(){if(!this.isStarted())return;let e=[];await Promise.all(this.connectionManager.getConnections().map(async t=>{try{if(!(await this.peerStore.get(t.remotePeer)).protocols.includes(this.identifyPushProtocolStr))return;e.push(t)}catch(n){if(n.code!==ji)throw n}})),await this.pushToConnections(e)}async _identify(e,t={}){let n;if(t.signal==null){let s=AbortSignal.timeout(this.timeout);cn(1/0,s),t={...t,signal:s}}try{n=await e.newStream(this.identifyProtocolStr,{...t,runOnTransientConnection:this.runOnTransientConnection});let o=await on(n,{maxDataLength:this.maxIdentifyMessageSize??ki}).pb(tr).read(t);return await n.close(t),o}catch(s){throw this.log.error("error while reading identify message",s),n?.abort(s),s}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:s,protocols:o,observedAddr:i}=n;if(s==null)throw new C("public key was missing from identify message","ERR_MISSING_PUBLIC_KEY");let a=await Ur(s);if(!e.remotePeer.equals(a))throw new C("identified peer does not match the expected peer","ERR_INVALID_PEER");if(this.peerId.equals(a))throw new C("identified peer is our own peer id?","ERR_INVALID_PEER");let c=r0(i);return this.log("identify completed for peer %p and protocols %o",a,o),this.log("our observed address is %a",c),c!=null&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(this.log("storing our observed address %a",c),this.addressManager.addObservedAddr(c)),this.#e(e,n)}async _handleIdentify(e){let{connection:t,stream:n}=e,s=AbortSignal.timeout(this.timeout);cn(1/0,s);try{let o=this.peerId.publicKey??new Uint8Array(0),i=await this.peerStore.get(this.peerId),a=this.addressManager.getAddresses().map(l=>l.decapsulateCode(j("p2p").code)),c=i.peerRecordEnvelope;if(a.length>0&&c==null){let l=new Bt({peerId:this.peerId,multiaddrs:a});c=(await Ht.seal(l,this.peerId)).marshal().subarray()}let f=t.remoteAddr.bytes;_l.matches(t.remoteAddr)||(f=void 0),await on(n).pb(tr).write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:o,listenAddrs:a.map(l=>l.bytes),signedPeerRecord:c,observedAddr:f,protocols:i.protocols},{signal:s}),await n.close({signal:s})}catch(o){this.log.error("could not respond to identify request",o),n.abort(o)}}async _handlePush(e){let{connection:t,stream:n}=e;try{if(this.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");let s={signal:AbortSignal.timeout(this.timeout)},i=await on(n,{maxDataLength:this.maxIdentifyMessageSize??ki}).pb(tr).read(s);await n.close(s),await this.#e(t,i)}catch(s){this.log.error("received invalid message",s),n.abort(s);return}this.log("handled push from %p",t.remotePeer)}async#e(e,t){if(this.log("received identify from %p",e.remotePeer),t==null)throw new C("message was null or undefined","ERR_INVALID_MESSAGE");let n={};if(t.listenAddrs.length>0&&(n.addresses=t.listenAddrs.map(i=>({isCertified:!1,multiaddr:Ft(i)}))),t.protocols.length>0&&(n.protocols=t.protocols),t.publicKey!=null&&(n.publicKey=t.publicKey,!(await Ur(t.publicKey)).equals(e.remotePeer)))throw new C("public key did not match remote PeerId","ERR_INVALID_PUBLIC_KEY");let s;if(t.signedPeerRecord!=null){this.log("received signedPeerRecord from %p",e.remotePeer);let i=t.signedPeerRecord,a=await Ht.openAndCertify(i,Bt.DOMAIN),c=Bt.createFromProtobuf(a.payload);if(!c.peerId.equals(a.peerId))throw new C("signing key does not match PeerId in the PeerRecord","ERR_INVALID_SIGNING_KEY");if(!e.remotePeer.equals(c.peerId))throw new C("signing key does not match remote PeerId","ERR_INVALID_PEER_RECORD_KEY");let f;try{f=await this.peerStore.get(c.peerId)}catch(u){if(u.code!=="ERR_NOT_FOUND")throw u}if(f!=null&&(n.metadata=f.metadata,f.peerRecordEnvelope!=null)){let u=await Ht.createFromProtobuf(f.peerRecordEnvelope),l=Bt.createFromProtobuf(u.payload);l.seqNumber>=c.seqNumber&&(this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",l.seqNumber,c.seqNumber),c=l,i=f.peerRecordEnvelope)}n.peerRecordEnvelope=i,n.addresses=c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u})),s={seq:c.seqNumber,addresses:c.multiaddrs}}else this.log("%p did not send a signed peer record",e.remotePeer);if(this.log("patching %p with",e.remotePeer,n),await this.peerStore.patch(e.remotePeer,n),t.agentVersion!=null||t.protocolVersion!=null){let i={};t.agentVersion!=null&&(i.AgentVersion=F(t.agentVersion)),t.protocolVersion!=null&&(i.ProtocolVersion=F(t.protocolVersion)),this.log("merging %p metadata",e.remotePeer,i),await this.peerStore.merge(e.remotePeer,{metadata:i})}let o={peerId:e.remotePeer,protocolVersion:t.protocolVersion,agentVersion:t.agentVersion,publicKey:t.publicKey,listenAddrs:t.listenAddrs.map(i=>Ft(i)),observedAddr:t.observedAddr==null?void 0:Ft(t.observedAddr),protocols:t.protocols,signedPeerRecord:s,connection:e};return this.events.safeDispatchEvent("peer:identify",{detail:o}),o}};function r0(r){if(r!=null&&r.length>0)try{return Ft(r)}catch{}}var n0={IDENTIFY:Mi,IDENTIFY_PUSH:Hi};function s0(r={}){return e=>new Ps(e,r)}return cu(o0);})();
|
|
8
8
|
/*! Bundled license information:
|
|
9
9
|
|
|
10
10
|
pvtsutils/build/index.js:
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"Identify": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_identify.Identify.html",
|
|
3
|
+
".:Identify": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_identify.Identify.html",
|
|
4
|
+
"IdentifyComponents": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_identify.IdentifyComponents.html",
|
|
5
|
+
".:IdentifyComponents": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_identify.IdentifyComponents.html",
|
|
6
|
+
"IdentifyInit": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_identify.IdentifyInit.html",
|
|
7
|
+
".:IdentifyInit": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_identify.IdentifyInit.html",
|
|
8
|
+
"multicodecs": "https://libp2p.github.io/js-libp2p/variables/_libp2p_identify.multicodecs.html",
|
|
9
|
+
".:multicodecs": "https://libp2p.github.io/js-libp2p/variables/_libp2p_identify.multicodecs.html",
|
|
10
|
+
"identify": "https://libp2p.github.io/js-libp2p/functions/_libp2p_identify.identify-1.html",
|
|
11
|
+
".:identify": "https://libp2p.github.io/js-libp2p/functions/_libp2p_identify.identify-1.html"
|
|
12
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@libp2p/identify",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.13",
|
|
4
4
|
"description": "Implementation of the Identify Protocol",
|
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
|
6
6
|
"homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/protocol-identify#readme",
|
|
@@ -51,29 +51,29 @@
|
|
|
51
51
|
"dep-check": "aegir dep-check"
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
|
-
"@libp2p/interface": "1.1.
|
|
55
|
-
"@libp2p/interface-internal": "1.0.
|
|
56
|
-
"@libp2p/peer-id": "4.0.
|
|
57
|
-
"@libp2p/peer-record": "7.0.
|
|
58
|
-
"@multiformats/multiaddr": "^12.1.
|
|
59
|
-
"@multiformats/multiaddr-matcher": "^1.1.
|
|
60
|
-
"it-protobuf-stream": "^1.1.
|
|
61
|
-
"protons-runtime": "^5.
|
|
62
|
-
"uint8arraylist": "^2.4.
|
|
63
|
-
"uint8arrays": "^5.0.
|
|
54
|
+
"@libp2p/interface": "^1.1.3",
|
|
55
|
+
"@libp2p/interface-internal": "^1.0.8",
|
|
56
|
+
"@libp2p/peer-id": "^4.0.6",
|
|
57
|
+
"@libp2p/peer-record": "^7.0.8",
|
|
58
|
+
"@multiformats/multiaddr": "^12.1.14",
|
|
59
|
+
"@multiformats/multiaddr-matcher": "^1.1.2",
|
|
60
|
+
"it-protobuf-stream": "^1.1.2",
|
|
61
|
+
"protons-runtime": "^5.4.0",
|
|
62
|
+
"uint8arraylist": "^2.4.8",
|
|
63
|
+
"uint8arrays": "^5.0.1",
|
|
64
64
|
"wherearewe": "^2.0.1"
|
|
65
65
|
},
|
|
66
66
|
"devDependencies": {
|
|
67
|
-
"@libp2p/interface-compliance-tests": "5.
|
|
68
|
-
"@libp2p/logger": "4.0.
|
|
69
|
-
"@libp2p/peer-id-factory": "4.0.
|
|
70
|
-
"aegir": "^42.
|
|
67
|
+
"@libp2p/interface-compliance-tests": "^5.3.0",
|
|
68
|
+
"@libp2p/logger": "^4.0.6",
|
|
69
|
+
"@libp2p/peer-id-factory": "^4.0.6",
|
|
70
|
+
"aegir": "^42.2.3",
|
|
71
71
|
"delay": "^6.0.0",
|
|
72
72
|
"it-drain": "^3.0.5",
|
|
73
|
-
"it-length-prefixed": "^9.0.
|
|
73
|
+
"it-length-prefixed": "^9.0.4",
|
|
74
74
|
"it-pair": "^2.0.6",
|
|
75
|
-
"it-pushable": "^3.2.
|
|
76
|
-
"protons": "^7.
|
|
75
|
+
"it-pushable": "^3.2.3",
|
|
76
|
+
"protons": "^7.5.0",
|
|
77
77
|
"sinon-ts": "^2.0.0"
|
|
78
78
|
},
|
|
79
79
|
"sideEffects": false
|