nostr-double-ratchet 0.0.1

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.
@@ -0,0 +1 @@
1
+ (function(M,W){typeof exports=="object"&&typeof module<"u"?W(exports):typeof define=="function"&&define.amd?define(["exports"],W):(M=typeof globalThis<"u"?globalThis:M||self,W(M["nostr-double-ratchet"]={}))})(this,function(M){"use strict";var Cc=Object.defineProperty;var Ic=(M,W,Ke)=>W in M?Cc(M,W,{enumerable:!0,configurable:!0,writable:!0,value:Ke}):M[W]=Ke;var ne=(M,W,Ke)=>Ic(M,typeof W!="symbol"?W+"":W,Ke);function W(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function Ke(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");W(e.outputLen),W(e.blockLen)}function it(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){Ke(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 mn=e=>e instanceof Uint8Array,It=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),re=(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 Ut(e){if(typeof e=="string"&&(e=ui(e)),!mn(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}function li(...e){const t=new Uint8Array(e.reduce((r,i)=>r+i.length,0));let n=0;return e.forEach(r=>{if(!mn(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(Ut(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Sn(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),c=Number(n&o),a=r?4:0,u=r?0:4;e.setUint32(t+a,s,r),e.setUint32(t+u,c,r)}let hi=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=It(this.buffer)}update(t){it(this);const{view:n,buffer:r,blockLen:i}=this;t=Ut(t);const o=t.length;for(let s=0;s<o;){const c=Math.min(i-this.pos,o-s);if(c===i){const a=It(t);for(;i<=o-s;s+=i)this.process(a,s);continue}r.set(t.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){it(this),ci(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 l=s;l<i;l++)n[l]=0;di(r,i-8,BigInt(this.length*8),o),this.process(r,0);const c=It(t),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=a/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)c.setUint32(4*l,f[l],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:c}=this;return t.length=i,t.pos=c,t.finished=o,t.destroyed=s,i%n&&t.buffer.set(r),t}};const gi=(e,t,n)=>e&t^~e&n,pi=(e,t,n)=>e&t^e&n^t&n,yi=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]),be=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ve=new Uint32Array(64);let wi=class extends hi{constructor(){super(64,32,8,!1),this.A=be[0]|0,this.B=be[1]|0,this.C=be[2]|0,this.D=be[3]|0,this.E=be[4]|0,this.F=be[5]|0,this.G=be[6]|0,this.H=be[7]|0}get(){const{A:t,B:n,C:r,D:i,E:o,F:s,G:c,H:a}=this;return[t,n,r,i,o,s,c,a]}set(t,n,r,i,o,s,c,a){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=c|0,this.H=a|0}process(t,n){for(let l=0;l<16;l++,n+=4)ve[l]=t.getUint32(n,!1);for(let l=16;l<64;l++){const h=ve[l-15],w=ve[l-2],y=re(h,7)^re(h,18)^h>>>3,d=re(w,17)^re(w,19)^w>>>10;ve[l]=d+ve[l-7]+y+ve[l-16]|0}let{A:r,B:i,C:o,D:s,E:c,F:a,G:u,H:f}=this;for(let l=0;l<64;l++){const h=re(c,6)^re(c,11)^re(c,25),w=f+h+gi(c,a,u)+yi[l]+ve[l]|0,d=(re(r,2)^re(r,13)^re(r,22))+pi(r,i,o)|0;f=u,u=a,a=c,c=s+w|0,s=o,o=i,i=r,r=w+d|0}r=r+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,i,o,s,c,a,u,f)}roundClean(){ve.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),ot=BigInt(1),bi=BigInt(2),st=e=>e instanceof Uint8Array,vi=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Re(e){if(!st(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=vi[e[n]];return t}function Bn(e){const t=e.toString(16);return t.length&1?`0${t}`:t}function _t(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return BigInt(e===""?"0":`0x${e}`)}function Pe(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 G(e){return _t(Re(e))}function Lt(e){if(!st(e))throw new Error("Uint8Array expected");return _t(Re(Uint8Array.from(e).reverse()))}function Ee(e,t){return Pe(e.toString(16).padStart(t*2,"0"))}function Tt(e,t){return Ee(e,t).reverse()}function Ei(e){return Pe(Bn(e))}function Z(e,t,n){let r;if(typeof t=="string")try{r=Pe(t)}catch(o){throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${o}`)}else if(st(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 _e(...e){const t=new Uint8Array(e.reduce((r,i)=>r+i.length,0));let n=0;return e.forEach(r=>{if(!st(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}function mi(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>>=ot,t+=1);return t}function Ai(e,t){return e>>BigInt(t)&ot}const Bi=(e,t,n)=>e|(n?ot:An)<<BigInt(t),kt=e=>(bi<<BigInt(e-1))-ot,$t=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=$t(e),i=$t(e),o=0;const s=()=>{r.fill(1),i.fill(0),o=0},c=(...l)=>n(i,r,...l),a=(l=$t())=>{i=c(Nn([0]),l),r=c(),l.length!==0&&(i=c(Nn([1]),l),r=c())},u=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const h=[];for(;l<t;){r=c();const w=r.slice();h.push(w),l+=r.length}return _e(...h)};return(l,h)=>{s(),a(l);let w;for(;!(w=h(u()));)a();return s(),w}}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,o,s)=>{const c=Ni[o];if(typeof c!="function")throw new Error(`Invalid validator "${o}", expected function`);const a=e[i];if(!(s&&a===void 0)&&!c(a,e))throw new Error(`Invalid param ${String(i)}=${a} (${typeof a}), 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 Ci=Object.freeze(Object.defineProperty({__proto__:null,bitGet:Ai,bitLen:Si,bitMask:kt,bitSet:Bi,bytesToHex:Re,bytesToNumberBE:G,bytesToNumberLE:Lt,concatBytes:_e,createHmacDrbg:Cn,ensureBytes:Z,equalBytes:mi,hexToBytes:Pe,hexToNumber:_t,numberToBytesBE:Ee,numberToBytesLE:Tt,numberToHexUnpadded:Bn,numberToVarBytesBE:Ei,utf8ToBytes:xi,validateObject:We},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const z=BigInt(0),q=BigInt(1),Le=BigInt(2),Ii=BigInt(3),Rt=BigInt(4),In=BigInt(5),Un=BigInt(8);BigInt(9),BigInt(16);function V(e,t){const n=e%t;return n>=z?n:t+n}function Ui(e,t,n){if(n<=z||t<z)throw new Error("Expected power/modulo > 0");if(n===q)return z;let r=q;for(;t>z;)t&q&&(r=r*e%n),e=e*e%n,t>>=q;return r}function Y(e,t,n){let r=e;for(;t-- >z;)r*=r,r%=n;return r}function Pt(e,t){if(e===z||t<=z)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let n=V(e,t),r=t,i=z,o=q;for(;n!==z;){const c=r/n,a=r%n,u=i-o*c;r=n,n=a,i=o,o=u}if(r!==q)throw new Error("invert: does not exist");return V(i,t)}function Ki(e){const t=(e-q)/Le;let n,r,i;for(n=e-q,r=0;n%Le===z;n/=Le,r++);for(i=Le;i<e&&Ui(i,t,e)!==e-q;i++);if(r===1){const s=(e+q)/Rt;return function(a,u){const f=a.pow(u,s);if(!a.eql(a.sqr(f),u))throw new Error("Cannot find square root");return f}}const o=(n+q)/Le;return function(c,a){if(c.pow(a,t)===c.neg(c.ONE))throw new Error("Cannot find square root");let u=r,f=c.pow(c.mul(c.ONE,i),n),l=c.pow(a,o),h=c.pow(a,n);for(;!c.eql(h,c.ONE);){if(c.eql(h,c.ZERO))return c.ZERO;let w=1;for(let d=c.sqr(h);w<u&&!c.eql(d,c.ONE);w++)d=c.sqr(d);const y=c.pow(f,q<<BigInt(u-w-1));f=c.sqr(y),l=c.mul(l,y),h=c.mul(h,f),u=w}return l}}function _i(e){if(e%Rt===Ii){const t=(e+q)/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%Un===In){const t=(e-In)/Un;return function(r,i){const o=r.mul(i,Le),s=r.pow(o,t),c=r.mul(i,s),a=r.mul(r.mul(c,Le),s),u=r.mul(c,r.sub(a,r.ONE));if(!r.eql(r.sqr(u),i))throw new Error("Cannot find square root");return u}}return Ki(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 ki(e,t,n){if(n<z)throw new Error("Expected power > 0");if(n===z)return e.ONE;if(n===q)return t;let r=e.ONE,i=t;for(;n>z;)n&q&&(r=e.mul(r,i)),i=e.sqr(i),n>>=q;return r}function $i(e,t){const n=new Array(t.length),r=t.reduce((o,s,c)=>e.is0(s)?o:(n[c]=o,e.mul(o,s)),e.ONE),i=e.inv(r);return t.reduceRight((o,s,c)=>e.is0(s)?o:(n[c]=e.mul(o,n[c]),e.mul(o,s)),i),n}function Kn(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:o}=Kn(e,t);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");const s=_i(e),c=Object.freeze({ORDER:e,BITS:i,BYTES:o,MASK:kt(i),ZERO:z,ONE:q,create:a=>V(a,e),isValid:a=>{if(typeof a!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof a}`);return z<=a&&a<e},is0:a=>a===z,isOdd:a=>(a&q)===q,neg:a=>V(-a,e),eql:(a,u)=>a===u,sqr:a=>V(a*a,e),add:(a,u)=>V(a+u,e),sub:(a,u)=>V(a-u,e),mul:(a,u)=>V(a*u,e),pow:(a,u)=>ki(c,a,u),div:(a,u)=>V(a*Pt(u,e),e),sqrN:a=>a*a,addN:(a,u)=>a+u,subN:(a,u)=>a-u,mulN:(a,u)=>a*u,inv:a=>Pt(a,e),sqrt:r.sqrt||(a=>s(c,a)),invertBatch:a=>$i(c,a),cmov:(a,u,f)=>f?u:a,toBytes:a=>n?Tt(a,o):Ee(a,o),fromBytes:a=>{if(a.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${a.length}`);return n?Lt(a):G(a)}});return Object.freeze(c)}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 Pi(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?G(e):Lt(e),c=V(s,t-q)+q;return n?Tt(c,i):Ee(c,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Oi=BigInt(0),Ot=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,c=i;for(;o>Oi;)o&Ot&&(s=s.add(c)),c=c.double(),o>>=Ot;return s},precomputeWindow(i,o){const{windows:s,windowSize:c}=r(o),a=[];let u=i,f=u;for(let l=0;l<s;l++){f=u,a.push(f);for(let h=1;h<c;h++)f=f.add(u),a.push(f);u=f.double()}return a},wNAF(i,o,s){const{windows:c,windowSize:a}=r(i);let u=e.ZERO,f=e.BASE;const l=BigInt(2**i-1),h=2**i,w=BigInt(i);for(let y=0;y<c;y++){const d=y*a;let g=Number(s&l);s>>=w,g>a&&(g-=h,s+=Ot);const p=d,m=d+Math.abs(g)-1,B=y%2!==0,_=g<0;g===0?f=f.add(n(B,o[p])):u=u.add(n(_,o[m]))}return{p:u,f}},wNAFCached(i,o,s,c){const a=i._WINDOW_SIZE||1;let u=o.get(i);return u||(u=this.precomputeWindow(i,a),a!==1&&o.set(i,c(u))),this.wNAF(a,u,s)}}}function Tn(e){return Ti(e.Fp),We(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Kn(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Mi(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:qi,hexToBytes:Di}=Ci,Te={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(e){const{Err:t}=Te;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}=Te,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:o}=Te._parseInt(n.subarray(2)),{d:s,l:c}=Te._parseInt(o);if(c.length)throw new t("Invalid signature: left bytes after parsing");return{r:i,s}},hexFromSig(e){const t=u=>Number.parseInt(u[0],16)&8?"00"+u:u,n=u=>{const f=u.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,c=n(o),a=n(s);return`30${n(s+o+4)}02${a}${i}02${c}${r}`}},fe=BigInt(0),X=BigInt(1);BigInt(2);const kn=BigInt(3);BigInt(4);function ji(e){const t=Mi(e),{Fp:n}=t,r=t.toBytes||((y,d,g)=>{const p=d.toAffine();return _e(Uint8Array.from([4]),n.toBytes(p.x),n.toBytes(p.y))}),i=t.fromBytes||(y=>{const d=y.subarray(1),g=n.fromBytes(d.subarray(0,n.BYTES)),p=n.fromBytes(d.subarray(n.BYTES,2*n.BYTES));return{x:g,y:p}});function o(y){const{a:d,b:g}=t,p=n.sqr(y),m=n.mul(p,y);return n.add(n.add(m,n.mul(y,d)),g)}if(!n.eql(n.sqr(t.Gy),o(t.Gx)))throw new Error("bad generator point: equation left != right");function s(y){return typeof y=="bigint"&&fe<y&&y<t.n}function c(y){if(!s(y))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function a(y){const{allowedPrivateKeyLengths:d,nByteLength:g,wrapPrivateKey:p,n:m}=t;if(d&&typeof y!="bigint"){if(y instanceof Uint8Array&&(y=Re(y)),typeof y!="string"||!d.includes(y.length))throw new Error("Invalid key");y=y.padStart(g*2,"0")}let B;try{B=typeof y=="bigint"?y:G(Z("private key",y,g))}catch{throw new Error(`private key must be ${g} bytes, hex or bigint, not ${typeof y}`)}return p&&(B=V(B,m)),c(B),B}const u=new Map;function f(y){if(!(y instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(d,g,p){if(this.px=d,this.py=g,this.pz=p,d==null||!n.isValid(d))throw new Error("x required");if(g==null||!n.isValid(g))throw new Error("y required");if(p==null||!n.isValid(p))throw new Error("z required")}static fromAffine(d){const{x:g,y:p}=d||{};if(!d||!n.isValid(g)||!n.isValid(p))throw new Error("invalid affine point");if(d instanceof l)throw new Error("projective point not allowed");const m=B=>n.eql(B,n.ZERO);return m(g)&&m(p)?l.ZERO:new l(g,p,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(d){const g=n.invertBatch(d.map(p=>p.pz));return d.map((p,m)=>p.toAffine(g[m])).map(l.fromAffine)}static fromHex(d){const g=l.fromAffine(i(Z("pointHex",d)));return g.assertValidity(),g}static fromPrivateKey(d){return l.BASE.multiply(a(d))}_setWindowSize(d){this._WINDOW_SIZE=d,u.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!n.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:d,y:g}=this.toAffine();if(!n.isValid(d)||!n.isValid(g))throw new Error("bad point: x or y not FE");const p=n.sqr(g),m=o(d);if(!n.eql(p,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:d}=this.toAffine();if(n.isOdd)return!n.isOdd(d);throw new Error("Field doesn't support isOdd")}equals(d){f(d);const{px:g,py:p,pz:m}=this,{px:B,py:_,pz:I}=d,E=n.eql(n.mul(g,I),n.mul(B,m)),x=n.eql(n.mul(p,I),n.mul(_,m));return E&&x}negate(){return new l(this.px,n.neg(this.py),this.pz)}double(){const{a:d,b:g}=t,p=n.mul(g,kn),{px:m,py:B,pz:_}=this;let I=n.ZERO,E=n.ZERO,x=n.ZERO,S=n.mul(m,m),O=n.mul(B,B),K=n.mul(_,_),N=n.mul(m,B);return N=n.add(N,N),x=n.mul(m,_),x=n.add(x,x),I=n.mul(d,x),E=n.mul(p,K),E=n.add(I,E),I=n.sub(O,E),E=n.add(O,E),E=n.mul(I,E),I=n.mul(N,I),x=n.mul(p,x),K=n.mul(d,K),N=n.sub(S,K),N=n.mul(d,N),N=n.add(N,x),x=n.add(S,S),S=n.add(x,S),S=n.add(S,K),S=n.mul(S,N),E=n.add(E,S),K=n.mul(B,_),K=n.add(K,K),S=n.mul(K,N),I=n.sub(I,S),x=n.mul(K,O),x=n.add(x,x),x=n.add(x,x),new l(I,E,x)}add(d){f(d);const{px:g,py:p,pz:m}=this,{px:B,py:_,pz:I}=d;let E=n.ZERO,x=n.ZERO,S=n.ZERO;const O=t.a,K=n.mul(t.b,kn);let N=n.mul(g,B),$=n.mul(p,_),R=n.mul(m,I),H=n.add(g,p),b=n.add(B,_);H=n.mul(H,b),b=n.add(N,$),H=n.sub(H,b),b=n.add(g,m);let v=n.add(B,I);return b=n.mul(b,v),v=n.add(N,R),b=n.sub(b,v),v=n.add(p,m),E=n.add(_,I),v=n.mul(v,E),E=n.add($,R),v=n.sub(v,E),S=n.mul(O,b),E=n.mul(K,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(O,R),b=n.mul(K,b),$=n.add($,R),R=n.sub(N,R),R=n.mul(O,R),b=n.add(b,R),N=n.mul($,b),x=n.add(x,N),N=n.mul(v,b),E=n.mul(H,E),E=n.sub(E,N),N=n.mul(H,$),S=n.mul(v,S),S=n.add(S,N),new l(E,x,S)}subtract(d){return this.add(d.negate())}is0(){return this.equals(l.ZERO)}wNAF(d){return w.wNAFCached(this,u,d,g=>{const p=n.invertBatch(g.map(m=>m.pz));return g.map((m,B)=>m.toAffine(p[B])).map(l.fromAffine)})}multiplyUnsafe(d){const g=l.ZERO;if(d===fe)return g;if(c(d),d===X)return this;const{endo:p}=t;if(!p)return w.unsafeLadder(this,d);let{k1neg:m,k1:B,k2neg:_,k2:I}=p.splitScalar(d),E=g,x=g,S=this;for(;B>fe||I>fe;)B&X&&(E=E.add(S)),I&X&&(x=x.add(S)),S=S.double(),B>>=X,I>>=X;return m&&(E=E.negate()),_&&(x=x.negate()),x=new l(n.mul(x.px,p.beta),x.py,x.pz),E.add(x)}multiply(d){c(d);let g=d,p,m;const{endo:B}=t;if(B){const{k1neg:_,k1:I,k2neg:E,k2:x}=B.splitScalar(g);let{p:S,f:O}=this.wNAF(I),{p:K,f:N}=this.wNAF(x);S=w.constTimeNegate(_,S),K=w.constTimeNegate(E,K),K=new l(n.mul(K.px,B.beta),K.py,K.pz),p=S.add(K),m=O.add(N)}else{const{p:_,f:I}=this.wNAF(g);p=_,m=I}return l.normalizeZ([p,m])[0]}multiplyAndAddUnsafe(d,g,p){const m=l.BASE,B=(I,E)=>E===fe||E===X||!I.equals(m)?I.multiplyUnsafe(E):I.multiply(E),_=B(this,g).add(B(d,p));return _.is0()?void 0:_}toAffine(d){const{px:g,py:p,pz:m}=this,B=this.is0();d==null&&(d=B?n.ONE:n.inv(m));const _=n.mul(g,d),I=n.mul(p,d),E=n.mul(m,d);if(B)return{x:n.ZERO,y:n.ZERO};if(!n.eql(E,n.ONE))throw new Error("invZ was invalid");return{x:_,y:I}}isTorsionFree(){const{h:d,isTorsionFree:g}=t;if(d===X)return!0;if(g)return g(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:d,clearCofactor:g}=t;return d===X?this:g?g(l,this):this.multiplyUnsafe(t.h)}toRawBytes(d=!0){return this.assertValidity(),r(l,this,d)}toHex(d=!0){return Re(this.toRawBytes(d))}}l.BASE=new l(t.Gx,t.Gy,n.ONE),l.ZERO=new l(n.ZERO,n.ONE,n.ZERO);const h=t.nBitLength,w=Hi(l,t.endo?Math.ceil(h/2):h);return{CURVE:t,ProjectivePoint:l,normPrivateKeyToScalar:a,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 Vi(e){const t=zi(e),{Fp:n,n:r}=t,i=n.BYTES+1,o=2*n.BYTES+1;function s(b){return fe<b&&b<n.ORDER}function c(b){return V(b,r)}function a(b){return Pt(b,r)}const{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:l,isWithinCurveOrder:h}=ji({...t,toBytes(b,v,A){const U=v.toAffine(),C=n.toBytes(U.x),T=_e;return A?T(Uint8Array.from([v.hasEvenY()?2:3]),C):T(Uint8Array.from([4]),C,n.toBytes(U.y))},fromBytes(b){const v=b.length,A=b[0],U=b.subarray(1);if(v===i&&(A===2||A===3)){const C=G(U);if(!s(C))throw new Error("Point is not on curve");const T=l(C);let P=n.sqrt(T);const k=(P&X)===X;return(A&1)===1!==k&&(P=n.neg(P)),{x:C,y:P}}else if(v===o&&A===4){const C=n.fromBytes(U.subarray(0,n.BYTES)),T=n.fromBytes(U.subarray(n.BYTES,2*n.BYTES));return{x:C,y:T}}else throw new Error(`Point of length ${v} was invalid. Expected ${i} compressed bytes or ${o} uncompressed bytes`)}}),w=b=>Re(Ee(b,t.nByteLength));function y(b){const v=r>>X;return b>v}function d(b){return y(b)?c(-b):b}const g=(b,v,A)=>G(b.slice(v,A));class p{constructor(v,A,U){this.r=v,this.s=A,this.recovery=U,this.assertValidity()}static fromCompact(v){const A=t.nByteLength;return v=Z("compactSignature",v,A*2),new p(g(v,0,A),g(v,A,2*A))}static fromDER(v){const{r:A,s:U}=Te.toSig(Z("DER",v));return new p(A,U)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(v){return new p(this.r,this.s,v)}recoverPublicKey(v){const{r:A,s:U,recovery:C}=this,T=x(Z("msgHash",v));if(C==null||![0,1,2,3].includes(C))throw new Error("recovery id invalid");const P=C===2||C===3?A+t.n:A;if(P>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const k=C&1?"03":"02",ee=u.fromHex(k+w(P)),Ie=a(P),ze=c(-T*Ie),rt=c(U*Ie),Ue=u.BASE.multiplyAndAddUnsafe(ee,ze,rt);if(!Ue)throw new Error("point at infinify");return Ue.assertValidity(),Ue}hasHighS(){return y(this.s)}normalizeS(){return this.hasHighS()?new p(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Pe(this.toDERHex())}toDERHex(){return Te.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Pe(this.toCompactHex())}toCompactHex(){return w(this.r)+w(this.s)}}const m={isValidPrivateKey(b){try{return f(b),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{const b=Ln(t.n);return Pi(t.randomBytes(b),t.n)},precompute(b=8,v=u.BASE){return v._setWindowSize(b),v.multiply(BigInt(3)),v}};function B(b,v=!0){return u.fromPrivateKey(b).toRawBytes(v)}function _(b){const v=b instanceof Uint8Array,A=typeof b=="string",U=(v||A)&&b.length;return v?U===i||U===o:A?U===2*i||U===2*o:b instanceof u}function I(b,v,A=!0){if(_(b))throw new Error("first arg must be private key");if(!_(v))throw new Error("second arg must be public key");return u.fromHex(v).multiply(f(b)).toRawBytes(A)}const E=t.bits2int||function(b){const v=G(b),A=b.length*8-t.nBitLength;return A>0?v>>BigInt(A):v},x=t.bits2int_modN||function(b){return c(E(b))},S=kt(t.nBitLength);function O(b){if(typeof b!="bigint")throw new Error("bigint expected");if(!(fe<=b&&b<S))throw new Error(`bigint expected < 2^${t.nBitLength}`);return Ee(b,t.nByteLength)}function K(b,v,A=N){if(["recovered","canonical"].some($e=>$e in A))throw new Error("sign() legacy options not supported");const{hash:U,randomBytes:C}=t;let{lowS:T,prehash:P,extraEntropy:k}=A;T==null&&(T=!0),b=Z("msgHash",b),P&&(b=Z("prehashed msgHash",U(b)));const ee=x(b),Ie=f(v),ze=[O(Ie),O(ee)];if(k!=null){const $e=k===!0?C(n.BYTES):k;ze.push(Z("extraEntropy",$e))}const rt=_e(...ze),Ue=ee;function En($e){const Ve=E($e);if(!h(Ve))return;const ii=a(Ve),Ze=u.BASE.multiply(Ve).toAffine(),te=c(Ze.x);if(te===fe)return;const Fe=c(ii*c(Ue+te*Ie));if(Fe===fe)return;let oi=(Ze.x===te?0:2)|Number(Ze.y&X),si=Fe;return T&&y(Fe)&&(si=d(Fe),oi^=1),new p(te,si,oi)}return{seed:rt,k2sig:En}}const N={lowS:t.lowS,prehash:!1},$={lowS:t.lowS,prehash:!1};function R(b,v,A=N){const{seed:U,k2sig:C}=K(b,v,A),T=t;return Cn(T.hash.outputLen,T.nByteLength,T.hmac)(U,C)}u.BASE._setWindowSize(8);function H(b,v,A,U=$){var Ze;const C=b;if(v=Z("msgHash",v),A=Z("publicKey",A),"strict"in U)throw new Error("options.strict was renamed to lowS");const{lowS:T,prehash:P}=U;let k,ee;try{if(typeof C=="string"||C instanceof Uint8Array)try{k=p.fromDER(C)}catch(te){if(!(te instanceof Te.Err))throw te;k=p.fromCompact(C)}else if(typeof C=="object"&&typeof C.r=="bigint"&&typeof C.s=="bigint"){const{r:te,s:Fe}=C;k=new p(te,Fe)}else throw new Error("PARSE");ee=u.fromHex(A)}catch(te){if(te.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(T&&k.hasHighS())return!1;P&&(v=t.hash(v));const{r:Ie,s:ze}=k,rt=x(v),Ue=a(ze),En=c(rt*Ue),$e=c(Ie*Ue),Ve=(Ze=u.BASE.multiplyAndAddUnsafe(ee,En,$e))==null?void 0:Ze.toAffine();return Ve?c(Ve.x)===Ie:!1}return{CURVE:t,getPublicKey:B,getSharedSecret:I,sign:R,verify:H,ProjectivePoint:u,Signature:p,utils:m}}let $n=class extends xn{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,ai(t);const r=Ut(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 it(this),this.iHash.update(t),this}digestInto(t){it(this),Ke(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:c}=this;return t=t,t.finished=i,t.destroyed=o,t.blockLen=s,t.outputLen=c,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,li(...n)),randomBytes:Sn}}function Fi(e,t){const n=r=>Vi({...e,...Zi(r)});return Object.freeze({...n(t),create:n})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const at=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),ct=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Pn=BigInt(1),ut=BigInt(2),On=(e,t)=>(e+t/ut)/t;function Hn(e){const t=at,n=BigInt(3),r=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),c=BigInt(44),a=BigInt(88),u=e*e*e%t,f=u*u*e%t,l=Y(f,n,t)*f%t,h=Y(l,n,t)*f%t,w=Y(h,ut,t)*u%t,y=Y(w,i,t)*w%t,d=Y(y,o,t)*y%t,g=Y(d,c,t)*d%t,p=Y(g,a,t)*g%t,m=Y(p,c,t)*d%t,B=Y(m,n,t)*f%t,_=Y(B,s,t)*y%t,I=Y(_,r,t)*u%t,E=Y(I,ut,t);if(!Ht.eql(Ht.sqr(E),e))throw new Error("Cannot find square root");return E}const Ht=Ri(at,void 0,void 0,{sqrt:Hn}),ke=Fi({a:BigInt(0),b:BigInt(7),Fp:Ht,n:ct,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=ct,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Pn*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=n,s=BigInt("0x100000000000000000000000000000000"),c=On(o*e,t),a=On(-r*e,t);let u=V(e-c*n-a*i,t),f=V(-c*r-a*o,t);const l=u>s,h=f>s;if(l&&(u=t-u),h&&(f=t-f),u>s||f>s)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:l,k1:u,k2neg:h,k2:f}}}},Kt),lt=BigInt(0),Mn=e=>typeof e=="bigint"&&lt<e&&e<at,Wi=e=>typeof e=="bigint"&&lt<e&&e<ct,qn={};function ft(e,...t){let n=qn[e];if(n===void 0){const r=Kt(Uint8Array.from(e,i=>i.charCodeAt(0)));n=_e(r,r),qn[e]=n}return Kt(_e(n,...t))}const Mt=e=>e.toRawBytes(!0).slice(1),qt=e=>Ee(e,32),Dt=e=>V(e,at),Ge=e=>V(e,ct),jt=ke.ProjectivePoint,Gi=(e,t,n)=>jt.BASE.multiplyAndAddUnsafe(e,t,n);function zt(e){let t=ke.utils.normPrivateKeyToScalar(e),n=jt.fromPrivateKey(t);return{scalar:n.hasEvenY()?t:Ge(-t),bytes:Mt(n)}}function Dn(e){if(!Mn(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%ut!==lt&&(r=Dt(-r));const i=new jt(e,r,Pn);return i.assertValidity(),i}function jn(...e){return Ge(G(ft("BIP0340/challenge",...e)))}function Ji(e){return zt(e).bytes}function Yi(e,t,n=Sn(32)){const r=Z("message",e),{bytes:i,scalar:o}=zt(t),s=Z("auxRand",n,32),c=qt(o^G(ft("BIP0340/aux",s))),a=ft("BIP0340/nonce",c,i,r),u=Ge(G(a));if(u===lt)throw new Error("sign failed: k is zero");const{bytes:f,scalar:l}=zt(u),h=jn(f,i,r),w=new Uint8Array(64);if(w.set(f,0),w.set(qt(Ge(l+h*o)),32),!zn(w,r,i))throw new Error("sign: Invalid signature produced");return w}function zn(e,t,n){const r=Z("signature",e,64),i=Z("message",t),o=Z("publicKey",n,32);try{const s=Dn(G(o)),c=G(r.subarray(0,32));if(!Mn(c))return!1;const a=G(r.subarray(32,64));if(!Wi(a))return!1;const u=jn(qt(c),Mt(s),i),f=Gi(s,a,Ge(-u));return!(!f||!f.hasEvenY()||f.toAffine().x!==c)}catch{return!1}}const Je={getPublicKey:Ji,sign:Yi,verify:zn,utils:{randomPrivateKey:ke.utils.randomPrivateKey,lift_x:Dn,pointToBytes:Mt,numberToBytesBE:Ee,bytesToNumberBE:G,taggedHash:ft,mod:V}},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,Ft=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");const Xi=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function j(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 J(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 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 dt(...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 Vn{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 Wt(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function eo(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 to(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 no(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 ro(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:Wt,bool:eo,bytes:Wn,hash:to,exists:no,output:ro};function io(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),c=Number(n&o),a=r?4:0,u=r?0:4;e.setUint32(t+a,s,r),e.setUint32(t+u,c,r)}class oo extends Vn{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){oe.exists(this);const{view:n,buffer:r,blockLen:i}=this;t=Ye(t);const o=t.length;for(let s=0;s<o;){const c=Math.min(i-this.pos,o-s);if(c===i){const a=Ft(t);for(;i<=o-s;s+=i)this.process(a,s);continue}r.set(t.subarray(s,s+c),this.pos),this.pos+=c,s+=c,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: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 l=s;l<i;l++)n[l]=0;io(r,i-8,BigInt(this.length*8),o),this.process(r,0);const c=Ft(t),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=a/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)c.setUint32(4*l,f[l],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:c}=this;return t.length=i,t.pos=c,t.finished=o,t.destroyed=s,i%n&&t.buffer.set(r),t}}const so=(e,t,n)=>e&t^~e&n,ao=(e,t,n)=>e&t^e&n^t&n,co=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]),me=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),xe=new Uint32Array(64);class Gn extends oo{constructor(){super(64,32,8,!1),this.A=me[0]|0,this.B=me[1]|0,this.C=me[2]|0,this.D=me[3]|0,this.E=me[4]|0,this.F=me[5]|0,this.G=me[6]|0,this.H=me[7]|0}get(){const{A:t,B:n,C:r,D:i,E:o,F:s,G:c,H:a}=this;return[t,n,r,i,o,s,c,a]}set(t,n,r,i,o,s,c,a){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=c|0,this.H=a|0}process(t,n){for(let l=0;l<16;l++,n+=4)xe[l]=t.getUint32(n,!1);for(let l=16;l<64;l++){const h=xe[l-15],w=xe[l-2],y=ie(h,7)^ie(h,18)^h>>>3,d=ie(w,17)^ie(w,19)^w>>>10;xe[l]=d+xe[l-7]+y+xe[l-16]|0}let{A:r,B:i,C:o,D:s,E:c,F:a,G:u,H:f}=this;for(let l=0;l<64;l++){const h=ie(c,6)^ie(c,11)^ie(c,25),w=f+h+so(c,a,u)+co[l]+xe[l]|0,d=(ie(r,2)^ie(r,13)^ie(r,22))+ao(r,i,o)|0;f=u,u=a,a=c,c=s+w|0,s=o,o=i,i=r,r=w+d|0}r=r+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,i,o,s,c,a,u,f)}roundClean(){xe.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class uo 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 Se=Zn(()=>new Gn);Zn(()=>new uo);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Oe(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function de(...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(Oe(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 ge(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(Oe(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=[],o=Array.from(e);for(o.forEach(s=>{if(Oe(s),s<0||s>=t)throw new Error(`Wrong integer: ${s}`)});;){let s=0,c=!0;for(let a=r;a<o.length;a++){const u=o[a],f=t*s+u;if(!Number.isSafeInteger(f)||t*s/t!==s||f-u!==t*s)throw new Error("convertRadix: carry overflow");if(s=f%n,o[a]=Math.floor(f/n),!Number.isSafeInteger(o[a])||o[a]*n+s!==f)throw new Error("convertRadix: carry overflow");if(c)o[a]?c=!1:r=a;else continue}if(i.push(s),c)break}for(let s=0;s<e.length-1&&e[s]===0;s++)i.push(0);return i.reverse()}const Xn=(e,t)=>t?Xn(t,e%t):e,gt=(e,t)=>e+(t-Xn(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(gt(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${gt(t,n)}`);let i=0,o=0;const s=2**n-1,c=[];for(const a of e){if(Oe(a),a>=2**t)throw new Error(`convertRadix2: invalid data word=${a} from=${t}`);if(i=i<<t|a,o+t>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${t}`);for(o+=t;o>=n;o-=n)c.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&&c.push(i>>>0),c}function lo(e){return Oe(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 Ae(e,t=!1){if(Oe(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(gt(8,e)>32||gt(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 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 fo=de(Ae(4),he("0123456789ABCDEF"),ge("")),ho=de(Ae(5),he("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),ht(5),ge(""));de(Ae(5),he("0123456789ABCDEFGHIJKLMNOPQRSTUV"),ht(5),ge("")),de(Ae(5),he("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),ge(""),Jn(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const pe=de(Ae(6),he("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),ht(6),ge("")),go=de(Ae(6),he("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),ht(6),ge("")),Jt=e=>de(lo(58),he(e),ge("")),pt=Jt("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");Jt("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),Jt("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const er=[0,2,3,5,6,7,9,10,11],po={encode(e){let t="";for(let n=0;n<e.length;n+=8){const r=e.subarray(n,n+8);t+=pt.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),o=pt.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)}},Yt=de(he("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),ge("")),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 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,Yt.encode(Gt([i%2**30],30,5,!1))}function rr(e){const t=e==="bech32"?1:734539939,n=Ae(5),r=n.decode,i=n.encode,o=Qn(r);function s(f,l,h=90){if(typeof f!="string")throw new Error(`bech32.encode prefix should be string, not ${typeof f}`);if(!Array.isArray(l)||l.length&&typeof l[0]!="number")throw new Error(`bech32.encode words should be array of numbers, not ${typeof l}`);const w=f.length+7+l.length;if(h!==!1&&w>h)throw new TypeError(`Length ${w} exceeds limit ${h}`);return f=f.toLowerCase(),`${f}1${Yt.encode(l)}${nr(f,l,t)}`}function c(f,l=90){if(typeof f!="string")throw new Error(`bech32.decode input should be string, not ${typeof f}`);if(f.length<8||l!==!1&&f.length>l)throw new TypeError(`Wrong string length: ${f.length} (${f}). Expected (8..${l})`);const h=f.toLowerCase();if(f!==h&&f!==f.toUpperCase())throw new Error("String must be lowercase or uppercase");f=h;const w=f.lastIndexOf("1");if(w===0||w===-1)throw new Error('Letter "1" must be present between prefix and data only');const y=f.slice(0,w),d=f.slice(w+1);if(d.length<6)throw new Error("Data must be at least 6 characters long");const g=Yt.decode(d).slice(0,-6),p=nr(y,g,t);if(!d.endsWith(p))throw new Error(`Invalid checksum in ${f}: expected "${p}"`);return{prefix:y,words:g}}const a=Qn(c);function u(f){const{prefix:l,words:h}=c(f,!1);return{prefix:l,words:h,bytes:r(h)}}return{encode:s,decode:c,decodeToBytes:u,decodeUnsafe:a,fromWords:r,fromWordsUnsafe:o,toWords:i}}const He=rr("bech32");rr("bech32m");const yo={encode:e=>new TextDecoder().decode(e),decode:e=>new TextEncoder().encode(e)},wo=de(Ae(4),he("0123456789abcdef"),ge(""),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:yo,hex:wo,base16:fo,base32:ho,base64:pe,base64url:go,base58:pt,base58xmr:po}).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 bo(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}function ye(e,...t){if(!bo(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 F=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 vo(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function Eo(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 mo=(e,t)=>(Object.assign(t,e),t),Be=16,xo=283;function Qt(e){return e<<1^xo&-(e>>7)}function Me(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})(),So=en.map((e,t)=>en.indexOf(t)),Ao=e=>e<<24|e>>>8,tn=e=>e<<8|e>>>24;function or(e,t){if(e.length!==256)throw new Error("Wrong sbox length");const n=new Uint32Array(256).map((u,f)=>t(e[f])),r=n.map(tn),i=r.map(tn),o=i.map(tn),s=new Uint32Array(256*256),c=new Uint32Array(256*256),a=new Uint16Array(256*256);for(let u=0;u<256;u++)for(let f=0;f<256;f++){const l=u*256+f;s[l]=n[u]^r[f],c[l]=i[u]^o[f],a[l]=e[u]<<8|e[f]}return{sbox:e,sbox2:a,T0:n,T1:r,T2:i,T3:o,T01:s,T23:c}}const nn=or(en,e=>Me(e,3)<<24|e<<16|e<<8|Me(e,2)),sr=or(So,e=>Me(e,11)<<24|Me(e,13)<<16|Me(e,9)<<8|Me(e,14)),Bo=(()=>{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){ye(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=F(e),i=r.length,o=c=>se(n,c,c,c,c),s=new Uint32Array(t+28);s.set(r);for(let c=i;c<s.length;c++){let a=s[c-1];c%i===0?a=o(Ao(a))^Bo[c/i-1]:i>6&&c%i===4&&(a=o(a)),s[c]=s[c-i]^a}return s}function No(e){const t=ar(e),n=t.slice(),r=t.length,{sbox2:i}=nn,{T0:o,T1:s,T2:c,T3:a}=sr;for(let u=0;u<r;u+=4)for(let f=0;f<4;f++)n[u+f]=t[r-u-4+f];t.fill(0);for(let u=4;u<r-4;u++){const f=n[u],l=se(i,f,f,f,f);n[u]=o[l&255]^s[l>>>8&255]^c[l>>>16&255]^a[l>>>24]}return n}function Ne(e,t,n,r,i,o){return e[n<<8&65280|r>>>8&255]^t[i>>>8&65280|o>>>24&255]}function se(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:o,T01:s,T23:c}=nn;let a=0;t^=e[a++],n^=e[a++],r^=e[a++],i^=e[a++];const u=e.length/4-2;for(let y=0;y<u;y++){const d=e[a++]^Ne(s,c,t,n,r,i),g=e[a++]^Ne(s,c,n,r,i,t),p=e[a++]^Ne(s,c,r,i,t,n),m=e[a++]^Ne(s,c,i,t,n,r);t=d,n=g,r=p,i=m}const f=e[a++]^se(o,t,n,r,i),l=e[a++]^se(o,n,r,i,t),h=e[a++]^se(o,r,i,t,n),w=e[a++]^se(o,i,t,n,r);return{s0:f,s1:l,s2:h,s3:w}}function Co(e,t,n,r,i){const{sbox2:o,T01:s,T23:c}=sr;let a=0;t^=e[a++],n^=e[a++],r^=e[a++],i^=e[a++];const u=e.length/4-2;for(let y=0;y<u;y++){const d=e[a++]^Ne(s,c,t,i,r,n),g=e[a++]^Ne(s,c,n,t,i,r),p=e[a++]^Ne(s,c,r,n,t,i),m=e[a++]^Ne(s,c,i,r,n,t);t=d,n=g,r=p,i=m}const f=e[a++]^se(o,t,i,r,n),l=e[a++]^se(o,n,t,i,r),h=e[a++]^se(o,r,n,t,i),w=e[a++]^se(o,i,r,n,t);return{s0:f,s1:l,s2:h,s3:w}}function ur(e,t){if(!t)return new Uint8Array(e);if(ye(t),t.length<e)throw new Error(`aes: wrong destination length, expected at least ${e}, got: ${t.length}`);return t}function Io(e){if(ye(e),e.length%Be!==0)throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${Be}`)}function Uo(e,t,n){let r=e.length;const i=r%Be;if(!t&&i!==0)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");const o=F(e);if(t){let a=Be-i;a||(a=Be),r=r+a}const s=ur(r,n),c=F(s);return{b:o,o:c,out:s}}function Ko(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=F(t);t.set(e);const r=Be-e.length;for(let i=Be-r;i<Be;i++)t[i]=r;return n}const lr=mo({blockSize:16,nonceLength:16},function(t,n,r={}){ye(t),ye(n,16);const i=!r.disablePadding;return{encrypt:(o,s)=>{const c=ar(t),{b:a,o:u,out:f}=Uo(o,i,s),l=F(n);let h=l[0],w=l[1],y=l[2],d=l[3],g=0;for(;g+4<=a.length;)h^=a[g+0],w^=a[g+1],y^=a[g+2],d^=a[g+3],{s0:h,s1:w,s2:y,s3:d}=cr(c,h,w,y,d),u[g++]=h,u[g++]=w,u[g++]=y,u[g++]=d;if(i){const p=_o(o.subarray(g*4));h^=p[0],w^=p[1],y^=p[2],d^=p[3],{s0:h,s1:w,s2:y,s3:d}=cr(c,h,w,y,d),u[g++]=h,u[g++]=w,u[g++]=y,u[g++]=d}return c.fill(0),f},decrypt:(o,s)=>{Io(o);const c=No(t),a=F(n),u=ur(o.length,s),f=F(o),l=F(u);let h=a[0],w=a[1],y=a[2],d=a[3];for(let g=0;g+4<=f.length;){const p=h,m=w,B=y,_=d;h=f[g+0],w=f[g+1],y=f[g+2],d=f[g+3];const{s0:I,s1:E,s2:x,s3:S}=Co(c,h,w,y,d);l[g++]=I^p,l[g++]=E^m,l[g++]=x^B,l[g++]=S^_}return c.fill(0),Ko(u,i)}}}),fr=e=>Uint8Array.from(e.split("").map(t=>t.charCodeAt(0))),Lo=fr("expand 16-byte k"),To=fr("expand 32-byte k"),ko=F(Lo),dr=F(To);dr.slice();function L(e,t){return e<<t|e>>>32-t}function rn(e){return e.byteOffset%4===0}const yt=64,$o=16,hr=2**32-1,gr=new Uint32Array;function Ro(e,t,n,r,i,o,s,c){const a=i.length,u=new Uint8Array(yt),f=F(u),l=rn(i)&&rn(o),h=l?F(i):gr,w=l?F(o):gr;for(let y=0;y<a;s++){if(e(t,n,r,f,s,c),s>=hr)throw new Error("arx: counter overflow");const d=Math.min(yt,a-y);if(l&&d===yt){const g=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let p=0,m;p<$o;p++)m=g+p,w[m]=h[m]^f[p];y+=yt;continue}for(let g=0,p;g<d;g++)p=y+g,o[p]=i[p]^u[g];y+=d}}function Po(e,t){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:o,rounds:s}=vo({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(s),ir(o),ir(n),(c,a,u,f,l=0)=>{ye(c),ye(a),ye(u);const h=u.length;if(f||(f=new Uint8Array(h)),ye(f),Xt(l),l<0||l>=hr)throw new Error("arx: counter overflow");if(f.length<h)throw new Error(`arx: output (${f.length}) is shorter than data (${h})`);const w=[];let y=c.length,d,g;if(y===32)d=c.slice(),w.push(d),g=dr;else if(y===16&&n)d=new Uint8Array(32),d.set(c),d.set(c,16),g=ko,w.push(d);else throw new Error(`arx: invalid 32-byte key, got length=${y}`);rn(a)||(a=a.slice(),w.push(a));const p=F(d);if(r){if(a.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(g,p,F(a.subarray(0,16)),p),a=a.subarray(16)}const m=16-i;if(m!==a.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(m!==12){const _=new Uint8Array(12);_.set(a,o?0:12-a.length),a=_,w.push(a)}const B=F(a);for(Ro(e,g,p,B,u,f,l,s);w.length>0;)w.pop().fill(0);return f}}function Oo(e,t,n,r,i,o=20){let s=e[0],c=e[1],a=e[2],u=e[3],f=t[0],l=t[1],h=t[2],w=t[3],y=t[4],d=t[5],g=t[6],p=t[7],m=i,B=n[0],_=n[1],I=n[2],E=s,x=c,S=a,O=u,K=f,N=l,$=h,R=w,H=y,b=d,v=g,A=p,U=m,C=B,T=_,P=I;for(let ee=0;ee<o;ee+=2)E=E+K|0,U=L(U^E,16),H=H+U|0,K=L(K^H,12),E=E+K|0,U=L(U^E,8),H=H+U|0,K=L(K^H,7),x=x+N|0,C=L(C^x,16),b=b+C|0,N=L(N^b,12),x=x+N|0,C=L(C^x,8),b=b+C|0,N=L(N^b,7),S=S+$|0,T=L(T^S,16),v=v+T|0,$=L($^v,12),S=S+$|0,T=L(T^S,8),v=v+T|0,$=L($^v,7),O=O+R|0,P=L(P^O,16),A=A+P|0,R=L(R^A,12),O=O+R|0,P=L(P^O,8),A=A+P|0,R=L(R^A,7),E=E+N|0,P=L(P^E,16),v=v+P|0,N=L(N^v,12),E=E+N|0,P=L(P^E,8),v=v+P|0,N=L(N^v,7),x=x+$|0,U=L(U^x,16),A=A+U|0,$=L($^A,12),x=x+$|0,U=L(U^x,8),A=A+U|0,$=L($^A,7),S=S+R|0,C=L(C^S,16),H=H+C|0,R=L(R^H,12),S=S+R|0,C=L(C^S,8),H=H+C|0,R=L(R^H,7),O=O+K|0,T=L(T^O,16),b=b+T|0,K=L(K^b,12),O=O+K|0,T=L(T^O,8),b=b+T|0,K=L(K^b,7);let k=0;r[k++]=s+E|0,r[k++]=c+x|0,r[k++]=a+S|0,r[k++]=u+O|0,r[k++]=f+K|0,r[k++]=l+N|0,r[k++]=h+$|0,r[k++]=w+R|0,r[k++]=y+H|0,r[k++]=d+b|0,r[k++]=g+v|0,r[k++]=p+A|0,r[k++]=m+U|0,r[k++]=B+C|0,r[k++]=_+T|0,r[k++]=I+P|0}const pr=Po(Oo,{counterRight:!1,counterLength:4,allowShortKeys:!1});class yr extends Vn{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,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 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:o,blockLen:s,outputLen:c}=this;return t=t,t.finished=i,t.destroyed=o,t.blockLen=s,t.outputLen=c,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const wt=(e,t,n)=>new yr(e,t).update(n).digest();wt.create=(e,t)=>new yr(e,t);function on(e,t,n){return oe.hash(e),n===void 0&&(n=new Uint8Array(e.outputLen)),wt(e,Ye(n),Ye(t))}const sn=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 o=new Uint8Array(i*e.outputLen),s=wt.create(e,t),c=s._cloneInto(),a=new Uint8Array(s.outputLen);for(let u=0;u<i;u++)sn[0]=u+1,c.update(u===0?wr:a).update(n).update(sn).digestInto(a),o.set(a,e.outputLen*u),s._cloneInto(c);return s.destroy(),c.destroy(),a.fill(0),sn.fill(0),o.slice(0,r)}var Ho=Object.defineProperty,D=(e,t)=>{for(var n in t)Ho(e,n,{get:t[n],enumerable:!0})},qe=Symbol("verified"),Mo=e=>e instanceof Object;function vr(e){if(!Mo(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 qo={};D(qo,{Queue:()=>Vo,QueueNode:()=>Er,binarySearch:()=>an,insertEventIntoAscendingList:()=>zo,insertEventIntoDescendingList:()=>jo,normalizeURL:()=>Do,utf8Decoder:()=>ae,utf8Encoder:()=>Q});var ae=new TextDecoder("utf-8"),Q=new TextEncoder;function Do(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 jo(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 zo(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),o=t(e[i]);if(o===0)return[i,!0];o<0?r=i-1:n=i+1}return[n,!1]}var Er=class{constructor(e){ne(this,"value");ne(this,"next",null);ne(this,"prev",null);this.value=e}},Vo=class{constructor(){ne(this,"first");ne(this,"last");this.first=null,this.last=null}enqueue(e){const t=new Er(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}},Zo=class{generateSecretKey(){return Je.utils.randomPrivateKey()}getPublicKey(e){return j(Je.getPublicKey(e))}finalizeEvent(e,t){const n=e;return n.pubkey=j(Je.getPublicKey(t)),n.id=bt(n),n.sig=j(Je.sign(bt(n),t)),n[qe]=!0,n}verifyEvent(e){if(typeof e[qe]=="boolean")return e[qe];const t=bt(e);if(t!==e.id)return e[qe]=!1,!1;try{const n=Je.verify(e.sig,t,e.pubkey);return e[qe]=n,n}catch{return e[qe]=!1,!1}}};function Fo(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 bt(e){let t=Se(Q.encode(Fo(e)));return j(t)}var vt=new Zo,De=vt.generateSecretKey,Ce=vt.getPublicKey,ce=vt.finalizeEvent,cn=vt.verifyEvent,Wo={};D(Wo,{Application:()=>Ws,BadgeAward:()=>rs,BadgeDefinition:()=>qs,BlockedRelaysList:()=>Ns,BookmarkList:()=>Ss,Bookmarksets:()=>Os,Calendar:()=>ta,CalendarEventRSVP:()=>na,ChannelCreation:()=>Br,ChannelHideMessage:()=>Ir,ChannelMessage:()=>Cr,ChannelMetadata:()=>Nr,ChannelMuteUser:()=>Ur,ClassifiedListing:()=>Ys,ClientAuth:()=>Kr,CommunitiesList:()=>As,CommunityDefinition:()=>oa,CommunityPostApproval:()=>ds,Contacts:()=>Qo,CreateOrUpdateProduct:()=>zs,CreateOrUpdateStall:()=>js,Curationsets:()=>Hs,Date:()=>Qs,DraftClassifiedListing:()=>Xs,DraftLong:()=>Zs,Emojisets:()=>Fs,EncryptedDirectMessage:()=>es,EncryptedDirectMessages:()=>ts,EventDeletion:()=>ns,FileMetadata:()=>ss,FileServerPreference:()=>Ks,Followsets:()=>$s,GenericRepost:()=>is,Genericlists:()=>Rs,HTTPAuth:()=>fn,Handlerinformation:()=>ia,Handlerrecommendation:()=>ra,Highlights:()=>vs,InterestsList:()=>Is,Interestsets:()=>Ds,JobFeedback:()=>ps,JobRequest:()=>hs,JobResult:()=>gs,Label:()=>fs,LightningPubRPC:()=>Ls,LiveChatMessage:()=>as,LiveEvent:()=>Gs,LongFormArticle:()=>Vs,Metadata:()=>Jo,Mutelist:()=>Es,NWCWalletInfo:()=>_s,NWCWalletRequest:()=>_r,NWCWalletResponse:()=>Ts,NostrConnect:()=>ks,OpenTimestamps:()=>os,Pinlist:()=>ms,ProblemTracker:()=>cs,ProfileBadges:()=>Ms,PublicChatsList:()=>Bs,Reaction:()=>ln,RecommendRelay:()=>Xo,RelayList:()=>xs,Relaysets:()=>Ps,Report:()=>us,Reporting:()=>ls,Repost:()=>un,SearchRelaysList:()=>Cs,ShortTextNote:()=>Yo,Time:()=>ea,UserEmojiList:()=>Us,UserStatuses:()=>Js,Zap:()=>bs,ZapGoal:()=>ys,ZapRequest:()=>ws,classifyKind:()=>Go,isEphemeralKind:()=>Sr,isParameterizedReplaceableKind:()=>Ar,isRegularKind:()=>mr,isReplaceableKind:()=>xr});function mr(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 Go(e){return mr(e)?"regular":xr(e)?"replaceable":Sr(e)?"ephemeral":Ar(e)?"parameterized":"unknown"}var Jo=0,Yo=1,Xo=2,Qo=3,es=4,ts=4,ns=5,un=6,ln=7,rs=8,is=16,Br=40,Nr=41,Cr=42,Ir=43,Ur=44,os=1040,ss=1063,as=1311,cs=1971,us=1984,ls=1984,fs=1985,ds=4550,hs=5999,gs=6999,ps=7e3,ys=9041,ws=9734,bs=9735,vs=9802,Es=1e4,ms=10001,xs=10002,Ss=10003,As=10004,Bs=10005,Ns=10006,Cs=10007,Is=10015,Us=10030,Ks=10096,_s=13194,Ls=21e3,Kr=22242,_r=23194,Ts=23195,ks=24133,fn=27235,$s=3e4,Rs=30001,Ps=30002,Os=30003,Hs=30004,Ms=30008,qs=30009,Ds=30015,js=30017,zs=30018,Vs=30023,Zs=30024,Fs=30030,Ws=30078,Gs=30311,Js=30315,Ys=30402,Xs=30403,Qs=31922,ea=31923,ta=31924,na=31925,ra=31989,ia=31990,oa=34550,sa={};D(sa,{getHex64:()=>dn,getInt:()=>Lr,getSubscriptionId:()=>aa,matchEventId:()=>ca,matchEventKind:()=>la,matchEventPubkey:()=>ua});function dn(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 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 o=r+1+i;return e.slice(r+1,o)}function ca(e,t){return t===dn(e,"id")}function ua(e,t){return t===dn(e,"pubkey")}function la(e,t){return t===Lr(e,"kind")}var fa={};D(fa,{makeAuthEvent:()=>da});function da(e,t){return{kind:Kr,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",t]],content:""}}var ha;try{ha=WebSocket}catch{}var ga;try{ga=WebSocket}catch{}var Qe={};D(Qe,{BECH32_REGEX:()=>Tr,Bech32MaxSize:()=>hn,decode:()=>Et,encodeBytes:()=>xt,naddrEncode:()=>ma,neventEncode:()=>Ea,noteEncode:()=>ba,nprofileEncode:()=>va,npubEncode:()=>wa,nrelayEncode:()=>xa,nsecEncode:()=>ya});var hn=5e3,Tr=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function pa(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 Et(e){var i,o,s,c,a,u,f,l;let{prefix:t,words:n}=He.decode(e,hn),r=new Uint8Array(He.fromWords(n));switch(t){case"nprofile":{let h=mt(r);if(!((i=h[0])!=null&&i[0]))throw new Error("missing TLV 0 for nprofile");if(h[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:j(h[0][0]),relays:h[1]?h[1].map(w=>ae.decode(w)):[]}}}case"nevent":{let h=mt(r);if(!((o=h[0])!=null&&o[0]))throw new Error("missing TLV 0 for nevent");if(h[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(h[2]&&h[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(h[3]&&h[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:j(h[0][0]),relays:h[1]?h[1].map(w=>ae.decode(w)):[],author:(s=h[2])!=null&&s[0]?j(h[2][0]):void 0,kind:(c=h[3])!=null&&c[0]?parseInt(j(h[3][0]),16):void 0}}}case"naddr":{let h=mt(r);if(!((a=h[0])!=null&&a[0]))throw new Error("missing TLV 0 for naddr");if(!((u=h[2])!=null&&u[0]))throw new Error("missing TLV 2 for naddr");if(h[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!((f=h[3])!=null&&f[0]))throw new Error("missing TLV 3 for naddr");if(h[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:ae.decode(h[0][0]),pubkey:j(h[2][0]),kind:parseInt(j(h[3][0]),16),relays:h[1]?h[1].map(w=>ae.decode(w)):[]}}}case"nrelay":{let h=mt(r);if(!((l=h[0])!=null&&l[0]))throw new Error("missing TLV 0 for nrelay");return{type:"nrelay",data:ae.decode(h[0][0])}}case"nsec":return{type:t,data:r};case"npub":case"note":return{type:t,data:j(r)};default:throw new Error(`unknown prefix ${t}`)}}function mt(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 ya(e){return xt("nsec",e)}function wa(e){return xt("npub",J(e))}function ba(e){return xt("note",J(e))}function et(e,t){let n=He.toWords(t);return He.encode(e,n,hn)}function xt(e,t){return et(e,t)}function va(e){let t=St({0:[J(e.pubkey)],1:(e.relays||[]).map(n=>Q.encode(n))});return et("nprofile",t)}function Ea(e){let t;e.kind!==void 0&&(t=pa(e.kind));let n=St({0:[J(e.id)],1:(e.relays||[]).map(r=>Q.encode(r)),2:e.author?[J(e.author)]:[],3:t?[new Uint8Array(t)]:[]});return et("nevent",n)}function ma(e){let t=new ArrayBuffer(4);new DataView(t).setUint32(0,e.kind,!1);let n=St({0:[Q.encode(e.identifier)],1:(e.relays||[]).map(r=>Q.encode(r)),2:[J(e.pubkey)],3:[new Uint8Array(t)]});return et("naddr",n)}function xa(e){let t=St({0:[Q.encode(e)]});return et("nrelay",t)}function St(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)})}),dt(...t)}var Sa={};D(Sa,{decrypt:()=>Aa,encrypt:()=>kr});async function kr(e,t,n){const r=e instanceof Uint8Array?j(e):e,i=ke.getSharedSecret(r,"02"+t),o=$r(i);let s=Uint8Array.from(Fn(16)),c=Q.encode(n),a=lr(o,s).encrypt(c),u=pe.encode(new Uint8Array(a)),f=pe.encode(new Uint8Array(s.buffer));return`${u}?iv=${f}`}async function Aa(e,t,n){const r=e instanceof Uint8Array?j(e):e;let[i,o]=n.split("?iv="),s=ke.getSharedSecret(r,"02"+t),c=$r(s),a=pe.decode(o),u=pe.decode(i),f=lr(c,a).decrypt(u);return ae.decode(f)}function $r(e){return e.slice(1,33)}var Ba={};D(Ba,{NIP05_REGEX:()=>Rr,isValid:()=>Ia,queryProfile:()=>Pr,searchDomain:()=>Ca,useFetchImplementation:()=>Na});var Rr=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,At;try{At=fetch}catch{}function Na(e){At=e}async function Ca(e,t=""){try{const n=`https://${e}/.well-known/nostr.json?name=${t}`;return(await(await At(n,{redirect:"error"})).json()).names}catch{return{}}}async function Pr(e){var o;const t=e.match(Rr);if(!t)return null;const[n,r="_",i]=t;try{const s=`https://${i}/.well-known/nostr.json?name=${r}`,c=await(await At(s,{redirect:"error"})).json();let a=c.names[r];return a?{pubkey:a,relays:(o=c.relays)==null?void 0:o[a]}:null}catch{return null}}async function Ia(e,t){let n=await Pr(t);return n?n.pubkey===e:!1}var Ua={};D(Ua,{parse:()=>Ka});function Ka(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,c,a]=i,u={id:s,relays:c?[c]:[]},f=r===0,l=r===n.length-1;if(a==="root"){t.root=u;continue}if(a==="reply"){t.reply=u;continue}if(a==="mention"){t.mentions.push(u);continue}if(f){t.root=u;continue}if(l){t.reply=u;continue}t.mentions.push(u)}return t}var _a={};D(_a,{fetchRelayInformation:()=>Ta,useFetchImplementation:()=>La});var Or;try{Or=fetch}catch{}function La(e){Or=e}async function Ta(e){return await(await fetch(e.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var ka={};D(ka,{getPow:()=>Hr,minePow:()=>$a});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 $a(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=bt(r),Hr(r.id)>=t)break}return r}var Ra={};D(Ra,{finishRepostEvent:()=>Pa,getRepostedEvent:()=>Oa,getRepostedEventPointer:()=>Mr});function Pa(e,t,n,r){return ce({kind:un,tags:[...e.tags??[],["e",t.id,n],["p",t.pubkey]],content:e.content===""?"":JSON.stringify(t),created_at:e.created_at},r)}function Mr(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)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 Oa(e,{skipVerification:t}={}){const n=Mr(e);if(n===void 0||e.content==="")return;let r;try{r=JSON.parse(e.content)}catch{return}if(r.id===n.id&&!(!t&&!cn(r)))return r}var Ha={};D(Ha,{NOSTR_URI_REGEX:()=>Bt,parse:()=>qa,test:()=>Ma});var Bt=new RegExp(`nostr:(${Tr.source})`);function Ma(e){return typeof e=="string"&&new RegExp(`^${Bt.source}$`).test(e)}function qa(e){const t=e.match(new RegExp(`^${Bt.source}$`));if(!t)throw new Error(`Invalid Nostr URI: ${e}`);return{uri:t[0],value:t[1],decoded:Et(t[1])}}var Da={};D(Da,{finishReactionEvent:()=>ja,getReactedEventPointer:()=>za});function ja(e,t,n){const r=t.tags.filter(i=>i.length>=2&&(i[0]==="e"||i[0]==="p"));return ce({...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 Va={};D(Va,{matchAll:()=>Za,regex:()=>gn,replaceAll:()=>Fa});var gn=()=>new RegExp(`\\b${Bt.source}\\b`,"g");function*Za(e){const t=e.matchAll(gn());for(const n of t)try{const[r,i]=n;yield{uri:r,value:i,decoded:Et(i),start:n.index,end:n.index+r.length}}catch{}}function Fa(e,t){return e.replaceAll(gn(),(n,r)=>t({uri:n,value:r,decoded:Et(r)}))}var Wa={};D(Wa,{channelCreateEvent:()=>Ga,channelHideMessageEvent:()=>Xa,channelMessageEvent:()=>Ya,channelMetadataEvent:()=>Ja,channelMuteUserEvent:()=>Qa});var Ga=(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 ce({kind:Br,tags:[...e.tags??[]],content:n,created_at:e.created_at},t)},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 ce({kind:Nr,tags:[["e",e.channel_create_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},Ya=(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"]),ce({kind:Cr,tags:[...n,...e.tags??[]],content:e.content,created_at:e.created_at},t)},Xa=(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 ce({kind:Ir,tags:[["e",e.channel_message_event_id],...e.tags??[]],content:n,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 ce({kind:Ur,tags:[["p",e.pubkey_to_mute],...e.tags??[]],content:n,created_at:e.created_at},t)},ec={};D(ec,{EMOJI_SHORTCODE_REGEX:()=>qr,matchAll:()=>tc,regex:()=>pn,replaceAll:()=>nc});var qr=/:(\w+):/,pn=()=>new RegExp(`\\B${qr.source}\\B`,"g");function*tc(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 nc(e,t){return e.replaceAll(pn(),(n,r)=>t({shortcode:n,name:r}))}var rc={};D(rc,{useFetchImplementation:()=>ic,validateGithub:()=>oc});var yn;try{yn=fetch}catch{}function ic(e){yn=e}async function oc(e,t,n){try{return await(await yn(`https://gist.github.com/${t}/${n}/raw`)).text()===`Verifying that I control the following Nostr public key: ${e}`}catch{return!1}}var we={};D(we,{decrypt:()=>Wr,encrypt:()=>Fr,getConversationKey:()=>zr,v2:()=>lc});var Dr=1,jr=65535;function zr(e,t){const n=ke.getSharedSecret(e,"02"+t).subarray(1,33);return on(Se,n,"nip44-v2")}function Vr(e,t){const n=br(Se,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 sc(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 ac(e){const t=Q.encode(e),n=t.length,r=sc(n),i=new Uint8Array(wn(n)-n);return dt(r,t,i)}function cc(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+wn(t))throw new Error("invalid padding");return ae.decode(n)}function Zr(e,t,n){if(n.length!==32)throw new Error("AAD associated data must be 32 bytes");const r=dt(n,t);return wt(Se,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=pe.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 Fr(e,t,n=Fn(32)){const{chacha_key:r,chacha_nonce:i,hmac_key:o}=Vr(t,n),s=ac(e),c=pr(r,i,s),a=Zr(o,c,n);return pe.encode(dt(new Uint8Array([2]),n,c,a))}function Wr(e,t){const{nonce:n,ciphertext:r,mac:i}=uc(e),{chacha_key:o,chacha_nonce:s,hmac_key:c}=Vr(t,n),a=Zr(c,r,n);if(!Eo(a,i))throw new Error("invalid MAC");const u=pr(o,s,r);return cc(u)}var lc={utils:{getConversationKey:zr,calcPaddedLen:wn},encrypt:Fr,decrypt:Wr},fc={};D(fc,{makeNwcRequestEvent:()=>hc,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 hc(e,t,n){const i=await kr(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 ce(o,t)}var gc={};D(gc,{getZapEndpoint:()=>yc,makeZapReceipt:()=>vc,makeZapRequest:()=>wc,useFetchImplementation:()=>pc,validateZapRequest:()=>bc});var bn;try{bn=fetch}catch{}function pc(e){bn=e}async function yc(e){try{let t="",{lud06:n,lud16:r}=JSON.parse(e.content);if(n){let{words:s}=He.decode(n,1e3),c=He.fromWords(s);t=ae.decode(c)}else if(r){let[s,c]=r.split("@");t=new URL(`/.well-known/lnurlp/${s}`,`https://${c}`).toString()}else return null;let o=await(await bn(t)).json();if(o.allowsNostr&&o.nostrPubkey)return o.callback}catch{}return null}function wc({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 bc(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(!cn(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 vc({zapRequest:e,preimage:t,bolt11:n,paidAt:r}){let i=JSON.parse(e),o=i.tags.filter(([c])=>c==="e"||c==="p"||c==="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 Ec={};D(Ec,{getToken:()=>mc,hashPayload:()=>vn,unpackEventFromToken:()=>Jr,validateEvent:()=>ni,validateEventKind:()=>Xr,validateEventMethodTag:()=>ei,validateEventPayloadTag:()=>ti,validateEventTimestamp:()=>Yr,validateEventUrlTag:()=>Qr,validateToken:()=>xc});var Gr="Nostr ";async function mc(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?Gr:"")+pe.encode(Q.encode(JSON.stringify(s)))}async function xc(e,t,n){const r=await Jr(e).catch(o=>{throw o});return await ni(r,t,n).catch(o=>{throw o})}async function Jr(e){if(!e)throw new Error("Missing token");e=e.replace(Gr,"");const t=ae.decode(pe.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===fn}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 vn(e){const t=Se(Q.encode(JSON.stringify(e)));return j(t)}function ti(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 ni(e,t,n,r){if(!cn(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 je=4,Sc=100;var ue=(e=>(e[e.Us=0]="Us",e[e.Them=1]="Them",e))(ue||{}),le=(e=>(e[e.Current=0]="Current",e[e.Next=1]="Next",e))(le||{});function Ac(e){return JSON.stringify({theirCurrentNostrPublicKey:e.theirCurrentNostrPublicKey,ourCurrentNostrKey:{publicKey:e.ourCurrentNostrKey.publicKey,privateKey:j(e.ourCurrentNostrKey.privateKey)},ourNextNostrKey:{publicKey:e.ourNextNostrKey.publicKey,privateKey:j(e.ourNextNostrKey.privateKey)},receivingChainKey:j(e.receivingChainKey),nextReceivingChainKey:j(e.nextReceivingChainKey),sendingChainKey:j(e.sendingChainKey),sendingChainMessageNumber:e.sendingChainMessageNumber,receivingChainMessageNumber:e.receivingChainMessageNumber,previousSendingChainMessageCount:e.previousSendingChainMessageCount,skippedMessageKeys:Object.fromEntries(Object.entries(e.skippedMessageKeys).map(([t,n])=>[t,j(n)]))})}function Bc(e){const t=JSON.parse(e);return{theirCurrentNostrPublicKey:t.theirCurrentNostrPublicKey,ourCurrentNostrKey:{publicKey:t.ourCurrentNostrKey.publicKey,privateKey:J(t.ourCurrentNostrKey.privateKey)},ourNextNostrKey:{publicKey:t.ourNextNostrKey.publicKey,privateKey:J(t.ourNextNostrKey.privateKey)},receivingChainKey:J(t.receivingChainKey),nextReceivingChainKey:J(t.nextReceivingChainKey),sendingChainKey:J(t.sendingChainKey),sendingChainMessageNumber:t.sendingChainMessageNumber,receivingChainMessageNumber:t.receivingChainMessageNumber,previousSendingChainMessageCount:t.previousSendingChainMessageCount,skippedMessageKeys:Object.fromEntries(Object.entries(t.skippedMessageKeys).map(([n,r])=>[n,J(r)]))}}async function*Nc(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 ri(e,t=new Uint8Array(32)){const n=on(Se,e,t);return br(Se,n,new Uint8Array([1]),32)}class tt{constructor(t,n){ne(this,"nostrUnsubscribe");ne(this,"nostrNextUnsubscribe");ne(this,"currentInternalSubscriptionId",0);ne(this,"internalSubscriptions",new Map);ne(this,"name",Math.random().toString(36).substring(2,6));this.nostrSubscribe=t,this.state=n,this.name=Math.random().toString(36).substring(2,6)}static init(t,n,r,i){const o=De(),s={theirCurrentNostrPublicKey:n,ourCurrentNostrKey:{publicKey:Ce(r),privateKey:r},ourNextNostrKey:{publicKey:Ce(o),privateKey:o},receivingChainKey:new Uint8Array,nextReceivingChainKey:new Uint8Array,sendingChainKey:new Uint8Array,sendingChainMessageNumber:0,receivingChainMessageNumber:0,previousSendingChainMessageCount:0,skippedMessageKeys:{}},c=new tt(t,s);return c.updateTheirCurrentNostrPublicKey(n),i&&(c.name=i),c}updateTheirCurrentNostrPublicKey(t){this.state.theirCurrentNostrPublicKey=t,this.state.previousSendingChainMessageCount=this.state.sendingChainMessageNumber,this.state.sendingChainMessageNumber=0,this.state.receivingChainMessageNumber=0,this.state.receivingChainKey=this.getNostrSenderKeypair(ue.Them,le.Current).privateKey,this.state.nextReceivingChainKey=this.getNostrSenderKeypair(ue.Them,le.Next).privateKey,this.state.sendingChainKey=this.getNostrSenderKeypair(ue.Us,le.Current).privateKey}rotateOurCurrentNostrKey(){this.state.ourCurrentNostrKey=this.state.ourNextNostrKey;const t=De();this.state.ourNextNostrKey={publicKey:Ce(t),privateKey:t}}getNostrSenderKeypair(t,n){if(t===ue.Us&&n===le.Next)throw new Error("We don't have their next key");const r=n===le.Current?this.state.ourCurrentNostrKey.privateKey:this.state.ourNextNostrKey.privateKey,i=this.state.theirCurrentNostrPublicKey,o=t===ue.Us?Ce(r):i,s=ri(we.getConversationKey(r,i),J(o));return{publicKey:Ce(s),privateKey:s}}nostrSubscribeNext(){const t=this.getNostrSenderKeypair(ue.Them,le.Next).publicKey,n=this.state.nextReceivingChainKey;this.nostrNextUnsubscribe=this.nostrSubscribe({authors:[t],kinds:[je]},r=>{var o;const i=JSON.parse(we.decrypt(r.content,n));i.nextPublicKey!==this.state.theirCurrentNostrPublicKey&&(this.rotateOurCurrentNostrKey(),this.updateTheirCurrentNostrPublicKey(i.nextPublicKey),(o=this.nostrUnsubscribe)==null||o.call(this),this.nostrUnsubscribe=this.nostrNextUnsubscribe,this.nostrSubscribeNext()),this.internalSubscriptions.forEach(s=>s({id:r.id,data:i.data,pubkey:i.nextPublicKey,time:i.time}))})}subscribeToNostrEvents(){if(this.nostrUnsubscribe)return;const t=this.getNostrSenderKeypair(ue.Them,le.Current).publicKey,n=this.state.receivingChainKey;this.nostrUnsubscribe=this.nostrSubscribe({authors:[t],kinds:[je]},r=>{const i=JSON.parse(we.decrypt(r.content,n));i.nextPublicKey!==this.state.theirCurrentNostrPublicKey&&this.updateTheirCurrentNostrPublicKey(i.nextPublicKey),this.internalSubscriptions.forEach(o=>o({id:r.id,data:i.data,pubkey:i.nextPublicKey,time:i.time}))}),this.nostrSubscribeNext()}onMessage(t){const n=this.currentInternalSubscriptionId++;return this.internalSubscriptions.set(n,t),this.subscribeToNostrEvents(),()=>this.internalSubscriptions.delete(n)}send(t){const n={number:this.state.sendingChainMessageNumber,data:t,nextPublicKey:this.state.ourNextNostrKey.publicKey,time:Date.now()};this.state.sendingChainMessageNumber++;const r=this.getNostrSenderKeypair(ue.Us,le.Current).privateKey,i=we.encrypt(JSON.stringify(n),this.state.sendingChainKey);return ce({content:i,kind:je,tags:[],created_at:Math.floor(Date.now()/1e3)},r)}}new TextDecoder("utf-8"),new TextEncoder;function Nt(e,t){const n=ke.getSharedSecret(e,"02"+t).subarray(1,33);return on(Se,n,"nip44-v2")}class nt{constructor(t,n,r,i,o,s,c=[]){this.inviterSessionPublicKey=t,this.linkSecret=n,this.inviter=r,this.inviterSessionPrivateKey=i,this.label=o,this.maxUses=s,this.usedBy=c}static createNew(t,n,r){const i=De(),o=Ce(i),s=pt.encode(De()).slice(8,40);return new nt(o,s,t,i,n,r)}static fromUrl(t){const n=new URL(t),r=n.pathname.slice(1),i=n.searchParams.get("s"),o=n.hash.slice(1);if(!r)throw new Error("Inviter not found in the URL");if(!i)throw new Error("Session key not found in the URL");const s=Qe.decode(r),c=Qe.decode(i);if(typeof s.data!="string")throw new Error("Decoded inviter is not a string");if(typeof c.data!="string")throw new Error("Decoded session key is not a string");const a=s.data,u=c.data;return new nt(u,o,a)}static deserialize(t){const n=JSON.parse(t);return new nt(n.inviterSessionPublicKey,n.linkSecret,n.inviter,n.inviterSessionPrivateKey?new Uint8Array(n.inviterSessionPrivateKey):void 0,n.label,n.maxUses,n.usedBy)}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=new URL(`${t}/${Qe.npubEncode(this.inviter)}`);return n.searchParams.set("s",Qe.npubEncode(this.inviterSessionPublicKey)),n.hash=this.linkSecret,n.toString()}async acceptInvite(t,n,r){const i=De(),o=Ce(i),s=this.inviter||this.inviterSessionPublicKey,c=tt.init(t,this.inviterSessionPublicKey,i),a=De(),u=Ce(a),f=typeof r=="function"?r:(w,y)=>Promise.resolve(we.encrypt(w,Nt(r,y))),l={pubkey:n,tags:[["secret",this.linkSecret]],content:await f(o,s),created_at:Math.floor(Date.now()/1e3)},h={kind:je,pubkey:u,content:we.encrypt(JSON.stringify(l),Nt(a,this.inviterSessionPublicKey)),created_at:Math.floor(Date.now()/1e3),tags:[["p",this.inviterSessionPublicKey]]};return{channel:c,event:ce(h,a)}}listen(t,n,r){if(!this.inviterSessionPrivateKey)throw new Error("Inviter session key is not available");const i={kinds:[je],"#p":[this.inviterSessionPublicKey]};return n(i,async o=>{try{const s=await we.decrypt(o.content,Nt(this.inviterSessionPrivateKey,o.pubkey)),c=JSON.parse(s);if(!c.tags||!c.tags.some(([l,h])=>l==="secret"&&h===this.linkSecret)){console.error("Invalid secret from event",o);return}const u=await(typeof t=="function"?t:(l,h)=>Promise.resolve(we.decrypt(l,Nt(t,h))))(c.content,c.pubkey),f=tt.init(n,u,this.inviterSessionPrivateKey);r(f,c.pubkey)}catch(s){console.error("Error processing invite message:",s)}})}}M.Channel=tt,M.EVENT_KIND=je,M.InviteLink=nt,M.KeyType=le,M.MAX_SKIP=Sc,M.Sender=ue,M.createMessageStream=Nc,M.deserializeChannelState=Bc,M.kdf=ri,M.serializeChannelState=Ac,Object.defineProperty(M,Symbol.toStringTag,{value:"Module"})});
@@ -0,0 +1,58 @@
1
+ import { VerifiedEvent } from "nostr-tools";
2
+ export type Message = {
3
+ id: string;
4
+ data: string;
5
+ pubkey: string;
6
+ time: number;
7
+ };
8
+ export type RatchetMessage = {
9
+ number: number;
10
+ data: string;
11
+ nextPublicKey: string;
12
+ time: number;
13
+ };
14
+ export type NostrFilter = {
15
+ authors?: string[];
16
+ kinds?: number[];
17
+ };
18
+ export type KeyPair = {
19
+ publicKey: string;
20
+ privateKey: Uint8Array;
21
+ };
22
+ export interface ChannelState {
23
+ theirCurrentNostrPublicKey: string;
24
+ ourCurrentNostrKey: KeyPair;
25
+ ourNextNostrKey: KeyPair;
26
+ receivingChainKey: Uint8Array;
27
+ nextReceivingChainKey: Uint8Array;
28
+ sendingChainKey: Uint8Array;
29
+ sendingChainMessageNumber: number;
30
+ receivingChainMessageNumber: number;
31
+ previousSendingChainMessageCount: number;
32
+ skippedMessageKeys: Record<number, Uint8Array>;
33
+ }
34
+ export type Unsubscribe = () => void;
35
+ export type NostrSubscribe = (filter: NostrFilter, onEvent: (e: VerifiedEvent) => void) => Unsubscribe;
36
+ export type MessageCallback = (message: Message) => void;
37
+ export declare const EVENT_KIND = 4;
38
+ export declare const MAX_SKIP = 100;
39
+ export type NostrEvent = {
40
+ id: string;
41
+ pubkey: string;
42
+ created_at: number;
43
+ kind: number;
44
+ tags: string[][];
45
+ content: string;
46
+ sig: string;
47
+ };
48
+ export declare enum Sender {
49
+ Us = 0,
50
+ Them = 1
51
+ }
52
+ export declare enum KeyType {
53
+ Current = 0,
54
+ Next = 1
55
+ }
56
+ export type EncryptFunction = (plaintext: string, pubkey: string) => Promise<string>;
57
+ export type DecryptFunction = (ciphertext: string, pubkey: string) => Promise<string>;
58
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,MAAM,MAAM,OAAO,GAAG;IACpB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;CACd,CAAA;AAED,MAAM,MAAM,cAAc,GAAG;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,aAAa,EAAE,MAAM,CAAC;IACtB,IAAI,EAAE,MAAM,CAAC;CACd,CAAA;AAED,MAAM,MAAM,WAAW,GAAG;IACxB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;CAClB,CAAA;AAED,MAAM,MAAM,OAAO,GAAG;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,UAAU,CAAC;CACxB,CAAA;AAED,MAAM,WAAW,YAAY;IAC3B,0BAA0B,EAAE,MAAM,CAAC;IACnC,kBAAkB,EAAE,OAAO,CAAC;IAC5B,eAAe,EAAE,OAAO,CAAC;IACzB,iBAAiB,EAAE,UAAU,CAAC;IAC9B,qBAAqB,EAAE,UAAU,CAAC;IAClC,eAAe,EAAE,UAAU,CAAC;IAC5B,yBAAyB,EAAE,MAAM,CAAC;IAClC,2BAA2B,EAAE,MAAM,CAAC;IACpC,gCAAgC,EAAE,MAAM,CAAC;IACzC,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;CAChD;AAED,MAAM,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC;AACrC,MAAM,MAAM,cAAc,GAAG,CAAC,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC,CAAC,EAAE,aAAa,KAAK,IAAI,KAAK,WAAW,CAAC;AACvG,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;AAEzD,eAAO,MAAM,UAAU,IAAI,CAAC;AAC5B,eAAO,MAAM,QAAQ,MAAM,CAAC;AAE5B,MAAM,MAAM,UAAU,GAAG;IACvB,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,EAAE,EAAE,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;CACb,CAAA;AAED,oBAAY,MAAM;IAChB,EAAE,IAAA;IACF,IAAI,IAAA;CACL;AAED,oBAAY,OAAO;IACjB,OAAO,IAAA;IACP,IAAI,IAAA;CACL;AAED,MAAM,MAAM,eAAe,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;AACrF,MAAM,MAAM,eAAe,GAAG,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC"}
@@ -0,0 +1,7 @@
1
+ import { ChannelState, Message } from "./types";
2
+ import { Channel } from "./Channel";
3
+ export declare function serializeChannelState(state: ChannelState): string;
4
+ export declare function deserializeChannelState(data: string): ChannelState;
5
+ export declare function createMessageStream(channel: Channel): AsyncGenerator<Message, void, unknown>;
6
+ export declare function kdf(input1: Uint8Array, input2?: Uint8Array): Uint8Array;
7
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAIpC,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,YAAY,GAAG,MAAM,CAwBjE;AAED,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,CAyBlE;AAED,wBAAuB,mBAAmB,CAAC,OAAO,EAAE,OAAO,GAAG,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,CA0BnG;AAED,wBAAgB,GAAG,CAAC,MAAM,EAAE,UAAU,EAAE,MAAM,GAAE,UAA+B,cAG9E"}
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "nostr-double-ratchet",
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "packageManager": "yarn@1.22.22",
6
+ "description": "Nostr double ratchet library",
7
+ "main": "dist/nostr-double-ratchet.umd.js",
8
+ "module": "dist/nostr-double-ratchet.es.js",
9
+ "types": "dist/index.d.ts",
10
+ "scripts": {
11
+ "test": "vitest --exclude '**/*.integration.test.ts'",
12
+ "test:once": "vitest run --exclude '**/*.integration.test.ts'",
13
+ "test:integration": "DEBUG='ndk:*' vitest '**/*.integration.test.ts'",
14
+ "build": "vite build && tsc",
15
+ "examples": "cd examples && vite build && tsc",
16
+ "examples-dev": "cd examples && vite && tsc"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/mmalmi/nostr-double-ratchet.git"
21
+ },
22
+ "author": "Martti Malmi",
23
+ "license": "MIT",
24
+ "bugs": {
25
+ "url": "https://github.com/mmalmi/nostr-double-ratchet/issues"
26
+ },
27
+ "homepage": "https://github.com/mmalmi/nostr-double-ratchet",
28
+ "files": [
29
+ "src",
30
+ "dist",
31
+ "data"
32
+ ],
33
+ "devDependencies": {
34
+ "@nostr-dev-kit/ndk": "2.8.2",
35
+ "@types/lodash": "^4.17.7",
36
+ "@types/node": "^22.5.5",
37
+ "@typescript-eslint/eslint-plugin": "^7.1.1",
38
+ "@typescript-eslint/parser": "^7.1.1",
39
+ "@vitejs/plugin-react": "^4.3.1",
40
+ "autoprefixer": "^10.4.20",
41
+ "classnames": "^2.5.1",
42
+ "daisyui": "^4.12.10",
43
+ "eslint": "^8.57.0",
44
+ "eslint-config-prettier": "^9.1.0",
45
+ "eslint-plugin-prettier": "^5.1.3",
46
+ "eslint-plugin-simple-import-sort": "^12.0.0",
47
+ "fuse.js": "^7.0.0",
48
+ "localforage": "^1.10.0",
49
+ "lodash": "^4.17.21",
50
+ "minidenticons": "^4.2.1",
51
+ "postcss": "^8.4.47",
52
+ "prettier": "^3.2.5",
53
+ "react": "^18.3.1",
54
+ "react-dom": "^18.3.1",
55
+ "react-router-dom": "^6.26.2",
56
+ "tailwindcss": "^3.4.12",
57
+ "tsx": "^3.12.7",
58
+ "typedoc": "^0.25.12",
59
+ "typescript": "^5.3.3",
60
+ "typescript-lru-cache": "^2.0.0",
61
+ "vite": "^5.4.6",
62
+ "vitest": "^2.1.1",
63
+ "ws": "^8.18.0"
64
+ },
65
+ "dependencies": {
66
+ "nostr-tools": "^2.7.2"
67
+ }
68
+ }
package/src/Channel.ts ADDED
@@ -0,0 +1,143 @@
1
+ import { generateSecretKey, getPublicKey, nip44, finalizeEvent, VerifiedEvent } from "nostr-tools";
2
+ import { hexToBytes } from "@noble/hashes/utils";
3
+ import {
4
+ ChannelState,
5
+ RatchetMessage,
6
+ Unsubscribe,
7
+ NostrSubscribe,
8
+ MessageCallback,
9
+ EVENT_KIND,
10
+ KeyPair,
11
+ Sender,
12
+ KeyType,
13
+ } from "./types";
14
+ import { kdf } from "./utils";
15
+
16
+ export class Channel {
17
+ nostrUnsubscribe: Unsubscribe | undefined
18
+ nostrNextUnsubscribe: Unsubscribe | undefined
19
+ currentInternalSubscriptionId = 0
20
+ internalSubscriptions = new Map<number, MessageCallback>()
21
+ name = Math.random().toString(36).substring(2, 6)
22
+
23
+ constructor(private nostrSubscribe: NostrSubscribe, public state: ChannelState) {
24
+ this.name = Math.random().toString(36).substring(2, 6)
25
+ }
26
+
27
+ /**
28
+ * To preserve forward secrecy, do not use long-term keys for channel initialization. Use e.g. InviteLink to exchange session keys.
29
+ */
30
+ static init(nostrSubscribe: NostrSubscribe, theirCurrentNostrPublicKey: string, ourCurrentPrivateKey: Uint8Array, name?: string): Channel {
31
+ const ourNextPrivateKey = generateSecretKey()
32
+ const state: ChannelState = {
33
+ theirCurrentNostrPublicKey,
34
+ ourCurrentNostrKey: { publicKey: getPublicKey(ourCurrentPrivateKey), privateKey: ourCurrentPrivateKey },
35
+ ourNextNostrKey: { publicKey: getPublicKey(ourNextPrivateKey), privateKey: ourNextPrivateKey },
36
+ receivingChainKey: new Uint8Array(),
37
+ nextReceivingChainKey: new Uint8Array(),
38
+ sendingChainKey: new Uint8Array(),
39
+ sendingChainMessageNumber: 0,
40
+ receivingChainMessageNumber: 0,
41
+ previousSendingChainMessageCount: 0,
42
+ skippedMessageKeys: {}
43
+ }
44
+ const channel = new Channel(nostrSubscribe, state)
45
+ channel.updateTheirCurrentNostrPublicKey(theirCurrentNostrPublicKey)
46
+ if (name) channel.name = name
47
+ return channel
48
+ }
49
+
50
+ updateTheirCurrentNostrPublicKey(theirNewPublicKey: string) {
51
+ this.state.theirCurrentNostrPublicKey = theirNewPublicKey
52
+ this.state.previousSendingChainMessageCount = this.state.sendingChainMessageNumber
53
+ this.state.sendingChainMessageNumber = 0
54
+ this.state.receivingChainMessageNumber = 0
55
+ this.state.receivingChainKey = this.getNostrSenderKeypair(Sender.Them, KeyType.Current).privateKey
56
+ this.state.nextReceivingChainKey = this.getNostrSenderKeypair(Sender.Them, KeyType.Next).privateKey
57
+ this.state.sendingChainKey = this.getNostrSenderKeypair(Sender.Us, KeyType.Current).privateKey
58
+ }
59
+
60
+ private rotateOurCurrentNostrKey() {
61
+ this.state.ourCurrentNostrKey = this.state.ourNextNostrKey
62
+ const ourNextSecretKey = generateSecretKey()
63
+ this.state.ourNextNostrKey = {
64
+ publicKey: getPublicKey(ourNextSecretKey),
65
+ privateKey: ourNextSecretKey
66
+ }
67
+ }
68
+
69
+ getNostrSenderKeypair(sender: Sender, keyType: KeyType): KeyPair {
70
+ if (sender === Sender.Us && keyType === KeyType.Next) {
71
+ throw new Error("We don't have their next key")
72
+ }
73
+ const ourPrivate = keyType === KeyType.Current ? this.state.ourCurrentNostrKey.privateKey : this.state.ourNextNostrKey.privateKey
74
+ const theirPublic = this.state.theirCurrentNostrPublicKey
75
+ const senderPubKey = sender === Sender.Us ? getPublicKey(ourPrivate) : theirPublic
76
+ const privateKey = kdf(nip44.getConversationKey(ourPrivate, theirPublic), hexToBytes(senderPubKey))
77
+ return {
78
+ publicKey: getPublicKey(privateKey),
79
+ privateKey
80
+ }
81
+ }
82
+
83
+ private nostrSubscribeNext() {
84
+ const nextReceivingPublicKey = this.getNostrSenderKeypair(Sender.Them, KeyType.Next).publicKey
85
+ const decryptKey = this.state.nextReceivingChainKey
86
+ this.nostrNextUnsubscribe = this.nostrSubscribe({authors: [nextReceivingPublicKey], kinds: [EVENT_KIND]}, (e) => {
87
+ // they acknowledged our next key and sent with the corresponding new nostr sender key
88
+ const msg = JSON.parse(nip44.decrypt(e.content, decryptKey)) as RatchetMessage
89
+ if (msg.nextPublicKey !== this.state.theirCurrentNostrPublicKey) {
90
+ this.rotateOurCurrentNostrKey()
91
+ this.updateTheirCurrentNostrPublicKey(msg.nextPublicKey)
92
+ this.nostrUnsubscribe?.()
93
+ this.nostrUnsubscribe = this.nostrNextUnsubscribe
94
+ this.nostrSubscribeNext()
95
+ }
96
+ this.internalSubscriptions.forEach(callback => callback({id: e.id, data: msg.data, pubkey: msg.nextPublicKey, time: msg.time}))
97
+ })
98
+ }
99
+
100
+ private subscribeToNostrEvents() {
101
+ if (this.nostrUnsubscribe) {
102
+ return
103
+ }
104
+ const receivingPublicKey = this.getNostrSenderKeypair(Sender.Them, KeyType.Current).publicKey
105
+ const decryptKey = this.state.receivingChainKey
106
+ this.nostrUnsubscribe = this.nostrSubscribe({authors: [receivingPublicKey], kinds: [EVENT_KIND]}, (e) => {
107
+ const msg = JSON.parse(nip44.decrypt(e.content, decryptKey)) as RatchetMessage
108
+ if (msg.nextPublicKey !== this.state.theirCurrentNostrPublicKey) {
109
+ // they announced their next key: we will use it to derive the next nostr sender key
110
+ this.updateTheirCurrentNostrPublicKey(msg.nextPublicKey)
111
+ }
112
+ this.internalSubscriptions.forEach(callback => callback({id: e.id, data: msg.data, pubkey: msg.nextPublicKey, time: msg.time}))
113
+ })
114
+ this.nostrSubscribeNext()
115
+ }
116
+
117
+ onMessage(callback: MessageCallback): Unsubscribe {
118
+ const id = this.currentInternalSubscriptionId++
119
+ this.internalSubscriptions.set(id, callback)
120
+ this.subscribeToNostrEvents()
121
+ return () => this.internalSubscriptions.delete(id)
122
+ }
123
+
124
+ send(data: string): VerifiedEvent {
125
+ const message: RatchetMessage = {
126
+ number: this.state.sendingChainMessageNumber,
127
+ data: data,
128
+ nextPublicKey: this.state.ourNextNostrKey.publicKey,
129
+ time: Date.now()
130
+ }
131
+ this.state.sendingChainMessageNumber++
132
+ const sendingPrivateKey = this.getNostrSenderKeypair(Sender.Us, KeyType.Current).privateKey
133
+ const encryptedData = nip44.encrypt(JSON.stringify(message), this.state.sendingChainKey)
134
+ const nostrEvent = finalizeEvent({
135
+ content: encryptedData,
136
+ kind: EVENT_KIND,
137
+ tags: [],
138
+ created_at: Math.floor(Date.now() / 1000)
139
+ }, sendingPrivateKey)
140
+
141
+ return nostrEvent
142
+ }
143
+ }