nostr-double-ratchet 0.0.8 → 0.0.10

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.
@@ -1 +1 @@
1
- (function(H,J){typeof exports=="object"&&typeof module<"u"?J(exports):typeof define=="function"&&define.amd?define(["exports"],J):(H=typeof globalThis<"u"?globalThis:H||self,J(H["nostr-double-ratchet"]={}))})(this,function(H){"use strict";var Bc=Object.defineProperty;var Ic=(H,J,Ce)=>J in H?Bc(H,J,{enumerable:!0,configurable:!0,writable:!0,value:Ce}):H[J]=Ce;var re=(H,J,Ce)=>Ic(H,typeof J!="symbol"?J+"":J,Ce);function J(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function Ce(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function ci(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");J(e.outputLen),J(e.blockLen)}function rt(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function li(e,t){Ce(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const Ct=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const xn=e=>e instanceof Uint8Array,kt=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),ie=(e,t)=>e<<32-t|e>>>t;if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");function ui(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function Bt(e){if(typeof e=="string"&&(e=ui(e)),!xn(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}function fi(...e){const t=new Uint8Array(e.reduce((r,i)=>r+i.length,0));let n=0;return e.forEach(r=>{if(!xn(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}let Sn=class{clone(){return this._cloneInto()}};function hi(e){const t=r=>e().update(Bt(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function An(e=32){if(Ct&&typeof Ct.getRandomValues=="function")return Ct.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function di(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const i=BigInt(32),o=BigInt(4294967295),s=Number(n>>i&o),a=Number(n&o),c=r?4:0,l=r?0:4;e.setUint32(t+c,s,r),e.setUint32(t+l,a,r)}let yi=class extends Sn{constructor(t,n,r,i){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=kt(this.buffer)}update(t){rt(this);const{view:n,buffer:r,blockLen:i}=this;t=Bt(t);const o=t.length;for(let s=0;s<o;){const a=Math.min(i-this.pos,o-s);if(a===i){const c=kt(t);for(;i<=o-s;s+=i)this.process(c,s);continue}r.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){rt(this),li(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:o}=this;let{pos:s}=this;n[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>i-s&&(this.process(r,0),s=0);for(let u=s;u<i;u++)n[u]=0;di(r,i-8,BigInt(this.length*8),o),this.process(r,0);const a=kt(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,f=this.get();if(l>f.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,f[u],o)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:o,destroyed:s,pos:a}=this;return t.length=i,t.pos=a,t.finished=o,t.destroyed=s,i%n&&t.buffer.set(r),t}};const pi=(e,t,n)=>e&t^~e&n,gi=(e,t,n)=>e&t^e&n^t&n,wi=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ge=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),we=new Uint32Array(64);let bi=class extends yi{constructor(){super(64,32,8,!1),this.A=ge[0]|0,this.B=ge[1]|0,this.C=ge[2]|0,this.D=ge[3]|0,this.E=ge[4]|0,this.F=ge[5]|0,this.G=ge[6]|0,this.H=ge[7]|0}get(){const{A:t,B:n,C:r,D:i,E:o,F:s,G:a,H:c}=this;return[t,n,r,i,o,s,a,c]}set(t,n,r,i,o,s,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,n){for(let u=0;u<16;u++,n+=4)we[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const d=we[u-15],p=we[u-2],g=ie(d,7)^ie(d,18)^d>>>3,h=ie(p,17)^ie(p,19)^p>>>10;we[u]=h+we[u-7]+g+we[u-16]|0}let{A:r,B:i,C:o,D:s,E:a,F:c,G:l,H:f}=this;for(let u=0;u<64;u++){const d=ie(a,6)^ie(a,11)^ie(a,25),p=f+d+pi(a,c,l)+wi[u]+we[u]|0,h=(ie(r,2)^ie(r,13)^ie(r,22))+gi(r,i,o)|0;f=l,l=c,c=a,a=s+p|0,s=o,o=i,i=r,r=p+h|0}r=r+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,f=f+this.H|0,this.set(r,i,o,s,a,c,l,f)}roundClean(){we.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const It=hi(()=>new bi);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Kn=BigInt(0),it=BigInt(1),vi=BigInt(2),ot=e=>e instanceof Uint8Array,Ei=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Oe(e){if(!ot(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=Ei[e[n]];return t}function Nn(e){const t=e.toString(16);return t.length&1?`0${t}`:t}function Ut(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return BigInt(e===""?"0":`0x${e}`)}function Me(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);const t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(t/2);for(let r=0;r<n.length;r++){const i=r*2,o=e.slice(i,i+2),s=Number.parseInt(o,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");n[r]=s}return n}function Y(e){return Ut(Oe(e))}function _t(e){if(!ot(e))throw new Error("Uint8Array expected");return Ut(Oe(Uint8Array.from(e).reverse()))}function be(e,t){return Me(e.toString(16).padStart(t*2,"0"))}function Lt(e,t){return be(e,t).reverse()}function mi(e){return Me(Nn(e))}function F(e,t,n){let r;if(typeof t=="string")try{r=Me(t)}catch(o){throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${o}`)}else if(ot(t))r=Uint8Array.from(t);else throw new Error(`${e} must be hex string or Uint8Array`);const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(`${e} expected ${n} bytes, got ${i}`);return r}function ke(...e){const t=new Uint8Array(e.reduce((r,i)=>r+i.length,0));let n=0;return e.forEach(r=>{if(!ot(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}function xi(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Si(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function Ai(e){let t;for(t=0;e>Kn;e>>=it,t+=1);return t}function Ki(e,t){return e>>BigInt(t)&it}const Ni=(e,t,n)=>e|(n?it:Kn)<<BigInt(t),Tt=e=>(vi<<BigInt(e-1))-it,$t=e=>new Uint8Array(e),Cn=e=>Uint8Array.from(e);function kn(e,t,n){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=$t(e),i=$t(e),o=0;const s=()=>{r.fill(1),i.fill(0),o=0},a=(...u)=>n(i,r,...u),c=(u=$t())=>{i=a(Cn([0]),u),r=a(),u.length!==0&&(i=a(Cn([1]),u),r=a())},l=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let u=0;const d=[];for(;u<t;){r=a();const p=r.slice();d.push(p),u+=r.length}return ke(...d)};return(u,d)=>{s(),c(u);let p;for(;!(p=d(l()));)c();return s(),p}}const Ci={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||e instanceof Uint8Array,isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function We(e,t,n={}){const r=(i,o,s)=>{const a=Ci[o];if(typeof a!="function")throw new Error(`Invalid validator "${o}", expected function`);const c=e[i];if(!(s&&c===void 0)&&!a(c,e))throw new Error(`Invalid param ${String(i)}=${c} (${typeof c}), expected ${o}`)};for(const[i,o]of Object.entries(t))r(i,o,!1);for(const[i,o]of Object.entries(n))r(i,o,!0);return e}const ki=Object.freeze(Object.defineProperty({__proto__:null,bitGet:Ki,bitLen:Ai,bitMask:Tt,bitSet:Ni,bytesToHex:Oe,bytesToNumberBE:Y,bytesToNumberLE:_t,concatBytes:ke,createHmacDrbg:kn,ensureBytes:F,equalBytes:xi,hexToBytes:Me,hexToNumber:Ut,numberToBytesBE:be,numberToBytesLE:Lt,numberToHexUnpadded:Nn,numberToVarBytesBE:mi,utf8ToBytes:Si,validateObject:We},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const z=BigInt(0),D=BigInt(1),Be=BigInt(2),Bi=BigInt(3),Rt=BigInt(4),Bn=BigInt(5),In=BigInt(8);BigInt(9),BigInt(16);function Z(e,t){const n=e%t;return n>=z?n:t+n}function Ii(e,t,n){if(n<=z||t<z)throw new Error("Expected power/modulo > 0");if(n===D)return z;let r=D;for(;t>z;)t&D&&(r=r*e%n),e=e*e%n,t>>=D;return r}function X(e,t,n){let r=e;for(;t-- >z;)r*=r,r%=n;return r}function Ot(e,t){if(e===z||t<=z)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let n=Z(e,t),r=t,i=z,o=D;for(;n!==z;){const a=r/n,c=r%n,l=i-o*a;r=n,n=c,i=o,o=l}if(r!==D)throw new Error("invert: does not exist");return Z(i,t)}function Ui(e){const t=(e-D)/Be;let n,r,i;for(n=e-D,r=0;n%Be===z;n/=Be,r++);for(i=Be;i<e&&Ii(i,t,e)!==e-D;i++);if(r===1){const s=(e+D)/Rt;return function(c,l){const f=c.pow(l,s);if(!c.eql(c.sqr(f),l))throw new Error("Cannot find square root");return f}}const o=(n+D)/Be;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=r,f=a.pow(a.mul(a.ONE,i),n),u=a.pow(c,o),d=a.pow(c,n);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let p=1;for(let h=a.sqr(d);p<l&&!a.eql(h,a.ONE);p++)h=a.sqr(h);const g=a.pow(f,D<<BigInt(l-p-1));f=a.sqr(g),u=a.mul(u,g),d=a.mul(d,f),l=p}return u}}function _i(e){if(e%Rt===Bi){const t=(e+D)/Rt;return function(r,i){const o=r.pow(i,t);if(!r.eql(r.sqr(o),i))throw new Error("Cannot find square root");return o}}if(e%In===Bn){const t=(e-Bn)/In;return function(r,i){const o=r.mul(i,Be),s=r.pow(o,t),a=r.mul(i,s),c=r.mul(r.mul(a,Be),s),l=r.mul(a,r.sub(c,r.ONE));if(!r.eql(r.sqr(l),i))throw new Error("Cannot find square root");return l}}return Ui(e)}const Li=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ti(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=Li.reduce((r,i)=>(r[i]="function",r),t);return We(e,n)}function $i(e,t,n){if(n<z)throw new Error("Expected power > 0");if(n===z)return e.ONE;if(n===D)return t;let r=e.ONE,i=t;for(;n>z;)n&D&&(r=e.mul(r,i)),i=e.sqr(i),n>>=D;return r}function Ri(e,t){const n=new Array(t.length),r=t.reduce((o,s,a)=>e.is0(s)?o:(n[a]=o,e.mul(o,s)),e.ONE),i=e.inv(r);return t.reduceRight((o,s,a)=>e.is0(s)?o:(n[a]=e.mul(o,n[a]),e.mul(o,s)),i),n}function Un(e,t){const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Oi(e,t,n=!1,r={}){if(e<=z)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:i,nByteLength:o}=Un(e,t);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");const s=_i(e),a=Object.freeze({ORDER:e,BITS:i,BYTES:o,MASK:Tt(i),ZERO:z,ONE:D,create:c=>Z(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return z<=c&&c<e},is0:c=>c===z,isOdd:c=>(c&D)===D,neg:c=>Z(-c,e),eql:(c,l)=>c===l,sqr:c=>Z(c*c,e),add:(c,l)=>Z(c+l,e),sub:(c,l)=>Z(c-l,e),mul:(c,l)=>Z(c*l,e),pow:(c,l)=>$i(a,c,l),div:(c,l)=>Z(c*Ot(l,e),e),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Ot(c,e),sqrt:r.sqrt||(c=>s(a,c)),invertBatch:c=>Ri(a,c),cmov:(c,l,f)=>f?l:c,toBytes:c=>n?Lt(c,o):be(c,o),fromBytes:c=>{if(c.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${c.length}`);return n?_t(c):Y(c)}});return Object.freeze(a)}function _n(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Ln(e){const t=_n(e);return t+Math.ceil(t/2)}function Mi(e,t,n=!1){const r=e.length,i=_n(t),o=Ln(t);if(r<16||r<o||r>1024)throw new Error(`expected ${o}-1024 bytes of input, got ${r}`);const s=n?Y(e):_t(e),a=Z(s,t-D)+D;return n?Lt(a,i):be(a,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Pi=BigInt(0),Mt=BigInt(1);function Hi(e,t){const n=(i,o)=>{const s=o.negate();return i?s:o},r=i=>{const o=Math.ceil(t/i)+1,s=2**(i-1);return{windows:o,windowSize:s}};return{constTimeNegate:n,unsafeLadder(i,o){let s=e.ZERO,a=i;for(;o>Pi;)o&Mt&&(s=s.add(a)),a=a.double(),o>>=Mt;return s},precomputeWindow(i,o){const{windows:s,windowSize:a}=r(o),c=[];let l=i,f=l;for(let u=0;u<s;u++){f=l,c.push(f);for(let d=1;d<a;d++)f=f.add(l),c.push(f);l=f.double()}return c},wNAF(i,o,s){const{windows:a,windowSize:c}=r(i);let l=e.ZERO,f=e.BASE;const u=BigInt(2**i-1),d=2**i,p=BigInt(i);for(let g=0;g<a;g++){const h=g*c;let y=Number(s&u);s>>=p,y>c&&(y-=d,s+=Mt);const w=h,m=h+Math.abs(y)-1,K=g%2!==0,U=y<0;y===0?f=f.add(n(K,o[w])):l=l.add(n(U,o[m]))}return{p:l,f}},wNAFCached(i,o,s,a){const c=i._WINDOW_SIZE||1;let l=o.get(i);return l||(l=this.precomputeWindow(i,c),c!==1&&o.set(i,a(l))),this.wNAF(c,l,s)}}}function Tn(e){return Ti(e.Fp),We(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Un(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function qi(e){const t=Tn(e);We(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:n,Fp:r,a:i}=t;if(n){if(!r.eql(i,r.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof n!="object"||typeof n.beta!="bigint"||typeof n.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}const{bytesToNumberBE:Di,hexToBytes:ji}=ki,Ie={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(e){const{Err:t}=Ie;if(e.length<2||e[0]!==2)throw new t("Invalid signature integer tag");const n=e[1],r=e.subarray(2,n+2);if(!n||r.length!==n)throw new t("Invalid signature integer: wrong length");if(r[0]&128)throw new t("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return{d:Di(r),l:e.subarray(n+2)}},toSig(e){const{Err:t}=Ie,n=typeof e=="string"?ji(e):e;if(!(n instanceof Uint8Array))throw new Error("ui8a expected");let r=n.length;if(r<2||n[0]!=48)throw new t("Invalid signature tag");if(n[1]!==r-2)throw new t("Invalid signature: incorrect length");const{d:i,l:o}=Ie._parseInt(n.subarray(2)),{d:s,l:a}=Ie._parseInt(o);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:i,s}},hexFromSig(e){const t=l=>Number.parseInt(l[0],16)&8?"00"+l:l,n=l=>{const f=l.toString(16);return f.length&1?`0${f}`:f},r=t(n(e.s)),i=t(n(e.r)),o=r.length/2,s=i.length/2,a=n(o),c=n(s);return`30${n(s+o+4)}02${c}${i}02${a}${r}`}},ue=BigInt(0),Q=BigInt(1);BigInt(2);const $n=BigInt(3);BigInt(4);function Vi(e){const t=qi(e),{Fp:n}=t,r=t.toBytes||((g,h,y)=>{const w=h.toAffine();return ke(Uint8Array.from([4]),n.toBytes(w.x),n.toBytes(w.y))}),i=t.fromBytes||(g=>{const h=g.subarray(1),y=n.fromBytes(h.subarray(0,n.BYTES)),w=n.fromBytes(h.subarray(n.BYTES,2*n.BYTES));return{x:y,y:w}});function o(g){const{a:h,b:y}=t,w=n.sqr(g),m=n.mul(w,g);return n.add(n.add(m,n.mul(g,h)),y)}if(!n.eql(n.sqr(t.Gy),o(t.Gx)))throw new Error("bad generator point: equation left != right");function s(g){return typeof g=="bigint"&&ue<g&&g<t.n}function a(g){if(!s(g))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(g){const{allowedPrivateKeyLengths:h,nByteLength:y,wrapPrivateKey:w,n:m}=t;if(h&&typeof g!="bigint"){if(g instanceof Uint8Array&&(g=Oe(g)),typeof g!="string"||!h.includes(g.length))throw new Error("Invalid key");g=g.padStart(y*2,"0")}let K;try{K=typeof g=="bigint"?g:Y(F("private key",g,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof g}`)}return w&&(K=Z(K,m)),a(K),K}const l=new Map;function f(g){if(!(g instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(h,y,w){if(this.px=h,this.py=y,this.pz=w,h==null||!n.isValid(h))throw new Error("x required");if(y==null||!n.isValid(y))throw new Error("y required");if(w==null||!n.isValid(w))throw new Error("z required")}static fromAffine(h){const{x:y,y:w}=h||{};if(!h||!n.isValid(y)||!n.isValid(w))throw new Error("invalid affine point");if(h instanceof u)throw new Error("projective point not allowed");const m=K=>n.eql(K,n.ZERO);return m(y)&&m(w)?u.ZERO:new u(y,w,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){const y=n.invertBatch(h.map(w=>w.pz));return h.map((w,m)=>w.toAffine(y[m])).map(u.fromAffine)}static fromHex(h){const y=u.fromAffine(i(F("pointHex",h)));return y.assertValidity(),y}static fromPrivateKey(h){return u.BASE.multiply(c(h))}_setWindowSize(h){this._WINDOW_SIZE=h,l.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!n.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:h,y}=this.toAffine();if(!n.isValid(h)||!n.isValid(y))throw new Error("bad point: x or y not FE");const w=n.sqr(y),m=o(h);if(!n.eql(w,m))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:h}=this.toAffine();if(n.isOdd)return!n.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){f(h);const{px:y,py:w,pz:m}=this,{px:K,py:U,pz:k}=h,E=n.eql(n.mul(y,k),n.mul(K,m)),x=n.eql(n.mul(w,k),n.mul(U,m));return E&&x}negate(){return new u(this.px,n.neg(this.py),this.pz)}double(){const{a:h,b:y}=t,w=n.mul(y,$n),{px:m,py:K,pz:U}=this;let k=n.ZERO,E=n.ZERO,x=n.ZERO,S=n.mul(m,m),P=n.mul(K,K),I=n.mul(U,U),N=n.mul(m,K);return N=n.add(N,N),x=n.mul(m,U),x=n.add(x,x),k=n.mul(h,x),E=n.mul(w,I),E=n.add(k,E),k=n.sub(P,E),E=n.add(P,E),E=n.mul(k,E),k=n.mul(N,k),x=n.mul(w,x),I=n.mul(h,I),N=n.sub(S,I),N=n.mul(h,N),N=n.add(N,x),x=n.add(S,S),S=n.add(x,S),S=n.add(S,I),S=n.mul(S,N),E=n.add(E,S),I=n.mul(K,U),I=n.add(I,I),S=n.mul(I,N),k=n.sub(k,S),x=n.mul(I,P),x=n.add(x,x),x=n.add(x,x),new u(k,E,x)}add(h){f(h);const{px:y,py:w,pz:m}=this,{px:K,py:U,pz:k}=h;let E=n.ZERO,x=n.ZERO,S=n.ZERO;const P=t.a,I=n.mul(t.b,$n);let N=n.mul(y,K),$=n.mul(w,U),R=n.mul(m,k),q=n.add(y,w),b=n.add(K,U);q=n.mul(q,b),b=n.add(N,$),q=n.sub(q,b),b=n.add(y,m);let v=n.add(K,k);return b=n.mul(b,v),v=n.add(N,R),b=n.sub(b,v),v=n.add(w,m),E=n.add(U,k),v=n.mul(v,E),E=n.add($,R),v=n.sub(v,E),S=n.mul(P,b),E=n.mul(I,R),S=n.add(E,S),E=n.sub($,S),S=n.add($,S),x=n.mul(E,S),$=n.add(N,N),$=n.add($,N),R=n.mul(P,R),b=n.mul(I,b),$=n.add($,R),R=n.sub(N,R),R=n.mul(P,R),b=n.add(b,R),N=n.mul($,b),x=n.add(x,N),N=n.mul(v,b),E=n.mul(q,E),E=n.sub(E,N),N=n.mul(q,$),S=n.mul(v,S),S=n.add(S,N),new u(E,x,S)}subtract(h){return this.add(h.negate())}is0(){return this.equals(u.ZERO)}wNAF(h){return p.wNAFCached(this,l,h,y=>{const w=n.invertBatch(y.map(m=>m.pz));return y.map((m,K)=>m.toAffine(w[K])).map(u.fromAffine)})}multiplyUnsafe(h){const y=u.ZERO;if(h===ue)return y;if(a(h),h===Q)return this;const{endo:w}=t;if(!w)return p.unsafeLadder(this,h);let{k1neg:m,k1:K,k2neg:U,k2:k}=w.splitScalar(h),E=y,x=y,S=this;for(;K>ue||k>ue;)K&Q&&(E=E.add(S)),k&Q&&(x=x.add(S)),S=S.double(),K>>=Q,k>>=Q;return m&&(E=E.negate()),U&&(x=x.negate()),x=new u(n.mul(x.px,w.beta),x.py,x.pz),E.add(x)}multiply(h){a(h);let y=h,w,m;const{endo:K}=t;if(K){const{k1neg:U,k1:k,k2neg:E,k2:x}=K.splitScalar(y);let{p:S,f:P}=this.wNAF(k),{p:I,f:N}=this.wNAF(x);S=p.constTimeNegate(U,S),I=p.constTimeNegate(E,I),I=new u(n.mul(I.px,K.beta),I.py,I.pz),w=S.add(I),m=P.add(N)}else{const{p:U,f:k}=this.wNAF(y);w=U,m=k}return u.normalizeZ([w,m])[0]}multiplyAndAddUnsafe(h,y,w){const m=u.BASE,K=(k,E)=>E===ue||E===Q||!k.equals(m)?k.multiplyUnsafe(E):k.multiply(E),U=K(this,y).add(K(h,w));return U.is0()?void 0:U}toAffine(h){const{px:y,py:w,pz:m}=this,K=this.is0();h==null&&(h=K?n.ONE:n.inv(m));const U=n.mul(y,h),k=n.mul(w,h),E=n.mul(m,h);if(K)return{x:n.ZERO,y:n.ZERO};if(!n.eql(E,n.ONE))throw new Error("invZ was invalid");return{x:U,y:k}}isTorsionFree(){const{h,isTorsionFree:y}=t;if(h===Q)return!0;if(y)return y(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h,clearCofactor:y}=t;return h===Q?this:y?y(u,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return this.assertValidity(),r(u,this,h)}toHex(h=!0){return Oe(this.toRawBytes(h))}}u.BASE=new u(t.Gx,t.Gy,n.ONE),u.ZERO=new u(n.ZERO,n.ONE,n.ZERO);const d=t.nBitLength,p=Hi(u,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:u,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:s}}function zi(e){const t=Tn(e);return We(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Zi(e){const t=zi(e),{Fp:n,n:r}=t,i=n.BYTES+1,o=2*n.BYTES+1;function s(b){return ue<b&&b<n.ORDER}function a(b){return Z(b,r)}function c(b){return Ot(b,r)}const{ProjectivePoint:l,normPrivateKeyToScalar:f,weierstrassEquation:u,isWithinCurveOrder:d}=Vi({...t,toBytes(b,v,A){const B=v.toAffine(),C=n.toBytes(B.x),L=ke;return A?L(Uint8Array.from([v.hasEvenY()?2:3]),C):L(Uint8Array.from([4]),C,n.toBytes(B.y))},fromBytes(b){const v=b.length,A=b[0],B=b.subarray(1);if(v===i&&(A===2||A===3)){const C=Y(B);if(!s(C))throw new Error("Point is not on curve");const L=u(C);let O=n.sqrt(L);const T=(O&Q)===Q;return(A&1)===1!==T&&(O=n.neg(O)),{x:C,y:O}}else if(v===o&&A===4){const C=n.fromBytes(B.subarray(0,n.BYTES)),L=n.fromBytes(B.subarray(n.BYTES,2*n.BYTES));return{x:C,y:L}}else throw new Error(`Point of length ${v} was invalid. Expected ${i} compressed bytes or ${o} uncompressed bytes`)}}),p=b=>Oe(be(b,t.nByteLength));function g(b){const v=r>>Q;return b>v}function h(b){return g(b)?a(-b):b}const y=(b,v,A)=>Y(b.slice(v,A));class w{constructor(v,A,B){this.r=v,this.s=A,this.recovery=B,this.assertValidity()}static fromCompact(v){const A=t.nByteLength;return v=F("compactSignature",v,A*2),new w(y(v,0,A),y(v,A,2*A))}static fromDER(v){const{r:A,s:B}=Ie.toSig(F("DER",v));return new w(A,B)}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(v){return new w(this.r,this.s,v)}recoverPublicKey(v){const{r:A,s:B,recovery:C}=this,L=x(F("msgHash",v));if(C==null||![0,1,2,3].includes(C))throw new Error("recovery id invalid");const O=C===2||C===3?A+t.n:A;if(O>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const T=C&1?"03":"02",te=l.fromHex(T+p(O)),Ke=c(O),Ve=a(-L*Ke),nt=a(B*Ke),Ne=l.BASE.multiplyAndAddUnsafe(te,Ve,nt);if(!Ne)throw new Error("point at infinify");return Ne.assertValidity(),Ne}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return Me(this.toDERHex())}toDERHex(){return Ie.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Me(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const m={isValidPrivateKey(b){try{return f(b),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{const b=Ln(t.n);return Mi(t.randomBytes(b),t.n)},precompute(b=8,v=l.BASE){return v._setWindowSize(b),v.multiply(BigInt(3)),v}};function K(b,v=!0){return l.fromPrivateKey(b).toRawBytes(v)}function U(b){const v=b instanceof Uint8Array,A=typeof b=="string",B=(v||A)&&b.length;return v?B===i||B===o:A?B===2*i||B===2*o:b instanceof l}function k(b,v,A=!0){if(U(b))throw new Error("first arg must be private key");if(!U(v))throw new Error("second arg must be public key");return l.fromHex(v).multiply(f(b)).toRawBytes(A)}const E=t.bits2int||function(b){const v=Y(b),A=b.length*8-t.nBitLength;return A>0?v>>BigInt(A):v},x=t.bits2int_modN||function(b){return a(E(b))},S=Tt(t.nBitLength);function P(b){if(typeof b!="bigint")throw new Error("bigint expected");if(!(ue<=b&&b<S))throw new Error(`bigint expected < 2^${t.nBitLength}`);return be(b,t.nByteLength)}function I(b,v,A=N){if(["recovered","canonical"].some(Re=>Re in A))throw new Error("sign() legacy options not supported");const{hash:B,randomBytes:C}=t;let{lowS:L,prehash:O,extraEntropy:T}=A;L==null&&(L=!0),b=F("msgHash",b),O&&(b=F("prehashed msgHash",B(b)));const te=x(b),Ke=f(v),Ve=[P(Ke),P(te)];if(T!=null){const Re=T===!0?C(n.BYTES):T;Ve.push(F("extraEntropy",Re))}const nt=ke(...Ve),Ne=te;function mn(Re){const ze=E(Re);if(!d(ze))return;const oi=c(ze),Ze=l.BASE.multiply(ze).toAffine(),ne=a(Ze.x);if(ne===ue)return;const Fe=a(oi*a(Ne+ne*Ke));if(Fe===ue)return;let si=(Ze.x===ne?0:2)|Number(Ze.y&Q),ai=Fe;return L&&g(Fe)&&(ai=h(Fe),si^=1),new w(ne,ai,si)}return{seed:nt,k2sig:mn}}const N={lowS:t.lowS,prehash:!1},$={lowS:t.lowS,prehash:!1};function R(b,v,A=N){const{seed:B,k2sig:C}=I(b,v,A),L=t;return kn(L.hash.outputLen,L.nByteLength,L.hmac)(B,C)}l.BASE._setWindowSize(8);function q(b,v,A,B=$){var Ze;const C=b;if(v=F("msgHash",v),A=F("publicKey",A),"strict"in B)throw new Error("options.strict was renamed to lowS");const{lowS:L,prehash:O}=B;let T,te;try{if(typeof C=="string"||C instanceof Uint8Array)try{T=w.fromDER(C)}catch(ne){if(!(ne instanceof Ie.Err))throw ne;T=w.fromCompact(C)}else if(typeof C=="object"&&typeof C.r=="bigint"&&typeof C.s=="bigint"){const{r:ne,s:Fe}=C;T=new w(ne,Fe)}else throw new Error("PARSE");te=l.fromHex(A)}catch(ne){if(ne.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(L&&T.hasHighS())return!1;O&&(v=t.hash(v));const{r:Ke,s:Ve}=T,nt=x(v),Ne=c(Ve),mn=a(nt*Ne),Re=a(Ke*Ne),ze=(Ze=l.BASE.multiplyAndAddUnsafe(te,mn,Re))==null?void 0:Ze.toAffine();return ze?a(ze.x)===Ke:!1}return{CURVE:t,getPublicKey:K,getSharedSecret:k,sign:R,verify:q,ProjectivePoint:l,Signature:w,utils:m}}let Rn=class extends Sn{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,ci(t);const r=Bt(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,o=new Uint8Array(i);o.set(r.length>i?t.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),o.fill(0)}update(t){return rt(this),this.iHash.update(t),this}digestInto(t){rt(this),Ce(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return t=t,t.finished=i,t.destroyed=o,t.blockLen=s,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const On=(e,t,n)=>new Rn(e,t).update(n).digest();On.create=(e,t)=>new Rn(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Fi(e){return{hash:e,hmac:(t,...n)=>On(e,t,fi(...n)),randomBytes:An}}function Wi(e,t){const n=r=>Zi({...e,...Fi(r)});return Object.freeze({...n(t),create:n})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const st=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),at=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Mn=BigInt(1),ct=BigInt(2),Pn=(e,t)=>(e+t/ct)/t;function Hn(e){const t=st,n=BigInt(3),r=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,f=l*l*e%t,u=X(f,n,t)*f%t,d=X(u,n,t)*f%t,p=X(d,ct,t)*l%t,g=X(p,i,t)*p%t,h=X(g,o,t)*g%t,y=X(h,a,t)*h%t,w=X(y,c,t)*y%t,m=X(w,a,t)*h%t,K=X(m,n,t)*f%t,U=X(K,s,t)*g%t,k=X(U,r,t)*l%t,E=X(k,ct,t);if(!Pt.eql(Pt.sqr(E),e))throw new Error("Cannot find square root");return E}const Pt=Oi(st,void 0,void 0,{sqrt:Hn}),Ue=Wi({a:BigInt(0),b:BigInt(7),Fp:Pt,n:at,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=at,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Mn*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=n,s=BigInt("0x100000000000000000000000000000000"),a=Pn(o*e,t),c=Pn(-r*e,t);let l=Z(e-a*n-c*i,t),f=Z(-a*r-c*o,t);const u=l>s,d=f>s;if(u&&(l=t-l),d&&(f=t-f),l>s||f>s)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:u,k1:l,k2neg:d,k2:f}}}},It),lt=BigInt(0),qn=e=>typeof e=="bigint"&&lt<e&&e<st,Gi=e=>typeof e=="bigint"&&lt<e&&e<at,Dn={};function ut(e,...t){let n=Dn[e];if(n===void 0){const r=It(Uint8Array.from(e,i=>i.charCodeAt(0)));n=ke(r,r),Dn[e]=n}return It(ke(n,...t))}const Ht=e=>e.toRawBytes(!0).slice(1),qt=e=>be(e,32),Dt=e=>Z(e,st),Ge=e=>Z(e,at),jt=Ue.ProjectivePoint,Ji=(e,t,n)=>jt.BASE.multiplyAndAddUnsafe(e,t,n);function Vt(e){let t=Ue.utils.normPrivateKeyToScalar(e),n=jt.fromPrivateKey(t);return{scalar:n.hasEvenY()?t:Ge(-t),bytes:Ht(n)}}function jn(e){if(!qn(e))throw new Error("bad x: need 0 < x < p");const t=Dt(e*e),n=Dt(t*e+BigInt(7));let r=Hn(n);r%ct!==lt&&(r=Dt(-r));const i=new jt(e,r,Mn);return i.assertValidity(),i}function Vn(...e){return Ge(Y(ut("BIP0340/challenge",...e)))}function Yi(e){return Vt(e).bytes}function Xi(e,t,n=An(32)){const r=F("message",e),{bytes:i,scalar:o}=Vt(t),s=F("auxRand",n,32),a=qt(o^Y(ut("BIP0340/aux",s))),c=ut("BIP0340/nonce",a,i,r),l=Ge(Y(c));if(l===lt)throw new Error("sign failed: k is zero");const{bytes:f,scalar:u}=Vt(l),d=Vn(f,i,r),p=new Uint8Array(64);if(p.set(f,0),p.set(qt(Ge(u+d*o)),32),!zn(p,r,i))throw new Error("sign: Invalid signature produced");return p}function zn(e,t,n){const r=F("signature",e,64),i=F("message",t),o=F("publicKey",n,32);try{const s=jn(Y(o)),a=Y(r.subarray(0,32));if(!qn(a))return!1;const c=Y(r.subarray(32,64));if(!Gi(c))return!1;const l=Vn(qt(a),Ht(s),i),f=Ji(s,c,Ge(-l));return!(!f||!f.hasEvenY()||f.toAffine().x!==a)}catch{return!1}}const Je={getPublicKey:Yi,sign:Xi,verify:zn,utils:{randomPrivateKey:Ue.utils.randomPrivateKey,lift_x:jn,pointToBytes:Ht,numberToBytesBE:be,bytesToNumberBE:Y,taggedHash:ut,mod:Z}},zt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Zt=e=>e instanceof Uint8Array,Ft=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),oe=(e,t)=>e<<32-t|e>>>t;if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");const Qi=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function M(e){if(!Zt(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=Qi[e[n]];return t}function G(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);const t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(t/2);for(let r=0;r<n.length;r++){const i=r*2,o=e.slice(i,i+2),s=Number.parseInt(o,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");n[r]=s}return n}function eo(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function Ye(e){if(typeof e=="string"&&(e=eo(e)),!Zt(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}function ft(...e){const t=new Uint8Array(e.reduce((r,i)=>r+i.length,0));let n=0;return e.forEach(r=>{if(!Zt(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}class Zn{clone(){return this._cloneInto()}}function Fn(e){const t=r=>e().update(Ye(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Wn(e=32){if(zt&&typeof zt.getRandomValues=="function")return zt.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function Wt(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function to(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}function Gn(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function no(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Wt(e.outputLen),Wt(e.blockLen)}function ro(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function io(e,t){Gn(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const se={number:Wt,bool:to,bytes:Gn,hash:no,exists:ro,output:io};function oo(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const i=BigInt(32),o=BigInt(4294967295),s=Number(n>>i&o),a=Number(n&o),c=r?4:0,l=r?0:4;e.setUint32(t+c,s,r),e.setUint32(t+l,a,r)}class so extends Zn{constructor(t,n,r,i){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Ft(this.buffer)}update(t){se.exists(this);const{view:n,buffer:r,blockLen:i}=this;t=Ye(t);const o=t.length;for(let s=0;s<o;){const a=Math.min(i-this.pos,o-s);if(a===i){const c=Ft(t);for(;i<=o-s;s+=i)this.process(c,s);continue}r.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){se.exists(this),se.output(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:o}=this;let{pos:s}=this;n[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>i-s&&(this.process(r,0),s=0);for(let u=s;u<i;u++)n[u]=0;oo(r,i-8,BigInt(this.length*8),o),this.process(r,0);const a=Ft(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,f=this.get();if(l>f.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,f[u],o)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:o,destroyed:s,pos:a}=this;return t.length=i,t.pos=a,t.finished=o,t.destroyed=s,i%n&&t.buffer.set(r),t}}const ao=(e,t,n)=>e&t^~e&n,co=(e,t,n)=>e&t^e&n^t&n,lo=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]),ve=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ee=new Uint32Array(64);class Jn extends so{constructor(){super(64,32,8,!1),this.A=ve[0]|0,this.B=ve[1]|0,this.C=ve[2]|0,this.D=ve[3]|0,this.E=ve[4]|0,this.F=ve[5]|0,this.G=ve[6]|0,this.H=ve[7]|0}get(){const{A:t,B:n,C:r,D:i,E:o,F:s,G:a,H:c}=this;return[t,n,r,i,o,s,a,c]}set(t,n,r,i,o,s,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,n){for(let u=0;u<16;u++,n+=4)Ee[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const d=Ee[u-15],p=Ee[u-2],g=oe(d,7)^oe(d,18)^d>>>3,h=oe(p,17)^oe(p,19)^p>>>10;Ee[u]=h+Ee[u-7]+g+Ee[u-16]|0}let{A:r,B:i,C:o,D:s,E:a,F:c,G:l,H:f}=this;for(let u=0;u<64;u++){const d=oe(a,6)^oe(a,11)^oe(a,25),p=f+d+ao(a,c,l)+lo[u]+Ee[u]|0,h=(oe(r,2)^oe(r,13)^oe(r,22))+co(r,i,o)|0;f=l,l=c,c=a,a=s+p|0,s=o,o=i,i=r,r=p+h|0}r=r+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,f=f+this.H|0,this.set(r,i,o,s,a,c,l,f)}roundClean(){Ee.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class uo extends Jn{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const me=Fn(()=>new Jn);Fn(()=>new uo);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Pe(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function fe(...e){const t=(i,o)=>s=>i(o(s)),n=Array.from(e).reverse().reduce((i,o)=>i?t(i,o.encode):o.encode,void 0),r=e.reduce((i,o)=>i?t(i,o.decode):o.decode,void 0);return{encode:n,decode:r}}function he(e){return{encode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return t.map(n=>{if(Pe(n),n<0||n>=e.length)throw new Error(`Digit index outside alphabet: ${n} (alphabet: ${e.length})`);return e[n]})},decode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("alphabet.decode input should be array of strings");return t.map(n=>{if(typeof n!="string")throw new Error(`alphabet.decode: not string element=${n}`);const r=e.indexOf(n);if(r===-1)throw new Error(`Unknown letter: "${n}". Allowed: ${e}`);return r})}}}function de(e=""){if(typeof e!="string")throw new Error("join separator should be string");return{encode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("join.encode input should be array of strings");for(let n of t)if(typeof n!="string")throw new Error(`join.encode: non-string input=${n}`);return t.join(e)},decode:t=>{if(typeof t!="string")throw new Error("join.decode input should be string");return t.split(e)}}}function ht(e,t="="){if(Pe(e),typeof t!="string")throw new Error("padding chr should be string");return{encode(n){if(!Array.isArray(n)||n.length&&typeof n[0]!="string")throw new Error("padding.encode input should be array of strings");for(let r of n)if(typeof r!="string")throw new Error(`padding.encode: non-string input=${r}`);for(;n.length*e%8;)n.push(t);return n},decode(n){if(!Array.isArray(n)||n.length&&typeof n[0]!="string")throw new Error("padding.encode input should be array of strings");for(let i of n)if(typeof i!="string")throw new Error(`padding.decode: non-string input=${i}`);let r=n.length;if(r*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;r>0&&n[r-1]===t;r--)if(!((r-1)*e%8))throw new Error("Invalid padding: string has too much padding");return n.slice(0,r)}}}function Yn(e){if(typeof e!="function")throw new Error("normalize fn should be function");return{encode:t=>t,decode:t=>e(t)}}function Xn(e,t,n){if(t<2)throw new Error(`convertRadix: wrong from=${t}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let r=0;const i=[],o=Array.from(e);for(o.forEach(s=>{if(Pe(s),s<0||s>=t)throw new Error(`Wrong integer: ${s}`)});;){let s=0,a=!0;for(let c=r;c<o.length;c++){const l=o[c],f=t*s+l;if(!Number.isSafeInteger(f)||t*s/t!==s||f-l!==t*s)throw new Error("convertRadix: carry overflow");if(s=f%n,o[c]=Math.floor(f/n),!Number.isSafeInteger(o[c])||o[c]*n+s!==f)throw new Error("convertRadix: carry overflow");if(a)o[c]?a=!1:r=c;else continue}if(i.push(s),a)break}for(let s=0;s<e.length-1&&e[s]===0;s++)i.push(0);return i.reverse()}const Qn=(e,t)=>t?Qn(t,e%t):e,dt=(e,t)=>e+(t-Qn(e,t));function Gt(e,t,n,r){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(dt(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${dt(t,n)}`);let i=0,o=0;const s=2**n-1,a=[];for(const c of e){if(Pe(c),c>=2**t)throw new Error(`convertRadix2: invalid data word=${c} from=${t}`);if(i=i<<t|c,o+t>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${t}`);for(o+=t;o>=n;o-=n)a.push((i>>o-n&s)>>>0);i&=2**o-1}if(i=i<<n-o&s,!r&&o>=t)throw new Error("Excess padding");if(!r&&i)throw new Error(`Non-zero padding: ${i}`);return r&&o>0&&a.push(i>>>0),a}function fo(e){return Pe(e),{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return Xn(Array.from(t),2**8,e)},decode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="number")throw new Error("radix.decode input should be array of strings");return Uint8Array.from(Xn(t,e,2**8))}}}function xe(e,t=!1){if(Pe(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(dt(8,e)>32||dt(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!(n instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return Gt(Array.from(n),8,e,!t)},decode:n=>{if(!Array.isArray(n)||n.length&&typeof n[0]!="number")throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(Gt(n,e,8,t))}}}function er(e){if(typeof e!="function")throw new Error("unsafeWrapper fn should be function");return function(...t){try{return e.apply(null,t)}catch{}}}const ho=fe(xe(4),he("0123456789ABCDEF"),de("")),yo=fe(xe(5),he("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),ht(5),de(""));fe(xe(5),he("0123456789ABCDEFGHIJKLMNOPQRSTUV"),ht(5),de("")),fe(xe(5),he("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),de(""),Yn(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const ye=fe(xe(6),he("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),ht(6),de("")),po=fe(xe(6),he("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),ht(6),de("")),Jt=e=>fe(fo(58),he(e),de("")),Yt=Jt("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");Jt("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),Jt("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const tr=[0,2,3,5,6,7,9,10,11],go={encode(e){let t="";for(let n=0;n<e.length;n+=8){const r=e.subarray(n,n+8);t+=Yt.encode(r).padStart(tr[r.length],"1")}return t},decode(e){let t=[];for(let n=0;n<e.length;n+=11){const r=e.slice(n,n+11),i=tr.indexOf(r.length),o=Yt.decode(r);for(let s=0;s<o.length-i;s++)if(o[s]!==0)throw new Error("base58xmr: wrong padding");t=t.concat(Array.from(o.slice(o.length-i)))}return Uint8Array.from(t)}},Xt=fe(he("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),de("")),nr=[996825010,642813549,513874426,1027748829,705979059];function Xe(e){const t=e>>25;let n=(e&33554431)<<5;for(let r=0;r<nr.length;r++)(t>>r&1)===1&&(n^=nr[r]);return n}function rr(e,t,n=1){const r=e.length;let i=1;for(let o=0;o<r;o++){const s=e.charCodeAt(o);if(s<33||s>126)throw new Error(`Invalid prefix (${e})`);i=Xe(i)^s>>5}i=Xe(i);for(let o=0;o<r;o++)i=Xe(i)^e.charCodeAt(o)&31;for(let o of t)i=Xe(i)^o;for(let o=0;o<6;o++)i=Xe(i);return i^=n,Xt.encode(Gt([i%2**30],30,5,!1))}function ir(e){const t=e==="bech32"?1:734539939,n=xe(5),r=n.decode,i=n.encode,o=er(r);function s(f,u,d=90){if(typeof f!="string")throw new Error(`bech32.encode prefix should be string, not ${typeof f}`);if(!Array.isArray(u)||u.length&&typeof u[0]!="number")throw new Error(`bech32.encode words should be array of numbers, not ${typeof u}`);const p=f.length+7+u.length;if(d!==!1&&p>d)throw new TypeError(`Length ${p} exceeds limit ${d}`);return f=f.toLowerCase(),`${f}1${Xt.encode(u)}${rr(f,u,t)}`}function a(f,u=90){if(typeof f!="string")throw new Error(`bech32.decode input should be string, not ${typeof f}`);if(f.length<8||u!==!1&&f.length>u)throw new TypeError(`Wrong string length: ${f.length} (${f}). Expected (8..${u})`);const d=f.toLowerCase();if(f!==d&&f!==f.toUpperCase())throw new Error("String must be lowercase or uppercase");f=d;const p=f.lastIndexOf("1");if(p===0||p===-1)throw new Error('Letter "1" must be present between prefix and data only');const g=f.slice(0,p),h=f.slice(p+1);if(h.length<6)throw new Error("Data must be at least 6 characters long");const y=Xt.decode(h).slice(0,-6),w=rr(g,y,t);if(!h.endsWith(w))throw new Error(`Invalid checksum in ${f}: expected "${w}"`);return{prefix:g,words:y}}const c=er(a);function l(f){const{prefix:u,words:d}=a(f,!1);return{prefix:u,words:d,bytes:r(d)}}return{encode:s,decode:a,decodeToBytes:l,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:o,toWords:i}}const He=ir("bech32");ir("bech32m");const wo={encode:e=>new TextDecoder().decode(e),decode:e=>new TextEncoder().encode(e)},bo=fe(xe(4),he("0123456789abcdef"),de(""),Yn(e=>{if(typeof e!="string"||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));`${Object.keys({utf8:wo,hex:bo,base16:ho,base32:yo,base64:ye,base64url:po,base58:Yt,base58xmr:go}).join(", ")}`;function Qt(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function or(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function vo(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}function pe(e,...t){if(!vo(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */const W=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");function Eo(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function mo(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}const xo=(e,t)=>(Object.assign(t,e),t),Se=16,So=283;function en(e){return e<<1^So&-(e>>7)}function qe(e,t){let n=0;for(;t>0;t>>=1)n^=e&-(t&1),e=en(e);return n}const tn=(()=>{let e=new Uint8Array(256);for(let n=0,r=1;n<256;n++,r^=en(r))e[n]=r;const t=new Uint8Array(256);t[0]=99;for(let n=0;n<255;n++){let r=e[255-n];r|=r<<8,t[e[n]]=(r^r>>4^r>>5^r>>6^r>>7^99)&255}return t})(),Ao=tn.map((e,t)=>tn.indexOf(t)),Ko=e=>e<<24|e>>>8,nn=e=>e<<8|e>>>24;function sr(e,t){if(e.length!==256)throw new Error("Wrong sbox length");const n=new Uint32Array(256).map((l,f)=>t(e[f])),r=n.map(nn),i=r.map(nn),o=i.map(nn),s=new Uint32Array(256*256),a=new Uint32Array(256*256),c=new Uint16Array(256*256);for(let l=0;l<256;l++)for(let f=0;f<256;f++){const u=l*256+f;s[u]=n[l]^r[f],a[u]=i[l]^o[f],c[u]=e[l]<<8|e[f]}return{sbox:e,sbox2:c,T0:n,T1:r,T2:i,T3:o,T01:s,T23:a}}const rn=sr(tn,e=>qe(e,3)<<24|e<<16|e<<8|qe(e,2)),ar=sr(Ao,e=>qe(e,11)<<24|qe(e,13)<<16|qe(e,9)<<8|qe(e,14)),No=(()=>{const e=new Uint8Array(16);for(let t=0,n=1;t<16;t++,n=en(n))e[t]=n;return e})();function cr(e){pe(e);const t=e.length;if(![16,24,32].includes(t))throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${t}`);const{sbox2:n}=rn,r=W(e),i=r.length,o=a=>ae(n,a,a,a,a),s=new Uint32Array(t+28);s.set(r);for(let a=i;a<s.length;a++){let c=s[a-1];a%i===0?c=o(Ko(c))^No[a/i-1]:i>6&&a%i===4&&(c=o(c)),s[a]=s[a-i]^c}return s}function Co(e){const t=cr(e),n=t.slice(),r=t.length,{sbox2:i}=rn,{T0:o,T1:s,T2:a,T3:c}=ar;for(let l=0;l<r;l+=4)for(let f=0;f<4;f++)n[l+f]=t[r-l-4+f];t.fill(0);for(let l=4;l<r-4;l++){const f=n[l],u=ae(i,f,f,f,f);n[l]=o[u&255]^s[u>>>8&255]^a[u>>>16&255]^c[u>>>24]}return n}function Ae(e,t,n,r,i,o){return e[n<<8&65280|r>>>8&255]^t[i>>>8&65280|o>>>24&255]}function ae(e,t,n,r,i){return e[t&255|n&65280]|e[r>>>16&255|i>>>16&65280]<<16}function lr(e,t,n,r,i){const{sbox2:o,T01:s,T23:a}=rn;let c=0;t^=e[c++],n^=e[c++],r^=e[c++],i^=e[c++];const l=e.length/4-2;for(let g=0;g<l;g++){const h=e[c++]^Ae(s,a,t,n,r,i),y=e[c++]^Ae(s,a,n,r,i,t),w=e[c++]^Ae(s,a,r,i,t,n),m=e[c++]^Ae(s,a,i,t,n,r);t=h,n=y,r=w,i=m}const f=e[c++]^ae(o,t,n,r,i),u=e[c++]^ae(o,n,r,i,t),d=e[c++]^ae(o,r,i,t,n),p=e[c++]^ae(o,i,t,n,r);return{s0:f,s1:u,s2:d,s3:p}}function ko(e,t,n,r,i){const{sbox2:o,T01:s,T23:a}=ar;let c=0;t^=e[c++],n^=e[c++],r^=e[c++],i^=e[c++];const l=e.length/4-2;for(let g=0;g<l;g++){const h=e[c++]^Ae(s,a,t,i,r,n),y=e[c++]^Ae(s,a,n,t,i,r),w=e[c++]^Ae(s,a,r,n,t,i),m=e[c++]^Ae(s,a,i,r,n,t);t=h,n=y,r=w,i=m}const f=e[c++]^ae(o,t,i,r,n),u=e[c++]^ae(o,n,t,i,r),d=e[c++]^ae(o,r,n,t,i),p=e[c++]^ae(o,i,r,n,t);return{s0:f,s1:u,s2:d,s3:p}}function ur(e,t){if(!t)return new Uint8Array(e);if(pe(t),t.length<e)throw new Error(`aes: wrong destination length, expected at least ${e}, got: ${t.length}`);return t}function Bo(e){if(pe(e),e.length%Se!==0)throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${Se}`)}function Io(e,t,n){let r=e.length;const i=r%Se;if(!t&&i!==0)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");const o=W(e);if(t){let c=Se-i;c||(c=Se),r=r+c}const s=ur(r,n),a=W(s);return{b:o,o:a,out:s}}function Uo(e,t){if(!t)return e;const n=e.length;if(!n)throw new Error("aes/pcks5: empty ciphertext not allowed");const r=e[n-1];if(r<=0||r>16)throw new Error(`aes/pcks5: wrong padding byte: ${r}`);const i=e.subarray(0,-r);for(let o=0;o<r;o++)if(e[n-o-1]!==r)throw new Error("aes/pcks5: wrong padding");return i}function _o(e){const t=new Uint8Array(16),n=W(t);t.set(e);const r=Se-e.length;for(let i=Se-r;i<Se;i++)t[i]=r;return n}const fr=xo({blockSize:16,nonceLength:16},function(t,n,r={}){pe(t),pe(n,16);const i=!r.disablePadding;return{encrypt:(o,s)=>{const a=cr(t),{b:c,o:l,out:f}=Io(o,i,s),u=W(n);let d=u[0],p=u[1],g=u[2],h=u[3],y=0;for(;y+4<=c.length;)d^=c[y+0],p^=c[y+1],g^=c[y+2],h^=c[y+3],{s0:d,s1:p,s2:g,s3:h}=lr(a,d,p,g,h),l[y++]=d,l[y++]=p,l[y++]=g,l[y++]=h;if(i){const w=_o(o.subarray(y*4));d^=w[0],p^=w[1],g^=w[2],h^=w[3],{s0:d,s1:p,s2:g,s3:h}=lr(a,d,p,g,h),l[y++]=d,l[y++]=p,l[y++]=g,l[y++]=h}return a.fill(0),f},decrypt:(o,s)=>{Bo(o);const a=Co(t),c=W(n),l=ur(o.length,s),f=W(o),u=W(l);let d=c[0],p=c[1],g=c[2],h=c[3];for(let y=0;y+4<=f.length;){const w=d,m=p,K=g,U=h;d=f[y+0],p=f[y+1],g=f[y+2],h=f[y+3];const{s0:k,s1:E,s2:x,s3:S}=ko(a,d,p,g,h);u[y++]=k^w,u[y++]=E^m,u[y++]=x^K,u[y++]=S^U}return a.fill(0),Uo(l,i)}}}),hr=e=>Uint8Array.from(e.split("").map(t=>t.charCodeAt(0))),Lo=hr("expand 16-byte k"),To=hr("expand 32-byte k"),$o=W(Lo),dr=W(To);dr.slice();function _(e,t){return e<<t|e>>>32-t}function on(e){return e.byteOffset%4===0}const yt=64,Ro=16,yr=2**32-1,pr=new Uint32Array;function Oo(e,t,n,r,i,o,s,a){const c=i.length,l=new Uint8Array(yt),f=W(l),u=on(i)&&on(o),d=u?W(i):pr,p=u?W(o):pr;for(let g=0;g<c;s++){if(e(t,n,r,f,s,a),s>=yr)throw new Error("arx: counter overflow");const h=Math.min(yt,c-g);if(u&&h===yt){const y=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,m;w<Ro;w++)m=y+w,p[m]=d[m]^f[w];g+=yt;continue}for(let y=0,w;y<h;y++)w=g+y,o[w]=i[w]^l[y];g+=h}}function Mo(e,t){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:o,rounds:s}=Eo({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return Qt(i),Qt(s),or(o),or(n),(a,c,l,f,u=0)=>{pe(a),pe(c),pe(l);const d=l.length;if(f||(f=new Uint8Array(d)),pe(f),Qt(u),u<0||u>=yr)throw new Error("arx: counter overflow");if(f.length<d)throw new Error(`arx: output (${f.length}) is shorter than data (${d})`);const p=[];let g=a.length,h,y;if(g===32)h=a.slice(),p.push(h),y=dr;else if(g===16&&n)h=new Uint8Array(32),h.set(a),h.set(a,16),y=$o,p.push(h);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);on(c)||(c=c.slice(),p.push(c));const w=W(h);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(y,w,W(c.subarray(0,16)),w),c=c.subarray(16)}const m=16-i;if(m!==c.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(m!==12){const U=new Uint8Array(12);U.set(c,o?0:12-c.length),c=U,p.push(c)}const K=W(c);for(Oo(e,y,w,K,l,f,u,s);p.length>0;)p.pop().fill(0);return f}}function Po(e,t,n,r,i,o=20){let s=e[0],a=e[1],c=e[2],l=e[3],f=t[0],u=t[1],d=t[2],p=t[3],g=t[4],h=t[5],y=t[6],w=t[7],m=i,K=n[0],U=n[1],k=n[2],E=s,x=a,S=c,P=l,I=f,N=u,$=d,R=p,q=g,b=h,v=y,A=w,B=m,C=K,L=U,O=k;for(let te=0;te<o;te+=2)E=E+I|0,B=_(B^E,16),q=q+B|0,I=_(I^q,12),E=E+I|0,B=_(B^E,8),q=q+B|0,I=_(I^q,7),x=x+N|0,C=_(C^x,16),b=b+C|0,N=_(N^b,12),x=x+N|0,C=_(C^x,8),b=b+C|0,N=_(N^b,7),S=S+$|0,L=_(L^S,16),v=v+L|0,$=_($^v,12),S=S+$|0,L=_(L^S,8),v=v+L|0,$=_($^v,7),P=P+R|0,O=_(O^P,16),A=A+O|0,R=_(R^A,12),P=P+R|0,O=_(O^P,8),A=A+O|0,R=_(R^A,7),E=E+N|0,O=_(O^E,16),v=v+O|0,N=_(N^v,12),E=E+N|0,O=_(O^E,8),v=v+O|0,N=_(N^v,7),x=x+$|0,B=_(B^x,16),A=A+B|0,$=_($^A,12),x=x+$|0,B=_(B^x,8),A=A+B|0,$=_($^A,7),S=S+R|0,C=_(C^S,16),q=q+C|0,R=_(R^q,12),S=S+R|0,C=_(C^S,8),q=q+C|0,R=_(R^q,7),P=P+I|0,L=_(L^P,16),b=b+L|0,I=_(I^b,12),P=P+I|0,L=_(L^P,8),b=b+L|0,I=_(I^b,7);let T=0;r[T++]=s+E|0,r[T++]=a+x|0,r[T++]=c+S|0,r[T++]=l+P|0,r[T++]=f+I|0,r[T++]=u+N|0,r[T++]=d+$|0,r[T++]=p+R|0,r[T++]=g+q|0,r[T++]=h+b|0,r[T++]=y+v|0,r[T++]=w+A|0,r[T++]=m+B|0,r[T++]=K+C|0,r[T++]=U+L|0,r[T++]=k+O|0}const gr=Mo(Po,{counterRight:!1,counterLength:4,allowShortKeys:!1});class wr extends Zn{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,se.hash(t);const r=Ye(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,o=new Uint8Array(i);o.set(r.length>i?t.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),o.fill(0)}update(t){return se.exists(this),this.iHash.update(t),this}digestInto(t){se.exists(this),se.bytes(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return t=t,t.finished=i,t.destroyed=o,t.blockLen=s,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const pt=(e,t,n)=>new wr(e,t).update(n).digest();pt.create=(e,t)=>new wr(e,t);function sn(e,t,n){return se.hash(e),n===void 0&&(n=new Uint8Array(e.outputLen)),pt(e,Ye(n),Ye(t))}const an=new Uint8Array([0]),br=new Uint8Array;function vr(e,t,n,r=32){if(se.hash(e),se.number(r),r>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(r/e.outputLen);n===void 0&&(n=br);const o=new Uint8Array(i*e.outputLen),s=pt.create(e,t),a=s._cloneInto(),c=new Uint8Array(s.outputLen);for(let l=0;l<i;l++)an[0]=l+1,a.update(l===0?br:c).update(n).update(an).digestInto(c),o.set(c,e.outputLen*l),s._cloneInto(a);return s.destroy(),a.destroy(),c.fill(0),an.fill(0),o.slice(0,r)}var Ho=Object.defineProperty,j=(e,t)=>{for(var n in t)Ho(e,n,{get:t[n],enumerable:!0})},De=Symbol("verified"),qo=e=>e instanceof Object;function Er(e){if(!qo(e)||typeof e.kind!="number"||typeof e.content!="string"||typeof e.created_at!="number"||typeof e.pubkey!="string"||!e.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(e.tags))return!1;for(let t=0;t<e.tags.length;t++){let n=e.tags[t];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]=="object")return!1}return!0}var Do={};j(Do,{Queue:()=>Zo,QueueNode:()=>mr,binarySearch:()=>cn,insertEventIntoAscendingList:()=>zo,insertEventIntoDescendingList:()=>Vo,normalizeURL:()=>jo,utf8Decoder:()=>ce,utf8Encoder:()=>ee});var ce=new TextDecoder("utf-8"),ee=new TextEncoder;function jo(e){e.indexOf("://")===-1&&(e="wss://"+e);let t=new URL(e);return t.pathname=t.pathname.replace(/\/+/g,"/"),t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),(t.port==="80"&&t.protocol==="ws:"||t.port==="443"&&t.protocol==="wss:")&&(t.port=""),t.searchParams.sort(),t.hash="",t.toString()}function Vo(e,t){const[n,r]=cn(e,i=>t.id===i.id?0:t.created_at===i.created_at?-1:i.created_at-t.created_at);return r||e.splice(n,0,t),e}function zo(e,t){const[n,r]=cn(e,i=>t.id===i.id?0:t.created_at===i.created_at?-1:t.created_at-i.created_at);return r||e.splice(n,0,t),e}function cn(e,t){let n=0,r=e.length-1;for(;n<=r;){const i=Math.floor((n+r)/2),o=t(e[i]);if(o===0)return[i,!0];o<0?r=i-1:n=i+1}return[n,!1]}var mr=class{constructor(e){re(this,"value");re(this,"next",null);re(this,"prev",null);this.value=e}},Zo=class{constructor(){re(this,"first");re(this,"last");this.first=null,this.last=null}enqueue(e){const t=new mr(e);return this.last?this.last===this.first?(this.last=t,this.last.prev=this.first,this.first.next=t):(t.prev=this.last,this.last.next=t,this.last=t):(this.first=t,this.last=t),!0}dequeue(){if(!this.first)return null;if(this.first===this.last){const t=this.first;return this.first=null,this.last=null,t.value}const e=this.first;return this.first=e.next,e.value}},Fo=class{generateSecretKey(){return Je.utils.randomPrivateKey()}getPublicKey(e){return M(Je.getPublicKey(e))}finalizeEvent(e,t){const n=e;return n.pubkey=M(Je.getPublicKey(t)),n.id=gt(n),n.sig=M(Je.sign(gt(n),t)),n[De]=!0,n}verifyEvent(e){if(typeof e[De]=="boolean")return e[De];const t=gt(e);if(t!==e.id)return e[De]=!1,!1;try{const n=Je.verify(e.sig,t,e.pubkey);return e[De]=n,n}catch{return e[De]=!1,!1}}};function Wo(e){if(!Er(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function gt(e){let t=me(ee.encode(Wo(e)));return M(t)}var wt=new Fo,je=wt.generateSecretKey,_e=wt.getPublicKey,le=wt.finalizeEvent,bt=wt.verifyEvent,Go={};j(Go,{Application:()=>Gs,BadgeAward:()=>is,BadgeDefinition:()=>Ds,BlockedRelaysList:()=>Cs,BookmarkList:()=>As,Bookmarksets:()=>Ps,Calendar:()=>na,CalendarEventRSVP:()=>ra,ChannelCreation:()=>Nr,ChannelHideMessage:()=>Br,ChannelMessage:()=>kr,ChannelMetadata:()=>Cr,ChannelMuteUser:()=>Ir,ClassifiedListing:()=>Xs,ClientAuth:()=>Ur,CommunitiesList:()=>Ks,CommunityDefinition:()=>sa,CommunityPostApproval:()=>ds,Contacts:()=>es,CreateOrUpdateProduct:()=>zs,CreateOrUpdateStall:()=>Vs,Curationsets:()=>Hs,Date:()=>ea,DraftClassifiedListing:()=>Qs,DraftLong:()=>Fs,Emojisets:()=>Ws,EncryptedDirectMessage:()=>ts,EncryptedDirectMessages:()=>ns,EventDeletion:()=>rs,FileMetadata:()=>as,FileServerPreference:()=>Us,Followsets:()=>Rs,GenericRepost:()=>os,Genericlists:()=>Os,HTTPAuth:()=>fn,Handlerinformation:()=>oa,Handlerrecommendation:()=>ia,Highlights:()=>Es,InterestsList:()=>Bs,Interestsets:()=>js,JobFeedback:()=>gs,JobRequest:()=>ys,JobResult:()=>ps,Label:()=>hs,LightningPubRPC:()=>Ls,LiveChatMessage:()=>cs,LiveEvent:()=>Js,LongFormArticle:()=>Zs,Metadata:()=>Yo,Mutelist:()=>ms,NWCWalletInfo:()=>_s,NWCWalletRequest:()=>_r,NWCWalletResponse:()=>Ts,NostrConnect:()=>$s,OpenTimestamps:()=>ss,Pinlist:()=>xs,ProblemTracker:()=>ls,ProfileBadges:()=>qs,PublicChatsList:()=>Ns,Reaction:()=>un,RecommendRelay:()=>Qo,RelayList:()=>Ss,Relaysets:()=>Ms,Report:()=>us,Reporting:()=>fs,Repost:()=>ln,SearchRelaysList:()=>ks,ShortTextNote:()=>Xo,Time:()=>ta,UserEmojiList:()=>Is,UserStatuses:()=>Ys,Zap:()=>vs,ZapGoal:()=>ws,ZapRequest:()=>bs,classifyKind:()=>Jo,isEphemeralKind:()=>Ar,isParameterizedReplaceableKind:()=>Kr,isRegularKind:()=>xr,isReplaceableKind:()=>Sr});function xr(e){return 1e3<=e&&e<1e4||[1,2,4,5,6,7,8,16,40,41,42,43,44].includes(e)}function Sr(e){return[0,3].includes(e)||1e4<=e&&e<2e4}function Ar(e){return 2e4<=e&&e<3e4}function Kr(e){return 3e4<=e&&e<4e4}function Jo(e){return xr(e)?"regular":Sr(e)?"replaceable":Ar(e)?"ephemeral":Kr(e)?"parameterized":"unknown"}var Yo=0,Xo=1,Qo=2,es=3,ts=4,ns=4,rs=5,ln=6,un=7,is=8,os=16,Nr=40,Cr=41,kr=42,Br=43,Ir=44,ss=1040,as=1063,cs=1311,ls=1971,us=1984,fs=1984,hs=1985,ds=4550,ys=5999,ps=6999,gs=7e3,ws=9041,bs=9734,vs=9735,Es=9802,ms=1e4,xs=10001,Ss=10002,As=10003,Ks=10004,Ns=10005,Cs=10006,ks=10007,Bs=10015,Is=10030,Us=10096,_s=13194,Ls=21e3,Ur=22242,_r=23194,Ts=23195,$s=24133,fn=27235,Rs=3e4,Os=30001,Ms=30002,Ps=30003,Hs=30004,qs=30008,Ds=30009,js=30015,Vs=30017,zs=30018,Zs=30023,Fs=30024,Ws=30030,Gs=30078,Js=30311,Ys=30315,Xs=30402,Qs=30403,ea=31922,ta=31923,na=31924,ra=31925,ia=31989,oa=31990,sa=34550,aa={};j(aa,{getHex64:()=>hn,getInt:()=>Lr,getSubscriptionId:()=>ca,matchEventId:()=>la,matchEventKind:()=>fa,matchEventPubkey:()=>ua});function hn(e,t){let n=t.length+3,r=e.indexOf(`"${t}":`)+n,i=e.slice(r).indexOf('"')+r+1;return e.slice(i,i+64)}function Lr(e,t){let n=t.length,r=e.indexOf(`"${t}":`)+n+3,i=e.slice(r),o=Math.min(i.indexOf(","),i.indexOf("}"));return parseInt(i.slice(0,o),10)}function ca(e){let t=e.slice(0,22).indexOf('"EVENT"');if(t===-1)return null;let n=e.slice(t+7+1).indexOf('"');if(n===-1)return null;let r=t+7+1+n,i=e.slice(r+1,80).indexOf('"');if(i===-1)return null;let o=r+1+i;return e.slice(r+1,o)}function la(e,t){return t===hn(e,"id")}function ua(e,t){return t===hn(e,"pubkey")}function fa(e,t){return t===Lr(e,"kind")}var ha={};j(ha,{makeAuthEvent:()=>da});function da(e,t){return{kind:Ur,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",t]],content:""}}var ya;try{ya=WebSocket}catch{}var pa;try{pa=WebSocket}catch{}var Qe={};j(Qe,{BECH32_REGEX:()=>Tr,Bech32MaxSize:()=>dn,decode:()=>vt,encodeBytes:()=>mt,naddrEncode:()=>xa,neventEncode:()=>ma,noteEncode:()=>va,nprofileEncode:()=>Ea,npubEncode:()=>ba,nrelayEncode:()=>Sa,nsecEncode:()=>wa});var dn=5e3,Tr=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function ga(e){const t=new Uint8Array(4);return t[0]=e>>24&255,t[1]=e>>16&255,t[2]=e>>8&255,t[3]=e&255,t}function vt(e){var i,o,s,a,c,l,f,u;let{prefix:t,words:n}=He.decode(e,dn),r=new Uint8Array(He.fromWords(n));switch(t){case"nprofile":{let d=Et(r);if(!((i=d[0])!=null&&i[0]))throw new Error("missing TLV 0 for nprofile");if(d[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:M(d[0][0]),relays:d[1]?d[1].map(p=>ce.decode(p)):[]}}}case"nevent":{let d=Et(r);if(!((o=d[0])!=null&&o[0]))throw new Error("missing TLV 0 for nevent");if(d[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(d[2]&&d[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(d[3]&&d[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:M(d[0][0]),relays:d[1]?d[1].map(p=>ce.decode(p)):[],author:(s=d[2])!=null&&s[0]?M(d[2][0]):void 0,kind:(a=d[3])!=null&&a[0]?parseInt(M(d[3][0]),16):void 0}}}case"naddr":{let d=Et(r);if(!((c=d[0])!=null&&c[0]))throw new Error("missing TLV 0 for naddr");if(!((l=d[2])!=null&&l[0]))throw new Error("missing TLV 2 for naddr");if(d[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!((f=d[3])!=null&&f[0]))throw new Error("missing TLV 3 for naddr");if(d[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:ce.decode(d[0][0]),pubkey:M(d[2][0]),kind:parseInt(M(d[3][0]),16),relays:d[1]?d[1].map(p=>ce.decode(p)):[]}}}case"nrelay":{let d=Et(r);if(!((u=d[0])!=null&&u[0]))throw new Error("missing TLV 0 for nrelay");return{type:"nrelay",data:ce.decode(d[0][0])}}case"nsec":return{type:t,data:r};case"npub":case"note":return{type:t,data:M(r)};default:throw new Error(`unknown prefix ${t}`)}}function Et(e){let t={},n=e;for(;n.length>0;){let r=n[0],i=n[1],o=n.slice(2,2+i);if(n=n.slice(2+i),o.length<i)throw new Error(`not enough data to read on TLV ${r}`);t[r]=t[r]||[],t[r].push(o)}return t}function wa(e){return mt("nsec",e)}function ba(e){return mt("npub",G(e))}function va(e){return mt("note",G(e))}function et(e,t){let n=He.toWords(t);return He.encode(e,n,dn)}function mt(e,t){return et(e,t)}function Ea(e){let t=xt({0:[G(e.pubkey)],1:(e.relays||[]).map(n=>ee.encode(n))});return et("nprofile",t)}function ma(e){let t;e.kind!==void 0&&(t=ga(e.kind));let n=xt({0:[G(e.id)],1:(e.relays||[]).map(r=>ee.encode(r)),2:e.author?[G(e.author)]:[],3:t?[new Uint8Array(t)]:[]});return et("nevent",n)}function xa(e){let t=new ArrayBuffer(4);new DataView(t).setUint32(0,e.kind,!1);let n=xt({0:[ee.encode(e.identifier)],1:(e.relays||[]).map(r=>ee.encode(r)),2:[G(e.pubkey)],3:[new Uint8Array(t)]});return et("naddr",n)}function Sa(e){let t=xt({0:[ee.encode(e)]});return et("nrelay",t)}function xt(e){let t=[];return Object.entries(e).reverse().forEach(([n,r])=>{r.forEach(i=>{let o=new Uint8Array(i.length+2);o.set([parseInt(n)],0),o.set([i.length],1),o.set(i,2),t.push(o)})}),ft(...t)}var Aa={};j(Aa,{decrypt:()=>Ka,encrypt:()=>$r});async function $r(e,t,n){const r=e instanceof Uint8Array?M(e):e,i=Ue.getSharedSecret(r,"02"+t),o=Rr(i);let s=Uint8Array.from(Wn(16)),a=ee.encode(n),c=fr(o,s).encrypt(a),l=ye.encode(new Uint8Array(c)),f=ye.encode(new Uint8Array(s.buffer));return`${l}?iv=${f}`}async function Ka(e,t,n){const r=e instanceof Uint8Array?M(e):e;let[i,o]=n.split("?iv="),s=Ue.getSharedSecret(r,"02"+t),a=Rr(s),c=ye.decode(o),l=ye.decode(i),f=fr(a,c).decrypt(l);return ce.decode(f)}function Rr(e){return e.slice(1,33)}var Na={};j(Na,{NIP05_REGEX:()=>Or,isValid:()=>Ba,queryProfile:()=>Mr,searchDomain:()=>ka,useFetchImplementation:()=>Ca});var Or=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,St;try{St=fetch}catch{}function Ca(e){St=e}async function ka(e,t=""){try{const n=`https://${e}/.well-known/nostr.json?name=${t}`;return(await(await St(n,{redirect:"error"})).json()).names}catch{return{}}}async function Mr(e){var o;const t=e.match(Or);if(!t)return null;const[n,r="_",i]=t;try{const s=`https://${i}/.well-known/nostr.json?name=${r}`,a=await(await St(s,{redirect:"error"})).json();let c=a.names[r];return c?{pubkey:c,relays:(o=a.relays)==null?void 0:o[c]}:null}catch{return null}}async function Ba(e,t){let n=await Mr(t);return n?n.pubkey===e:!1}var Ia={};j(Ia,{parse:()=>Ua});function Ua(e){const t={reply:void 0,root:void 0,mentions:[],profiles:[]},n=[];for(const r of e.tags)r[0]==="e"&&r[1]&&n.push(r),r[0]==="p"&&r[1]&&t.profiles.push({pubkey:r[1],relays:r[2]?[r[2]]:[]});for(let r=0;r<n.length;r++){const i=n[r],[o,s,a,c]=i,l={id:s,relays:a?[a]:[]},f=r===0,u=r===n.length-1;if(c==="root"){t.root=l;continue}if(c==="reply"){t.reply=l;continue}if(c==="mention"){t.mentions.push(l);continue}if(f){t.root=l;continue}if(u){t.reply=l;continue}t.mentions.push(l)}return t}var _a={};j(_a,{fetchRelayInformation:()=>Ta,useFetchImplementation:()=>La});var Pr;try{Pr=fetch}catch{}function La(e){Pr=e}async function Ta(e){return await(await fetch(e.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var $a={};j($a,{getPow:()=>Hr,minePow:()=>Ra});function Hr(e){let t=0;for(let n=0;n<e.length;n++){const r=parseInt(e[n],16);if(r===0)t+=4;else{t+=Math.clz32(r)-28;break}}return t}function Ra(e,t){let n=0;const r=e,i=["nonce",n.toString(),t.toString()];for(r.tags.push(i);;){const o=Math.floor(new Date().getTime()/1e3);if(o!==r.created_at&&(n=0,r.created_at=o),i[1]=(++n).toString(),r.id=gt(r),Hr(r.id)>=t)break}return r}var Oa={};j(Oa,{finishRepostEvent:()=>Ma,getRepostedEvent:()=>Pa,getRepostedEventPointer:()=>qr});function Ma(e,t,n,r){return le({kind:ln,tags:[...e.tags??[],["e",t.id,n],["p",t.pubkey]],content:e.content===""?"":JSON.stringify(t),created_at:e.created_at},r)}function qr(e){if(e.kind!==ln)return;let t,n;for(let r=e.tags.length-1;r>=0&&(t===void 0||n===void 0);r--){const i=e.tags[r];i.length>=2&&(i[0]==="e"&&t===void 0?t=i:i[0]==="p"&&n===void 0&&(n=i))}if(t!==void 0)return{id:t[1],relays:[t[2],n==null?void 0:n[2]].filter(r=>typeof r=="string"),author:n==null?void 0:n[1]}}function Pa(e,{skipVerification:t}={}){const n=qr(e);if(n===void 0||e.content==="")return;let r;try{r=JSON.parse(e.content)}catch{return}if(r.id===n.id&&!(!t&&!bt(r)))return r}var Ha={};j(Ha,{NOSTR_URI_REGEX:()=>At,parse:()=>Da,test:()=>qa});var At=new RegExp(`nostr:(${Tr.source})`);function qa(e){return typeof e=="string"&&new RegExp(`^${At.source}$`).test(e)}function Da(e){const t=e.match(new RegExp(`^${At.source}$`));if(!t)throw new Error(`Invalid Nostr URI: ${e}`);return{uri:t[0],value:t[1],decoded:vt(t[1])}}var ja={};j(ja,{finishReactionEvent:()=>Va,getReactedEventPointer:()=>za});function Va(e,t,n){const r=t.tags.filter(i=>i.length>=2&&(i[0]==="e"||i[0]==="p"));return le({...e,kind:un,tags:[...e.tags??[],...r,["e",t.id],["p",t.pubkey]],content:e.content??"+"},n)}function za(e){if(e.kind!==un)return;let t,n;for(let r=e.tags.length-1;r>=0&&(t===void 0||n===void 0);r--){const i=e.tags[r];i.length>=2&&(i[0]==="e"&&t===void 0?t=i:i[0]==="p"&&n===void 0&&(n=i))}if(!(t===void 0||n===void 0))return{id:t[1],relays:[t[2],n[2]].filter(r=>r!==void 0),author:n[1]}}var Za={};j(Za,{matchAll:()=>Fa,regex:()=>yn,replaceAll:()=>Wa});var yn=()=>new RegExp(`\\b${At.source}\\b`,"g");function*Fa(e){const t=e.matchAll(yn());for(const n of t)try{const[r,i]=n;yield{uri:r,value:i,decoded:vt(i),start:n.index,end:n.index+r.length}}catch{}}function Wa(e,t){return e.replaceAll(yn(),(n,r)=>t({uri:n,value:r,decoded:vt(r)}))}var Ga={};j(Ga,{channelCreateEvent:()=>Ja,channelHideMessageEvent:()=>Qa,channelMessageEvent:()=>Xa,channelMetadataEvent:()=>Ya,channelMuteUserEvent:()=>ec});var Ja=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return le({kind:Nr,tags:[...e.tags??[]],content:n,created_at:e.created_at},t)},Ya=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return le({kind:Cr,tags:[["e",e.channel_create_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},Xa=(e,t)=>{const n=[["e",e.channel_create_event_id,e.relay_url,"root"]];return e.reply_to_channel_message_event_id&&n.push(["e",e.reply_to_channel_message_event_id,e.relay_url,"reply"]),le({kind:kr,tags:[...n,...e.tags??[]],content:e.content,created_at:e.created_at},t)},Qa=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return le({kind:Br,tags:[["e",e.channel_message_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},ec=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return le({kind:Ir,tags:[["p",e.pubkey_to_mute],...e.tags??[]],content:n,created_at:e.created_at},t)},tc={};j(tc,{EMOJI_SHORTCODE_REGEX:()=>Dr,matchAll:()=>nc,regex:()=>pn,replaceAll:()=>rc});var Dr=/:(\w+):/,pn=()=>new RegExp(`\\B${Dr.source}\\B`,"g");function*nc(e){const t=e.matchAll(pn());for(const n of t)try{const[r,i]=n;yield{shortcode:r,name:i,start:n.index,end:n.index+r.length}}catch{}}function rc(e,t){return e.replaceAll(pn(),(n,r)=>t({shortcode:n,name:r}))}var ic={};j(ic,{useFetchImplementation:()=>oc,validateGithub:()=>sc});var gn;try{gn=fetch}catch{}function oc(e){gn=e}async function sc(e,t,n){try{return await(await gn(`https://gist.github.com/${t}/${n}/raw`)).text()===`Verifying that I control the following Nostr public key: ${e}`}catch{return!1}}var V={};j(V,{decrypt:()=>Gr,encrypt:()=>Wr,getConversationKey:()=>zr,v2:()=>fc});var jr=1,Vr=65535;function zr(e,t){const n=Ue.getSharedSecret(e,"02"+t).subarray(1,33);return sn(me,n,"nip44-v2")}function Zr(e,t){const n=vr(me,e,t,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function wn(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("expected positive integer");if(e<=32)return 32;const t=1<<Math.floor(Math.log2(e-1))+1,n=t<=256?32:t/8;return n*(Math.floor((e-1)/n)+1)}function ac(e){if(!Number.isSafeInteger(e)||e<jr||e>Vr)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");const t=new Uint8Array(2);return new DataView(t.buffer).setUint16(0,e,!1),t}function cc(e){const t=ee.encode(e),n=t.length,r=ac(n),i=new Uint8Array(wn(n)-n);return ft(r,t,i)}function lc(e){const t=new DataView(e.buffer).getUint16(0),n=e.subarray(2,2+t);if(t<jr||t>Vr||n.length!==t||e.length!==2+wn(t))throw new Error("invalid padding");return ce.decode(n)}function Fr(e,t,n){if(n.length!==32)throw new Error("AAD associated data must be 32 bytes");const r=ft(n,t);return pt(me,e,r)}function uc(e){if(typeof e!="string")throw new Error("payload must be a valid string");const t=e.length;if(t<132||t>87472)throw new Error("invalid payload length: "+t);if(e[0]==="#")throw new Error("unknown encryption version");let n;try{n=ye.decode(e)}catch(o){throw new Error("invalid base64: "+o.message)}const r=n.length;if(r<99||r>65603)throw new Error("invalid data length: "+r);const i=n[0];if(i!==2)throw new Error("unknown encryption version "+i);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}function Wr(e,t,n=Wn(32)){const{chacha_key:r,chacha_nonce:i,hmac_key:o}=Zr(t,n),s=cc(e),a=gr(r,i,s),c=Fr(o,a,n);return ye.encode(ft(new Uint8Array([2]),n,a,c))}function Gr(e,t){const{nonce:n,ciphertext:r,mac:i}=uc(e),{chacha_key:o,chacha_nonce:s,hmac_key:a}=Zr(t,n),c=Fr(a,r,n);if(!mo(c,i))throw new Error("invalid MAC");const l=gr(o,s,r);return lc(l)}var fc={utils:{getConversationKey:zr,calcPaddedLen:wn},encrypt:Wr,decrypt:Gr},hc={};j(hc,{makeNwcRequestEvent:()=>yc,parseConnectionString:()=>dc});function dc(e){const{pathname:t,searchParams:n}=new URL(e),r=t,i=n.get("relay"),o=n.get("secret");if(!r||!i||!o)throw new Error("invalid connection string");return{pubkey:r,relay:i,secret:o}}async function yc(e,t,n){const i=await $r(t,e,JSON.stringify({method:"pay_invoice",params:{invoice:n}})),o={kind:_r,created_at:Math.round(Date.now()/1e3),content:i,tags:[["p",e]]};return le(o,t)}var pc={};j(pc,{getZapEndpoint:()=>wc,makeZapReceipt:()=>Ec,makeZapRequest:()=>bc,useFetchImplementation:()=>gc,validateZapRequest:()=>vc});var bn;try{bn=fetch}catch{}function gc(e){bn=e}async function wc(e){try{let t="",{lud06:n,lud16:r}=JSON.parse(e.content);if(n){let{words:s}=He.decode(n,1e3),a=He.fromWords(s);t=ce.decode(a)}else if(r){let[s,a]=r.split("@");t=new URL(`/.well-known/lnurlp/${s}`,`https://${a}`).toString()}else return null;let o=await(await bn(t)).json();if(o.allowsNostr&&o.nostrPubkey)return o.callback}catch{}return null}function bc({profile:e,event:t,amount:n,relays:r,comment:i=""}){if(!n)throw new Error("amount not given");if(!e)throw new Error("profile not given");let o={kind:9734,created_at:Math.round(Date.now()/1e3),content:i,tags:[["p",e],["amount",n.toString()],["relays",...r]]};return t&&o.tags.push(["e",t]),o}function vc(e){let t;try{t=JSON.parse(e)}catch{return"Invalid zap request JSON."}if(!Er(t))return"Zap request is not a valid Nostr event.";if(!bt(t))return"Invalid signature on zap request.";let n=t.tags.find(([o,s])=>o==="p"&&s);if(!n)return"Zap request doesn't have a 'p' tag.";if(!n[1].match(/^[a-f0-9]{64}$/))return"Zap request 'p' tag is not valid hex.";let r=t.tags.find(([o,s])=>o==="e"&&s);return r&&!r[1].match(/^[a-f0-9]{64}$/)?"Zap request 'e' tag is not valid hex.":t.tags.find(([o,s])=>o==="relays"&&s)?null:"Zap request doesn't have a 'relays' tag."}function Ec({zapRequest:e,preimage:t,bolt11:n,paidAt:r}){let i=JSON.parse(e),o=i.tags.filter(([a])=>a==="e"||a==="p"||a==="a"),s={kind:9735,created_at:Math.round(r.getTime()/1e3),content:"",tags:[...o,["P",i.pubkey],["bolt11",n],["description",e]]};return t&&s.tags.push(["preimage",t]),s}var mc={};j(mc,{getToken:()=>xc,hashPayload:()=>vn,unpackEventFromToken:()=>Yr,validateEvent:()=>ri,validateEventKind:()=>Qr,validateEventMethodTag:()=>ti,validateEventPayloadTag:()=>ni,validateEventTimestamp:()=>Xr,validateEventUrlTag:()=>ei,validateToken:()=>Sc});var Jr="Nostr ";async function xc(e,t,n,r=!1,i){const o={kind:fn,tags:[["u",e],["method",t]],created_at:Math.round(new Date().getTime()/1e3),content:""};i&&o.tags.push(["payload",vn(i)]);const s=await n(o);return(r?Jr:"")+ye.encode(ee.encode(JSON.stringify(s)))}async function Sc(e,t,n){const r=await Yr(e).catch(o=>{throw o});return await ri(r,t,n).catch(o=>{throw o})}async function Yr(e){if(!e)throw new Error("Missing token");e=e.replace(Jr,"");const t=ce.decode(ye.decode(e));if(!t||t.length===0||!t.startsWith("{"))throw new Error("Invalid token");return JSON.parse(t)}function Xr(e){return e.created_at?Math.round(new Date().getTime()/1e3)-e.created_at<60:!1}function Qr(e){return e.kind===fn}function ei(e,t){const n=e.tags.find(r=>r[0]==="u");return n?n.length>0&&n[1]===t:!1}function ti(e,t){const n=e.tags.find(r=>r[0]==="method");return n?n.length>0&&n[1].toLowerCase()===t.toLowerCase():!1}function vn(e){const t=me(ee.encode(JSON.stringify(e)));return M(t)}function ni(e,t){const n=e.tags.find(i=>i[0]==="payload");if(!n)return!1;const r=vn(t);return n.length>0&&n[1]===r}async function ri(e,t,n,r){if(!bt(e))throw new Error("Invalid nostr event, signature invalid");if(!Qr(e))throw new Error("Invalid nostr event, kind invalid");if(!Xr(e))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!ei(e,t))throw new Error("Invalid nostr event, url tag invalid");if(!ti(e,n))throw new Error("Invalid nostr event, method tag invalid");if(r&&typeof r=="object"&&Object.keys(r).length>0&&!ni(e,r))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}const Le=4,En=30078,Ac=100;var ii=(e=>(e[e.Us=0]="Us",e[e.Them=1]="Them",e))(ii||{});function Kc(e){return JSON.stringify({rootKey:M(e.rootKey),theirNostrPublicKey:e.theirNostrPublicKey,ourCurrentNostrKey:e.ourCurrentNostrKey?{publicKey:e.ourCurrentNostrKey.publicKey,privateKey:M(e.ourCurrentNostrKey.privateKey)}:void 0,ourNextNostrKey:{publicKey:e.ourNextNostrKey.publicKey,privateKey:M(e.ourNextNostrKey.privateKey)},receivingChainKey:e.receivingChainKey?M(e.receivingChainKey):void 0,sendingChainKey:e.sendingChainKey?M(e.sendingChainKey):void 0,sendingChainMessageNumber:e.sendingChainMessageNumber,receivingChainMessageNumber:e.receivingChainMessageNumber,previousSendingChainMessageCount:e.previousSendingChainMessageCount,skippedMessageKeys:Object.fromEntries(Object.entries(e.skippedMessageKeys).map(([t,n])=>[t,M(n)])),skippedHeaderKeys:Object.fromEntries(Object.entries(e.skippedHeaderKeys).map(([t,n])=>[t,n.map(r=>M(r))]))})}function Nc(e){const t=JSON.parse(e);return{rootKey:G(t.rootKey),theirNostrPublicKey:t.theirNostrPublicKey,ourCurrentNostrKey:t.ourCurrentNostrKey?{publicKey:t.ourCurrentNostrKey.publicKey,privateKey:G(t.ourCurrentNostrKey.privateKey)}:void 0,ourNextNostrKey:{publicKey:t.ourNextNostrKey.publicKey,privateKey:G(t.ourNextNostrKey.privateKey)},receivingChainKey:t.receivingChainKey?G(t.receivingChainKey):void 0,sendingChainKey:t.sendingChainKey?G(t.sendingChainKey):void 0,sendingChainMessageNumber:t.sendingChainMessageNumber,receivingChainMessageNumber:t.receivingChainMessageNumber,previousSendingChainMessageCount:t.previousSendingChainMessageCount,skippedMessageKeys:Object.fromEntries(Object.entries(t.skippedMessageKeys).map(([n,r])=>[n,G(r)])),skippedHeaderKeys:Object.fromEntries(Object.entries(t.skippedHeaderKeys||{}).map(([n,r])=>[n,r.map(i=>G(i))]))}}async function*Cc(e){const t=[];let n=null;const r=e.onMessage(i=>{n?(n(i),n=null):t.push(i)});try{for(;;)t.length>0?yield t.shift():yield new Promise(i=>{n=i})}finally{r()}}function Te(e,t=new Uint8Array(32),n=1){const r=sn(me,e,t),i=[];for(let o=1;o<=n;o++)i.push(vr(me,r,new Uint8Array([o]),32));return i}function Kt(e,t){return`${e}:${t}`}const kc=1e3;class tt{constructor(t,n){re(this,"nostrUnsubscribe");re(this,"nostrNextUnsubscribe");re(this,"internalSubscriptions",new Map);re(this,"currentInternalSubscriptionId",0);re(this,"name");this.nostrSubscribe=t,this.state=n,this.name=Math.random().toString(36).substring(2,6)}static init(t,n,r,i,o,s){const a=je(),[c,l]=Te(o,V.getConversationKey(a,n),2);let f,u;i?(f={publicKey:_e(r),privateKey:r},u={publicKey:_e(a),privateKey:a}):u={publicKey:_e(r),privateKey:r};const d={rootKey:i?c:o,theirNostrPublicKey:n,ourCurrentNostrKey:f,ourNextNostrKey:u,receivingChainKey:void 0,sendingChainKey:i?l:void 0,sendingChainMessageNumber:0,receivingChainMessageNumber:0,previousSendingChainMessageCount:0,skippedMessageKeys:{},skippedHeaderKeys:{}},p=new tt(t,d);return s&&(p.name=s),p}send(t){if(!this.state.theirNostrPublicKey||!this.state.ourCurrentNostrKey)throw new Error("we are not the initiator, so we can't send the first message");const[n,r]=this.ratchetEncrypt(t),i=V.getConversationKey(this.state.ourCurrentNostrKey.privateKey,this.state.theirNostrPublicKey),o=V.encrypt(JSON.stringify(n),i);return le({content:r,kind:Le,tags:[["header",o]],created_at:Math.floor(Date.now()/1e3)},this.state.ourCurrentNostrKey.privateKey)}onMessage(t){const n=this.currentInternalSubscriptionId++;return this.internalSubscriptions.set(n,t),this.subscribeToNostrEvents(),()=>this.internalSubscriptions.delete(n)}close(){var t,n;(t=this.nostrUnsubscribe)==null||t.call(this),(n=this.nostrNextUnsubscribe)==null||n.call(this)}ratchetEncrypt(t){const[n,r]=Te(this.state.sendingChainKey,new Uint8Array([1]),2);return this.state.sendingChainKey=n,[{number:this.state.sendingChainMessageNumber++,nextPublicKey:this.state.ourNextNostrKey.publicKey,time:Date.now(),previousChainLength:this.state.previousSendingChainMessageCount},V.encrypt(t,r)]}ratchetDecrypt(t,n,r){const i=this.trySkippedMessageKeys(t,n,r);if(i)return i;this.skipMessageKeys(t.number,r);const[o,s]=Te(this.state.receivingChainKey,new Uint8Array([1]),2);this.state.receivingChainKey=o,this.state.receivingChainMessageNumber++;try{return V.decrypt(n,s)}catch(a){throw console.error(this.name,"Decryption failed:",a,{messageKey:M(s).slice(0,4),receivingChainKey:M(this.state.receivingChainKey).slice(0,4),sendingChainKey:this.state.sendingChainKey&&M(this.state.sendingChainKey).slice(0,4),rootKey:M(this.state.rootKey).slice(0,4)}),a}}ratchetStep(t){this.state.previousSendingChainMessageCount=this.state.sendingChainMessageNumber,this.state.sendingChainMessageNumber=0,this.state.receivingChainMessageNumber=0,this.state.theirNostrPublicKey=t;const n=V.getConversationKey(this.state.ourNextNostrKey.privateKey,this.state.theirNostrPublicKey),[r,i]=Te(this.state.rootKey,n,2);this.state.receivingChainKey=i,this.state.ourCurrentNostrKey=this.state.ourNextNostrKey;const o=je();this.state.ourNextNostrKey={publicKey:_e(o),privateKey:o};const s=V.getConversationKey(this.state.ourNextNostrKey.privateKey,this.state.theirNostrPublicKey),[a,c]=Te(r,s,2);this.state.rootKey=a,this.state.sendingChainKey=c}skipMessageKeys(t,n){if(this.state.receivingChainMessageNumber+kc<t)throw new Error("Too many skipped messages");for(;this.state.receivingChainMessageNumber<t;){const[r,i]=Te(this.state.receivingChainKey,new Uint8Array([1]),2);this.state.receivingChainKey=r;const o=Kt(n,this.state.receivingChainMessageNumber);if(this.state.skippedMessageKeys[o]=i,!this.state.skippedHeaderKeys[n]){const s=[];if(this.state.ourCurrentNostrKey){const c=V.getConversationKey(this.state.ourCurrentNostrKey.privateKey,n);s.push(c)}const a=V.getConversationKey(this.state.ourNextNostrKey.privateKey,n);s.push(a),this.state.skippedHeaderKeys[n]=s}this.state.receivingChainMessageNumber++}}trySkippedMessageKeys(t,n,r){var o;const i=Kt(r,t.number);if(i in this.state.skippedMessageKeys){const s=this.state.skippedMessageKeys[i];return delete this.state.skippedMessageKeys[i],Object.keys(this.state.skippedMessageKeys).some(c=>c.startsWith(`${r}:`))||(delete this.state.skippedHeaderKeys[r],(o=this.nostrUnsubscribe)==null||o.call(this),this.nostrUnsubscribe=void 0),V.decrypt(n,s)}return null}decryptHeader(t){const n=t.tags[0][1];if(this.state.ourCurrentNostrKey){const o=V.getConversationKey(this.state.ourCurrentNostrKey.privateKey,t.pubkey);try{return[JSON.parse(V.decrypt(n,o)),!1,!1]}catch{}}const r=V.getConversationKey(this.state.ourNextNostrKey.privateKey,t.pubkey);try{return[JSON.parse(V.decrypt(n,r)),!0,!1]}catch{}const i=this.state.skippedHeaderKeys[t.pubkey];if(i)for(const o of i)try{return[JSON.parse(V.decrypt(n,o)),!1,!0]}catch{}throw new Error("Failed to decrypt header with current and skipped header keys")}handleNostrEvent(t){var s;const[n,r,i]=this.decryptHeader(t);if(!i)this.state.theirNostrPublicKey!==n.nextPublicKey&&(this.state.theirNostrPublicKey=n.nextPublicKey,(s=this.nostrUnsubscribe)==null||s.call(this),this.nostrUnsubscribe=this.nostrNextUnsubscribe,this.nostrNextUnsubscribe=this.nostrSubscribe({authors:[this.state.theirNostrPublicKey],kinds:[Le]},a=>this.handleNostrEvent(a))),r&&(this.skipMessageKeys(n.previousChainLength,t.pubkey),this.ratchetStep(n.nextPublicKey));else if(!(Kt(t.pubkey,n.number)in this.state.skippedMessageKeys))return;const o=this.ratchetDecrypt(n,t.content,t.pubkey);this.internalSubscriptions.forEach(a=>a({id:t.id,data:o,pubkey:n.nextPublicKey,time:n.time}))}subscribeToNostrEvents(){if(this.nostrNextUnsubscribe)return;this.nostrNextUnsubscribe=this.nostrSubscribe({authors:[this.state.theirNostrPublicKey],kinds:[Le]},n=>this.handleNostrEvent(n));const t=Object.keys(this.state.skippedHeaderKeys);t.length>0&&(this.nostrUnsubscribe=this.nostrSubscribe({authors:t,kinds:[Le]},n=>this.handleNostrEvent(n)))}}new TextDecoder("utf-8"),new TextEncoder;function Nt(e,t){const n=Ue.getSharedSecret(e,"02"+t).subarray(1,33);return sn(me,n,"nip44-v2")}class $e{constructor(t,n,r,i,o,s,a=[]){this.inviterSessionPublicKey=t,this.linkSecret=n,this.inviter=r,this.inviterSessionPrivateKey=i,this.label=o,this.maxUses=s,this.usedBy=a}static createNew(t,n,r){const i=je(),o=_e(i),s=M(je());return new $e(o,s,t,i,n,r)}static fromUrl(t){const r=new URL(t).hash.slice(1);if(!r)throw new Error("No invite data found in the URL hash.");const i=decodeURIComponent(r);let o;try{o=JSON.parse(i)}catch(u){throw new Error("Invite data in URL hash is not valid JSON: "+u)}const{inviter:s,sessionKey:a,linkSecret:c}=o;if(!s||!a||!c)throw new Error("Missing required fields (inviter, sessionKey, linkSecret) in invite data.");const l=Qe.decode(s),f=Qe.decode(a);if(typeof l.data!="string")throw new Error("Decoded inviter is not a string");if(typeof f.data!="string")throw new Error("Decoded session key is not a string");return new $e(f.data,c,l.data)}static deserialize(t){const n=JSON.parse(t);return new $e(n.inviterSessionPublicKey,n.linkSecret,n.inviter,n.inviterSessionPrivateKey?new Uint8Array(n.inviterSessionPrivateKey):void 0,n.label,n.maxUses,n.usedBy)}static fromEvent(t){var s,a;if(!t.sig)throw new Error("Event is not signed");if(!bt(t))throw new Error("Event signature is invalid");const{tags:n}=t,r=(s=n.find(([c])=>c==="sessionKey"))==null?void 0:s[1],i=(a=n.find(([c])=>c==="linkSecret"))==null?void 0:a[1],o=t.pubkey;if(!r||!i)throw new Error("Invalid invite event: missing session key or link secret");return new $e(r,i,o)}static fromUser(t,n){const r={kinds:[En],pubkey:t,limit:1,"#d":["nostr-double-ratchet/invite"]};return new Promise(i=>{const o=n(r,s=>{try{const a=$e.fromEvent(s);o(),i(a)}catch{o(),i(void 0)}});setTimeout(()=>{o(),i(void 0)},1e4)})}serialize(){return JSON.stringify({inviterSessionPublicKey:this.inviterSessionPublicKey,linkSecret:this.linkSecret,inviter:this.inviter,inviterSessionPrivateKey:this.inviterSessionPrivateKey?Array.from(this.inviterSessionPrivateKey):void 0,label:this.label,maxUses:this.maxUses,usedBy:this.usedBy})}getUrl(t="https://iris.to"){const n={inviter:Qe.npubEncode(this.inviter),sessionKey:Qe.npubEncode(this.inviterSessionPublicKey),linkSecret:this.linkSecret},r=new URL(t);return r.hash=encodeURIComponent(JSON.stringify(n)),console.log("url",r.toString()),r.toString()}getEvent(){return{kind:En,pubkey:this.inviter,content:"",created_at:Math.floor(Date.now()/1e3),tags:[["sessionKey",this.inviterSessionPublicKey],["linkSecret",this.linkSecret],["d","nostr-double-ratchet/invite"]]}}async accept(t,n,r){const i=je(),o=_e(i),s=this.inviter||this.inviterSessionPublicKey,a=G(this.linkSecret),c=tt.init(t,this.inviterSessionPublicKey,i,!0,a,void 0),l=je(),f=_e(l),u=typeof r=="function"?r:(g,h)=>Promise.resolve(V.encrypt(g,Nt(r,h))),d={pubkey:n,tags:[["secret",this.linkSecret]],content:await u(o,s),created_at:Math.floor(Date.now()/1e3)},p={kind:Le,pubkey:f,content:V.encrypt(JSON.stringify(d),Nt(l,this.inviterSessionPublicKey)),created_at:Math.floor(Date.now()/1e3),tags:[["p",this.inviterSessionPublicKey]]};return{channel:c,event:le(p,l)}}listen(t,n,r){if(!this.inviterSessionPrivateKey)throw new Error("Inviter session key is not available");const i={kinds:[Le],"#p":[this.inviterSessionPublicKey]};return n(i,async o=>{try{const s=await V.decrypt(o.content,Nt(this.inviterSessionPrivateKey,o.pubkey)),a=JSON.parse(s);if(!a.tags||!a.tags.some(([p,g])=>p==="secret"&&g===this.linkSecret)){console.error("Invalid secret from event",o);return}const l=await(typeof t=="function"?t:(p,g)=>Promise.resolve(V.decrypt(p,Nt(t,g))))(a.content,a.pubkey),f=G(this.linkSecret),u=o.id,d=tt.init(n,l,this.inviterSessionPrivateKey,!1,f,u);r(d,a.pubkey)}catch(s){console.error("Error processing invite message:",s)}})}}H.Channel=tt,H.INVITE_EVENT_KIND=En,H.Invite=$e,H.MAX_SKIP=Ac,H.MESSAGE_EVENT_KIND=Le,H.Sender=ii,H.createMessageStream=Cc,H.deserializeChannelState=Nc,H.kdf=Te,H.serializeChannelState=Kc,H.skippedMessageIndexKey=Kt,Object.defineProperty(H,Symbol.toStringTag,{value:"Module"})});
1
+ (function(H,J){typeof exports=="object"&&typeof module<"u"?J(exports):typeof define=="function"&&define.amd?define(["exports"],J):(H=typeof globalThis<"u"?globalThis:H||self,J(H["nostr-double-ratchet"]={}))})(this,function(H){"use strict";var kc=Object.defineProperty;var Ic=(H,J,Ce)=>J in H?kc(H,J,{enumerable:!0,configurable:!0,writable:!0,value:Ce}):H[J]=Ce;var re=(H,J,Ce)=>Ic(H,typeof J!="symbol"?J+"":J,Ce);function J(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function Ce(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function ai(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");J(e.outputLen),J(e.blockLen)}function nt(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ci(e,t){Ce(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const Nt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const En=e=>e instanceof Uint8Array,Ct=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),ie=(e,t)=>e<<32-t|e>>>t;if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");function li(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function Bt(e){if(typeof e=="string"&&(e=li(e)),!En(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}function ui(...e){const t=new Uint8Array(e.reduce((r,i)=>r+i.length,0));let n=0;return e.forEach(r=>{if(!En(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}let xn=class{clone(){return this._cloneInto()}};function fi(e){const t=r=>e().update(Bt(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Sn(e=32){if(Nt&&typeof Nt.getRandomValues=="function")return Nt.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function hi(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,a,r)}let di=class extends xn{constructor(t,n,r,i){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Ct(this.buffer)}update(t){nt(this);const{view:n,buffer:r,blockLen:i}=this;t=Bt(t);const s=t.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=Ct(t);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){nt(this),ci(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let u=o;u<i;u++)n[u]=0;hi(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=Ct(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,f=this.get();if(l>f.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,f[u],s)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return t.length=i,t.pos=a,t.finished=s,t.destroyed=o,i%n&&t.buffer.set(r),t}};const yi=(e,t,n)=>e&t^~e&n,pi=(e,t,n)=>e&t^e&n^t&n,gi=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ge=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),we=new Uint32Array(64);let wi=class extends di{constructor(){super(64,32,8,!1),this.A=ge[0]|0,this.B=ge[1]|0,this.C=ge[2]|0,this.D=ge[3]|0,this.E=ge[4]|0,this.F=ge[5]|0,this.G=ge[6]|0,this.H=ge[7]|0}get(){const{A:t,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[t,n,r,i,s,o,a,c]}set(t,n,r,i,s,o,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(t,n){for(let u=0;u<16;u++,n+=4)we[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const d=we[u-15],p=we[u-2],g=ie(d,7)^ie(d,18)^d>>>3,h=ie(p,17)^ie(p,19)^p>>>10;we[u]=h+we[u-7]+g+we[u-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:l,H:f}=this;for(let u=0;u<64;u++){const d=ie(a,6)^ie(a,11)^ie(a,25),p=f+d+yi(a,c,l)+gi[u]+we[u]|0,h=(ie(r,2)^ie(r,13)^ie(r,22))+pi(r,i,s)|0;f=l,l=c,c=a,a=o+p|0,o=s,s=i,i=r,r=p+h|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,f=f+this.H|0,this.set(r,i,s,o,a,c,l,f)}roundClean(){we.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const kt=fi(()=>new wi);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const An=BigInt(0),rt=BigInt(1),bi=BigInt(2),it=e=>e instanceof Uint8Array,vi=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Oe(e){if(!it(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=vi[e[n]];return t}function Kn(e){const t=e.toString(16);return t.length&1?`0${t}`:t}function It(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return BigInt(e===""?"0":`0x${e}`)}function Me(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);const t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(t/2);for(let r=0;r<n.length;r++){const i=r*2,s=e.slice(i,i+2),o=Number.parseInt(s,16);if(Number.isNaN(o)||o<0)throw new Error("Invalid byte sequence");n[r]=o}return n}function Y(e){return It(Oe(e))}function Ut(e){if(!it(e))throw new Error("Uint8Array expected");return It(Oe(Uint8Array.from(e).reverse()))}function be(e,t){return Me(e.toString(16).padStart(t*2,"0"))}function _t(e,t){return be(e,t).reverse()}function mi(e){return Me(Kn(e))}function F(e,t,n){let r;if(typeof t=="string")try{r=Me(t)}catch(s){throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${s}`)}else if(it(t))r=Uint8Array.from(t);else throw new Error(`${e} must be hex string or Uint8Array`);const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(`${e} expected ${n} bytes, got ${i}`);return r}function Be(...e){const t=new Uint8Array(e.reduce((r,i)=>r+i.length,0));let n=0;return e.forEach(r=>{if(!it(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}function Ei(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function xi(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function Si(e){let t;for(t=0;e>An;e>>=rt,t+=1);return t}function Ai(e,t){return e>>BigInt(t)&rt}const Ki=(e,t,n)=>e|(n?rt:An)<<BigInt(t),Lt=e=>(bi<<BigInt(e-1))-rt,Tt=e=>new Uint8Array(e),Nn=e=>Uint8Array.from(e);function Cn(e,t,n){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=Tt(e),i=Tt(e),s=0;const o=()=>{r.fill(1),i.fill(0),s=0},a=(...u)=>n(i,r,...u),c=(u=Tt())=>{i=a(Nn([0]),u),r=a(),u.length!==0&&(i=a(Nn([1]),u),r=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let u=0;const d=[];for(;u<t;){r=a();const p=r.slice();d.push(p),u+=r.length}return Be(...d)};return(u,d)=>{o(),c(u);let p;for(;!(p=d(l()));)c();return o(),p}}const Ni={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||e instanceof Uint8Array,isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function We(e,t,n={}){const r=(i,s,o)=>{const a=Ni[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);const c=e[i];if(!(o&&c===void 0)&&!a(c,e))throw new Error(`Invalid param ${String(i)}=${c} (${typeof c}), expected ${s}`)};for(const[i,s]of Object.entries(t))r(i,s,!1);for(const[i,s]of Object.entries(n))r(i,s,!0);return e}const Ci=Object.freeze(Object.defineProperty({__proto__:null,bitGet:Ai,bitLen:Si,bitMask:Lt,bitSet:Ki,bytesToHex:Oe,bytesToNumberBE:Y,bytesToNumberLE:Ut,concatBytes:Be,createHmacDrbg:Cn,ensureBytes:F,equalBytes:Ei,hexToBytes:Me,hexToNumber:It,numberToBytesBE:be,numberToBytesLE:_t,numberToHexUnpadded:Kn,numberToVarBytesBE:mi,utf8ToBytes:xi,validateObject:We},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const z=BigInt(0),D=BigInt(1),ke=BigInt(2),Bi=BigInt(3),$t=BigInt(4),Bn=BigInt(5),kn=BigInt(8);BigInt(9),BigInt(16);function Z(e,t){const n=e%t;return n>=z?n:t+n}function ki(e,t,n){if(n<=z||t<z)throw new Error("Expected power/modulo > 0");if(n===D)return z;let r=D;for(;t>z;)t&D&&(r=r*e%n),e=e*e%n,t>>=D;return r}function X(e,t,n){let r=e;for(;t-- >z;)r*=r,r%=n;return r}function Rt(e,t){if(e===z||t<=z)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let n=Z(e,t),r=t,i=z,s=D;for(;n!==z;){const a=r/n,c=r%n,l=i-s*a;r=n,n=c,i=s,s=l}if(r!==D)throw new Error("invert: does not exist");return Z(i,t)}function Ii(e){const t=(e-D)/ke;let n,r,i;for(n=e-D,r=0;n%ke===z;n/=ke,r++);for(i=ke;i<e&&ki(i,t,e)!==e-D;i++);if(r===1){const o=(e+D)/$t;return function(c,l){const f=c.pow(l,o);if(!c.eql(c.sqr(f),l))throw new Error("Cannot find square root");return f}}const s=(n+D)/ke;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=r,f=a.pow(a.mul(a.ONE,i),n),u=a.pow(c,s),d=a.pow(c,n);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let p=1;for(let h=a.sqr(d);p<l&&!a.eql(h,a.ONE);p++)h=a.sqr(h);const g=a.pow(f,D<<BigInt(l-p-1));f=a.sqr(g),u=a.mul(u,g),d=a.mul(d,f),l=p}return u}}function Ui(e){if(e%$t===Bi){const t=(e+D)/$t;return function(r,i){const s=r.pow(i,t);if(!r.eql(r.sqr(s),i))throw new Error("Cannot find square root");return s}}if(e%kn===Bn){const t=(e-Bn)/kn;return function(r,i){const s=r.mul(i,ke),o=r.pow(s,t),a=r.mul(i,o),c=r.mul(r.mul(a,ke),o),l=r.mul(a,r.sub(c,r.ONE));if(!r.eql(r.sqr(l),i))throw new Error("Cannot find square root");return l}}return Ii(e)}const _i=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Li(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=_i.reduce((r,i)=>(r[i]="function",r),t);return We(e,n)}function Ti(e,t,n){if(n<z)throw new Error("Expected power > 0");if(n===z)return e.ONE;if(n===D)return t;let r=e.ONE,i=t;for(;n>z;)n&D&&(r=e.mul(r,i)),i=e.sqr(i),n>>=D;return r}function $i(e,t){const n=new Array(t.length),r=t.reduce((s,o,a)=>e.is0(o)?s:(n[a]=s,e.mul(s,o)),e.ONE),i=e.inv(r);return t.reduceRight((s,o,a)=>e.is0(o)?s:(n[a]=e.mul(s,n[a]),e.mul(s,o)),i),n}function In(e,t){const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Ri(e,t,n=!1,r={}){if(e<=z)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:i,nByteLength:s}=In(e,t);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");const o=Ui(e),a=Object.freeze({ORDER:e,BITS:i,BYTES:s,MASK:Lt(i),ZERO:z,ONE:D,create:c=>Z(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return z<=c&&c<e},is0:c=>c===z,isOdd:c=>(c&D)===D,neg:c=>Z(-c,e),eql:(c,l)=>c===l,sqr:c=>Z(c*c,e),add:(c,l)=>Z(c+l,e),sub:(c,l)=>Z(c-l,e),mul:(c,l)=>Z(c*l,e),pow:(c,l)=>Ti(a,c,l),div:(c,l)=>Z(c*Rt(l,e),e),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Rt(c,e),sqrt:r.sqrt||(c=>o(a,c)),invertBatch:c=>$i(a,c),cmov:(c,l,f)=>f?l:c,toBytes:c=>n?_t(c,s):be(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return n?Ut(c):Y(c)}});return Object.freeze(a)}function Un(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function _n(e){const t=Un(e);return t+Math.ceil(t/2)}function Oi(e,t,n=!1){const r=e.length,i=Un(t),s=_n(t);if(r<16||r<s||r>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${r}`);const o=n?Y(e):Ut(e),a=Z(o,t-D)+D;return n?_t(a,i):be(a,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Mi=BigInt(0),Ot=BigInt(1);function Pi(e,t){const n=(i,s)=>{const o=s.negate();return i?o:s},r=i=>{const s=Math.ceil(t/i)+1,o=2**(i-1);return{windows:s,windowSize:o}};return{constTimeNegate:n,unsafeLadder(i,s){let o=e.ZERO,a=i;for(;s>Mi;)s&Ot&&(o=o.add(a)),a=a.double(),s>>=Ot;return o},precomputeWindow(i,s){const{windows:o,windowSize:a}=r(s),c=[];let l=i,f=l;for(let u=0;u<o;u++){f=l,c.push(f);for(let d=1;d<a;d++)f=f.add(l),c.push(f);l=f.double()}return c},wNAF(i,s,o){const{windows:a,windowSize:c}=r(i);let l=e.ZERO,f=e.BASE;const u=BigInt(2**i-1),d=2**i,p=BigInt(i);for(let g=0;g<a;g++){const h=g*c;let y=Number(o&u);o>>=p,y>c&&(y-=d,o+=Ot);const w=h,E=h+Math.abs(y)-1,K=g%2!==0,U=y<0;y===0?f=f.add(n(K,s[w])):l=l.add(n(U,s[E]))}return{p:l,f}},wNAFCached(i,s,o,a){const c=i._WINDOW_SIZE||1;let l=s.get(i);return l||(l=this.precomputeWindow(i,c),c!==1&&s.set(i,a(l))),this.wNAF(c,l,o)}}}function Ln(e){return Li(e.Fp),We(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...In(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Hi(e){const t=Ln(e);We(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:n,Fp:r,a:i}=t;if(n){if(!r.eql(i,r.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof n!="object"||typeof n.beta!="bigint"||typeof n.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}const{bytesToNumberBE:qi,hexToBytes:Di}=Ci,Ie={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(e){const{Err:t}=Ie;if(e.length<2||e[0]!==2)throw new t("Invalid signature integer tag");const n=e[1],r=e.subarray(2,n+2);if(!n||r.length!==n)throw new t("Invalid signature integer: wrong length");if(r[0]&128)throw new t("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return{d:qi(r),l:e.subarray(n+2)}},toSig(e){const{Err:t}=Ie,n=typeof e=="string"?Di(e):e;if(!(n instanceof Uint8Array))throw new Error("ui8a expected");let r=n.length;if(r<2||n[0]!=48)throw new t("Invalid signature tag");if(n[1]!==r-2)throw new t("Invalid signature: incorrect length");const{d:i,l:s}=Ie._parseInt(n.subarray(2)),{d:o,l:a}=Ie._parseInt(s);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:i,s:o}},hexFromSig(e){const t=l=>Number.parseInt(l[0],16)&8?"00"+l:l,n=l=>{const f=l.toString(16);return f.length&1?`0${f}`:f},r=t(n(e.s)),i=t(n(e.r)),s=r.length/2,o=i.length/2,a=n(s),c=n(o);return`30${n(o+s+4)}02${c}${i}02${a}${r}`}},ue=BigInt(0),Q=BigInt(1);BigInt(2);const Tn=BigInt(3);BigInt(4);function ji(e){const t=Hi(e),{Fp:n}=t,r=t.toBytes||((g,h,y)=>{const w=h.toAffine();return Be(Uint8Array.from([4]),n.toBytes(w.x),n.toBytes(w.y))}),i=t.fromBytes||(g=>{const h=g.subarray(1),y=n.fromBytes(h.subarray(0,n.BYTES)),w=n.fromBytes(h.subarray(n.BYTES,2*n.BYTES));return{x:y,y:w}});function s(g){const{a:h,b:y}=t,w=n.sqr(g),E=n.mul(w,g);return n.add(n.add(E,n.mul(g,h)),y)}if(!n.eql(n.sqr(t.Gy),s(t.Gx)))throw new Error("bad generator point: equation left != right");function o(g){return typeof g=="bigint"&&ue<g&&g<t.n}function a(g){if(!o(g))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(g){const{allowedPrivateKeyLengths:h,nByteLength:y,wrapPrivateKey:w,n:E}=t;if(h&&typeof g!="bigint"){if(g instanceof Uint8Array&&(g=Oe(g)),typeof g!="string"||!h.includes(g.length))throw new Error("Invalid key");g=g.padStart(y*2,"0")}let K;try{K=typeof g=="bigint"?g:Y(F("private key",g,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof g}`)}return w&&(K=Z(K,E)),a(K),K}const l=new Map;function f(g){if(!(g instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(h,y,w){if(this.px=h,this.py=y,this.pz=w,h==null||!n.isValid(h))throw new Error("x required");if(y==null||!n.isValid(y))throw new Error("y required");if(w==null||!n.isValid(w))throw new Error("z required")}static fromAffine(h){const{x:y,y:w}=h||{};if(!h||!n.isValid(y)||!n.isValid(w))throw new Error("invalid affine point");if(h instanceof u)throw new Error("projective point not allowed");const E=K=>n.eql(K,n.ZERO);return E(y)&&E(w)?u.ZERO:new u(y,w,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){const y=n.invertBatch(h.map(w=>w.pz));return h.map((w,E)=>w.toAffine(y[E])).map(u.fromAffine)}static fromHex(h){const y=u.fromAffine(i(F("pointHex",h)));return y.assertValidity(),y}static fromPrivateKey(h){return u.BASE.multiply(c(h))}_setWindowSize(h){this._WINDOW_SIZE=h,l.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!n.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:h,y}=this.toAffine();if(!n.isValid(h)||!n.isValid(y))throw new Error("bad point: x or y not FE");const w=n.sqr(y),E=s(h);if(!n.eql(w,E))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:h}=this.toAffine();if(n.isOdd)return!n.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){f(h);const{px:y,py:w,pz:E}=this,{px:K,py:U,pz:B}=h,m=n.eql(n.mul(y,B),n.mul(K,E)),x=n.eql(n.mul(w,B),n.mul(U,E));return m&&x}negate(){return new u(this.px,n.neg(this.py),this.pz)}double(){const{a:h,b:y}=t,w=n.mul(y,Tn),{px:E,py:K,pz:U}=this;let B=n.ZERO,m=n.ZERO,x=n.ZERO,S=n.mul(E,E),P=n.mul(K,K),I=n.mul(U,U),N=n.mul(E,K);return N=n.add(N,N),x=n.mul(E,U),x=n.add(x,x),B=n.mul(h,x),m=n.mul(w,I),m=n.add(B,m),B=n.sub(P,m),m=n.add(P,m),m=n.mul(B,m),B=n.mul(N,B),x=n.mul(w,x),I=n.mul(h,I),N=n.sub(S,I),N=n.mul(h,N),N=n.add(N,x),x=n.add(S,S),S=n.add(x,S),S=n.add(S,I),S=n.mul(S,N),m=n.add(m,S),I=n.mul(K,U),I=n.add(I,I),S=n.mul(I,N),B=n.sub(B,S),x=n.mul(I,P),x=n.add(x,x),x=n.add(x,x),new u(B,m,x)}add(h){f(h);const{px:y,py:w,pz:E}=this,{px:K,py:U,pz:B}=h;let m=n.ZERO,x=n.ZERO,S=n.ZERO;const P=t.a,I=n.mul(t.b,Tn);let N=n.mul(y,K),$=n.mul(w,U),R=n.mul(E,B),q=n.add(y,w),b=n.add(K,U);q=n.mul(q,b),b=n.add(N,$),q=n.sub(q,b),b=n.add(y,E);let v=n.add(K,B);return b=n.mul(b,v),v=n.add(N,R),b=n.sub(b,v),v=n.add(w,E),m=n.add(U,B),v=n.mul(v,m),m=n.add($,R),v=n.sub(v,m),S=n.mul(P,b),m=n.mul(I,R),S=n.add(m,S),m=n.sub($,S),S=n.add($,S),x=n.mul(m,S),$=n.add(N,N),$=n.add($,N),R=n.mul(P,R),b=n.mul(I,b),$=n.add($,R),R=n.sub(N,R),R=n.mul(P,R),b=n.add(b,R),N=n.mul($,b),x=n.add(x,N),N=n.mul(v,b),m=n.mul(q,m),m=n.sub(m,N),N=n.mul(q,$),S=n.mul(v,S),S=n.add(S,N),new u(m,x,S)}subtract(h){return this.add(h.negate())}is0(){return this.equals(u.ZERO)}wNAF(h){return p.wNAFCached(this,l,h,y=>{const w=n.invertBatch(y.map(E=>E.pz));return y.map((E,K)=>E.toAffine(w[K])).map(u.fromAffine)})}multiplyUnsafe(h){const y=u.ZERO;if(h===ue)return y;if(a(h),h===Q)return this;const{endo:w}=t;if(!w)return p.unsafeLadder(this,h);let{k1neg:E,k1:K,k2neg:U,k2:B}=w.splitScalar(h),m=y,x=y,S=this;for(;K>ue||B>ue;)K&Q&&(m=m.add(S)),B&Q&&(x=x.add(S)),S=S.double(),K>>=Q,B>>=Q;return E&&(m=m.negate()),U&&(x=x.negate()),x=new u(n.mul(x.px,w.beta),x.py,x.pz),m.add(x)}multiply(h){a(h);let y=h,w,E;const{endo:K}=t;if(K){const{k1neg:U,k1:B,k2neg:m,k2:x}=K.splitScalar(y);let{p:S,f:P}=this.wNAF(B),{p:I,f:N}=this.wNAF(x);S=p.constTimeNegate(U,S),I=p.constTimeNegate(m,I),I=new u(n.mul(I.px,K.beta),I.py,I.pz),w=S.add(I),E=P.add(N)}else{const{p:U,f:B}=this.wNAF(y);w=U,E=B}return u.normalizeZ([w,E])[0]}multiplyAndAddUnsafe(h,y,w){const E=u.BASE,K=(B,m)=>m===ue||m===Q||!B.equals(E)?B.multiplyUnsafe(m):B.multiply(m),U=K(this,y).add(K(h,w));return U.is0()?void 0:U}toAffine(h){const{px:y,py:w,pz:E}=this,K=this.is0();h==null&&(h=K?n.ONE:n.inv(E));const U=n.mul(y,h),B=n.mul(w,h),m=n.mul(E,h);if(K)return{x:n.ZERO,y:n.ZERO};if(!n.eql(m,n.ONE))throw new Error("invZ was invalid");return{x:U,y:B}}isTorsionFree(){const{h,isTorsionFree:y}=t;if(h===Q)return!0;if(y)return y(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h,clearCofactor:y}=t;return h===Q?this:y?y(u,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return this.assertValidity(),r(u,this,h)}toHex(h=!0){return Oe(this.toRawBytes(h))}}u.BASE=new u(t.Gx,t.Gy,n.ONE),u.ZERO=new u(n.ZERO,n.ONE,n.ZERO);const d=t.nBitLength,p=Pi(u,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:u,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:o}}function Vi(e){const t=Ln(e);return We(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function zi(e){const t=Vi(e),{Fp:n,n:r}=t,i=n.BYTES+1,s=2*n.BYTES+1;function o(b){return ue<b&&b<n.ORDER}function a(b){return Z(b,r)}function c(b){return Rt(b,r)}const{ProjectivePoint:l,normPrivateKeyToScalar:f,weierstrassEquation:u,isWithinCurveOrder:d}=ji({...t,toBytes(b,v,A){const k=v.toAffine(),C=n.toBytes(k.x),L=Be;return A?L(Uint8Array.from([v.hasEvenY()?2:3]),C):L(Uint8Array.from([4]),C,n.toBytes(k.y))},fromBytes(b){const v=b.length,A=b[0],k=b.subarray(1);if(v===i&&(A===2||A===3)){const C=Y(k);if(!o(C))throw new Error("Point is not on curve");const L=u(C);let O=n.sqrt(L);const T=(O&Q)===Q;return(A&1)===1!==T&&(O=n.neg(O)),{x:C,y:O}}else if(v===s&&A===4){const C=n.fromBytes(k.subarray(0,n.BYTES)),L=n.fromBytes(k.subarray(n.BYTES,2*n.BYTES));return{x:C,y:L}}else throw new Error(`Point of length ${v} was invalid. Expected ${i} compressed bytes or ${s} uncompressed bytes`)}}),p=b=>Oe(be(b,t.nByteLength));function g(b){const v=r>>Q;return b>v}function h(b){return g(b)?a(-b):b}const y=(b,v,A)=>Y(b.slice(v,A));class w{constructor(v,A,k){this.r=v,this.s=A,this.recovery=k,this.assertValidity()}static fromCompact(v){const A=t.nByteLength;return v=F("compactSignature",v,A*2),new w(y(v,0,A),y(v,A,2*A))}static fromDER(v){const{r:A,s:k}=Ie.toSig(F("DER",v));return new w(A,k)}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(v){return new w(this.r,this.s,v)}recoverPublicKey(v){const{r:A,s:k,recovery:C}=this,L=x(F("msgHash",v));if(C==null||![0,1,2,3].includes(C))throw new Error("recovery id invalid");const O=C===2||C===3?A+t.n:A;if(O>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const T=C&1?"03":"02",te=l.fromHex(T+p(O)),Ke=c(O),Ve=a(-L*Ke),tt=a(k*Ke),Ne=l.BASE.multiplyAndAddUnsafe(te,Ve,tt);if(!Ne)throw new Error("point at infinify");return Ne.assertValidity(),Ne}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return Me(this.toDERHex())}toDERHex(){return Ie.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Me(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const E={isValidPrivateKey(b){try{return f(b),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{const b=_n(t.n);return Oi(t.randomBytes(b),t.n)},precompute(b=8,v=l.BASE){return v._setWindowSize(b),v.multiply(BigInt(3)),v}};function K(b,v=!0){return l.fromPrivateKey(b).toRawBytes(v)}function U(b){const v=b instanceof Uint8Array,A=typeof b=="string",k=(v||A)&&b.length;return v?k===i||k===s:A?k===2*i||k===2*s:b instanceof l}function B(b,v,A=!0){if(U(b))throw new Error("first arg must be private key");if(!U(v))throw new Error("second arg must be public key");return l.fromHex(v).multiply(f(b)).toRawBytes(A)}const m=t.bits2int||function(b){const v=Y(b),A=b.length*8-t.nBitLength;return A>0?v>>BigInt(A):v},x=t.bits2int_modN||function(b){return a(m(b))},S=Lt(t.nBitLength);function P(b){if(typeof b!="bigint")throw new Error("bigint expected");if(!(ue<=b&&b<S))throw new Error(`bigint expected < 2^${t.nBitLength}`);return be(b,t.nByteLength)}function I(b,v,A=N){if(["recovered","canonical"].some(Re=>Re in A))throw new Error("sign() legacy options not supported");const{hash:k,randomBytes:C}=t;let{lowS:L,prehash:O,extraEntropy:T}=A;L==null&&(L=!0),b=F("msgHash",b),O&&(b=F("prehashed msgHash",k(b)));const te=x(b),Ke=f(v),Ve=[P(Ke),P(te)];if(T!=null){const Re=T===!0?C(n.BYTES):T;Ve.push(F("extraEntropy",Re))}const tt=Be(...Ve),Ne=te;function mn(Re){const ze=m(Re);if(!d(ze))return;const ii=c(ze),Ze=l.BASE.multiply(ze).toAffine(),ne=a(Ze.x);if(ne===ue)return;const Fe=a(ii*a(Ne+ne*Ke));if(Fe===ue)return;let si=(Ze.x===ne?0:2)|Number(Ze.y&Q),oi=Fe;return L&&g(Fe)&&(oi=h(Fe),si^=1),new w(ne,oi,si)}return{seed:tt,k2sig:mn}}const N={lowS:t.lowS,prehash:!1},$={lowS:t.lowS,prehash:!1};function R(b,v,A=N){const{seed:k,k2sig:C}=I(b,v,A),L=t;return Cn(L.hash.outputLen,L.nByteLength,L.hmac)(k,C)}l.BASE._setWindowSize(8);function q(b,v,A,k=$){var Ze;const C=b;if(v=F("msgHash",v),A=F("publicKey",A),"strict"in k)throw new Error("options.strict was renamed to lowS");const{lowS:L,prehash:O}=k;let T,te;try{if(typeof C=="string"||C instanceof Uint8Array)try{T=w.fromDER(C)}catch(ne){if(!(ne instanceof Ie.Err))throw ne;T=w.fromCompact(C)}else if(typeof C=="object"&&typeof C.r=="bigint"&&typeof C.s=="bigint"){const{r:ne,s:Fe}=C;T=new w(ne,Fe)}else throw new Error("PARSE");te=l.fromHex(A)}catch(ne){if(ne.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(L&&T.hasHighS())return!1;O&&(v=t.hash(v));const{r:Ke,s:Ve}=T,tt=x(v),Ne=c(Ve),mn=a(tt*Ne),Re=a(Ke*Ne),ze=(Ze=l.BASE.multiplyAndAddUnsafe(te,mn,Re))==null?void 0:Ze.toAffine();return ze?a(ze.x)===Ke:!1}return{CURVE:t,getPublicKey:K,getSharedSecret:B,sign:R,verify:q,ProjectivePoint:l,Signature:w,utils:E}}let $n=class extends xn{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,ai(t);const r=Bt(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?t.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),s.fill(0)}update(t){return nt(this),this.iHash.update(t),this}digestInto(t){nt(this),Ce(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return t=t,t.finished=i,t.destroyed=s,t.blockLen=o,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Rn=(e,t,n)=>new $n(e,t).update(n).digest();Rn.create=(e,t)=>new $n(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Zi(e){return{hash:e,hmac:(t,...n)=>Rn(e,t,ui(...n)),randomBytes:Sn}}function Fi(e,t){const n=r=>zi({...e,...Zi(r)});return Object.freeze({...n(t),create:n})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const st=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),ot=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),On=BigInt(1),at=BigInt(2),Mn=(e,t)=>(e+t/at)/t;function Pn(e){const t=st,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,f=l*l*e%t,u=X(f,n,t)*f%t,d=X(u,n,t)*f%t,p=X(d,at,t)*l%t,g=X(p,i,t)*p%t,h=X(g,s,t)*g%t,y=X(h,a,t)*h%t,w=X(y,c,t)*y%t,E=X(w,a,t)*h%t,K=X(E,n,t)*f%t,U=X(K,o,t)*g%t,B=X(U,r,t)*l%t,m=X(B,at,t);if(!Mt.eql(Mt.sqr(m),e))throw new Error("Cannot find square root");return m}const Mt=Ri(st,void 0,void 0,{sqrt:Pn}),Ue=Fi({a:BigInt(0),b:BigInt(7),Fp:Mt,n:ot,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=ot,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-On*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,o=BigInt("0x100000000000000000000000000000000"),a=Mn(s*e,t),c=Mn(-r*e,t);let l=Z(e-a*n-c*i,t),f=Z(-a*r-c*s,t);const u=l>o,d=f>o;if(u&&(l=t-l),d&&(f=t-f),l>o||f>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:u,k1:l,k2neg:d,k2:f}}}},kt),ct=BigInt(0),Hn=e=>typeof e=="bigint"&&ct<e&&e<st,Wi=e=>typeof e=="bigint"&&ct<e&&e<ot,qn={};function lt(e,...t){let n=qn[e];if(n===void 0){const r=kt(Uint8Array.from(e,i=>i.charCodeAt(0)));n=Be(r,r),qn[e]=n}return kt(Be(n,...t))}const Pt=e=>e.toRawBytes(!0).slice(1),Ht=e=>be(e,32),qt=e=>Z(e,st),Ge=e=>Z(e,ot),Dt=Ue.ProjectivePoint,Gi=(e,t,n)=>Dt.BASE.multiplyAndAddUnsafe(e,t,n);function jt(e){let t=Ue.utils.normPrivateKeyToScalar(e),n=Dt.fromPrivateKey(t);return{scalar:n.hasEvenY()?t:Ge(-t),bytes:Pt(n)}}function Dn(e){if(!Hn(e))throw new Error("bad x: need 0 < x < p");const t=qt(e*e),n=qt(t*e+BigInt(7));let r=Pn(n);r%at!==ct&&(r=qt(-r));const i=new Dt(e,r,On);return i.assertValidity(),i}function jn(...e){return Ge(Y(lt("BIP0340/challenge",...e)))}function Ji(e){return jt(e).bytes}function Yi(e,t,n=Sn(32)){const r=F("message",e),{bytes:i,scalar:s}=jt(t),o=F("auxRand",n,32),a=Ht(s^Y(lt("BIP0340/aux",o))),c=lt("BIP0340/nonce",a,i,r),l=Ge(Y(c));if(l===ct)throw new Error("sign failed: k is zero");const{bytes:f,scalar:u}=jt(l),d=jn(f,i,r),p=new Uint8Array(64);if(p.set(f,0),p.set(Ht(Ge(u+d*s)),32),!Vn(p,r,i))throw new Error("sign: Invalid signature produced");return p}function Vn(e,t,n){const r=F("signature",e,64),i=F("message",t),s=F("publicKey",n,32);try{const o=Dn(Y(s)),a=Y(r.subarray(0,32));if(!Hn(a))return!1;const c=Y(r.subarray(32,64));if(!Wi(c))return!1;const l=jn(Ht(a),Pt(o),i),f=Gi(o,c,Ge(-l));return!(!f||!f.hasEvenY()||f.toAffine().x!==a)}catch{return!1}}const Je={getPublicKey:Ji,sign:Yi,verify:Vn,utils:{randomPrivateKey:Ue.utils.randomPrivateKey,lift_x:Dn,pointToBytes:Pt,numberToBytesBE:be,bytesToNumberBE:Y,taggedHash:lt,mod:Z}},Vt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const zt=e=>e instanceof Uint8Array,Zt=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),se=(e,t)=>e<<32-t|e>>>t;if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");const Xi=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function M(e){if(!zt(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=Xi[e[n]];return t}function G(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);const t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(t/2);for(let r=0;r<n.length;r++){const i=r*2,s=e.slice(i,i+2),o=Number.parseInt(s,16);if(Number.isNaN(o)||o<0)throw new Error("Invalid byte sequence");n[r]=o}return n}function Qi(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function Ye(e){if(typeof e=="string"&&(e=Qi(e)),!zt(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}function ut(...e){const t=new Uint8Array(e.reduce((r,i)=>r+i.length,0));let n=0;return e.forEach(r=>{if(!zt(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}class zn{clone(){return this._cloneInto()}}function Zn(e){const t=r=>e().update(Ye(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Fn(e=32){if(Vt&&typeof Vt.getRandomValues=="function")return Vt.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function Ft(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function es(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}function Wn(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function ts(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ft(e.outputLen),Ft(e.blockLen)}function ns(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function rs(e,t){Wn(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const oe={number:Ft,bool:es,bytes:Wn,hash:ts,exists:ns,output:rs};function is(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,a,r)}class ss extends zn{constructor(t,n,r,i){super(),this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Zt(this.buffer)}update(t){oe.exists(this);const{view:n,buffer:r,blockLen:i}=this;t=Ye(t);const s=t.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=Zt(t);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){oe.exists(this),oe.output(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let u=o;u<i;u++)n[u]=0;is(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=Zt(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,f=this.get();if(l>f.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,f[u],s)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return t.length=i,t.pos=a,t.finished=s,t.destroyed=o,i%n&&t.buffer.set(r),t}}const os=(e,t,n)=>e&t^~e&n,as=(e,t,n)=>e&t^e&n^t&n,cs=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]),ve=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),me=new Uint32Array(64);class Gn extends ss{constructor(){super(64,32,8,!1),this.A=ve[0]|0,this.B=ve[1]|0,this.C=ve[2]|0,this.D=ve[3]|0,this.E=ve[4]|0,this.F=ve[5]|0,this.G=ve[6]|0,this.H=ve[7]|0}get(){const{A:t,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[t,n,r,i,s,o,a,c]}set(t,n,r,i,s,o,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(t,n){for(let u=0;u<16;u++,n+=4)me[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const d=me[u-15],p=me[u-2],g=se(d,7)^se(d,18)^d>>>3,h=se(p,17)^se(p,19)^p>>>10;me[u]=h+me[u-7]+g+me[u-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:l,H:f}=this;for(let u=0;u<64;u++){const d=se(a,6)^se(a,11)^se(a,25),p=f+d+os(a,c,l)+cs[u]+me[u]|0,h=(se(r,2)^se(r,13)^se(r,22))+as(r,i,s)|0;f=l,l=c,c=a,a=o+p|0,o=s,s=i,i=r,r=p+h|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,f=f+this.H|0,this.set(r,i,s,o,a,c,l,f)}roundClean(){me.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class ls extends Gn{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const Ee=Zn(()=>new Gn);Zn(()=>new ls);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Pe(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function fe(...e){const t=(i,s)=>o=>i(s(o)),n=Array.from(e).reverse().reduce((i,s)=>i?t(i,s.encode):s.encode,void 0),r=e.reduce((i,s)=>i?t(i,s.decode):s.decode,void 0);return{encode:n,decode:r}}function he(e){return{encode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return t.map(n=>{if(Pe(n),n<0||n>=e.length)throw new Error(`Digit index outside alphabet: ${n} (alphabet: ${e.length})`);return e[n]})},decode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("alphabet.decode input should be array of strings");return t.map(n=>{if(typeof n!="string")throw new Error(`alphabet.decode: not string element=${n}`);const r=e.indexOf(n);if(r===-1)throw new Error(`Unknown letter: "${n}". Allowed: ${e}`);return r})}}}function de(e=""){if(typeof e!="string")throw new Error("join separator should be string");return{encode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("join.encode input should be array of strings");for(let n of t)if(typeof n!="string")throw new Error(`join.encode: non-string input=${n}`);return t.join(e)},decode:t=>{if(typeof t!="string")throw new Error("join.decode input should be string");return t.split(e)}}}function ft(e,t="="){if(Pe(e),typeof t!="string")throw new Error("padding chr should be string");return{encode(n){if(!Array.isArray(n)||n.length&&typeof n[0]!="string")throw new Error("padding.encode input should be array of strings");for(let r of n)if(typeof r!="string")throw new Error(`padding.encode: non-string input=${r}`);for(;n.length*e%8;)n.push(t);return n},decode(n){if(!Array.isArray(n)||n.length&&typeof n[0]!="string")throw new Error("padding.encode input should be array of strings");for(let i of n)if(typeof i!="string")throw new Error(`padding.decode: non-string input=${i}`);let r=n.length;if(r*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;r>0&&n[r-1]===t;r--)if(!((r-1)*e%8))throw new Error("Invalid padding: string has too much padding");return n.slice(0,r)}}}function Jn(e){if(typeof e!="function")throw new Error("normalize fn should be function");return{encode:t=>t,decode:t=>e(t)}}function Yn(e,t,n){if(t<2)throw new Error(`convertRadix: wrong from=${t}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let r=0;const i=[],s=Array.from(e);for(s.forEach(o=>{if(Pe(o),o<0||o>=t)throw new Error(`Wrong integer: ${o}`)});;){let o=0,a=!0;for(let c=r;c<s.length;c++){const l=s[c],f=t*o+l;if(!Number.isSafeInteger(f)||t*o/t!==o||f-l!==t*o)throw new Error("convertRadix: carry overflow");if(o=f%n,s[c]=Math.floor(f/n),!Number.isSafeInteger(s[c])||s[c]*n+o!==f)throw new Error("convertRadix: carry overflow");if(a)s[c]?a=!1:r=c;else continue}if(i.push(o),a)break}for(let o=0;o<e.length-1&&e[o]===0;o++)i.push(0);return i.reverse()}const Xn=(e,t)=>t?Xn(t,e%t):e,ht=(e,t)=>e+(t-Xn(e,t));function Wt(e,t,n,r){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(ht(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${ht(t,n)}`);let i=0,s=0;const o=2**n-1,a=[];for(const c of e){if(Pe(c),c>=2**t)throw new Error(`convertRadix2: invalid data word=${c} from=${t}`);if(i=i<<t|c,s+t>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${t}`);for(s+=t;s>=n;s-=n)a.push((i>>s-n&o)>>>0);i&=2**s-1}if(i=i<<n-s&o,!r&&s>=t)throw new Error("Excess padding");if(!r&&i)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&a.push(i>>>0),a}function us(e){return Pe(e),{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return Yn(Array.from(t),2**8,e)},decode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="number")throw new Error("radix.decode input should be array of strings");return Uint8Array.from(Yn(t,e,2**8))}}}function xe(e,t=!1){if(Pe(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(ht(8,e)>32||ht(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!(n instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return Wt(Array.from(n),8,e,!t)},decode:n=>{if(!Array.isArray(n)||n.length&&typeof n[0]!="number")throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(Wt(n,e,8,t))}}}function Qn(e){if(typeof e!="function")throw new Error("unsafeWrapper fn should be function");return function(...t){try{return e.apply(null,t)}catch{}}}const fs=fe(xe(4),he("0123456789ABCDEF"),de("")),hs=fe(xe(5),he("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),ft(5),de(""));fe(xe(5),he("0123456789ABCDEFGHIJKLMNOPQRSTUV"),ft(5),de("")),fe(xe(5),he("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),de(""),Jn(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const ye=fe(xe(6),he("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),ft(6),de("")),ds=fe(xe(6),he("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),ft(6),de("")),Gt=e=>fe(us(58),he(e),de("")),Jt=Gt("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");Gt("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),Gt("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const er=[0,2,3,5,6,7,9,10,11],ys={encode(e){let t="";for(let n=0;n<e.length;n+=8){const r=e.subarray(n,n+8);t+=Jt.encode(r).padStart(er[r.length],"1")}return t},decode(e){let t=[];for(let n=0;n<e.length;n+=11){const r=e.slice(n,n+11),i=er.indexOf(r.length),s=Jt.decode(r);for(let o=0;o<s.length-i;o++)if(s[o]!==0)throw new Error("base58xmr: wrong padding");t=t.concat(Array.from(s.slice(s.length-i)))}return Uint8Array.from(t)}},Yt=fe(he("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),de("")),tr=[996825010,642813549,513874426,1027748829,705979059];function Xe(e){const t=e>>25;let n=(e&33554431)<<5;for(let r=0;r<tr.length;r++)(t>>r&1)===1&&(n^=tr[r]);return n}function nr(e,t,n=1){const r=e.length;let i=1;for(let s=0;s<r;s++){const o=e.charCodeAt(s);if(o<33||o>126)throw new Error(`Invalid prefix (${e})`);i=Xe(i)^o>>5}i=Xe(i);for(let s=0;s<r;s++)i=Xe(i)^e.charCodeAt(s)&31;for(let s of t)i=Xe(i)^s;for(let s=0;s<6;s++)i=Xe(i);return i^=n,Yt.encode(Wt([i%2**30],30,5,!1))}function rr(e){const t=e==="bech32"?1:734539939,n=xe(5),r=n.decode,i=n.encode,s=Qn(r);function o(f,u,d=90){if(typeof f!="string")throw new Error(`bech32.encode prefix should be string, not ${typeof f}`);if(!Array.isArray(u)||u.length&&typeof u[0]!="number")throw new Error(`bech32.encode words should be array of numbers, not ${typeof u}`);const p=f.length+7+u.length;if(d!==!1&&p>d)throw new TypeError(`Length ${p} exceeds limit ${d}`);return f=f.toLowerCase(),`${f}1${Yt.encode(u)}${nr(f,u,t)}`}function a(f,u=90){if(typeof f!="string")throw new Error(`bech32.decode input should be string, not ${typeof f}`);if(f.length<8||u!==!1&&f.length>u)throw new TypeError(`Wrong string length: ${f.length} (${f}). Expected (8..${u})`);const d=f.toLowerCase();if(f!==d&&f!==f.toUpperCase())throw new Error("String must be lowercase or uppercase");f=d;const p=f.lastIndexOf("1");if(p===0||p===-1)throw new Error('Letter "1" must be present between prefix and data only');const g=f.slice(0,p),h=f.slice(p+1);if(h.length<6)throw new Error("Data must be at least 6 characters long");const y=Yt.decode(h).slice(0,-6),w=nr(g,y,t);if(!h.endsWith(w))throw new Error(`Invalid checksum in ${f}: expected "${w}"`);return{prefix:g,words:y}}const c=Qn(a);function l(f){const{prefix:u,words:d}=a(f,!1);return{prefix:u,words:d,bytes:r(d)}}return{encode:o,decode:a,decodeToBytes:l,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:s,toWords:i}}const He=rr("bech32");rr("bech32m");const ps={encode:e=>new TextDecoder().decode(e),decode:e=>new TextEncoder().encode(e)},gs=fe(xe(4),he("0123456789abcdef"),de(""),Jn(e=>{if(typeof e!="string"||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));`${Object.keys({utf8:ps,hex:gs,base16:fs,base32:hs,base64:ye,base64url:ds,base58:Jt,base58xmr:ys}).join(", ")}`;function Xt(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function ir(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function ws(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}function pe(e,...t){if(!ws(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */const W=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");function bs(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function vs(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}const ms=(e,t)=>(Object.assign(t,e),t),Se=16,Es=283;function Qt(e){return e<<1^Es&-(e>>7)}function qe(e,t){let n=0;for(;t>0;t>>=1)n^=e&-(t&1),e=Qt(e);return n}const en=(()=>{let e=new Uint8Array(256);for(let n=0,r=1;n<256;n++,r^=Qt(r))e[n]=r;const t=new Uint8Array(256);t[0]=99;for(let n=0;n<255;n++){let r=e[255-n];r|=r<<8,t[e[n]]=(r^r>>4^r>>5^r>>6^r>>7^99)&255}return t})(),xs=en.map((e,t)=>en.indexOf(t)),Ss=e=>e<<24|e>>>8,tn=e=>e<<8|e>>>24;function sr(e,t){if(e.length!==256)throw new Error("Wrong sbox length");const n=new Uint32Array(256).map((l,f)=>t(e[f])),r=n.map(tn),i=r.map(tn),s=i.map(tn),o=new Uint32Array(256*256),a=new Uint32Array(256*256),c=new Uint16Array(256*256);for(let l=0;l<256;l++)for(let f=0;f<256;f++){const u=l*256+f;o[u]=n[l]^r[f],a[u]=i[l]^s[f],c[u]=e[l]<<8|e[f]}return{sbox:e,sbox2:c,T0:n,T1:r,T2:i,T3:s,T01:o,T23:a}}const nn=sr(en,e=>qe(e,3)<<24|e<<16|e<<8|qe(e,2)),or=sr(xs,e=>qe(e,11)<<24|qe(e,13)<<16|qe(e,9)<<8|qe(e,14)),As=(()=>{const e=new Uint8Array(16);for(let t=0,n=1;t<16;t++,n=Qt(n))e[t]=n;return e})();function ar(e){pe(e);const t=e.length;if(![16,24,32].includes(t))throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${t}`);const{sbox2:n}=nn,r=W(e),i=r.length,s=a=>ae(n,a,a,a,a),o=new Uint32Array(t+28);o.set(r);for(let a=i;a<o.length;a++){let c=o[a-1];a%i===0?c=s(Ss(c))^As[a/i-1]:i>6&&a%i===4&&(c=s(c)),o[a]=o[a-i]^c}return o}function Ks(e){const t=ar(e),n=t.slice(),r=t.length,{sbox2:i}=nn,{T0:s,T1:o,T2:a,T3:c}=or;for(let l=0;l<r;l+=4)for(let f=0;f<4;f++)n[l+f]=t[r-l-4+f];t.fill(0);for(let l=4;l<r-4;l++){const f=n[l],u=ae(i,f,f,f,f);n[l]=s[u&255]^o[u>>>8&255]^a[u>>>16&255]^c[u>>>24]}return n}function Ae(e,t,n,r,i,s){return e[n<<8&65280|r>>>8&255]^t[i>>>8&65280|s>>>24&255]}function ae(e,t,n,r,i){return e[t&255|n&65280]|e[r>>>16&255|i>>>16&65280]<<16}function cr(e,t,n,r,i){const{sbox2:s,T01:o,T23:a}=nn;let c=0;t^=e[c++],n^=e[c++],r^=e[c++],i^=e[c++];const l=e.length/4-2;for(let g=0;g<l;g++){const h=e[c++]^Ae(o,a,t,n,r,i),y=e[c++]^Ae(o,a,n,r,i,t),w=e[c++]^Ae(o,a,r,i,t,n),E=e[c++]^Ae(o,a,i,t,n,r);t=h,n=y,r=w,i=E}const f=e[c++]^ae(s,t,n,r,i),u=e[c++]^ae(s,n,r,i,t),d=e[c++]^ae(s,r,i,t,n),p=e[c++]^ae(s,i,t,n,r);return{s0:f,s1:u,s2:d,s3:p}}function Ns(e,t,n,r,i){const{sbox2:s,T01:o,T23:a}=or;let c=0;t^=e[c++],n^=e[c++],r^=e[c++],i^=e[c++];const l=e.length/4-2;for(let g=0;g<l;g++){const h=e[c++]^Ae(o,a,t,i,r,n),y=e[c++]^Ae(o,a,n,t,i,r),w=e[c++]^Ae(o,a,r,n,t,i),E=e[c++]^Ae(o,a,i,r,n,t);t=h,n=y,r=w,i=E}const f=e[c++]^ae(s,t,i,r,n),u=e[c++]^ae(s,n,t,i,r),d=e[c++]^ae(s,r,n,t,i),p=e[c++]^ae(s,i,r,n,t);return{s0:f,s1:u,s2:d,s3:p}}function lr(e,t){if(!t)return new Uint8Array(e);if(pe(t),t.length<e)throw new Error(`aes: wrong destination length, expected at least ${e}, got: ${t.length}`);return t}function Cs(e){if(pe(e),e.length%Se!==0)throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${Se}`)}function Bs(e,t,n){let r=e.length;const i=r%Se;if(!t&&i!==0)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");const s=W(e);if(t){let c=Se-i;c||(c=Se),r=r+c}const o=lr(r,n),a=W(o);return{b:s,o:a,out:o}}function ks(e,t){if(!t)return e;const n=e.length;if(!n)throw new Error("aes/pcks5: empty ciphertext not allowed");const r=e[n-1];if(r<=0||r>16)throw new Error(`aes/pcks5: wrong padding byte: ${r}`);const i=e.subarray(0,-r);for(let s=0;s<r;s++)if(e[n-s-1]!==r)throw new Error("aes/pcks5: wrong padding");return i}function Is(e){const t=new Uint8Array(16),n=W(t);t.set(e);const r=Se-e.length;for(let i=Se-r;i<Se;i++)t[i]=r;return n}const ur=ms({blockSize:16,nonceLength:16},function(t,n,r={}){pe(t),pe(n,16);const i=!r.disablePadding;return{encrypt:(s,o)=>{const a=ar(t),{b:c,o:l,out:f}=Bs(s,i,o),u=W(n);let d=u[0],p=u[1],g=u[2],h=u[3],y=0;for(;y+4<=c.length;)d^=c[y+0],p^=c[y+1],g^=c[y+2],h^=c[y+3],{s0:d,s1:p,s2:g,s3:h}=cr(a,d,p,g,h),l[y++]=d,l[y++]=p,l[y++]=g,l[y++]=h;if(i){const w=Is(s.subarray(y*4));d^=w[0],p^=w[1],g^=w[2],h^=w[3],{s0:d,s1:p,s2:g,s3:h}=cr(a,d,p,g,h),l[y++]=d,l[y++]=p,l[y++]=g,l[y++]=h}return a.fill(0),f},decrypt:(s,o)=>{Cs(s);const a=Ks(t),c=W(n),l=lr(s.length,o),f=W(s),u=W(l);let d=c[0],p=c[1],g=c[2],h=c[3];for(let y=0;y+4<=f.length;){const w=d,E=p,K=g,U=h;d=f[y+0],p=f[y+1],g=f[y+2],h=f[y+3];const{s0:B,s1:m,s2:x,s3:S}=Ns(a,d,p,g,h);u[y++]=B^w,u[y++]=m^E,u[y++]=x^K,u[y++]=S^U}return a.fill(0),ks(l,i)}}}),fr=e=>Uint8Array.from(e.split("").map(t=>t.charCodeAt(0))),Us=fr("expand 16-byte k"),_s=fr("expand 32-byte k"),Ls=W(Us),hr=W(_s);hr.slice();function _(e,t){return e<<t|e>>>32-t}function rn(e){return e.byteOffset%4===0}const dt=64,Ts=16,dr=2**32-1,yr=new Uint32Array;function $s(e,t,n,r,i,s,o,a){const c=i.length,l=new Uint8Array(dt),f=W(l),u=rn(i)&&rn(s),d=u?W(i):yr,p=u?W(s):yr;for(let g=0;g<c;o++){if(e(t,n,r,f,o,a),o>=dr)throw new Error("arx: counter overflow");const h=Math.min(dt,c-g);if(u&&h===dt){const y=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,E;w<Ts;w++)E=y+w,p[E]=d[E]^f[w];g+=dt;continue}for(let y=0,w;y<h;y++)w=g+y,s[w]=i[w]^l[y];g+=h}}function Rs(e,t){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=bs({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return Xt(i),Xt(o),ir(s),ir(n),(a,c,l,f,u=0)=>{pe(a),pe(c),pe(l);const d=l.length;if(f||(f=new Uint8Array(d)),pe(f),Xt(u),u<0||u>=dr)throw new Error("arx: counter overflow");if(f.length<d)throw new Error(`arx: output (${f.length}) is shorter than data (${d})`);const p=[];let g=a.length,h,y;if(g===32)h=a.slice(),p.push(h),y=hr;else if(g===16&&n)h=new Uint8Array(32),h.set(a),h.set(a,16),y=Ls,p.push(h);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);rn(c)||(c=c.slice(),p.push(c));const w=W(h);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(y,w,W(c.subarray(0,16)),w),c=c.subarray(16)}const E=16-i;if(E!==c.length)throw new Error(`arx: nonce must be ${E} or 16 bytes`);if(E!==12){const U=new Uint8Array(12);U.set(c,s?0:12-c.length),c=U,p.push(c)}const K=W(c);for($s(e,y,w,K,l,f,u,o);p.length>0;)p.pop().fill(0);return f}}function Os(e,t,n,r,i,s=20){let o=e[0],a=e[1],c=e[2],l=e[3],f=t[0],u=t[1],d=t[2],p=t[3],g=t[4],h=t[5],y=t[6],w=t[7],E=i,K=n[0],U=n[1],B=n[2],m=o,x=a,S=c,P=l,I=f,N=u,$=d,R=p,q=g,b=h,v=y,A=w,k=E,C=K,L=U,O=B;for(let te=0;te<s;te+=2)m=m+I|0,k=_(k^m,16),q=q+k|0,I=_(I^q,12),m=m+I|0,k=_(k^m,8),q=q+k|0,I=_(I^q,7),x=x+N|0,C=_(C^x,16),b=b+C|0,N=_(N^b,12),x=x+N|0,C=_(C^x,8),b=b+C|0,N=_(N^b,7),S=S+$|0,L=_(L^S,16),v=v+L|0,$=_($^v,12),S=S+$|0,L=_(L^S,8),v=v+L|0,$=_($^v,7),P=P+R|0,O=_(O^P,16),A=A+O|0,R=_(R^A,12),P=P+R|0,O=_(O^P,8),A=A+O|0,R=_(R^A,7),m=m+N|0,O=_(O^m,16),v=v+O|0,N=_(N^v,12),m=m+N|0,O=_(O^m,8),v=v+O|0,N=_(N^v,7),x=x+$|0,k=_(k^x,16),A=A+k|0,$=_($^A,12),x=x+$|0,k=_(k^x,8),A=A+k|0,$=_($^A,7),S=S+R|0,C=_(C^S,16),q=q+C|0,R=_(R^q,12),S=S+R|0,C=_(C^S,8),q=q+C|0,R=_(R^q,7),P=P+I|0,L=_(L^P,16),b=b+L|0,I=_(I^b,12),P=P+I|0,L=_(L^P,8),b=b+L|0,I=_(I^b,7);let T=0;r[T++]=o+m|0,r[T++]=a+x|0,r[T++]=c+S|0,r[T++]=l+P|0,r[T++]=f+I|0,r[T++]=u+N|0,r[T++]=d+$|0,r[T++]=p+R|0,r[T++]=g+q|0,r[T++]=h+b|0,r[T++]=y+v|0,r[T++]=w+A|0,r[T++]=E+k|0,r[T++]=K+C|0,r[T++]=U+L|0,r[T++]=B+O|0}const pr=Rs(Os,{counterRight:!1,counterLength:4,allowShortKeys:!1});class gr extends zn{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,oe.hash(t);const r=Ye(n);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?t.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),s.fill(0)}update(t){return oe.exists(this),this.iHash.update(t),this}digestInto(t){oe.exists(this),oe.bytes(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return t=t,t.finished=i,t.destroyed=s,t.blockLen=o,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const yt=(e,t,n)=>new gr(e,t).update(n).digest();yt.create=(e,t)=>new gr(e,t);function sn(e,t,n){return oe.hash(e),n===void 0&&(n=new Uint8Array(e.outputLen)),yt(e,Ye(n),Ye(t))}const on=new Uint8Array([0]),wr=new Uint8Array;function br(e,t,n,r=32){if(oe.hash(e),oe.number(r),r>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(r/e.outputLen);n===void 0&&(n=wr);const s=new Uint8Array(i*e.outputLen),o=yt.create(e,t),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let l=0;l<i;l++)on[0]=l+1,a.update(l===0?wr:c).update(n).update(on).digestInto(c),s.set(c,e.outputLen*l),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),on.fill(0),s.slice(0,r)}var Ms=Object.defineProperty,j=(e,t)=>{for(var n in t)Ms(e,n,{get:t[n],enumerable:!0})},De=Symbol("verified"),Ps=e=>e instanceof Object;function vr(e){if(!Ps(e)||typeof e.kind!="number"||typeof e.content!="string"||typeof e.created_at!="number"||typeof e.pubkey!="string"||!e.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(e.tags))return!1;for(let t=0;t<e.tags.length;t++){let n=e.tags[t];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]=="object")return!1}return!0}var Hs={};j(Hs,{Queue:()=>Vs,QueueNode:()=>mr,binarySearch:()=>an,insertEventIntoAscendingList:()=>js,insertEventIntoDescendingList:()=>Ds,normalizeURL:()=>qs,utf8Decoder:()=>ce,utf8Encoder:()=>ee});var ce=new TextDecoder("utf-8"),ee=new TextEncoder;function qs(e){e.indexOf("://")===-1&&(e="wss://"+e);let t=new URL(e);return t.pathname=t.pathname.replace(/\/+/g,"/"),t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),(t.port==="80"&&t.protocol==="ws:"||t.port==="443"&&t.protocol==="wss:")&&(t.port=""),t.searchParams.sort(),t.hash="",t.toString()}function Ds(e,t){const[n,r]=an(e,i=>t.id===i.id?0:t.created_at===i.created_at?-1:i.created_at-t.created_at);return r||e.splice(n,0,t),e}function js(e,t){const[n,r]=an(e,i=>t.id===i.id?0:t.created_at===i.created_at?-1:t.created_at-i.created_at);return r||e.splice(n,0,t),e}function an(e,t){let n=0,r=e.length-1;for(;n<=r;){const i=Math.floor((n+r)/2),s=t(e[i]);if(s===0)return[i,!0];s<0?r=i-1:n=i+1}return[n,!1]}var mr=class{constructor(e){re(this,"value");re(this,"next",null);re(this,"prev",null);this.value=e}},Vs=class{constructor(){re(this,"first");re(this,"last");this.first=null,this.last=null}enqueue(e){const t=new mr(e);return this.last?this.last===this.first?(this.last=t,this.last.prev=this.first,this.first.next=t):(t.prev=this.last,this.last.next=t,this.last=t):(this.first=t,this.last=t),!0}dequeue(){if(!this.first)return null;if(this.first===this.last){const t=this.first;return this.first=null,this.last=null,t.value}const e=this.first;return this.first=e.next,e.value}},zs=class{generateSecretKey(){return Je.utils.randomPrivateKey()}getPublicKey(e){return M(Je.getPublicKey(e))}finalizeEvent(e,t){const n=e;return n.pubkey=M(Je.getPublicKey(t)),n.id=pt(n),n.sig=M(Je.sign(pt(n),t)),n[De]=!0,n}verifyEvent(e){if(typeof e[De]=="boolean")return e[De];const t=pt(e);if(t!==e.id)return e[De]=!1,!1;try{const n=Je.verify(e.sig,t,e.pubkey);return e[De]=n,n}catch{return e[De]=!1,!1}}};function Zs(e){if(!vr(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function pt(e){let t=Ee(ee.encode(Zs(e)));return M(t)}var gt=new zs,je=gt.generateSecretKey,_e=gt.getPublicKey,le=gt.finalizeEvent,wt=gt.verifyEvent,Fs={};j(Fs,{Application:()=>Wo,BadgeAward:()=>no,BadgeDefinition:()=>qo,BlockedRelaysList:()=>No,BookmarkList:()=>So,Bookmarksets:()=>Mo,Calendar:()=>ta,CalendarEventRSVP:()=>na,ChannelCreation:()=>Kr,ChannelHideMessage:()=>Br,ChannelMessage:()=>Cr,ChannelMetadata:()=>Nr,ChannelMuteUser:()=>kr,ClassifiedListing:()=>Yo,ClientAuth:()=>Ir,CommunitiesList:()=>Ao,CommunityDefinition:()=>sa,CommunityPostApproval:()=>fo,Contacts:()=>Xs,CreateOrUpdateProduct:()=>Vo,CreateOrUpdateStall:()=>jo,Curationsets:()=>Po,Date:()=>Qo,DraftClassifiedListing:()=>Xo,DraftLong:()=>Zo,Emojisets:()=>Fo,EncryptedDirectMessage:()=>Qs,EncryptedDirectMessages:()=>eo,EventDeletion:()=>to,FileMetadata:()=>so,FileServerPreference:()=>Io,Followsets:()=>$o,GenericRepost:()=>ro,Genericlists:()=>Ro,HTTPAuth:()=>un,Handlerinformation:()=>ia,Handlerrecommendation:()=>ra,Highlights:()=>vo,InterestsList:()=>Bo,Interestsets:()=>Do,JobFeedback:()=>po,JobRequest:()=>ho,JobResult:()=>yo,Label:()=>uo,LightningPubRPC:()=>_o,LiveChatMessage:()=>oo,LiveEvent:()=>Go,LongFormArticle:()=>zo,Metadata:()=>Gs,Mutelist:()=>mo,NWCWalletInfo:()=>Uo,NWCWalletRequest:()=>Ur,NWCWalletResponse:()=>Lo,NostrConnect:()=>To,OpenTimestamps:()=>io,Pinlist:()=>Eo,ProblemTracker:()=>ao,ProfileBadges:()=>Ho,PublicChatsList:()=>Ko,Reaction:()=>ln,RecommendRelay:()=>Ys,RelayList:()=>xo,Relaysets:()=>Oo,Report:()=>co,Reporting:()=>lo,Repost:()=>cn,SearchRelaysList:()=>Co,ShortTextNote:()=>Js,Time:()=>ea,UserEmojiList:()=>ko,UserStatuses:()=>Jo,Zap:()=>bo,ZapGoal:()=>go,ZapRequest:()=>wo,classifyKind:()=>Ws,isEphemeralKind:()=>Sr,isParameterizedReplaceableKind:()=>Ar,isRegularKind:()=>Er,isReplaceableKind:()=>xr});function Er(e){return 1e3<=e&&e<1e4||[1,2,4,5,6,7,8,16,40,41,42,43,44].includes(e)}function xr(e){return[0,3].includes(e)||1e4<=e&&e<2e4}function Sr(e){return 2e4<=e&&e<3e4}function Ar(e){return 3e4<=e&&e<4e4}function Ws(e){return Er(e)?"regular":xr(e)?"replaceable":Sr(e)?"ephemeral":Ar(e)?"parameterized":"unknown"}var Gs=0,Js=1,Ys=2,Xs=3,Qs=4,eo=4,to=5,cn=6,ln=7,no=8,ro=16,Kr=40,Nr=41,Cr=42,Br=43,kr=44,io=1040,so=1063,oo=1311,ao=1971,co=1984,lo=1984,uo=1985,fo=4550,ho=5999,yo=6999,po=7e3,go=9041,wo=9734,bo=9735,vo=9802,mo=1e4,Eo=10001,xo=10002,So=10003,Ao=10004,Ko=10005,No=10006,Co=10007,Bo=10015,ko=10030,Io=10096,Uo=13194,_o=21e3,Ir=22242,Ur=23194,Lo=23195,To=24133,un=27235,$o=3e4,Ro=30001,Oo=30002,Mo=30003,Po=30004,Ho=30008,qo=30009,Do=30015,jo=30017,Vo=30018,zo=30023,Zo=30024,Fo=30030,Wo=30078,Go=30311,Jo=30315,Yo=30402,Xo=30403,Qo=31922,ea=31923,ta=31924,na=31925,ra=31989,ia=31990,sa=34550,oa={};j(oa,{getHex64:()=>fn,getInt:()=>_r,getSubscriptionId:()=>aa,matchEventId:()=>ca,matchEventKind:()=>ua,matchEventPubkey:()=>la});function fn(e,t){let n=t.length+3,r=e.indexOf(`"${t}":`)+n,i=e.slice(r).indexOf('"')+r+1;return e.slice(i,i+64)}function _r(e,t){let n=t.length,r=e.indexOf(`"${t}":`)+n+3,i=e.slice(r),s=Math.min(i.indexOf(","),i.indexOf("}"));return parseInt(i.slice(0,s),10)}function aa(e){let t=e.slice(0,22).indexOf('"EVENT"');if(t===-1)return null;let n=e.slice(t+7+1).indexOf('"');if(n===-1)return null;let r=t+7+1+n,i=e.slice(r+1,80).indexOf('"');if(i===-1)return null;let s=r+1+i;return e.slice(r+1,s)}function ca(e,t){return t===fn(e,"id")}function la(e,t){return t===fn(e,"pubkey")}function ua(e,t){return t===_r(e,"kind")}var fa={};j(fa,{makeAuthEvent:()=>ha});function ha(e,t){return{kind:Ir,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",t]],content:""}}var da;try{da=WebSocket}catch{}var ya;try{ya=WebSocket}catch{}var pa={};j(pa,{BECH32_REGEX:()=>Lr,Bech32MaxSize:()=>hn,decode:()=>bt,encodeBytes:()=>mt,naddrEncode:()=>xa,neventEncode:()=>Ea,noteEncode:()=>va,nprofileEncode:()=>ma,npubEncode:()=>ba,nrelayEncode:()=>Sa,nsecEncode:()=>wa});var hn=5e3,Lr=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function ga(e){const t=new Uint8Array(4);return t[0]=e>>24&255,t[1]=e>>16&255,t[2]=e>>8&255,t[3]=e&255,t}function bt(e){var i,s,o,a,c,l,f,u;let{prefix:t,words:n}=He.decode(e,hn),r=new Uint8Array(He.fromWords(n));switch(t){case"nprofile":{let d=vt(r);if(!((i=d[0])!=null&&i[0]))throw new Error("missing TLV 0 for nprofile");if(d[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:M(d[0][0]),relays:d[1]?d[1].map(p=>ce.decode(p)):[]}}}case"nevent":{let d=vt(r);if(!((s=d[0])!=null&&s[0]))throw new Error("missing TLV 0 for nevent");if(d[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(d[2]&&d[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(d[3]&&d[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:M(d[0][0]),relays:d[1]?d[1].map(p=>ce.decode(p)):[],author:(o=d[2])!=null&&o[0]?M(d[2][0]):void 0,kind:(a=d[3])!=null&&a[0]?parseInt(M(d[3][0]),16):void 0}}}case"naddr":{let d=vt(r);if(!((c=d[0])!=null&&c[0]))throw new Error("missing TLV 0 for naddr");if(!((l=d[2])!=null&&l[0]))throw new Error("missing TLV 2 for naddr");if(d[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!((f=d[3])!=null&&f[0]))throw new Error("missing TLV 3 for naddr");if(d[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:ce.decode(d[0][0]),pubkey:M(d[2][0]),kind:parseInt(M(d[3][0]),16),relays:d[1]?d[1].map(p=>ce.decode(p)):[]}}}case"nrelay":{let d=vt(r);if(!((u=d[0])!=null&&u[0]))throw new Error("missing TLV 0 for nrelay");return{type:"nrelay",data:ce.decode(d[0][0])}}case"nsec":return{type:t,data:r};case"npub":case"note":return{type:t,data:M(r)};default:throw new Error(`unknown prefix ${t}`)}}function vt(e){let t={},n=e;for(;n.length>0;){let r=n[0],i=n[1],s=n.slice(2,2+i);if(n=n.slice(2+i),s.length<i)throw new Error(`not enough data to read on TLV ${r}`);t[r]=t[r]||[],t[r].push(s)}return t}function wa(e){return mt("nsec",e)}function ba(e){return mt("npub",G(e))}function va(e){return mt("note",G(e))}function Qe(e,t){let n=He.toWords(t);return He.encode(e,n,hn)}function mt(e,t){return Qe(e,t)}function ma(e){let t=Et({0:[G(e.pubkey)],1:(e.relays||[]).map(n=>ee.encode(n))});return Qe("nprofile",t)}function Ea(e){let t;e.kind!==void 0&&(t=ga(e.kind));let n=Et({0:[G(e.id)],1:(e.relays||[]).map(r=>ee.encode(r)),2:e.author?[G(e.author)]:[],3:t?[new Uint8Array(t)]:[]});return Qe("nevent",n)}function xa(e){let t=new ArrayBuffer(4);new DataView(t).setUint32(0,e.kind,!1);let n=Et({0:[ee.encode(e.identifier)],1:(e.relays||[]).map(r=>ee.encode(r)),2:[G(e.pubkey)],3:[new Uint8Array(t)]});return Qe("naddr",n)}function Sa(e){let t=Et({0:[ee.encode(e)]});return Qe("nrelay",t)}function Et(e){let t=[];return Object.entries(e).reverse().forEach(([n,r])=>{r.forEach(i=>{let s=new Uint8Array(i.length+2);s.set([parseInt(n)],0),s.set([i.length],1),s.set(i,2),t.push(s)})}),ut(...t)}var Aa={};j(Aa,{decrypt:()=>Ka,encrypt:()=>Tr});async function Tr(e,t,n){const r=e instanceof Uint8Array?M(e):e,i=Ue.getSharedSecret(r,"02"+t),s=$r(i);let o=Uint8Array.from(Fn(16)),a=ee.encode(n),c=ur(s,o).encrypt(a),l=ye.encode(new Uint8Array(c)),f=ye.encode(new Uint8Array(o.buffer));return`${l}?iv=${f}`}async function Ka(e,t,n){const r=e instanceof Uint8Array?M(e):e;let[i,s]=n.split("?iv="),o=Ue.getSharedSecret(r,"02"+t),a=$r(o),c=ye.decode(s),l=ye.decode(i),f=ur(a,c).decrypt(l);return ce.decode(f)}function $r(e){return e.slice(1,33)}var Na={};j(Na,{NIP05_REGEX:()=>Rr,isValid:()=>ka,queryProfile:()=>Or,searchDomain:()=>Ba,useFetchImplementation:()=>Ca});var Rr=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,xt;try{xt=fetch}catch{}function Ca(e){xt=e}async function Ba(e,t=""){try{const n=`https://${e}/.well-known/nostr.json?name=${t}`;return(await(await xt(n,{redirect:"error"})).json()).names}catch{return{}}}async function Or(e){var s;const t=e.match(Rr);if(!t)return null;const[n,r="_",i]=t;try{const o=`https://${i}/.well-known/nostr.json?name=${r}`,a=await(await xt(o,{redirect:"error"})).json();let c=a.names[r];return c?{pubkey:c,relays:(s=a.relays)==null?void 0:s[c]}:null}catch{return null}}async function ka(e,t){let n=await Or(t);return n?n.pubkey===e:!1}var Ia={};j(Ia,{parse:()=>Ua});function Ua(e){const t={reply:void 0,root:void 0,mentions:[],profiles:[]},n=[];for(const r of e.tags)r[0]==="e"&&r[1]&&n.push(r),r[0]==="p"&&r[1]&&t.profiles.push({pubkey:r[1],relays:r[2]?[r[2]]:[]});for(let r=0;r<n.length;r++){const i=n[r],[s,o,a,c]=i,l={id:o,relays:a?[a]:[]},f=r===0,u=r===n.length-1;if(c==="root"){t.root=l;continue}if(c==="reply"){t.reply=l;continue}if(c==="mention"){t.mentions.push(l);continue}if(f){t.root=l;continue}if(u){t.reply=l;continue}t.mentions.push(l)}return t}var _a={};j(_a,{fetchRelayInformation:()=>Ta,useFetchImplementation:()=>La});var Mr;try{Mr=fetch}catch{}function La(e){Mr=e}async function Ta(e){return await(await fetch(e.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var $a={};j($a,{getPow:()=>Pr,minePow:()=>Ra});function Pr(e){let t=0;for(let n=0;n<e.length;n++){const r=parseInt(e[n],16);if(r===0)t+=4;else{t+=Math.clz32(r)-28;break}}return t}function Ra(e,t){let n=0;const r=e,i=["nonce",n.toString(),t.toString()];for(r.tags.push(i);;){const s=Math.floor(new Date().getTime()/1e3);if(s!==r.created_at&&(n=0,r.created_at=s),i[1]=(++n).toString(),r.id=pt(r),Pr(r.id)>=t)break}return r}var Oa={};j(Oa,{finishRepostEvent:()=>Ma,getRepostedEvent:()=>Pa,getRepostedEventPointer:()=>Hr});function Ma(e,t,n,r){return le({kind:cn,tags:[...e.tags??[],["e",t.id,n],["p",t.pubkey]],content:e.content===""?"":JSON.stringify(t),created_at:e.created_at},r)}function Hr(e){if(e.kind!==cn)return;let t,n;for(let r=e.tags.length-1;r>=0&&(t===void 0||n===void 0);r--){const i=e.tags[r];i.length>=2&&(i[0]==="e"&&t===void 0?t=i:i[0]==="p"&&n===void 0&&(n=i))}if(t!==void 0)return{id:t[1],relays:[t[2],n==null?void 0:n[2]].filter(r=>typeof r=="string"),author:n==null?void 0:n[1]}}function Pa(e,{skipVerification:t}={}){const n=Hr(e);if(n===void 0||e.content==="")return;let r;try{r=JSON.parse(e.content)}catch{return}if(r.id===n.id&&!(!t&&!wt(r)))return r}var Ha={};j(Ha,{NOSTR_URI_REGEX:()=>St,parse:()=>Da,test:()=>qa});var St=new RegExp(`nostr:(${Lr.source})`);function qa(e){return typeof e=="string"&&new RegExp(`^${St.source}$`).test(e)}function Da(e){const t=e.match(new RegExp(`^${St.source}$`));if(!t)throw new Error(`Invalid Nostr URI: ${e}`);return{uri:t[0],value:t[1],decoded:bt(t[1])}}var ja={};j(ja,{finishReactionEvent:()=>Va,getReactedEventPointer:()=>za});function Va(e,t,n){const r=t.tags.filter(i=>i.length>=2&&(i[0]==="e"||i[0]==="p"));return le({...e,kind:ln,tags:[...e.tags??[],...r,["e",t.id],["p",t.pubkey]],content:e.content??"+"},n)}function za(e){if(e.kind!==ln)return;let t,n;for(let r=e.tags.length-1;r>=0&&(t===void 0||n===void 0);r--){const i=e.tags[r];i.length>=2&&(i[0]==="e"&&t===void 0?t=i:i[0]==="p"&&n===void 0&&(n=i))}if(!(t===void 0||n===void 0))return{id:t[1],relays:[t[2],n[2]].filter(r=>r!==void 0),author:n[1]}}var Za={};j(Za,{matchAll:()=>Fa,regex:()=>dn,replaceAll:()=>Wa});var dn=()=>new RegExp(`\\b${St.source}\\b`,"g");function*Fa(e){const t=e.matchAll(dn());for(const n of t)try{const[r,i]=n;yield{uri:r,value:i,decoded:bt(i),start:n.index,end:n.index+r.length}}catch{}}function Wa(e,t){return e.replaceAll(dn(),(n,r)=>t({uri:n,value:r,decoded:bt(r)}))}var Ga={};j(Ga,{channelCreateEvent:()=>Ja,channelHideMessageEvent:()=>Qa,channelMessageEvent:()=>Xa,channelMetadataEvent:()=>Ya,channelMuteUserEvent:()=>ec});var Ja=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return le({kind:Kr,tags:[...e.tags??[]],content:n,created_at:e.created_at},t)},Ya=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return le({kind:Nr,tags:[["e",e.channel_create_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},Xa=(e,t)=>{const n=[["e",e.channel_create_event_id,e.relay_url,"root"]];return e.reply_to_channel_message_event_id&&n.push(["e",e.reply_to_channel_message_event_id,e.relay_url,"reply"]),le({kind:Cr,tags:[...n,...e.tags??[]],content:e.content,created_at:e.created_at},t)},Qa=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return le({kind:Br,tags:[["e",e.channel_message_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},ec=(e,t)=>{let n;if(typeof e.content=="object")n=JSON.stringify(e.content);else if(typeof e.content=="string")n=e.content;else return;return le({kind:kr,tags:[["p",e.pubkey_to_mute],...e.tags??[]],content:n,created_at:e.created_at},t)},tc={};j(tc,{EMOJI_SHORTCODE_REGEX:()=>qr,matchAll:()=>nc,regex:()=>yn,replaceAll:()=>rc});var qr=/:(\w+):/,yn=()=>new RegExp(`\\B${qr.source}\\B`,"g");function*nc(e){const t=e.matchAll(yn());for(const n of t)try{const[r,i]=n;yield{shortcode:r,name:i,start:n.index,end:n.index+r.length}}catch{}}function rc(e,t){return e.replaceAll(yn(),(n,r)=>t({shortcode:n,name:r}))}var ic={};j(ic,{useFetchImplementation:()=>sc,validateGithub:()=>oc});var pn;try{pn=fetch}catch{}function sc(e){pn=e}async function oc(e,t,n){try{return await(await pn(`https://gist.github.com/${t}/${n}/raw`)).text()===`Verifying that I control the following Nostr public key: ${e}`}catch{return!1}}var V={};j(V,{decrypt:()=>Wr,encrypt:()=>Fr,getConversationKey:()=>Vr,v2:()=>fc});var Dr=1,jr=65535;function Vr(e,t){const n=Ue.getSharedSecret(e,"02"+t).subarray(1,33);return sn(Ee,n,"nip44-v2")}function zr(e,t){const n=br(Ee,e,t,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function gn(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("expected positive integer");if(e<=32)return 32;const t=1<<Math.floor(Math.log2(e-1))+1,n=t<=256?32:t/8;return n*(Math.floor((e-1)/n)+1)}function ac(e){if(!Number.isSafeInteger(e)||e<Dr||e>jr)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");const t=new Uint8Array(2);return new DataView(t.buffer).setUint16(0,e,!1),t}function cc(e){const t=ee.encode(e),n=t.length,r=ac(n),i=new Uint8Array(gn(n)-n);return ut(r,t,i)}function lc(e){const t=new DataView(e.buffer).getUint16(0),n=e.subarray(2,2+t);if(t<Dr||t>jr||n.length!==t||e.length!==2+gn(t))throw new Error("invalid padding");return ce.decode(n)}function Zr(e,t,n){if(n.length!==32)throw new Error("AAD associated data must be 32 bytes");const r=ut(n,t);return yt(Ee,e,r)}function uc(e){if(typeof e!="string")throw new Error("payload must be a valid string");const t=e.length;if(t<132||t>87472)throw new Error("invalid payload length: "+t);if(e[0]==="#")throw new Error("unknown encryption version");let n;try{n=ye.decode(e)}catch(s){throw new Error("invalid base64: "+s.message)}const r=n.length;if(r<99||r>65603)throw new Error("invalid data length: "+r);const i=n[0];if(i!==2)throw new Error("unknown encryption version "+i);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}function Fr(e,t,n=Fn(32)){const{chacha_key:r,chacha_nonce:i,hmac_key:s}=zr(t,n),o=cc(e),a=pr(r,i,o),c=Zr(s,a,n);return ye.encode(ut(new Uint8Array([2]),n,a,c))}function Wr(e,t){const{nonce:n,ciphertext:r,mac:i}=uc(e),{chacha_key:s,chacha_nonce:o,hmac_key:a}=zr(t,n),c=Zr(a,r,n);if(!vs(c,i))throw new Error("invalid MAC");const l=pr(s,o,r);return lc(l)}var fc={utils:{getConversationKey:Vr,calcPaddedLen:gn},encrypt:Fr,decrypt:Wr},hc={};j(hc,{makeNwcRequestEvent:()=>yc,parseConnectionString:()=>dc});function dc(e){const{pathname:t,searchParams:n}=new URL(e),r=t,i=n.get("relay"),s=n.get("secret");if(!r||!i||!s)throw new Error("invalid connection string");return{pubkey:r,relay:i,secret:s}}async function yc(e,t,n){const i=await Tr(t,e,JSON.stringify({method:"pay_invoice",params:{invoice:n}})),s={kind:Ur,created_at:Math.round(Date.now()/1e3),content:i,tags:[["p",e]]};return le(s,t)}var pc={};j(pc,{getZapEndpoint:()=>wc,makeZapReceipt:()=>mc,makeZapRequest:()=>bc,useFetchImplementation:()=>gc,validateZapRequest:()=>vc});var wn;try{wn=fetch}catch{}function gc(e){wn=e}async function wc(e){try{let t="",{lud06:n,lud16:r}=JSON.parse(e.content);if(n){let{words:o}=He.decode(n,1e3),a=He.fromWords(o);t=ce.decode(a)}else if(r){let[o,a]=r.split("@");t=new URL(`/.well-known/lnurlp/${o}`,`https://${a}`).toString()}else return null;let s=await(await wn(t)).json();if(s.allowsNostr&&s.nostrPubkey)return s.callback}catch{}return null}function bc({profile:e,event:t,amount:n,relays:r,comment:i=""}){if(!n)throw new Error("amount not given");if(!e)throw new Error("profile not given");let s={kind:9734,created_at:Math.round(Date.now()/1e3),content:i,tags:[["p",e],["amount",n.toString()],["relays",...r]]};return t&&s.tags.push(["e",t]),s}function vc(e){let t;try{t=JSON.parse(e)}catch{return"Invalid zap request JSON."}if(!vr(t))return"Zap request is not a valid Nostr event.";if(!wt(t))return"Invalid signature on zap request.";let n=t.tags.find(([s,o])=>s==="p"&&o);if(!n)return"Zap request doesn't have a 'p' tag.";if(!n[1].match(/^[a-f0-9]{64}$/))return"Zap request 'p' tag is not valid hex.";let r=t.tags.find(([s,o])=>s==="e"&&o);return r&&!r[1].match(/^[a-f0-9]{64}$/)?"Zap request 'e' tag is not valid hex.":t.tags.find(([s,o])=>s==="relays"&&o)?null:"Zap request doesn't have a 'relays' tag."}function mc({zapRequest:e,preimage:t,bolt11:n,paidAt:r}){let i=JSON.parse(e),s=i.tags.filter(([a])=>a==="e"||a==="p"||a==="a"),o={kind:9735,created_at:Math.round(r.getTime()/1e3),content:"",tags:[...s,["P",i.pubkey],["bolt11",n],["description",e]]};return t&&o.tags.push(["preimage",t]),o}var Ec={};j(Ec,{getToken:()=>xc,hashPayload:()=>bn,unpackEventFromToken:()=>Jr,validateEvent:()=>ni,validateEventKind:()=>Xr,validateEventMethodTag:()=>ei,validateEventPayloadTag:()=>ti,validateEventTimestamp:()=>Yr,validateEventUrlTag:()=>Qr,validateToken:()=>Sc});var Gr="Nostr ";async function xc(e,t,n,r=!1,i){const s={kind:un,tags:[["u",e],["method",t]],created_at:Math.round(new Date().getTime()/1e3),content:""};i&&s.tags.push(["payload",bn(i)]);const o=await n(s);return(r?Gr:"")+ye.encode(ee.encode(JSON.stringify(o)))}async function Sc(e,t,n){const r=await Jr(e).catch(s=>{throw s});return await ni(r,t,n).catch(s=>{throw s})}async function Jr(e){if(!e)throw new Error("Missing token");e=e.replace(Gr,"");const t=ce.decode(ye.decode(e));if(!t||t.length===0||!t.startsWith("{"))throw new Error("Invalid token");return JSON.parse(t)}function Yr(e){return e.created_at?Math.round(new Date().getTime()/1e3)-e.created_at<60:!1}function Xr(e){return e.kind===un}function Qr(e,t){const n=e.tags.find(r=>r[0]==="u");return n?n.length>0&&n[1]===t:!1}function ei(e,t){const n=e.tags.find(r=>r[0]==="method");return n?n.length>0&&n[1].toLowerCase()===t.toLowerCase():!1}function bn(e){const t=Ee(ee.encode(JSON.stringify(e)));return M(t)}function ti(e,t){const n=e.tags.find(i=>i[0]==="payload");if(!n)return!1;const r=bn(t);return n.length>0&&n[1]===r}async function ni(e,t,n,r){if(!wt(e))throw new Error("Invalid nostr event, signature invalid");if(!Xr(e))throw new Error("Invalid nostr event, kind invalid");if(!Yr(e))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!Qr(e,t))throw new Error("Invalid nostr event, url tag invalid");if(!ei(e,n))throw new Error("Invalid nostr event, method tag invalid");if(r&&typeof r=="object"&&Object.keys(r).length>0&&!ti(e,r))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}const Le=4,vn=30078,Ac=100;var ri=(e=>(e[e.Us=0]="Us",e[e.Them=1]="Them",e))(ri||{});function Kc(e){return JSON.stringify({rootKey:M(e.rootKey),theirNostrPublicKey:e.theirNostrPublicKey,ourCurrentNostrKey:e.ourCurrentNostrKey?{publicKey:e.ourCurrentNostrKey.publicKey,privateKey:M(e.ourCurrentNostrKey.privateKey)}:void 0,ourNextNostrKey:{publicKey:e.ourNextNostrKey.publicKey,privateKey:M(e.ourNextNostrKey.privateKey)},receivingChainKey:e.receivingChainKey?M(e.receivingChainKey):void 0,sendingChainKey:e.sendingChainKey?M(e.sendingChainKey):void 0,sendingChainMessageNumber:e.sendingChainMessageNumber,receivingChainMessageNumber:e.receivingChainMessageNumber,previousSendingChainMessageCount:e.previousSendingChainMessageCount,skippedMessageKeys:Object.fromEntries(Object.entries(e.skippedMessageKeys).map(([t,n])=>[t,M(n)])),skippedHeaderKeys:Object.fromEntries(Object.entries(e.skippedHeaderKeys).map(([t,n])=>[t,n.map(r=>M(r))]))})}function Nc(e){const t=JSON.parse(e);return{rootKey:G(t.rootKey),theirNostrPublicKey:t.theirNostrPublicKey,ourCurrentNostrKey:t.ourCurrentNostrKey?{publicKey:t.ourCurrentNostrKey.publicKey,privateKey:G(t.ourCurrentNostrKey.privateKey)}:void 0,ourNextNostrKey:{publicKey:t.ourNextNostrKey.publicKey,privateKey:G(t.ourNextNostrKey.privateKey)},receivingChainKey:t.receivingChainKey?G(t.receivingChainKey):void 0,sendingChainKey:t.sendingChainKey?G(t.sendingChainKey):void 0,sendingChainMessageNumber:t.sendingChainMessageNumber,receivingChainMessageNumber:t.receivingChainMessageNumber,previousSendingChainMessageCount:t.previousSendingChainMessageCount,skippedMessageKeys:Object.fromEntries(Object.entries(t.skippedMessageKeys).map(([n,r])=>[n,G(r)])),skippedHeaderKeys:Object.fromEntries(Object.entries(t.skippedHeaderKeys||{}).map(([n,r])=>[n,r.map(i=>G(i))]))}}async function*Cc(e){const t=[];let n=null;const r=e.onMessage(i=>{n?(n(i),n=null):t.push(i)});try{for(;;)t.length>0?yield t.shift():yield new Promise(i=>{n=i})}finally{r()}}function Te(e,t=new Uint8Array(32),n=1){const r=sn(Ee,e,t),i=[];for(let s=1;s<=n;s++)i.push(br(Ee,r,new Uint8Array([s]),32));return i}function At(e,t){return`${e}:${t}`}const Bc=1e3;class et{constructor(t,n){re(this,"nostrUnsubscribe");re(this,"nostrNextUnsubscribe");re(this,"internalSubscriptions",new Map);re(this,"currentInternalSubscriptionId",0);re(this,"name");this.nostrSubscribe=t,this.state=n,this.name=Math.random().toString(36).substring(2,6)}static init(t,n,r,i,s,o){const a=je(),[c,l]=Te(s,V.getConversationKey(a,n),2);let f,u;i?(f={publicKey:_e(r),privateKey:r},u={publicKey:_e(a),privateKey:a}):u={publicKey:_e(r),privateKey:r};const d={rootKey:i?c:s,theirNostrPublicKey:n,ourCurrentNostrKey:f,ourNextNostrKey:u,receivingChainKey:void 0,sendingChainKey:i?l:void 0,sendingChainMessageNumber:0,receivingChainMessageNumber:0,previousSendingChainMessageCount:0,skippedMessageKeys:{},skippedHeaderKeys:{}},p=new et(t,d);return o&&(p.name=o),p}send(t){if(!this.state.theirNostrPublicKey||!this.state.ourCurrentNostrKey)throw new Error("we are not the initiator, so we can't send the first message");const[n,r]=this.ratchetEncrypt(t),i=V.getConversationKey(this.state.ourCurrentNostrKey.privateKey,this.state.theirNostrPublicKey),s=V.encrypt(JSON.stringify(n),i);return le({content:r,kind:Le,tags:[["header",s]],created_at:Math.floor(Date.now()/1e3)},this.state.ourCurrentNostrKey.privateKey)}onMessage(t){const n=this.currentInternalSubscriptionId++;return this.internalSubscriptions.set(n,t),this.subscribeToNostrEvents(),()=>this.internalSubscriptions.delete(n)}close(){var t,n;(t=this.nostrUnsubscribe)==null||t.call(this),(n=this.nostrNextUnsubscribe)==null||n.call(this)}ratchetEncrypt(t){const[n,r]=Te(this.state.sendingChainKey,new Uint8Array([1]),2);return this.state.sendingChainKey=n,[{number:this.state.sendingChainMessageNumber++,nextPublicKey:this.state.ourNextNostrKey.publicKey,time:Date.now(),previousChainLength:this.state.previousSendingChainMessageCount},V.encrypt(t,r)]}ratchetDecrypt(t,n,r){const i=this.trySkippedMessageKeys(t,n,r);if(i)return i;this.skipMessageKeys(t.number,r);const[s,o]=Te(this.state.receivingChainKey,new Uint8Array([1]),2);this.state.receivingChainKey=s,this.state.receivingChainMessageNumber++;try{return V.decrypt(n,o)}catch(a){throw console.error(this.name,"Decryption failed:",a,{messageKey:M(o).slice(0,4),receivingChainKey:M(this.state.receivingChainKey).slice(0,4),sendingChainKey:this.state.sendingChainKey&&M(this.state.sendingChainKey).slice(0,4),rootKey:M(this.state.rootKey).slice(0,4)}),a}}ratchetStep(t){this.state.previousSendingChainMessageCount=this.state.sendingChainMessageNumber,this.state.sendingChainMessageNumber=0,this.state.receivingChainMessageNumber=0,this.state.theirNostrPublicKey=t;const n=V.getConversationKey(this.state.ourNextNostrKey.privateKey,this.state.theirNostrPublicKey),[r,i]=Te(this.state.rootKey,n,2);this.state.receivingChainKey=i,this.state.ourCurrentNostrKey=this.state.ourNextNostrKey;const s=je();this.state.ourNextNostrKey={publicKey:_e(s),privateKey:s};const o=V.getConversationKey(this.state.ourNextNostrKey.privateKey,this.state.theirNostrPublicKey),[a,c]=Te(r,o,2);this.state.rootKey=a,this.state.sendingChainKey=c}skipMessageKeys(t,n){if(this.state.receivingChainMessageNumber+Bc<t)throw new Error("Too many skipped messages");for(;this.state.receivingChainMessageNumber<t;){const[r,i]=Te(this.state.receivingChainKey,new Uint8Array([1]),2);this.state.receivingChainKey=r;const s=At(n,this.state.receivingChainMessageNumber);if(this.state.skippedMessageKeys[s]=i,!this.state.skippedHeaderKeys[n]){const o=[];if(this.state.ourCurrentNostrKey){const c=V.getConversationKey(this.state.ourCurrentNostrKey.privateKey,n);o.push(c)}const a=V.getConversationKey(this.state.ourNextNostrKey.privateKey,n);o.push(a),this.state.skippedHeaderKeys[n]=o}this.state.receivingChainMessageNumber++}}trySkippedMessageKeys(t,n,r){var s;const i=At(r,t.number);if(i in this.state.skippedMessageKeys){const o=this.state.skippedMessageKeys[i];return delete this.state.skippedMessageKeys[i],Object.keys(this.state.skippedMessageKeys).some(c=>c.startsWith(`${r}:`))||(delete this.state.skippedHeaderKeys[r],(s=this.nostrUnsubscribe)==null||s.call(this),this.nostrUnsubscribe=void 0),V.decrypt(n,o)}return null}decryptHeader(t){const n=t.tags[0][1];if(this.state.ourCurrentNostrKey){const s=V.getConversationKey(this.state.ourCurrentNostrKey.privateKey,t.pubkey);try{return[JSON.parse(V.decrypt(n,s)),!1,!1]}catch{}}const r=V.getConversationKey(this.state.ourNextNostrKey.privateKey,t.pubkey);try{return[JSON.parse(V.decrypt(n,r)),!0,!1]}catch{}const i=this.state.skippedHeaderKeys[t.pubkey];if(i)for(const s of i)try{return[JSON.parse(V.decrypt(n,s)),!1,!0]}catch{}throw new Error("Failed to decrypt header with current and skipped header keys")}handleNostrEvent(t){var o;const[n,r,i]=this.decryptHeader(t);if(!i)this.state.theirNostrPublicKey!==n.nextPublicKey&&(this.state.theirNostrPublicKey=n.nextPublicKey,(o=this.nostrUnsubscribe)==null||o.call(this),this.nostrUnsubscribe=this.nostrNextUnsubscribe,this.nostrNextUnsubscribe=this.nostrSubscribe({authors:[this.state.theirNostrPublicKey],kinds:[Le]},a=>this.handleNostrEvent(a))),r&&(this.skipMessageKeys(n.previousChainLength,t.pubkey),this.ratchetStep(n.nextPublicKey));else if(!(At(t.pubkey,n.number)in this.state.skippedMessageKeys))return;const s=this.ratchetDecrypt(n,t.content,t.pubkey);this.internalSubscriptions.forEach(a=>a({id:t.id,data:s,pubkey:n.nextPublicKey,time:n.time}))}subscribeToNostrEvents(){if(this.nostrNextUnsubscribe)return;this.nostrNextUnsubscribe=this.nostrSubscribe({authors:[this.state.theirNostrPublicKey],kinds:[Le]},n=>this.handleNostrEvent(n));const t=Object.keys(this.state.skippedHeaderKeys);t.length>0&&(this.nostrUnsubscribe=this.nostrSubscribe({authors:t,kinds:[Le]},n=>this.handleNostrEvent(n)))}}new TextDecoder("utf-8"),new TextEncoder;function Kt(e,t){const n=Ue.getSharedSecret(e,"02"+t).subarray(1,33);return sn(Ee,n,"nip44-v2")}class $e{constructor(t,n,r,i,s,o,a=[]){this.inviterSessionPublicKey=t,this.linkSecret=n,this.inviter=r,this.inviterSessionPrivateKey=i,this.label=s,this.maxUses=o,this.usedBy=a}static createNew(t,n,r){const i=je(),s=_e(i),o=M(je());return new $e(s,o,t,i,n,r)}static fromUrl(t){const r=new URL(t).hash.slice(1);if(!r)throw new Error("No invite data found in the URL hash.");const i=decodeURIComponent(r);let s;try{s=JSON.parse(i)}catch(l){throw new Error("Invite data in URL hash is not valid JSON: "+l)}const{inviter:o,sessionKey:a,linkSecret:c}=s;if(!o||!a||!c)throw new Error("Missing required fields (inviter, sessionKey, linkSecret) in invite data.");return new $e(a,c,o)}static deserialize(t){const n=JSON.parse(t);return new $e(n.inviterSessionPublicKey,n.linkSecret,n.inviter,n.inviterSessionPrivateKey?new Uint8Array(n.inviterSessionPrivateKey):void 0,n.label,n.maxUses,n.usedBy)}static fromEvent(t){var o,a;if(!t.sig)throw new Error("Event is not signed");if(!wt(t))throw new Error("Event signature is invalid");const{tags:n}=t,r=(o=n.find(([c])=>c==="sessionKey"))==null?void 0:o[1],i=(a=n.find(([c])=>c==="linkSecret"))==null?void 0:a[1],s=t.pubkey;if(!r||!i)throw new Error("Invalid invite event: missing session key or link secret");return new $e(r,i,s)}static fromUser(t,n){const r={kinds:[vn],authors:[t],limit:1,"#d":["nostr-double-ratchet/invite"]};return new Promise(i=>{const s=n(r,o=>{try{const a=$e.fromEvent(o);s(),i(a)}catch{s(),i(void 0)}});setTimeout(()=>{s(),i(void 0)},1e4)})}serialize(){return JSON.stringify({inviterSessionPublicKey:this.inviterSessionPublicKey,linkSecret:this.linkSecret,inviter:this.inviter,inviterSessionPrivateKey:this.inviterSessionPrivateKey?Array.from(this.inviterSessionPrivateKey):void 0,label:this.label,maxUses:this.maxUses,usedBy:this.usedBy})}getUrl(t="https://iris.to"){const n={inviter:this.inviter,sessionKey:this.inviterSessionPublicKey,linkSecret:this.linkSecret},r=new URL(t);return r.hash=encodeURIComponent(JSON.stringify(n)),console.log("url",r.toString()),r.toString()}getEvent(){return{kind:vn,pubkey:this.inviter,content:"",created_at:Math.floor(Date.now()/1e3),tags:[["sessionKey",this.inviterSessionPublicKey],["linkSecret",this.linkSecret],["d","nostr-double-ratchet/invite"]]}}async accept(t,n,r){const i=je(),s=_e(i),o=this.inviter||this.inviterSessionPublicKey,a=G(this.linkSecret),c=et.init(t,this.inviterSessionPublicKey,i,!0,a,void 0),l=je(),f=_e(l),u=typeof r=="function"?r:(g,h)=>Promise.resolve(V.encrypt(g,Kt(r,h))),d={pubkey:n,tags:[["secret",this.linkSecret]],content:await u(s,o),created_at:Math.floor(Date.now()/1e3)},p={kind:Le,pubkey:f,content:V.encrypt(JSON.stringify(d),Kt(l,this.inviterSessionPublicKey)),created_at:Math.floor(Date.now()/1e3),tags:[["p",this.inviterSessionPublicKey]]};return{channel:c,event:le(p,l)}}listen(t,n,r){if(!this.inviterSessionPrivateKey)throw new Error("Inviter session key is not available");const i={kinds:[Le],"#p":[this.inviterSessionPublicKey]};return n(i,async s=>{try{if(this.maxUses&&this.usedBy.length>=this.maxUses){console.error("Invite has reached maximum number of uses");return}const o=await V.decrypt(s.content,Kt(this.inviterSessionPrivateKey,s.pubkey)),a=JSON.parse(o);if(!a.tags||!a.tags.some(([g,h])=>g==="secret"&&h===this.linkSecret)){console.error("Invalid secret from event",s);return}const c=typeof t=="function"?t:(g,h)=>Promise.resolve(V.decrypt(g,Kt(t,h))),l=a.pubkey;this.usedBy.push(l);const f=await c(a.content,l),u=G(this.linkSecret),d=s.id,p=et.init(n,f,this.inviterSessionPrivateKey,!1,u,d);r(p,l)}catch(o){console.error("Error processing invite message:",o)}})}}H.Channel=et,H.INVITE_EVENT_KIND=vn,H.Invite=$e,H.MAX_SKIP=Ac,H.MESSAGE_EVENT_KIND=Le,H.Sender=ri,H.createMessageStream=Cc,H.deserializeChannelState=Nc,H.kdf=Te,H.serializeChannelState=Kc,H.skippedMessageIndexKey=At,Object.defineProperty(H,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nostr-double-ratchet",
3
- "version": "0.0.8",
3
+ "version": "0.0.10",
4
4
  "type": "module",
5
5
  "packageManager": "yarn@1.22.22",
6
6
  "description": "Nostr double ratchet library",
package/src/Invite.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { generateSecretKey, getPublicKey, nip44, finalizeEvent, VerifiedEvent, nip19, UnsignedEvent, verifyEvent } from "nostr-tools";
1
+ import { generateSecretKey, getPublicKey, nip44, finalizeEvent, VerifiedEvent, UnsignedEvent, verifyEvent, Filter } from "nostr-tools";
2
2
  import { INVITE_EVENT_KIND, NostrSubscribe, Unsubscribe } from "./types";
3
3
  import { getConversationKey } from "nostr-tools/nip44";
4
4
  import { Channel } from "./Channel";
@@ -7,14 +7,13 @@ import { EncryptFunction, DecryptFunction } from "./types";
7
7
  import { hexToBytes, bytesToHex } from "@noble/hashes/utils";
8
8
 
9
9
  /**
10
- * Invite link is a safe way to exchange session keys and initiate secret channels.
10
+ * Invite is a safe way to exchange session keys and initiate secret channels.
11
+ *
12
+ * It can be shared privately as an URL (e.g. QR code) or published as a Nostr event.
11
13
  *
12
14
  * Even if inviter's or invitee's long-term private key (identity key) and the shared secret (link) is compromised,
13
15
  * forward secrecy is preserved as long as the session keys are not compromised.
14
16
  *
15
- * Shared secret Nostr channel: inviter listens to it and invitees can write to it. Outside observers don't know who are communicating over it.
16
- * It is vulnerable to spam, so the link should only be given to trusted invitees or used with a reasonable maxUses limit.
17
- *
18
17
  * Also make sure to keep the session key safe.
19
18
  */
20
19
  export class Invite {
@@ -62,20 +61,10 @@ export class Invite {
62
61
  throw new Error("Missing required fields (inviter, sessionKey, linkSecret) in invite data.");
63
62
  }
64
63
 
65
- const decodedInviter = nip19.decode(inviter);
66
- const decodedSessionKey = nip19.decode(sessionKey);
67
-
68
- if (typeof decodedInviter.data !== 'string') {
69
- throw new Error("Decoded inviter is not a string");
70
- }
71
- if (typeof decodedSessionKey.data !== 'string') {
72
- throw new Error("Decoded session key is not a string");
73
- }
74
-
75
64
  return new Invite(
76
- decodedSessionKey.data,
65
+ sessionKey,
77
66
  linkSecret,
78
- decodedInviter.data
67
+ inviter
79
68
  );
80
69
  }
81
70
 
@@ -116,9 +105,9 @@ export class Invite {
116
105
  }
117
106
 
118
107
  static fromUser(user: string, subscribe: NostrSubscribe): Promise<Invite | undefined> {
119
- const filter = {
108
+ const filter: Filter = {
120
109
  kinds: [INVITE_EVENT_KIND],
121
- pubkey: user,
110
+ authors: [user],
122
111
  limit: 1,
123
112
  "#d": ["nostr-double-ratchet/invite"],
124
113
  };
@@ -142,6 +131,9 @@ export class Invite {
142
131
  });
143
132
  }
144
133
 
134
+ /**
135
+ * Save Invite as JSON. Includes the inviter's session private key, so don't share this.
136
+ */
145
137
  serialize(): string {
146
138
  return JSON.stringify({
147
139
  inviterSessionPublicKey: this.inviterSessionPublicKey,
@@ -154,10 +146,13 @@ export class Invite {
154
146
  });
155
147
  }
156
148
 
149
+ /**
150
+ * Invite parameters are in the URL's hash so they are not sent to the server.
151
+ */
157
152
  getUrl(root = "https://iris.to") {
158
153
  const data = {
159
- inviter: nip19.npubEncode(this.inviter),
160
- sessionKey: nip19.npubEncode(this.inviterSessionPublicKey),
154
+ inviter: this.inviter,
155
+ sessionKey: this.inviterSessionPublicKey,
161
156
  linkSecret: this.linkSecret
162
157
  };
163
158
  const url = new URL(root);
@@ -177,7 +172,7 @@ export class Invite {
177
172
  }
178
173
 
179
174
  /**
180
- * Accepts the invite and creates a new channel with the inviter.
175
+ * Called by the invitee. Accepts the invite and creates a new channel with the inviter.
181
176
  *
182
177
  * @param inviteeSecretKey - The invitee's secret key or a signing function
183
178
  * @param nostrSubscribe - A function to subscribe to Nostr events
@@ -241,6 +236,11 @@ export class Invite {
241
236
 
242
237
  return nostrSubscribe(filter, async (event) => {
243
238
  try {
239
+ if (this.maxUses && this.usedBy.length >= this.maxUses) {
240
+ console.error("Invite has reached maximum number of uses");
241
+ return;
242
+ }
243
+
244
244
  const decrypted = await nip44.decrypt(event.content, getConversationKey(this.inviterSessionPrivateKey!, event.pubkey));
245
245
  const innerEvent = JSON.parse(decrypted);
246
246
 
@@ -253,13 +253,16 @@ export class Invite {
253
253
  inviterSecretKey :
254
254
  (ciphertext: string, pubkey: string) => Promise.resolve(nip44.decrypt(ciphertext, getConversationKey(inviterSecretKey, pubkey)));
255
255
 
256
- const inviteeSessionPublicKey = await innerDecrypt(innerEvent.content, innerEvent.pubkey);
256
+ const inviteeIdentity = innerEvent.pubkey;
257
+ this.usedBy.push(inviteeIdentity);
258
+
259
+ const inviteeSessionPublicKey = await innerDecrypt(innerEvent.content, inviteeIdentity);
257
260
  const sharedSecret = hexToBytes(this.linkSecret);
258
261
 
259
262
  const name = event.id;
260
263
  const channel = Channel.init(nostrSubscribe, inviteeSessionPublicKey, this.inviterSessionPrivateKey!, false, sharedSecret, name);
261
264
 
262
- onChannel(channel, innerEvent.pubkey);
265
+ onChannel(channel, inviteeIdentity);
263
266
  } catch (error) {
264
267
  console.error("Error processing invite message:", error);
265
268
  }