@coinexams/lightning 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -61,15 +61,14 @@ const payment = client.checkInvoice({
61
61
  ```ts
62
62
  const sent = client.payInvoice({
63
63
  amountSat: 500,
64
- lightningAddress: "user@example.com",
64
+ address: "user@example.com",
65
65
  });
66
66
  // → { recipientAmountSat: 500, paymentHash: "...", ... }
67
67
 
68
- // On-chain:
68
+ // On-chain (auto-detected by address format):
69
69
  const onchain = client.payInvoice({
70
70
  amountSat: 10000,
71
- onChain: true,
72
- onChainAddress: "bc1...",
71
+ address: "bc1...",
73
72
  });
74
73
  ```
75
74
 
@@ -120,10 +119,10 @@ import {
120
119
  getBalance,
121
120
  } from "./lightning";
122
121
 
123
- const invoice = createInvoice(client, 1000);
124
- const paid = checkPayment(client, invoiceId, PaymentDirection.Incoming);
125
- const sent = sendPayment(client, 500, { lightningAddress: "u@ex.com" });
126
- const bal = getBalance(client);
122
+ const invoice = createInvoice({ client, amountSat: 1000 });
123
+ const paid = checkPayment({ client, invoiceId, type: PaymentDirection.Incoming });
124
+ const sent = sendPayment({ client, amountSat: 500, address: "u@ex.com" });
125
+ const bal = getBalance({ client });
127
126
  ```
128
127
 
129
128
  ## Environment Variables (example)
@@ -1,5 +1,5 @@
1
1
  import { LightningClient } from "./types";
2
- declare const startLightning: ({ password: directPassword, credentialsPath, port, cacheDurationMs, serverPrvKeyBytes, serverPubKeyHex, defaultRelays, domain, }: {
2
+ export declare const startLightning: ({ password: directPassword, credentialsPath, port, cacheDurationMs, serverPrvKeyBytes, serverPubKeyHex, defaultRelays, domain, }: {
3
3
  password?: string;
4
4
  credentialsPath?: string;
5
5
  port: number;
@@ -9,4 +9,3 @@ declare const startLightning: ({ password: directPassword, credentialsPath, port
9
9
  defaultRelays: string[];
10
10
  domain: string;
11
11
  }) => LightningClient;
12
- export { startLightning };
@@ -9,14 +9,10 @@ declare const checkPayment: ({ client, invoiceId, type, }: {
9
9
  invoiceId: string;
10
10
  type: PaymentDirection;
11
11
  }) => IncomingPayment | OutgoingPaymentLN | undefined;
12
- declare const sendPayment: ({ client, amountSat, opts, }: {
12
+ declare const sendPayment: ({ client, amountSat, address, }: {
13
13
  client: LightningClient;
14
14
  amountSat: number;
15
- opts?: {
16
- onChain?: boolean;
17
- lightningAddress?: string;
18
- onChainAddress?: string;
19
- };
15
+ address: string;
20
16
  }) => SentPayment | undefined;
21
17
  declare const getBalance: ({ client, }: {
22
18
  client: LightningClient;
@@ -1,7 +1,7 @@
1
1
  import { VerifiedEvent } from "nostr-tools";
2
2
  interface PaymentMakeRequest {
3
3
  amountSat: number;
4
- onChain?: boolean;
4
+ address: string;
5
5
  }
6
6
  interface PaymentNewRequest {
7
7
  amountSat: number;
@@ -98,33 +98,42 @@ interface NewInvoiceResponse {
98
98
  serialized: string;
99
99
  }
100
100
  interface LightningClient {
101
- newInvoice(opts: PaymentNewRequest): PaymentInvoiceDetails | undefined;
102
- checkInvoice(opts: PaymentCheck): IncomingPayment | OutgoingPaymentLN | undefined;
103
- payInvoice(opts: PaymentMakeRequest & {
104
- lightningAddress?: string;
105
- onChainAddress?: string;
106
- }): SentPayment | undefined;
107
- nodeQuery<T extends CacheData>(opts: LNDataRequest): T | undefined;
108
- zapSign(opts: {
109
- nostr: string;
110
- bolt11: string;
111
- }): {
112
- signedReceipt: VerifiedEvent;
113
- relays: string[];
114
- } | undefined;
115
- zapPublish(opts: {
116
- nostr: string;
117
- bolt11: string;
118
- invoiceId: string;
119
- }): Promise<void>;
120
- payRequest(opts: {
121
- user: string;
122
- amountMsat: number;
123
- nostr?: string;
124
- }): {
125
- invoice: LnurlPayResponse;
126
- invoiceId: string;
127
- } | undefined;
101
+ /** Create a new Lightning invoice for receiving payments */
102
+ newInvoice({ amountSat, description }: PaymentNewRequest): PaymentInvoiceDetails | undefined;
103
+ /** Check if a previously created invoice has been paid */
104
+ checkInvoice({ invoiceId, type }: PaymentCheck): IncomingPayment | OutgoingPaymentLN | undefined;
105
+ /** Send a Lightning or on-chain payment to an address */
106
+ payInvoice({ amountSat, address }: PaymentMakeRequest): SentPayment | undefined;
107
+ /** Query Phoenixd node state (balance, payments, info) */
108
+ nodeQuery<T extends CacheData>({ type, params }: LNDataRequest): T | undefined;
109
+ /** Sign a Nostr zap receipt (kind 9735) without publishing */
110
+ zapSign({ nostr, bolt11 }: ZapSignRequest): ZapSignResponse | undefined;
111
+ /** Poll invoice until paid, then sign and publish a Nostr zap receipt */
112
+ zapPublish({ nostr, bolt11, invoiceId }: ZapPublishRequest): Promise<void>;
113
+ /** Generate an LNURL-pay invoice, optionally with zap signing */
114
+ payRequest({ user, amountMsat, nostr }: PayRequest): PayRequestResponse | undefined;
115
+ }
116
+ interface ZapSignRequest {
117
+ nostr: string;
118
+ bolt11: string;
119
+ }
120
+ interface ZapSignResponse {
121
+ signedReceipt: VerifiedEvent;
122
+ relays: string[];
123
+ }
124
+ interface ZapPublishRequest {
125
+ nostr: string;
126
+ bolt11: string;
127
+ invoiceId: string;
128
+ }
129
+ interface PayRequest {
130
+ user: string;
131
+ amountMsat: number;
132
+ nostr?: string;
133
+ }
134
+ interface PayRequestResponse {
135
+ invoice: LnurlPayResponse;
136
+ invoiceId: string;
128
137
  }
129
138
  interface LnurlPayRequest {
130
139
  callback: string;
@@ -149,4 +158,4 @@ interface UserSeverData {
149
158
  }
150
159
  type CacheData = LNBalance | NewInvoiceResponse | PaymentDoneResponse | (IncomingPayment | OutgoingPaymentLN)[] | NodeInfo | SentPayment | string;
151
160
  export { PaymentDirection, LNDataType, };
152
- export type { CacheData, PaymentMakeRequest, PaymentNewRequest, PaymentInvoiceDetails, PaymentCheck, LNDataParams, LNDataRequest, LNBalance, IncomingPayment, OutgoingPaymentBase, OutgoingPaymentLN, OutgoingPaymentLiquidity, NodeInfo, SentPayment, PaymentDoneResponse, NewInvoiceResponse, LightningClient, LnurlPayRequest, LnurlPayResponse, UserStoredPayment, UserSeverData, };
161
+ export type { CacheData, PaymentMakeRequest, PaymentNewRequest, PaymentInvoiceDetails, PaymentCheck, LNDataParams, LNDataRequest, LNBalance, IncomingPayment, OutgoingPaymentBase, OutgoingPaymentLN, OutgoingPaymentLiquidity, NodeInfo, SentPayment, PaymentDoneResponse, NewInvoiceResponse, LightningClient, LnurlPayRequest, LnurlPayResponse, UserStoredPayment, UserSeverData, ZapSignRequest, ZapSignResponse, ZapPublishRequest, PayRequest, PayRequestResponse, };
package/dist/index.d.ts CHANGED
@@ -2,4 +2,4 @@ export { startLightning } from "./code/client";
2
2
  export { msatToSat } from "./code/utils";
3
3
  export { createInvoice, checkPayment, sendPayment, getBalance, getIncomingPayments, getOutgoingPayments, } from "./code/payment";
4
4
  export { PaymentDirection, LNDataType, } from "./code/types";
5
- export type { IncomingPayment, UserStoredPayment, UserSeverData, PaymentMakeRequest, PaymentNewRequest, PaymentInvoiceDetails, LNDataParams, LNBalance, OutgoingPaymentLN, SentPayment, } from "./code/types";
5
+ export type { IncomingPayment, UserStoredPayment, UserSeverData, PaymentMakeRequest, PaymentNewRequest, PaymentInvoiceDetails, LNDataParams, LNBalance, OutgoingPaymentLN, SentPayment, ZapSignRequest, ZapSignResponse, ZapPublishRequest, PayRequest, PayRequestResponse, } from "./code/types";
@@ -1,2 +1,2 @@
1
1
  /*! For license information please see lightning.node.min.js.LICENSE.txt */
2
- (()=>{"use strict";var e={13:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.startLightning=void 0;const r=n(421),o=n(24),i=n(534),s=n(329),a=n(805);t.startLightning=({password:e,credentialsPath:t="/root/.phoenix/credentials.json",port:n,cacheDurationMs:c,serverPrvKeyBytes:l,serverPubKeyHex:u,defaultRelays:d,domain:h})=>{const f=e||JSON.parse((0,o.readFileSync)(t,"utf-8"))?.password,p={},g=`http://localhost:${n}`,y=(e,t,n)=>{try{const o=["-s","-u",`:${f}`,"-X",t];let i=`${g}${e}`;if(n){const e=new URLSearchParams(Object.fromEntries(Object.entries(n).map((([e,t])=>[e,String(t)])))).toString();"GET"==t?i+=`?${e}`:o.push("-d",e)}o.push(i);const s=(0,r.execFileSync)("curl",o).toString();return s?.startsWith("{")||s?.startsWith("[")?JSON.parse(s):s}catch(t){console.error((0,a.seoDt)(),`Lightning node ${e} failed:`,t instanceof Error?t.message:String(t))}},w=e=>{try{const t=y("/createinvoice","POST",{amountSat:e.amountSat,description:e.description||"@NostrPro Username"});if(t?.serialized)return{invoiceString:t.serialized,invoiceId:t.paymentHash}}catch(e){console.error((0,a.seoDt)(),"newInvoice failed",e)}},m=e=>{try{const t=(0,a.tN)(),n=`${e.type}${e.params?JSON.stringify(e.params):""}`;if(p[n]&&p[n].time>t-c)return p[n].data;const r=y(`/${e.type}`,"GET",e.params);return r&&(p[n]={time:t,data:r}),r}catch(e){console.error((0,a.seoDt)(),"nodeQuery failed",e)}},b=e=>{try{const t=m({type:`payments/${e.type}`,params:{limit:30}});return t?.find((t=>t?.paymentHash==e.invoiceId))}catch(e){console.error((0,a.seoDt)(),"checkInvoice failed",e)}},v=({nostr:e,bolt11:t})=>{try{const n=(0,a.parseNostrEvent)(e);if(!n)return;const r={kind:9735,content:n.content||"",created_at:Math.round((0,a.tN)()/1e3),pubkey:u,tags:[...n.tags.filter((e=>["e","a","p","k"].includes(e[0]))),["bolt11",t],["description",JSON.stringify(n)],["P",n.pubkey]]},o=(0,i.finalizeEvent)(r,l);return(0,i.verifyEvent)(o)?{signedReceipt:o,relays:(0,a.eventRelays)(n)}:void console.error((0,a.seoDt)(),"zapSign verification failed",JSON.stringify(r))}catch(e){console.error((0,a.seoDt)(),"zapSign failed",e)}};return{newInvoice:w,checkInvoice:b,payInvoice:e=>{try{const t=e.onChain?e.onChainAddress:e.lightningAddress;if("number"!=typeof e.amountSat||!t)return;const n=a.lightningAddressRegex.test(t),r=y(`/${n?"paylnaddress":"sendtoaddress"}`,"POST",{address:t,amountSat:e.amountSat,...n?{}:{feerateSatByte:5}});if(r?.recipientAmountSat)return r}catch(e){console.error((0,a.seoDt)(),"payInvoice failed",e)}},nodeQuery:m,zapSign:v,zapPublish:async({nostr:e,bolt11:t,invoiceId:n})=>{try{const r=200,o=async()=>{const{signedReceipt:n,relays:r}=v({nostr:e,bolt11:t})||{};if(!n)return;const o=new i.SimplePool,s=(r||[]).concat(d).filter(((e,t,n)=>n.indexOf(e)===t));await Promise.allSettled(o.publish(s,n)),o.close(d)};let c=r;for(let e=0;e<30;e++){await(0,a.delayCode)(c);const e=b({invoiceId:n,type:s.PaymentDirection.Incoming});if(e?.isPaid)return void o();c+=r}}catch(e){console.error((0,a.seoDt)(),"zapPublish failed",e)}},payRequest:({user:e,amountMsat:t,nostr:n})=>{const r=(0,a.msatToSat)(t);if("number"!=typeof r||r<1)return;const o=`${e}@${h}`,{invoiceString:i="",invoiceId:s=""}=w({amountSat:r,description:`${n?"Zap":"Payment"} to ${o}`})||{};if(!i)return;const c={pr:i,routes:[]};if(n){const{signedReceipt:e}=v({nostr:n,bolt11:i})||{};if(!e)return}return{invoice:c,invoiceId:s}}}}},398:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getOutgoingPayments=t.getIncomingPayments=t.getBalance=t.sendPayment=t.checkPayment=t.createInvoice=void 0;t.createInvoice=({client:e,amountSat:t,description:n})=>e.newInvoice({amountSat:t,description:n});t.checkPayment=({client:e,invoiceId:t,type:n})=>e.checkInvoice({invoiceId:t,type:n});t.sendPayment=({client:e,amountSat:t,opts:n})=>e.payInvoice({amountSat:t,...n});t.getBalance=({client:e})=>e.nodeQuery({type:"getbalance"});t.getIncomingPayments=({client:e,limit:t=30})=>e.nodeQuery({type:"payments/incoming",params:{limit:t}});t.getOutgoingPayments=({client:e,limit:t=30})=>e.nodeQuery({type:"payments/outgoing",params:{limit:t}})},329:(e,t)=>{var n,r;Object.defineProperty(t,"__esModule",{value:!0}),t.LNDataType=t.PaymentDirection=void 0,function(e){e.Incoming="incoming",e.Outgoing="outgoing"}(n||(t.PaymentDirection=n={})),function(e){e.GetBalance="getbalance",e.GetInfo="getinfo",e.PaymentsIncoming="payments/incoming",e.PaymentsOutgoing="payments/outgoing"}(r||(t.LNDataType=r={}))},805:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eventRelays=t.parseNostrEvent=t.msatToSat=t.delayCode=t.seoDt=t.tN=t.lightningAddressRegex=void 0;const n=()=>(new Date).toISOString();t.lightningAddressRegex=/^[a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,}$/i,t.tN=()=>Date.now(),t.seoDt=n,t.delayCode=e=>new Promise((t=>setTimeout(t,e)));t.msatToSat=e=>{try{return Math.round(Number(BigInt(e)/1000n))}catch{return 0}};t.parseNostrEvent=e=>{try{const t=e?.includes("{")?e:Buffer.from(e,"base64").toString("utf-8");return JSON.parse(t)}catch(e){console.error(n(),"parseNostrEvent failed",e)}};t.eventRelays=e=>{try{return e?.tags?.find((e=>"relays"==e?.[0]))?.slice(1,10)?.map((e=>e.lastIndexOf("/")==e.length-1?e.slice(0,e.length-1):e))||[]}catch(e){console.error(n(),"eventRelays failed",e)}return[]}},421:e=>{e.exports=require("node:child_process")},24:e=>{e.exports=require("node:fs")},534:(e,t,n)=>{function r(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function o(e,t=""){if(!Number.isSafeInteger(e)||e<0){throw new Error(`${t&&`"${t}" `}expected integer >= 0, got ${e}`)}}function i(e,t,n=""){const o=r(e),i=e?.length,s=void 0!==t;if(!o||s&&i!==t){throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(o?`length=${i}`:"type="+typeof e))}return e}function s(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash must wrapped by utils.createHasher");o(e.outputLen),o(e.blockLen)}function a(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 c(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function l(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function u(e,t){return e<<32-t|e>>>t}n.r(t),n.d(t,{Relay:()=>Ga,SimplePool:()=>tc,finalizeEvent:()=>Gr,fj:()=>Na,generateSecretKey:()=>zr,getEventHash:()=>Vr,getFilterLimit:()=>_a,getPublicKey:()=>Kr,kinds:()=>Jr,matchFilter:()=>Pa,matchFilters:()=>La,mergeFilters:()=>Ua,nip04:()=>vc,nip05:()=>kc,nip10:()=>Lc,nip11:()=>_c,nip13:()=>$c,nip17:()=>Hc,nip18:()=>ml,nip19:()=>nc,nip21:()=>xl,nip22:()=>Rl,nip25:()=>_l,nip27:()=>$l,nip28:()=>ql,nip30:()=>Gl,nip39:()=>eu,nip42:()=>qa,nip44:()=>jc,nip47:()=>ru,nip54:()=>su,nip57:()=>lu,nip59:()=>qc,nip77:()=>yu,nip98:()=>Pu,parseReferences:()=>bc,serializeEvent:()=>jr,sortEvents:()=>qr,utils:()=>Tr,validateEvent:()=>Hr,verifiedSymbol:()=>Fr,verifyEvent:()=>Zr});const d=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),h=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function f(e){if(i(e),d)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=h[e[n]];return t}const p=48,g=57,y=65,w=70,m=97,b=102;function v(e){return e>=p&&e<=g?e-p:e>=y&&e<=w?e-(y-10):e>=m&&e<=b?e-(m-10):void 0}function E(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(d)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,o=0;t<n;t++,o+=2){const n=v(e.charCodeAt(o)),i=v(e.charCodeAt(o+1));if(void 0===n||void 0===i){const t=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+o)}r[t]=16*n+i}return r}function x(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];i(r),t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const o=e[t];n.set(o,r),r+=o.length}return n}function S(e,t={}){const n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}function k(e=32){const t="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof t?.getRandomValues)throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}const A=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function R(e,t,n){return e&t^e&n^t&n}class O{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=l(this.buffer)}update(e){a(this),i(e);const{view:t,buffer:n,blockLen:r}=this,o=e.length;for(let i=0;i<o;){const s=Math.min(r-this.pos,o-i);if(s!==r)n.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===r&&(this.process(t,0),this.pos=0);else{const t=l(e);for(;r<=o-i;i+=r)this.process(t,i)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){a(this),function(e,t){i(e,void 0,"digestInto() output");const n=t.outputLen;if(e.length<n)throw new Error('"digestInto() output" expected to be of length >='+n)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:o}=this;let{pos:s}=this;t[s++]=128,c(this.buffer.subarray(s)),this.padOffset>r-s&&(this.process(n,0),s=0);for(let e=s;e<r;e++)t[e]=0;n.setBigUint64(r-8,BigInt(8*this.length),o),this.process(n,0);const u=l(e),d=this.outputLen;if(d%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const h=d/4,f=this.get();if(h>f.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<h;e++)u.setUint32(4*e,f[e],o)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:o,destroyed:i,pos:s}=this;return e.destroyed=i,e.finished=o,e.length=r,e.pos=s,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const I=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);const B=Uint32Array.from([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]),T=new Uint32Array(64);class P extends O{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:t,C:n,D:r,E:o,F:i,G:s,H:a}=this;return[e,t,n,r,o,i,s,a]}set(e,t,n,r,o,i,s,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|o,this.F=0|i,this.G=0|s,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)T[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=T[e-15],n=T[e-2],r=u(t,7)^u(t,18)^t>>>3,o=u(n,17)^u(n,19)^n>>>10;T[e]=o+T[e-7]+r+T[e-16]|0}let{A:n,B:r,C:o,D:i,E:s,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(u(s,6)^u(s,11)^u(s,25))+((d=s)&a^~d&c)+B[e]+T[e]|0,h=(u(n,2)^u(n,13)^u(n,22))+R(n,r,o)|0;l=c,c=a,a=s,s=i+t|0,i=o,o=r,r=n,n=t+h|0}var d;n=n+this.A|0,r=r+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,o,i,s,a,c,l)}roundClean(){c(T)}destroy(){this.set(0,0,0,0,0,0,0,0),c(this.buffer)}}class L extends P{A=0|I[0];B=0|I[1];C=0|I[2];D=0|I[3];E=0|I[4];F=0|I[5];G=0|I[6];H=0|I[7];constructor(){super(32)}}const U=S((()=>new L),A(1)),_=BigInt(0),N=BigInt(1);function C(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}" `)+"expected boolean, got type="+typeof e)}return e}function $(e){if("bigint"==typeof e){if(!W(e))throw new Error("positive bigint expected, got "+e)}else o(e);return e}function M(e){const t=$(e).toString(16);return 1&t.length?"0"+t:t}function F(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?_:BigInt("0x"+e)}function D(e){return F(f(e))}function H(e){return F(f(function(e){return Uint8Array.from(e)}(i(e)).reverse()))}function q(e,t){o(t);const n=E((e=$(e)).toString(16).padStart(2*t,"0"));if(n.length!==t)throw new Error("number too large");return n}function j(e,t){return q(e,t).reverse()}function V(e){return Uint8Array.from(e,((t,n)=>{const r=t.charCodeAt(0);if(1!==t.length||r>127)throw new Error(`string contains non-ASCII character "${e[n]}" with code ${r} at position ${n}`);return r}))}const W=e=>"bigint"==typeof e&&_<=e;function z(e,t,n,r){if(!function(e,t,n){return W(e)&&W(t)&&W(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}const K=e=>(N<<BigInt(e))-N;function G(e,t={},n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");const r=(t,n)=>Object.entries(t).forEach((([t,r])=>function(t,n,r){const o=e[t];if(r&&void 0===o)return;const i=typeof o;if(i!==n||null===o)throw new Error(`param "${t}" is invalid: expected ${n}, got ${i}`)}(t,r,n)));r(t,!1),r(n,!0)}function Z(e){const t=new WeakMap;return(n,...r)=>{const o=t.get(n);if(void 0!==o)return o;const i=e(n,...r);return t.set(n,i),i}}const J=BigInt(0),X=BigInt(1),Y=BigInt(2),Q=BigInt(3),ee=BigInt(4),te=BigInt(5),ne=BigInt(7),re=BigInt(8),oe=BigInt(9),ie=BigInt(16);function se(e,t){const n=e%t;return n>=J?n:t+n}function ae(e,t,n){let r=e;for(;t-- >J;)r*=r,r%=n;return r}function ce(e,t){if(e===J)throw new Error("invert: expected non-zero number");if(t<=J)throw new Error("invert: expected positive modulus, got "+t);let n=se(e,t),r=t,o=J,i=X,s=X,a=J;for(;n!==J;){const e=r/n,t=r%n,c=o-s*e,l=i-a*e;r=n,n=t,o=s,i=a,s=c,a=l}if(r!==X)throw new Error("invert: does not exist");return se(o,t)}function le(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function ue(e,t){const n=(e.ORDER+X)/ee,r=e.pow(t,n);return le(e,r,t),r}function de(e,t){const n=(e.ORDER-te)/re,r=e.mul(t,Y),o=e.pow(r,n),i=e.mul(t,o),s=e.mul(e.mul(i,Y),o),a=e.mul(i,e.sub(s,e.ONE));return le(e,a,t),a}function he(e){if(e<Q)throw new Error("sqrt is not defined for small field");let t=e-X,n=0;for(;t%Y===J;)t/=Y,n++;let r=Y;const o=be(e);for(;1===we(o,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return ue;let i=o.pow(r,t);const s=(t+X)/Y;return function(e,r){if(e.is0(r))return r;if(1!==we(e,r))throw new Error("Cannot find square root");let o=n,a=e.mul(e.ONE,i),c=e.pow(r,t),l=e.pow(r,s);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===o)throw new Error("Cannot find square root");const r=X<<BigInt(o-t-1),i=e.pow(a,r);o=t,a=e.sqr(i),c=e.mul(c,a),l=e.mul(l,i)}return l}}function fe(e){return e%ee===Q?ue:e%re===te?de:e%ie===oe?function(e){const t=be(e),n=he(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+ne)/ie;return(e,t)=>{let n=e.pow(t,s),a=e.mul(n,r);const c=e.mul(n,o),l=e.mul(n,i),u=e.eql(e.sqr(a),t),d=e.eql(e.sqr(c),t);n=e.cmov(n,a,u),a=e.cmov(l,c,d);const h=e.eql(e.sqr(a),t),f=e.cmov(n,a,h);return le(e,f,t),f}}(e):he(e)}const pe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ge(e,t,n){if(n<J)throw new Error("invalid exponent, negatives unsupported");if(n===J)return e.ONE;if(n===X)return t;let r=e.ONE,o=t;for(;n>J;)n&X&&(r=e.mul(r,o)),o=e.sqr(o),n>>=X;return r}function ye(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),o=t.reduce(((t,n,o)=>e.is0(n)?t:(r[o]=t,e.mul(t,n))),e.ONE),i=e.inv(o);return t.reduceRight(((t,n,o)=>e.is0(n)?t:(r[o]=e.mul(t,r[o]),e.mul(t,n))),i),r}function we(e,t){const n=(e.ORDER-X)/Y,r=e.pow(t,n),o=e.eql(r,e.ONE),i=e.eql(r,e.ZERO),s=e.eql(r,e.neg(e.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}class me{ORDER;BITS;BYTES;isLE;ZERO=J;ONE=X;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=J)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,null!=t&&"object"==typeof t&&("number"==typeof t.BITS&&(n=t.BITS),"function"==typeof t.sqrt&&(this.sqrt=t.sqrt),"boolean"==typeof t.isLE&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),"boolean"==typeof t.modFromBytes&&(this._mod=t.modFromBytes));const{nBitLength:r,nByteLength:i}=function(e,t){void 0!==t&&o(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}(e,n);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=r,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return se(e,this.ORDER)}isValid(e){if("bigint"!=typeof e)throw new Error("invalid field element: expected bigint, got "+typeof e);return J<=e&&e<this.ORDER}is0(e){return e===J}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&X)===X}neg(e){return se(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return se(e*e,this.ORDER)}add(e,t){return se(e+t,this.ORDER)}sub(e,t){return se(e-t,this.ORDER)}mul(e,t){return se(e*t,this.ORDER)}pow(e,t){return ge(this,e,t)}div(e,t){return se(e*ce(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return ce(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=fe(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?j(e,this.BYTES):q(e,this.BYTES)}fromBytes(e,t=!1){i(e);const{_lengths:n,BYTES:r,isLE:o,ORDER:s,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>r)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);const t=new Uint8Array(r);t.set(e,o?0:t.length-e.length),e=t}if(e.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=o?H(e):D(e);if(a&&(c=se(c,s)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return ye(this,e)}cmov(e,t,n){return n?t:e}}function be(e,t={}){return new me(e,t)}function ve(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Ee(e){const t=ve(e);return t+Math.ceil(t/2)}function xe(e,t,n=!1){i(e);const r=e.length,o=ve(t),s=Ee(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const a=se(n?H(e):D(e),t-X)+X;return n?j(a,o):q(a,o)}const Se=BigInt(0),ke=BigInt(1);function Ae(e,t){const n=t.negate();return e?n:t}function Re(e,t){const n=ye(e.Fp,t.map((e=>e.Z)));return t.map(((t,r)=>e.fromAffine(t.toAffine(n[r]))))}function Oe(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Ie(e,t){Oe(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:K(e),maxNumber:n,shiftBy:BigInt(e)}}function Be(e,t,n){const{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n;let a=Number(e&o),c=e>>s;a>r&&(a-=i,c+=ke);const l=t*r;return{nextN:c,offset:l+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:l}}const Te=new WeakMap,Pe=new WeakMap;function Le(e){return Pe.get(e)||1}function Ue(e){if(e!==Se)throw new Error("invalid wNAF")}class _e{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>Se;)t&ke&&(n=n.add(r)),r=r.double(),t>>=ke;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=Ie(t,this.bits),o=[];let i=e,s=i;for(let e=0;e<n;e++){s=i,o.push(s);for(let e=1;e<r;e++)s=s.add(i),o.push(s);i=s.double()}return o}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,o=this.BASE;const i=Ie(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:s,offset:a,isZero:c,isNeg:l,isNegF:u,offsetF:d}=Be(n,e,i);n=s,c?o=o.add(Ae(u,t[d])):r=r.add(Ae(l,t[a]))}return Ue(n),{p:r,f:o}}wNAFUnsafe(e,t,n,r=this.ZERO){const o=Ie(e,this.bits);for(let e=0;e<o.windows&&n!==Se;e++){const{nextN:i,offset:s,isZero:a,isNeg:c}=Be(n,e,o);if(n=i,!a){const e=t[s];r=r.add(c?e.negate():e)}}return Ue(n),r}getPrecomputes(e,t,n){let r=Te.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),Te.set(t,r))),r}cached(e,t,n){const r=Le(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const o=Le(e);return 1===o?this._unsafeLadder(e,t,r):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,r)}createCache(e,t){Oe(t,this.bits),Pe.set(e,t),Te.delete(e)}hasCache(e){return 1!==Le(e)}}function Ne(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){G(e,pe.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return be(e,{isLE:n})}function Ce(e,t){return function(n){const r=e(n);return{secretKey:r,publicKey:t(r)}}}V("HashToScalar-");class $e{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(s(e),i(t,void 0,"key"),this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),c(r)}update(e){return a(this),this.iHash.update(e),this}digestInto(e){a(this),i(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});const{oHash:t,iHash:n,finished:r,destroyed:o,blockLen:i,outputLen:s}=this;return e.finished=r,e.destroyed=o,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Me=(e,t,n)=>new $e(e,t).update(n).digest();Me.create=(e,t)=>new $e(e,t);const Fe=(e,t)=>(e+(e>=0?t:-t)/Ke)/t;function De(e,t,n){const[[r,o],[i,s]]=t,a=Fe(s*e,n),c=Fe(-o*e,n);let l=e-a*r-c*i,u=-a*o-c*s;const d=l<We,h=u<We;d&&(l=-l),h&&(u=-u);const f=K(Math.ceil(function(e){let t;for(t=0;e>_;e>>=N,t+=1);return t}(n)/2))+ze;if(l<We||l>=f||u<We||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:l,k2neg:h,k2:u}}function He(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function qe(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return C(n.lowS,"lowS"),C(n.prehash,"prehash"),void 0!==n.format&&He(n.format),n}class je extends Error{constructor(e=""){super(e)}}const Ve={Err:je,_tlv:{encode:(e,t)=>{const{Err:n}=Ve;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(1&t.length)throw new n("tlv.encode: unpadded data");const r=t.length/2,o=M(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?M(o.length/2|128):"";return M(e)+i+o+t},decode(e,t){const{Err:n}=Ve;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const o=t[r++];let i=0;if(!!(128&o)){const e=127&o;if(!e)throw new n("tlv.decode(long): indefinite length not supported");if(e>4)throw new n("tlv.decode(long): byte length is too big");const s=t.subarray(r,r+e);if(s.length!==e)throw new n("tlv.decode: length bytes not complete");if(0===s[0])throw new n("tlv.decode(long): zero leftmost byte");for(const e of s)i=i<<8|e;if(r+=e,i<128)throw new n("tlv.decode(long): not minimal encoding")}else i=o;const s=t.subarray(r,r+i);if(s.length!==i)throw new n("tlv.decode: wrong value length");return{v:s,l:t.subarray(r+i)}}},_int:{encode(e){const{Err:t}=Ve;if(e<We)throw new t("integer: negative integers are not allowed");let n=M(e);if(8&Number.parseInt(n[0],16)&&(n="00"+n),1&n.length)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=Ve;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return D(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=Ve,o=i(e,void 0,"signature"),{v:s,l:a}=r.decode(48,o);if(a.length)throw new t("invalid signature: left bytes after parsing");const{v:c,l}=r.decode(2,s),{v:u,l:d}=r.decode(2,l);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(c),s:n.decode(u)}},hexFromSig(e){const{_tlv:t,_int:n}=Ve,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},We=BigInt(0),ze=BigInt(1),Ke=BigInt(2),Ge=BigInt(3),Ze=BigInt(4);function Je(e,t={}){const n=function(e,t,n={},r){if(void 0===r&&(r="edwards"===e),!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const n=t[e];if(!("bigint"==typeof n&&n>Se))throw new Error(`CURVE.${e} must be positive bigint`)}const o=Ne(t.p,n.Fp,r),i=Ne(t.n,n.Fn,r),s=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of s)if(!o.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:o,Fn:i}}("weierstrass",e,t),{Fp:r,Fn:o}=n;let s=n.CURVE;const{h:a,n:c}=s;G(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:l}=t;if(l&&(!r.is0(s.a)||"bigint"!=typeof l.beta||!Array.isArray(l.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=Ye(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const h=t.toBytes||function(e,t,n){const{x:o,y:i}=t.toAffine(),s=r.toBytes(o);if(C(n,"isCompressed"),n){d();return x(Xe(!r.isOdd(i)),s)}return x(Uint8Array.of(4),s,r.toBytes(i))},p=t.fromBytes||function(e){i(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=u,o=e.length,s=e[0],a=e.subarray(1);if(o!==t||2!==s&&3!==s){if(o===n&&4===s){const e=r.BYTES,t=r.fromBytes(a.subarray(0,e)),n=r.fromBytes(a.subarray(e,2*e));if(!y(t,n))throw new Error("bad point: is not on curve");return{x:t,y:n}}throw new Error(`bad point: got length ${o}, expected compressed=${t} or uncompressed=${n}`)}{const e=r.fromBytes(a);if(!r.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=g(e);let n;try{n=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("bad point: is not on curve, sqrt error"+t)}d();return!(1&~s)!==r.isOdd(n)&&(n=r.neg(n)),{x:e,y:n}}};function g(e){const t=r.sqr(e),n=r.mul(t,e);return r.add(r.add(n,r.mul(e,s.a)),s.b)}function y(e,t){const n=r.sqr(t),o=g(e);return r.eql(n,o)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const w=r.mul(r.pow(s.a,Ge),Ze),m=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(w,m)))throw new Error("bad curve params: a or b");function b(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function v(e){if(!(e instanceof O))throw new Error("Weierstrass Point expected")}function S(e){if(!l||!l.basises)throw new Error("no endo");return De(e,l.basises,o.ORDER)}const k=Z(((e,t)=>{const{X:n,Y:o,Z:i}=e;if(r.eql(i,r.ONE))return{x:n,y:o};const s=e.is0();null==t&&(t=s?r.ONE:r.inv(i));const a=r.mul(n,t),c=r.mul(o,t),l=r.mul(i,t);if(s)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw new Error("invZ was invalid");return{x:a,y:c}})),A=Z((e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:n,y:o}=e.toAffine();if(!r.isValid(n)||!r.isValid(o))throw new Error("bad point: x or y not field elements");if(!y(n,o))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0}));function R(e,t,n,o,i){return n=new O(r.mul(n.X,e),n.Y,n.Z),t=Ae(o,t),n=Ae(i,n),t.add(n)}class O{static BASE=new O(s.Gx,s.Gy,r.ONE);static ZERO=new O(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=o;X;Y;Z;constructor(e,t,n){this.X=b("x",e),this.Y=b("y",t,!0),this.Z=b("z",n),Object.freeze(this)}static CURVE(){return s}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw new Error("invalid affine point");if(e instanceof O)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?O.ZERO:new O(t,n,r.ONE)}static fromBytes(e){const t=O.fromAffine(p(i(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return O.fromBytes(E(e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return B.createCache(this,e),t||this.multiply(Ge),this}assertValidity(){A(this)}hasEvenY(){const{y:e}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(e)}equals(e){v(e);const{X:t,Y:n,Z:o}=this,{X:i,Y:s,Z:a}=e,c=r.eql(r.mul(t,a),r.mul(i,o)),l=r.eql(r.mul(n,a),r.mul(s,o));return c&&l}negate(){return new O(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=s,n=r.mul(t,Ge),{X:o,Y:i,Z:a}=this;let c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(o,o),h=r.mul(i,i),f=r.mul(a,a),p=r.mul(o,i);return p=r.add(p,p),u=r.mul(o,a),u=r.add(u,u),c=r.mul(e,u),l=r.mul(n,f),l=r.add(c,l),c=r.sub(h,l),l=r.add(h,l),l=r.mul(c,l),c=r.mul(p,c),u=r.mul(n,u),f=r.mul(e,f),p=r.sub(d,f),p=r.mul(e,p),p=r.add(p,u),u=r.add(d,d),d=r.add(u,d),d=r.add(d,f),d=r.mul(d,p),l=r.add(l,d),f=r.mul(i,a),f=r.add(f,f),d=r.mul(f,p),c=r.sub(c,d),u=r.mul(f,h),u=r.add(u,u),u=r.add(u,u),new O(c,l,u)}add(e){v(e);const{X:t,Y:n,Z:o}=this,{X:i,Y:a,Z:c}=e;let l=r.ZERO,u=r.ZERO,d=r.ZERO;const h=s.a,f=r.mul(s.b,Ge);let p=r.mul(t,i),g=r.mul(n,a),y=r.mul(o,c),w=r.add(t,n),m=r.add(i,a);w=r.mul(w,m),m=r.add(p,g),w=r.sub(w,m),m=r.add(t,o);let b=r.add(i,c);return m=r.mul(m,b),b=r.add(p,y),m=r.sub(m,b),b=r.add(n,o),l=r.add(a,c),b=r.mul(b,l),l=r.add(g,y),b=r.sub(b,l),d=r.mul(h,m),l=r.mul(f,y),d=r.add(l,d),l=r.sub(g,d),d=r.add(g,d),u=r.mul(l,d),g=r.add(p,p),g=r.add(g,p),y=r.mul(h,y),m=r.mul(f,m),g=r.add(g,y),y=r.sub(p,y),y=r.mul(h,y),m=r.add(m,y),p=r.mul(g,m),u=r.add(u,p),p=r.mul(b,m),l=r.mul(w,l),l=r.sub(l,p),p=r.mul(w,g),d=r.mul(b,d),d=r.add(d,p),new O(l,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(O.ZERO)}multiply(e){const{endo:n}=t;if(!o.isValidNot0(e))throw new Error("invalid scalar: out of range");let r,i;const s=e=>B.cached(this,e,(e=>Re(O,e)));if(n){const{k1neg:t,k1:o,k2neg:a,k2:c}=S(e),{p:l,f:u}=s(o),{p:d,f:h}=s(c);i=u.add(h),r=R(n.beta,l,d,t,a)}else{const{p:t,f:n}=s(e);r=t,i=n}return Re(O,[r,i])[0]}multiplyUnsafe(e){const{endo:n}=t,r=this;if(!o.isValid(e))throw new Error("invalid scalar: out of range");if(e===We||r.is0())return O.ZERO;if(e===ze)return r;if(B.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:o,k2neg:i,k2:s}=S(e),{p1:a,p2:c}=function(e,t,n,r){let o=t,i=e.ZERO,s=e.ZERO;for(;n>Se||r>Se;)n&ke&&(i=i.add(o)),r&ke&&(s=s.add(o)),o=o.double(),n>>=ke,r>>=ke;return{p1:i,p2:s}}(O,r,o,s);return R(n.beta,a,c,t,i)}return B.unsafe(r,e)}toAffine(e){return k(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return a===ze||(e?e(O,this):B.unsafe(this,c).is0())}clearCofactor(){const{clearCofactor:e}=t;return a===ze?this:e?e(O,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(e=!0){return C(e,"isCompressed"),this.assertValidity(),h(O,this,e)}toHex(e=!0){return f(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const I=o.BITS,B=new _e(O,t.endo?Math.ceil(I/2):I);return O.BASE.precompute(8),O}function Xe(e){return Uint8Array.of(e?2:3)}function Ye(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Qe(e,t,n={}){s(t),G(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const a=(n=Object.assign({},n)).randomBytes||k,c=n.hmac||((e,n)=>Me(t,e,n)),{Fp:l,Fn:u}=e,{ORDER:d,BITS:h}=u,{keygen:p,getPublicKey:g,getSharedSecret:y,utils:w,lengths:m}=function(e,t={}){const{Fn:n}=e,o=t.randomBytes||k,s=Object.assign(Ye(e.Fp,n),{seed:Ee(n.ORDER)});function a(e=o(s.seed)){return xe(i(e,s.seed,"seed"),n.ORDER)}function c(t,r=!0){return e.BASE.multiply(n.fromBytes(t)).toBytes(r)}function l(e){const{secretKey:t,publicKey:o,publicKeyUncompressed:a}=s;if(!r(e))return;if("_lengths"in n&&n._lengths||t===o)return;const c=i(e,void 0,"key").length;return c===o||c===a}const u={isValidSecretKey:function(e){try{const t=n.fromBytes(e);return n.isValidNot0(t)}catch(e){return!1}},isValidPublicKey:function(t,n){const{publicKey:r,publicKeyUncompressed:o}=s;try{const i=t.length;return!(!0===n&&i!==r||!1===n&&i!==o||!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:a},d=Ce(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:function(t,r,o=!0){if(!0===l(t))throw new Error("first arg must be private key");if(!1===l(r))throw new Error("second arg must be public key");const i=n.fromBytes(t);return e.fromBytes(r).multiply(i).toBytes(o)},keygen:d,Point:e,utils:u,lengths:s})}(e,n),b={prehash:!0,lowS:"boolean"!=typeof n.lowS||n.lowS,format:"compact",extraEntropy:!1},v=d*Ke<l.ORDER;function S(e){return e>d>>ze}function A(e,t){if(!u.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}function R(){if(v)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function O(e,t){He(t);const n=m.signature;return i(e,"compact"===t?n:"recovered"===t?n+1:void 0)}class I{r;s;recovery;constructor(e,t,n){if(this.r=A("r",e),this.s=A("s",t),null!=n){if(R(),![0,1,2,3].includes(n))throw new Error("invalid recovery id");this.recovery=n}Object.freeze(this)}static fromBytes(e,t=b.format){let n;if(O(e,t),"der"===t){const{r:t,s:n}=Ve.toSig(i(e));return new I(t,n)}"recovered"===t&&(n=e[0],t="compact",e=e.subarray(1));const r=m.signature/2,o=e.subarray(0,r),s=e.subarray(r,2*r);return new I(u.fromBytes(o),u.fromBytes(s),n)}static fromHex(e,t){return this.fromBytes(E(e),t)}assertRecovery(){const{recovery:e}=this;if(null==e)throw new Error("invalid recovery id: must be present");return e}addRecoveryBit(e){return new I(this.r,this.s,e)}recoverPublicKey(t){const{r:n,s:r}=this,o=this.assertRecovery(),s=2===o||3===o?n+d:n;if(!l.isValid(s))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const a=l.toBytes(s),c=e.fromBytes(x(Xe(!(1&o)),a)),h=u.inv(s),f=T(i(t,void 0,"msgHash")),p=u.create(-f*h),g=u.create(r*h),y=e.BASE.multiplyUnsafe(p).add(c.multiplyUnsafe(g));if(y.is0())throw new Error("invalid recovery: point at infinify");return y.assertValidity(),y}hasHighS(){return S(this.s)}toBytes(e=b.format){if(He(e),"der"===e)return E(Ve.hexFromSig(this));const{r:t,s:n}=this,r=u.toBytes(t),o=u.toBytes(n);return"recovered"===e?(R(),x(Uint8Array.of(this.assertRecovery()),r,o)):x(r,o)}toHex(e){return f(this.toBytes(e))}}const B=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=D(e),n=8*e.length-h;return n>0?t>>BigInt(n):t},T=n.bits2int_modN||function(e){return u.create(B(e))},P=K(h);function L(e){return z("num < 2^"+h,e,We,P),u.toBytes(e)}function U(e,n){return i(e,void 0,"message"),n?i(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:p,getPublicKey:g,getSharedSecret:y,utils:w,lengths:m,Point:e,sign:function(n,r,s={}){const{seed:l,k2sig:d}=function(t,n,r){const{lowS:o,prehash:s,extraEntropy:c}=qe(r,b);t=U(t,s);const l=T(t),d=u.fromBytes(n);if(!u.isValidNot0(d))throw new Error("invalid private key");const h=[L(d),L(l)];if(null!=c&&!1!==c){const e=!0===c?a(m.secretKey):c;h.push(i(e,void 0,"extraEntropy"))}const f=x(...h),p=l;return{seed:f,k2sig:function(t){const n=B(t);if(!u.isValidNot0(n))return;const r=u.inv(n),i=e.BASE.multiply(n).toAffine(),s=u.create(i.x);if(s===We)return;const a=u.create(r*u.create(p+s*d));if(a===We)return;let c=(i.x===s?0:2)|Number(i.y&ze),l=a;return o&&S(a)&&(l=u.neg(a),c^=1),new I(s,l,v?void 0:c)}}}(n,r,s),h=function(e,t,n){if(o(e,"hashLen"),o(t,"qByteLen"),"function"!=typeof n)throw new Error("hmacFn must be a function");const r=e=>new Uint8Array(e),i=Uint8Array.of(),s=Uint8Array.of(0),a=Uint8Array.of(1);let c=r(e),l=r(e),u=0;const d=()=>{c.fill(1),l.fill(0),u=0},h=(...e)=>n(l,x(c,...e)),f=(e=i)=>{l=h(s,e),c=h(),0!==e.length&&(l=h(a,e),c=h())},p=()=>{if(u++>=1e3)throw new Error("drbg: tried max amount of iterations");let e=0;const n=[];for(;e<t;){c=h();const t=c.slice();n.push(t),e+=c.length}return x(...n)};return(e,t)=>{let n;for(d(),f(e);!(n=t(p()));)f();return d(),n}}(t.outputLen,u.BYTES,c);return h(l,d).toBytes(s.format)},verify:function(t,n,o,s={}){const{lowS:a,prehash:c,format:l}=qe(s,b);if(o=i(o,void 0,"publicKey"),n=U(n,c),!r(t)){throw new Error("verify expects Uint8Array signature"+(t instanceof I?", use sig.toBytes()":""))}O(t,l);try{const r=I.fromBytes(t,l),i=e.fromBytes(o);if(a&&r.hasHighS())return!1;const{r:s,s:c}=r,d=T(n),h=u.inv(c),f=u.create(d*h),p=u.create(s*h),g=e.BASE.multiplyUnsafe(f).add(i.multiplyUnsafe(p));if(g.is0())return!1;return u.create(g.x)===s}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:r}=qe(n,b);return t=U(t,r),I.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:I,hash:t})}const et={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},tt={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},nt=BigInt(0),rt=BigInt(2);const ot=be(et.p,{sqrt:function(e){const t=et.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=ae(u,n,t)*u%t,h=ae(d,n,t)*u%t,f=ae(h,rt,t)*l%t,p=ae(f,o,t)*f%t,g=ae(p,i,t)*p%t,y=ae(g,a,t)*g%t,w=ae(y,c,t)*y%t,m=ae(w,a,t)*g%t,b=ae(m,n,t)*u%t,v=ae(b,s,t)*p%t,E=ae(v,r,t)*l%t,x=ae(E,rt,t);if(!ot.eql(ot.sqr(x),e))throw new Error("Cannot find square root");return x}}),it=Je(et,{Fp:ot,endo:tt}),st=Qe(it,U),at={};function ct(e,...t){let n=at[e];if(void 0===n){const t=U(V(e));n=x(t,t),at[e]=n}return U(x(n,...t))}const lt=e=>e.toBytes(!0).slice(1),ut=e=>e%rt===nt;function dt(e){const{Fn:t,BASE:n}=it,r=t.fromBytes(e),o=n.multiply(r);return{scalar:ut(o.y)?r:t.neg(r),bytes:lt(o)}}function ht(e){const t=ot;if(!t.isValidNot0(e))throw new Error("invalid x: Fail if x ≥ p");const n=t.create(e*e),r=t.create(n*e+BigInt(7));let o=t.sqrt(r);ut(o)||(o=t.neg(o));const i=it.fromAffine({x:e,y:o});return i.assertValidity(),i}const ft=D;function pt(...e){return it.Fn.create(ft(ct("BIP0340/challenge",...e)))}function gt(e){return dt(e).bytes}function yt(e,t,n=k(32)){const{Fn:r}=it,o=i(e,void 0,"message"),{bytes:s,scalar:a}=dt(t),c=i(n,32,"auxRand"),l=r.toBytes(a^ft(ct("BIP0340/aux",c))),u=ct("BIP0340/nonce",l,s,o),{bytes:d,scalar:h}=dt(u),f=pt(d,s,o),p=new Uint8Array(64);if(p.set(d,0),p.set(r.toBytes(r.create(h+f*a)),32),!wt(p,o,s))throw new Error("sign: Invalid signature produced");return p}function wt(e,t,n){const{Fp:r,Fn:o,BASE:s}=it,a=i(e,64,"signature"),c=i(t,void 0,"message"),l=i(n,32,"publicKey");try{const e=ht(ft(l)),t=ft(a.subarray(0,32));if(!r.isValidNot0(t))return!1;const n=ft(a.subarray(32,64));if(!o.isValidNot0(n))return!1;const i=pt(o.toBytes(t),lt(e),c),u=s.multiplyUnsafe(n).add(e.multiplyUnsafe(o.neg(i))),{x:d,y:h}=u.toAffine();return!(u.is0()||!ut(h)||d!==t)}catch(e){return!1}}const mt=(()=>{const e=(e=k(48))=>xe(e,et.n);return{keygen:Ce(e,gt),getPublicKey:gt,sign:yt,verify:wt,Point:it,utils:{randomSecretKey:e,taggedHash:ct,lift_x:ht,pointToBytes:lt},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();function bt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function vt(e){if(!bt(e))throw new Error("Uint8Array expected")}function Et(e,t){return!!Array.isArray(t)&&(0===t.length||(e?t.every((e=>"string"==typeof e)):t.every((e=>Number.isSafeInteger(e)))))}function xt(e){if("function"!=typeof e)throw new Error("function expected");return!0}function St(e,t){if("string"!=typeof t)throw new Error(`${e}: string expected`);return!0}function kt(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function At(e){if(!Array.isArray(e))throw new Error("array expected")}function Rt(e,t){if(!Et(!0,t))throw new Error(`${e}: array of strings expected`)}function Ot(e,t){if(!Et(!1,t))throw new Error(`${e}: array of numbers expected`)}function It(...e){const t=e=>e,n=(e,t)=>n=>e(t(n));return{encode:e.map((e=>e.encode)).reduceRight(n,t),decode:e.map((e=>e.decode)).reduce(n,t)}}function Bt(e){const t="string"==typeof e?e.split(""):e,n=t.length;Rt("alphabet",t);const r=new Map(t.map(((e,t)=>[e,t])));return{encode:r=>(At(r),r.map((r=>{if(!Number.isSafeInteger(r)||r<0||r>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${r}". Allowed: ${e}`);return t[r]}))),decode:t=>(At(t),t.map((t=>{St("alphabet.decode",t);const n=r.get(t);if(void 0===n)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return n})))}}function Tt(e=""){return St("join",e),{encode:t=>(Rt("join.decode",t),t.join(e)),decode:t=>(St("join.decode",t),t.split(e))}}function Pt(e,t="="){return kt(e),St("padding",t),{encode(n){for(Rt("padding.encode",n);n.length*e%8;)n.push(t);return n},decode(n){Rt("padding.decode",n);let r=n.length;if(r*e%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===t;r--){if((r-1)*e%8==0)throw new Error("padding: invalid, string has too much padding")}return n.slice(0,r)}}}function Lt(e){return xt(e),{encode:e=>e,decode:t=>e(t)}}function Ut(e,t,n){if(t<2)throw new Error(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: invalid to=${n}, base cannot be less than 2`);if(At(e),!e.length)return[];let r=0;const o=[],i=Array.from(e,(e=>{if(kt(e),e<0||e>=t)throw new Error(`invalid integer: ${e}`);return e})),s=i.length;for(;;){let e=0,a=!0;for(let o=r;o<s;o++){const s=i[o],c=t*e,l=c+s;if(!Number.isSafeInteger(l)||c/t!==e||l-s!==c)throw new Error("convertRadix: carry overflow");const u=l/n;e=l%n;const d=Math.floor(u);if(i[o]=d,!Number.isSafeInteger(d)||d*n+e!==l)throw new Error("convertRadix: carry overflow");a&&(d?a=!1:r=o)}if(o.push(e),a)break}for(let t=0;t<e.length-1&&0===e[t];t++)o.push(0);return o.reverse()}const _t=(e,t)=>0===t?e:_t(t,e%t),Nt=(e,t)=>e+(t-_t(e,t)),Ct=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function $t(e,t,n,r){if(At(e),t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(Nt(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${Nt(t,n)}`);let o=0,i=0;const s=Ct[t],a=Ct[n]-1,c=[];for(const r of e){if(kt(r),r>=s)throw new Error(`convertRadix2: invalid data word=${r} from=${t}`);if(o=o<<t|r,i+t>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${t}`);for(i+=t;i>=n;i-=n)c.push((o>>i-n&a)>>>0);const e=Ct[i];if(void 0===e)throw new Error("invalid carry");o&=e-1}if(o=o<<n-i&a,!r&&i>=t)throw new Error("Excess padding");if(!r&&o>0)throw new Error(`Non-zero padding: ${o}`);return r&&i>0&&c.push(o>>>0),c}function Mt(e){kt(e);return{encode:t=>{if(!bt(t))throw new Error("radix.encode input should be Uint8Array");return Ut(Array.from(t),256,e)},decode:t=>(Ot("radix.decode",t),Uint8Array.from(Ut(t,e,256)))}}function Ft(e,t=!1){if(kt(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(Nt(8,e)>32||Nt(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!bt(n))throw new Error("radix2.encode input should be Uint8Array");return $t(Array.from(n),8,e,!t)},decode:n=>(Ot("radix2.decode",n),Uint8Array.from($t(n,e,8,t)))}}function Dt(e){return xt(e),function(...t){try{return e.apply(null,t)}catch(e){}}}const Ht=It(Ft(4),Bt("0123456789ABCDEF"),Tt("")),qt=It(Ft(5),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Pt(5),Tt("")),jt=(It(Ft(5),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Tt("")),It(Ft(5),Bt("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Pt(5),Tt("")),It(Ft(5),Bt("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Tt("")),It(Ft(5),Bt("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),Tt(""),Lt((e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")))),(()=>"function"==typeof Uint8Array.from([]).toBase64&&"function"==typeof Uint8Array.fromBase64)()),Vt=(e,t)=>{St("base64",e);const n=t?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,r=t?"base64url":"base64";if(e.length>0&&!n.test(e))throw new Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:r,lastChunkHandling:"strict"})},Wt=jt?{encode:e=>(vt(e),e.toBase64()),decode:e=>Vt(e,!1)}:It(Ft(6),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Pt(6),Tt("")),zt=(It(Ft(6),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Tt("")),jt?{encode:e=>(vt(e),e.toBase64({alphabet:"base64url"})),decode:e=>Vt(e,!0)}:It(Ft(6),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Pt(6),Tt(""))),Kt=(It(Ft(6),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Tt("")),e=>It(Mt(58),Bt(e),Tt(""))),Gt=Kt("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),Zt=(Kt("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),Kt("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"),[0,2,3,5,6,7,9,10,11]),Jt={encode(e){let t="";for(let n=0;n<e.length;n+=8){const r=e.subarray(n,n+8);t+=Gt.encode(r).padStart(Zt[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),o=Zt.indexOf(r.length),i=Gt.decode(r);for(let e=0;e<i.length-o;e++)if(0!==i[e])throw new Error("base58xmr: wrong padding");t=t.concat(Array.from(i.slice(i.length-o)))}return Uint8Array.from(t)}},Xt=It(Bt("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Tt("")),Yt=[996825010,642813549,513874426,1027748829,705979059];function Qt(e){const t=e>>25;let n=(33554431&e)<<5;for(let e=0;e<Yt.length;e++)1==(t>>e&1)&&(n^=Yt[e]);return n}function en(e,t,n=1){const r=e.length;let o=1;for(let t=0;t<r;t++){const n=e.charCodeAt(t);if(n<33||n>126)throw new Error(`Invalid prefix (${e})`);o=Qt(o)^n>>5}o=Qt(o);for(let t=0;t<r;t++)o=Qt(o)^31&e.charCodeAt(t);for(let e of t)o=Qt(o)^e;for(let e=0;e<6;e++)o=Qt(o);return o^=n,Xt.encode($t([o%Ct[30]],30,5,!1))}function tn(e){const t="bech32"===e?1:734539939,n=Ft(5),r=n.decode,o=n.encode,i=Dt(r);function s(e,n,r=90){St("bech32.encode prefix",e),bt(n)&&(n=Array.from(n)),Ot("bech32.encode",n);const o=e.length;if(0===o)throw new TypeError(`Invalid prefix length ${o}`);const i=o+7+n.length;if(!1!==r&&i>r)throw new TypeError(`Length ${i} exceeds limit ${r}`);const s=e.toLowerCase(),a=en(s,n,t);return`${s}1${Xt.encode(n)}${a}`}function a(e,n=90){St("bech32.decode input",e);const r=e.length;if(r<8||!1!==n&&r>n)throw new TypeError(`invalid string length: ${r} (${e}). Expected (8..${n})`);const o=e.toLowerCase();if(e!==o&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const i=o.lastIndexOf("1");if(0===i||-1===i)throw new Error('Letter "1" must be present between prefix and data only');const s=o.slice(0,i),a=o.slice(i+1);if(a.length<6)throw new Error("Data must be at least 6 characters long");const c=Xt.decode(a).slice(0,-6),l=en(s,c,t);if(!a.endsWith(l))throw new Error(`Invalid checksum in ${e}: expected "${l}"`);return{prefix:s,words:c}}return{encode:s,decode:a,encodeFromBytes:function(e,t){return s(e,o(t))},decodeToBytes:function(e){const{prefix:t,words:n}=a(e,!1);return{prefix:t,words:n,bytes:r(n)}},decodeUnsafe:Dt(a),fromWords:r,fromWordsUnsafe:i,toWords:o}}const nn=tn("bech32"),rn=(tn("bech32m"),{encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)});(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)()||It(Ft(4),Bt("0123456789abcdef"),Tt(""),Lt((e=>{if("string"!=typeof e||e.length%2!=0)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()})));function on(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function sn(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function an(e,t,n=""){const r=(o=e)instanceof Uint8Array||ArrayBuffer.isView(o)&&"Uint8Array"===o.constructor.name;var o;const i=e?.length,s=void 0!==t;if(!r||s&&i!==t){throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(r?`length=${i}`:"type="+typeof e))}return e}function cn(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 ln(e,t){an(e,void 0,"output");const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function un(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function dn(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function hn(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}const fn=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function pn(e,t){return e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function gn(e,t){if(pn(e,t)&&e.byteOffset<t.byteOffset)throw new Error("complex overlap of input and output is not supported")}function yn(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 0===n}const wn=(e,t)=>{function n(n,...r){if(an(n,void 0,"key"),!fn)throw new Error("Non little-endian hardware is not yet supported");if(void 0!==e.nonceLength){an(r[0],e.varSizeNonce?void 0:e.nonceLength,"nonce")}const o=e.tagLength;o&&void 0!==r[1]&&an(r[1],void 0,"AAD");const i=t(n,...r),s=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");an(t,void 0,"output")}};let a=!1;return{encrypt(e,t){if(a)throw new Error("cannot encrypt() twice with same key + nonce");return a=!0,an(e),s(i.encrypt.length,t),i.encrypt(e,t)},decrypt(e,t){if(an(e),o&&e.length<o)throw new Error('"ciphertext" expected length bigger than tagLength='+o);return s(i.decrypt.length,t),i.decrypt(e,t)}}}return Object.assign(n,e),n};function mn(e,t,n=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw new Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(n&&!vn(t))throw new Error("invalid output, must be aligned");return t}function bn(e,t,n){on(n);const r=new Uint8Array(16),o=hn(r);return o.setBigUint64(0,BigInt(t),n),o.setBigUint64(8,BigInt(e),n),r}function vn(e){return e.byteOffset%4==0}function En(e){return Uint8Array.from(e)}const xn=16,Sn=new Uint8Array(16),kn=un(Sn),An=e=>(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255;class Rn{blockLen=xn;outputLen=xn;s0=0;s1=0;s2=0;s3=0;finished=!1;t;W;windowSize;constructor(e,t){an(e,16,"key");const n=hn(e=En(e));let r=n.getUint32(0,!1),o=n.getUint32(4,!1),i=n.getUint32(8,!1),s=n.getUint32(12,!1);const a=[];for(let e=0;e<128;e++)a.push({s0:An(r),s1:An(o),s2:An(i),s3:An(s)}),({s0:r,s1:o,s2:i,s3:s}={s3:(u=i)<<31|(d=s)>>>1,s2:(l=o)<<31|u>>>1,s1:(c=r)<<31|l>>>1,s0:c>>>1^225<<24&-(1&d)});var c,l,u,d;const h=(e=>e>65536?8:e>1024?4:2)(t||1024);if(![1,2,4,8].includes(h))throw new Error("ghash: invalid window size, expected 2, 4 or 8");this.W=h;const f=128/h,p=this.windowSize=2**h,g=[];for(let e=0;e<f;e++)for(let t=0;t<p;t++){let n=0,r=0,o=0,i=0;for(let s=0;s<h;s++){if(!(t>>>h-s-1&1))continue;const{s0:c,s1:l,s2:u,s3:d}=a[h*e+s];n^=c,r^=l,o^=u,i^=d}g.push({s0:n,s1:r,s2:o,s3:i})}this.t=g}_updateBlock(e,t,n,r){e^=this.s0,t^=this.s1,n^=this.s2,r^=this.s3;const{W:o,t:i,windowSize:s}=this;let a=0,c=0,l=0,u=0;const d=(1<<o)-1;let h=0;for(const f of[e,t,n,r])for(let e=0;e<4;e++){const t=f>>>8*e&255;for(let e=8/o-1;e>=0;e--){const n=t>>>o*e&d,{s0:r,s1:f,s2:p,s3:g}=i[h*s+n];a^=r,c^=f,l^=p,u^=g,h+=1}}this.s0=a,this.s1=c,this.s2=l,this.s3=u}update(e){cn(this),an(e);const t=un(e=En(e)),n=Math.floor(e.length/xn),r=e.length%xn;for(let e=0;e<n;e++)this._updateBlock(t[4*e+0],t[4*e+1],t[4*e+2],t[4*e+3]);return r&&(Sn.set(e.subarray(n*xn)),this._updateBlock(kn[0],kn[1],kn[2],kn[3]),dn(kn)),this}destroy(){const{t:e}=this;for(const t of e)t.s0=0,t.s1=0,t.s2=0,t.s3=0}digestInto(e){cn(this),ln(e,this),this.finished=!0;const{s0:t,s1:n,s2:r,s3:o}=this,i=un(e);return i[0]=t,i[1]=n,i[2]=r,i[3]=o,e}digest(){const e=new Uint8Array(xn);return this.digestInto(e),this.destroy(),e}}class On extends Rn{constructor(e,t){an(e);const n=function(e){e.reverse();const t=1&e[15];let n=0;for(let t=0;t<e.length;t++){const r=e[t];e[t]=r>>>1|n,n=(1&r)<<7}return e[0]^=225&-t,e}(En(e));super(n,t),dn(n)}update(e){cn(this),an(e);const t=un(e=En(e)),n=e.length%xn,r=Math.floor(e.length/xn);for(let e=0;e<r;e++)this._updateBlock(An(t[4*e+3]),An(t[4*e+2]),An(t[4*e+1]),An(t[4*e+0]));return n&&(Sn.set(e.subarray(r*xn)),this._updateBlock(An(kn[3]),An(kn[2]),An(kn[1]),An(kn[0])),dn(kn)),this}digestInto(e){cn(this),ln(e,this),this.finished=!0;const{s0:t,s1:n,s2:r,s3:o}=this,i=un(e);return i[0]=t,i[1]=n,i[2]=r,i[3]=o,e.reverse()}}function In(e){const t=(t,n)=>e(n,t.length).update(t).digest(),n=e(new Uint8Array(16),0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=(t,n)=>e(t,n),t}In(((e,t)=>new Rn(e,t))),In(((e,t)=>new On(e,t)));const Bn=16;function Tn(e){if(![16,24,32].includes(e.length))throw new Error('"aes key" expected Uint8Array of length 16/24/32, got length='+e.length)}function Pn(e){return e<<1^283&-(e>>7)}function Ln(e,t){let n=0;for(;t>0;t>>=1)n^=e&-(1&t),e=Pn(e);return n}const Un=(()=>{const e=new Uint8Array(256);for(let t=0,n=1;t<256;t++,n^=Pn(n))e[t]=n;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]]=255&(r^r>>4^r>>5^r>>6^r>>7^99)}return dn(e),t})(),_n=Un.map(((e,t)=>Un.indexOf(t))),Nn=e=>e<<8|e>>>24;function Cn(e,t){if(256!==e.length)throw new Error("Wrong sbox length");const n=new Uint32Array(256).map(((n,r)=>t(e[r]))),r=n.map(Nn),o=r.map(Nn),i=o.map(Nn),s=new Uint32Array(65536),a=new Uint32Array(65536),c=new Uint16Array(65536);for(let t=0;t<256;t++)for(let l=0;l<256;l++){const u=256*t+l;s[u]=n[t]^r[l],a[u]=o[t]^i[l],c[u]=e[t]<<8|e[l]}return{sbox:e,sbox2:c,T0:n,T1:r,T2:o,T3:i,T01:s,T23:a}}const $n=Cn(Un,(e=>Ln(e,3)<<24|e<<16|e<<8|Ln(e,2))),Mn=Cn(_n,(e=>Ln(e,11)<<24|Ln(e,13)<<16|Ln(e,9)<<8|Ln(e,14))),Fn=(()=>{const e=new Uint8Array(16);for(let t=0,n=1;t<16;t++,n=Pn(n))e[t]=n;return e})();function Dn(e){an(e);const t=e.length;Tn(e);const{sbox2:n}=$n,r=[];vn(e)||r.push(e=En(e));const o=un(e),i=o.length,s=e=>jn(n,e,e,e,e),a=new Uint32Array(t+28);a.set(o);for(let e=i;e<a.length;e++){let t=a[e-1];e%i==0?t=s((c=t)<<24|c>>>8)^Fn[e/i-1]:i>6&&e%i==4&&(t=s(t)),a[e]=a[e-i]^t}var c;return dn(...r),a}function Hn(e){const t=Dn(e),n=t.slice(),r=t.length,{sbox2:o}=$n,{T0:i,T1:s,T2:a,T3:c}=Mn;for(let e=0;e<r;e+=4)for(let o=0;o<4;o++)n[e+o]=t[r-e-4+o];dn(t);for(let e=4;e<r-4;e++){const t=n[e],r=jn(o,t,t,t,t);n[e]=i[255&r]^s[r>>>8&255]^a[r>>>16&255]^c[r>>>24]}return n}function qn(e,t,n,r,o,i){return e[n<<8&65280|r>>>8&255]^t[o>>>8&65280|i>>>24&255]}function jn(e,t,n,r,o){return e[255&t|65280&n]|e[r>>>16&255|o>>>16&65280]<<16}function Vn(e,t,n,r,o){const{sbox2:i,T01:s,T23:a}=$n;let c=0;t^=e[c++],n^=e[c++],r^=e[c++],o^=e[c++];const l=e.length/4-2;for(let i=0;i<l;i++){const i=e[c++]^qn(s,a,t,n,r,o),l=e[c++]^qn(s,a,n,r,o,t),u=e[c++]^qn(s,a,r,o,t,n),d=e[c++]^qn(s,a,o,t,n,r);t=i,n=l,r=u,o=d}return{s0:e[c++]^jn(i,t,n,r,o),s1:e[c++]^jn(i,n,r,o,t),s2:e[c++]^jn(i,r,o,t,n),s3:e[c++]^jn(i,o,t,n,r)}}function Wn(e,t,n,r,o){const{sbox2:i,T01:s,T23:a}=Mn;let c=0;t^=e[c++],n^=e[c++],r^=e[c++],o^=e[c++];const l=e.length/4-2;for(let i=0;i<l;i++){const i=e[c++]^qn(s,a,t,o,r,n),l=e[c++]^qn(s,a,n,t,o,r),u=e[c++]^qn(s,a,r,n,t,o),d=e[c++]^qn(s,a,o,r,n,t);t=i,n=l,r=u,o=d}return{s0:e[c++]^jn(i,t,o,r,n),s1:e[c++]^jn(i,n,t,o,r),s2:e[c++]^jn(i,r,n,t,o),s3:e[c++]^jn(i,o,r,n,t)}}function zn(e){if(an(e),e.length%Bn!=0)throw new Error("aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size 16")}function Kn(e,t,n){an(e);let r=e.length;const o=r%Bn;if(!t&&0!==o)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");vn(e)||(e=En(e));const i=un(e);if(t){let e=Bn-o;e||(e=Bn),r+=e}gn(e,n=mn(r,n));return{b:i,o:un(n),out:n}}function Gn(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");const o=e.subarray(0,-r);for(let t=0;t<r;t++)if(e[n-t-1]!==r)throw new Error("aes/pcks5: wrong padding");return o}function Zn(e){const t=new Uint8Array(16),n=un(t);t.set(e);const r=Bn-e.length;for(let e=Bn-r;e<Bn;e++)t[e]=r;return n}const Jn=wn({blockSize:16,nonceLength:16},(function(e,t,n={}){const r=!n.disablePadding;return{encrypt(n,o){const i=Dn(e),{b:s,o:a,out:c}=Kn(n,r,o);let l=t;const u=[i];vn(l)||u.push(l=En(l));const d=un(l);let h=d[0],f=d[1],p=d[2],g=d[3],y=0;for(;y+4<=s.length;)h^=s[y+0],f^=s[y+1],p^=s[y+2],g^=s[y+3],({s0:h,s1:f,s2:p,s3:g}=Vn(i,h,f,p,g)),a[y++]=h,a[y++]=f,a[y++]=p,a[y++]=g;if(r){const e=Zn(n.subarray(4*y));h^=e[0],f^=e[1],p^=e[2],g^=e[3],({s0:h,s1:f,s2:p,s3:g}=Vn(i,h,f,p,g)),a[y++]=h,a[y++]=f,a[y++]=p,a[y++]=g}return dn(...u),c},decrypt(n,o){zn(n);const i=Hn(e);let s=t;const a=[i];vn(s)||a.push(s=En(s));const c=un(s);o=mn(n.length,o),vn(n)||a.push(n=En(n)),gn(n,o);const l=un(n),u=un(o);let d=c[0],h=c[1],f=c[2],p=c[3];for(let e=0;e+4<=l.length;){const t=d,n=h,r=f,o=p;d=l[e+0],h=l[e+1],f=l[e+2],p=l[e+3];const{s0:s,s1:a,s2:c,s3:g}=Wn(i,d,h,f,p);u[e++]=s^t,u[e++]=a^n,u[e++]=c^r,u[e++]=g^o}return dn(...a),Gn(o,r)}}}));function Xn(e){return e instanceof Uint32Array||ArrayBuffer.isView(e)&&"Uint32Array"===e.constructor.name}function Yn(e,t){if(an(t,16,"block"),!Xn(e))throw new Error("_encryptBlock accepts result of expandKeyLE");const n=un(t);let{s0:r,s1:o,s2:i,s3:s}=Vn(e,n[0],n[1],n[2],n[3]);return n[0]=r,n[1]=o,n[2]=i,n[3]=s,t}function Qn(e){let t=0;for(let n=15;n>=0;n--){const r=(128&e[n])>>>7;e[n]=e[n]<<1|t,t=r}return t&&(e[15]^=135),e}function er(e,t){if(e.length!==t.length)throw new Error("xorBlock: blocks must have same length");for(let n=0;n<e.length;n++)e[n]=e[n]^t[n];return e}class tr{buffer;destroyed;k1;k2;xk;constructor(e){an(e),Tn(e),this.xk=Dn(e),this.buffer=new Uint8Array(0),this.destroyed=!1;const t=new Uint8Array(Bn);Yn(this.xk,t),this.k1=Qn(t),this.k2=Qn(new Uint8Array(this.k1))}update(e){const{destroyed:t,buffer:n}=this;if(t)throw new Error("CMAC instance was destroyed");an(e);const r=new Uint8Array(n.length+e.length);return r.set(n),r.set(e,n.length),this.buffer=r,this}digest(){if(this.destroyed)throw new Error("CMAC instance was destroyed");const{buffer:e}=this,t=e.length;let n,r=Math.ceil(t/Bn);0===r?(r=1,n=!1):n=t%Bn==0;const o=(r-1)*Bn,i=e.subarray(o);let s;if(n)s=er(new Uint8Array(i),this.k1);else{const e=new Uint8Array(Bn);e.set(i),e[i.length]=128,s=er(e,this.k2)}let a=new Uint8Array(Bn);for(let t=0;t<r-1;t++){er(a,e.subarray(t*Bn,(t+1)*Bn)),Yn(this.xk,a)}return er(a,s),Yn(this.xk,a),dn(s),a}destroy(){const{buffer:e,destroyed:t,xk:n,k1:r,k2:o}=this;t||(this.destroyed=!0,dn(e,n,r,o))}}const nr=(e,t)=>new tr(e).update(t).digest();nr.create=e=>new tr(e);const rr=e=>Uint8Array.from(e.split(""),(e=>e.charCodeAt(0))),or=rr("expand 16-byte k"),ir=rr("expand 32-byte k"),sr=un(or),ar=un(ir);function cr(e,t){return e<<t|e>>>32-t}function lr(e){return e.byteOffset%4==0}const ur=2**32-1,dr=Uint32Array.of();function hr(e,t){const{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:i,rounds:s}=function(e,t){if(null==t||"object"!=typeof t)throw new Error("options must be defined");return Object.assign(e,t)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if("function"!=typeof e)throw new Error("core must be a function");return sn(o),sn(s),on(i),on(n),(t,a,c,l,u=0)=>{an(t,void 0,"key"),an(a,void 0,"nonce"),an(c,void 0,"data");const d=c.length;if(void 0===l&&(l=new Uint8Array(d)),an(l,void 0,"output"),sn(u),u<0||u>=ur)throw new Error("arx: counter overflow");if(l.length<d)throw new Error(`arx: output (${l.length}) is shorter than data (${d})`);const h=[];let f,p,g=t.length;if(32===g)h.push(f=En(t)),p=ar;else{if(16!==g||!n)throw an(t,32,"arx key"),new Error("invalid key size");f=new Uint8Array(32),f.set(t),f.set(t,16),p=sr,h.push(f)}lr(a)||h.push(a=En(a));const y=un(f);if(r){if(24!==a.length)throw new Error("arx: extended nonce must be 24 bytes");r(p,y,un(a.subarray(0,16)),y),a=a.subarray(16)}const w=16-o;if(w!==a.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(12!==w){const e=new Uint8Array(12);e.set(a,i?0:12-a.length),a=e,h.push(a)}const m=un(a);return function(e,t,n,r,o,i,s,a){const c=o.length,l=new Uint8Array(64),u=un(l),d=lr(o)&&lr(i),h=d?un(o):dr,f=d?un(i):dr;for(let p=0;p<c;s++){if(e(t,n,r,u,s,a),s>=ur)throw new Error("arx: counter overflow");const g=Math.min(64,c-p);if(d&&64===g){const e=p/4;if(p%4!=0)throw new Error("arx: invalid block position");for(let t,n=0;n<16;n++)t=e+n,f[t]=h[t]^u[n];p+=64}else{for(let e,t=0;t<g;t++)e=p+t,i[e]=o[e]^l[t];p+=g}}}(e,p,y,m,c,l,u,s),dn(...h),l}}function fr(e,t){return 255&e[t++]|(255&e[t++])<<8}class pr{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;constructor(e){const t=fr(e=En(an(e,32,"key")),0),n=fr(e,2),r=fr(e,4),o=fr(e,6),i=fr(e,8),s=fr(e,10),a=fr(e,12),c=fr(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|n<<3),this.r[2]=7939&(n>>>10|r<<6),this.r[3]=8191&(r>>>7|o<<9),this.r[4]=255&(o>>>4|i<<12),this.r[5]=i>>>1&8190,this.r[6]=8191&(i>>>14|s<<2),this.r[7]=8065&(s>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=fr(e,16+2*t)}process(e,t,n=!1){const r=n?0:2048,{h:o,r:i}=this,s=i[0],a=i[1],c=i[2],l=i[3],u=i[4],d=i[5],h=i[6],f=i[7],p=i[8],g=i[9],y=fr(e,t+0),w=fr(e,t+2),m=fr(e,t+4),b=fr(e,t+6),v=fr(e,t+8),E=fr(e,t+10),x=fr(e,t+12),S=fr(e,t+14);let k=o[0]+(8191&y),A=o[1]+(8191&(y>>>13|w<<3)),R=o[2]+(8191&(w>>>10|m<<6)),O=o[3]+(8191&(m>>>7|b<<9)),I=o[4]+(8191&(b>>>4|v<<12)),B=o[5]+(v>>>1&8191),T=o[6]+(8191&(v>>>14|E<<2)),P=o[7]+(8191&(E>>>11|x<<5)),L=o[8]+(8191&(x>>>8|S<<8)),U=o[9]+(S>>>5|r),_=0,N=_+k*s+A*(5*g)+R*(5*p)+O*(5*f)+I*(5*h);_=N>>>13,N&=8191,N+=B*(5*d)+T*(5*u)+P*(5*l)+L*(5*c)+U*(5*a),_+=N>>>13,N&=8191;let C=_+k*a+A*s+R*(5*g)+O*(5*p)+I*(5*f);_=C>>>13,C&=8191,C+=B*(5*h)+T*(5*d)+P*(5*u)+L*(5*l)+U*(5*c),_+=C>>>13,C&=8191;let $=_+k*c+A*a+R*s+O*(5*g)+I*(5*p);_=$>>>13,$&=8191,$+=B*(5*f)+T*(5*h)+P*(5*d)+L*(5*u)+U*(5*l),_+=$>>>13,$&=8191;let M=_+k*l+A*c+R*a+O*s+I*(5*g);_=M>>>13,M&=8191,M+=B*(5*p)+T*(5*f)+P*(5*h)+L*(5*d)+U*(5*u),_+=M>>>13,M&=8191;let F=_+k*u+A*l+R*c+O*a+I*s;_=F>>>13,F&=8191,F+=B*(5*g)+T*(5*p)+P*(5*f)+L*(5*h)+U*(5*d),_+=F>>>13,F&=8191;let D=_+k*d+A*u+R*l+O*c+I*a;_=D>>>13,D&=8191,D+=B*s+T*(5*g)+P*(5*p)+L*(5*f)+U*(5*h),_+=D>>>13,D&=8191;let H=_+k*h+A*d+R*u+O*l+I*c;_=H>>>13,H&=8191,H+=B*a+T*s+P*(5*g)+L*(5*p)+U*(5*f),_+=H>>>13,H&=8191;let q=_+k*f+A*h+R*d+O*u+I*l;_=q>>>13,q&=8191,q+=B*c+T*a+P*s+L*(5*g)+U*(5*p),_+=q>>>13,q&=8191;let j=_+k*p+A*f+R*h+O*d+I*u;_=j>>>13,j&=8191,j+=B*l+T*c+P*a+L*s+U*(5*g),_+=j>>>13,j&=8191;let V=_+k*g+A*p+R*f+O*h+I*d;_=V>>>13,V&=8191,V+=B*u+T*l+P*c+L*a+U*s,_+=V>>>13,V&=8191,_=(_<<2)+_|0,_=_+N|0,N=8191&_,_>>>=13,C+=_,o[0]=N,o[1]=C,o[2]=$,o[3]=M,o[4]=F,o[5]=D,o[6]=H,o[7]=q,o[8]=j,o[9]=V}finalize(){const{h:e,pad:t}=this,n=new Uint16Array(10);let r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=5*r,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let o=(1^r)-1;for(let e=0;e<10;e++)n[e]&=o;o=~o;for(let t=0;t<10;t++)e[t]=e[t]&o|n[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let i=e[0]+t[0];e[0]=65535&i;for(let n=1;n<8;n++)i=(e[n]+t[n]|0)+(i>>>16)|0,e[n]=65535&i;dn(n)}update(e){cn(this),an(e),e=En(e);const{buffer:t,blockLen:n}=this,r=e.length;for(let o=0;o<r;){const i=Math.min(n-this.pos,r-o);if(i!==n)t.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===n&&(this.process(t,0,!1),this.pos=0);else for(;n<=r-o;o+=n)this.process(e,o)}return this}destroy(){dn(this.h,this.r,this.buffer,this.pad)}digestInto(e){cn(this),ln(e,this),this.finished=!0;const{buffer:t,h:n}=this;let{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let o=0;for(let t=0;t<8;t++)e[o++]=n[t]>>>0,e[o++]=n[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}}const gr=(()=>function(e){const t=(t,n)=>e(n).update(t).digest(),n=e(new Uint8Array(32));return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t}((e=>new pr(e))))();function yr(e,t,n,r,o,i=20){let s=e[0],a=e[1],c=e[2],l=e[3],u=t[0],d=t[1],h=t[2],f=t[3],p=t[4],g=t[5],y=t[6],w=t[7],m=o,b=n[0],v=n[1],E=n[2],x=s,S=a,k=c,A=l,R=u,O=d,I=h,B=f,T=p,P=g,L=y,U=w,_=m,N=b,C=v,$=E;for(let e=0;e<i;e+=2)x=x+R|0,_=cr(_^x,16),T=T+_|0,R=cr(R^T,12),x=x+R|0,_=cr(_^x,8),T=T+_|0,R=cr(R^T,7),S=S+O|0,N=cr(N^S,16),P=P+N|0,O=cr(O^P,12),S=S+O|0,N=cr(N^S,8),P=P+N|0,O=cr(O^P,7),k=k+I|0,C=cr(C^k,16),L=L+C|0,I=cr(I^L,12),k=k+I|0,C=cr(C^k,8),L=L+C|0,I=cr(I^L,7),A=A+B|0,$=cr($^A,16),U=U+$|0,B=cr(B^U,12),A=A+B|0,$=cr($^A,8),U=U+$|0,B=cr(B^U,7),x=x+O|0,$=cr($^x,16),L=L+$|0,O=cr(O^L,12),x=x+O|0,$=cr($^x,8),L=L+$|0,O=cr(O^L,7),S=S+I|0,_=cr(_^S,16),U=U+_|0,I=cr(I^U,12),S=S+I|0,_=cr(_^S,8),U=U+_|0,I=cr(I^U,7),k=k+B|0,N=cr(N^k,16),T=T+N|0,B=cr(B^T,12),k=k+B|0,N=cr(N^k,8),T=T+N|0,B=cr(B^T,7),A=A+R|0,C=cr(C^A,16),P=P+C|0,R=cr(R^P,12),A=A+R|0,C=cr(C^A,8),P=P+C|0,R=cr(R^P,7);let M=0;r[M++]=s+x|0,r[M++]=a+S|0,r[M++]=c+k|0,r[M++]=l+A|0,r[M++]=u+R|0,r[M++]=d+O|0,r[M++]=h+I|0,r[M++]=f+B|0,r[M++]=p+T|0,r[M++]=g+P|0,r[M++]=y+L|0,r[M++]=w+U|0,r[M++]=m+_|0,r[M++]=b+N|0,r[M++]=v+C|0,r[M++]=E+$|0}const wr=hr(yr,{counterRight:!1,counterLength:4,allowShortKeys:!1}),mr=hr(yr,{counterRight:!1,counterLength:8,extendNonceFn:function(e,t,n,r){let o=e[0],i=e[1],s=e[2],a=e[3],c=t[0],l=t[1],u=t[2],d=t[3],h=t[4],f=t[5],p=t[6],g=t[7],y=n[0],w=n[1],m=n[2],b=n[3];for(let e=0;e<20;e+=2)o=o+c|0,y=cr(y^o,16),h=h+y|0,c=cr(c^h,12),o=o+c|0,y=cr(y^o,8),h=h+y|0,c=cr(c^h,7),i=i+l|0,w=cr(w^i,16),f=f+w|0,l=cr(l^f,12),i=i+l|0,w=cr(w^i,8),f=f+w|0,l=cr(l^f,7),s=s+u|0,m=cr(m^s,16),p=p+m|0,u=cr(u^p,12),s=s+u|0,m=cr(m^s,8),p=p+m|0,u=cr(u^p,7),a=a+d|0,b=cr(b^a,16),g=g+b|0,d=cr(d^g,12),a=a+d|0,b=cr(b^a,8),g=g+b|0,d=cr(d^g,7),o=o+l|0,b=cr(b^o,16),p=p+b|0,l=cr(l^p,12),o=o+l|0,b=cr(b^o,8),p=p+b|0,l=cr(l^p,7),i=i+u|0,y=cr(y^i,16),g=g+y|0,u=cr(u^g,12),i=i+u|0,y=cr(y^i,8),g=g+y|0,u=cr(u^g,7),s=s+d|0,w=cr(w^s,16),h=h+w|0,d=cr(d^h,12),s=s+d|0,w=cr(w^s,8),h=h+w|0,d=cr(d^h,7),a=a+c|0,m=cr(m^a,16),f=f+m|0,c=cr(c^f,12),a=a+c|0,m=cr(m^a,8),f=f+m|0,c=cr(c^f,7);let v=0;r[v++]=o,r[v++]=i,r[v++]=s,r[v++]=a,r[v++]=y,r[v++]=w,r[v++]=m,r[v++]=b},allowShortKeys:!1}),br=new Uint8Array(16),vr=(e,t)=>{e.update(t);const n=t.length%16;n&&e.update(br.subarray(n))},Er=new Uint8Array(32);function xr(e,t,n,r,o){void 0!==o&&an(o,void 0,"AAD");const i=e(t,n,Er),s=bn(r.length,o?o.length:0,!0),a=gr.create(i);o&&vr(a,o),vr(a,r),a.update(s);const c=a.digest();return dn(i,s),c}const Sr=e=>(t,n,r)=>{const o=16;return{encrypt(i,s){const a=i.length;(s=mn(a+o,s,!1)).set(i);const c=s.subarray(0,-16);e(t,n,c,c,1);const l=xr(e,t,n,c,r);return s.set(l,a),dn(l),s},decrypt(i,s){s=mn(i.length-o,s,!1);const a=i.subarray(0,-16),c=i.subarray(-16),l=xr(e,t,n,a,r);if(!yn(c,l))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),e(t,n,s,s,1),dn(l),s}}};Sr(wr),Sr(mr);function kr(e,t,n){return s(e),void 0===n&&(n=new Uint8Array(e.outputLen)),Me(e,n,t)}const Ar=Uint8Array.of(0),Rr=Uint8Array.of();function Or(e,t,n,r=32){s(e),o(r,"length");const a=e.outputLen;if(r>255*a)throw new Error("Length must be <= 255*HashLen");const l=Math.ceil(r/a);void 0===n?n=Rr:i(n,void 0,"info");const u=new Uint8Array(l*a),d=Me.create(e,t),h=d._cloneInto(),f=new Uint8Array(d.outputLen);for(let e=0;e<l;e++)Ar[0]=e+1,h.update(0===e?Rr:f).update(n).update(Ar).digestInto(f),u.set(f,a*e),d._cloneInto(h);return d.destroy(),h.destroy(),c(f,Ar),u.slice(0,r)}var Ir=Object.defineProperty,Br=(e,t)=>{for(var n in t)Ir(e,n,{get:t[n],enumerable:!0})},Tr={};Br(Tr,{binarySearch:()=>Cr,bytesToHex:()=>f,hexToBytes:()=>E,insertEventIntoAscendingList:()=>Nr,insertEventIntoDescendingList:()=>_r,isHex32:()=>Mr,mergeReverseSortedLists:()=>$r,normalizeURL:()=>Ur,utf8Decoder:()=>Pr,utf8Encoder:()=>Lr});var Pr=new TextDecoder("utf-8"),Lr=new TextEncoder;function Ur(e){try{-1===e.indexOf("://")&&(e="wss://"+e);let t=new URL(e);return"http:"===t.protocol?t.protocol="ws:":"https:"===t.protocol&&(t.protocol="wss:"),t.pathname=t.pathname.replace(/\/+/g,"/"),t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),("80"===t.port&&"ws:"===t.protocol||"443"===t.port&&"wss:"===t.protocol)&&(t.port=""),t.searchParams.sort(),t.hash="",t.toString()}catch(t){throw new Error(`Invalid URL: ${e}`)}}function _r(e,t){const[n,r]=Cr(e,(e=>t.id===e.id?0:t.created_at===e.created_at?-1:e.created_at-t.created_at));return r||e.splice(n,0,t),e}function Nr(e,t){const[n,r]=Cr(e,(e=>t.id===e.id?0:t.created_at===e.created_at?-1:t.created_at-e.created_at));return r||e.splice(n,0,t),e}function Cr(e,t){let n=0,r=e.length-1;for(;n<=r;){const o=Math.floor((n+r)/2),i=t(e[o]);if(0===i)return[o,!0];i<0?r=o-1:n=o+1}return[n,!1]}function $r(e,t){const n=new Array(e.length+t.length);n.length=0;let r=0,o=0,i=[];for(;r<e.length&&o<t.length;){let s;if(e[r]?.created_at>t[o]?.created_at?(s=e[r],r++):(s=t[o],o++),n.length>0&&n[n.length-1].created_at===s.created_at){if(i.includes(s.id))continue}else i.length=0;n.push(s),i.push(s.id)}for(;r<e.length;){const t=e[r];if(r++,n.length>0&&n[n.length-1].created_at===t.created_at){if(i.includes(t.id))continue}else i.length=0;n.push(t),i.push(t.id)}for(;o<t.length;){const e=t[o];if(o++,n.length>0&&n[n.length-1].created_at===e.created_at){if(i.includes(e.id))continue}else i.length=0;n.push(e),i.push(e.id)}return n}function Mr(e){for(let t=0;t<64;t++){let n=e.charCodeAt(t);if(isNaN(n)||n<48||n>102||n>57&&n<97)return!1}return!0}var Fr=Symbol("verified"),Dr=e=>e instanceof Object;function Hr(e){if(!Dr(e))return!1;if("number"!=typeof e.kind)return!1;if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if("string"!=typeof e.pubkey)return!1;if(!Mr(e.pubkey))return!1;if(!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 e=0;e<n.length;e++)if("string"!=typeof n[e])return!1}return!0}function qr(e){return e.sort(((e,t)=>e.created_at!==t.created_at?t.created_at-e.created_at:e.id.localeCompare(t.id)))}function jr(e){if(!Hr(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 Vr(e){return f(U(Lr.encode(jr(e))))}var Wr=new class{generateSecretKey(){return mt.utils.randomSecretKey()}getPublicKey(e){return f(mt.getPublicKey(e))}finalizeEvent(e,t){const n=e;return n.pubkey=f(mt.getPublicKey(t)),n.id=Vr(n),n.sig=f(mt.sign(E(Vr(n)),t)),n[Fr]=!0,n}verifyEvent(e){if("boolean"==typeof e[Fr])return e[Fr];try{const t=Vr(e);if(t!==e.id)return e[Fr]=!1,!1;const n=mt.verify(E(e.sig),E(t),E(e.pubkey));return e[Fr]=n,n}catch(t){return e[Fr]=!1,!1}}},zr=Wr.generateSecretKey,Kr=Wr.getPublicKey,Gr=Wr.finalizeEvent,Zr=Wr.verifyEvent,Jr={};function Xr(e){return e<1e4&&0!==e&&3!==e}function Yr(e){return 0===e||3===e||1e4<=e&&e<2e4}function Qr(e){return 2e4<=e&&e<3e4}function eo(e){return 3e4<=e&&e<4e4}function to(e){return Xr(e)?"regular":Yr(e)?"replaceable":Qr(e)?"ephemeral":eo(e)?"parameterized":"unknown"}function no(e,t){const n=t instanceof Array?t:[t];return Hr(e)&&n.includes(e.kind)||!1}Br(Jr,{AIEmbeddings:()=>ai,AppCurationSet:()=>Ws,Application:()=>js,AuthoredPodcasts:()=>as,BadgeAward:()=>ho,BadgeDefinition:()=>Ps,Bid:()=>No,BidConfirmation:()=>Co,BlobsAuth:()=>Es,BlockedRelaysList:()=>ji,BlossomServerList:()=>ns,BookmarkList:()=>Di,Bookmarksets:()=>Rs,Calendar:()=>ca,CalendarEventRSVP:()=>la,CashuMintAnnouncement:()=>va,CashuWalletEvent:()=>gs,CashuWalletHistory:()=>bi,CashuWalletTokens:()=>mi,ChannelCreation:()=>Ro,ChannelHideMessage:()=>Bo,ChannelMessage:()=>Io,ChannelMetadata:()=>Oo,ChannelMuteUser:()=>To,ChatMessage:()=>fo,Chess:()=>Lo,ClassifiedListing:()=>Xs,ClientAuth:()=>ws,CodeSnippet:()=>zo,CoinjoinPool:()=>ui,Comment:()=>Ho,CommunitiesList:()=>Hi,CommunityDefinition:()=>ya,CommunityPostApproval:()=>fi,ConferenceEvent:()=>Gs,Contacts:()=>so,CreateOrUpdateProduct:()=>_s,CreateOrUpdateStall:()=>Us,CuratedVideoSets:()=>Is,Curationsets:()=>Os,Date:()=>sa,DecoupledEncryptionKeyDistribution:()=>hi,DecoupledKeyAnnouncement:()=>Qi,DecoupledKeyClientAnnouncement:()=>di,DirectMessageRelaysList:()=>es,DraftClassifiedListing:()=>Ys,DraftEvent:()=>ra,DraftLong:()=>Ms,Emojisets:()=>Fs,EncryptedDirectMessage:()=>ao,EventDeletion:()=>co,FavoriteFollowSets:()=>Xi,FavoritePodcasts:()=>ts,FavoriteRelays:()=>zi,FedimintAnnouncement:()=>Ea,Feed:()=>ia,FileMessage:()=>bo,FileMetadata:()=>Fo,FileServerPreference:()=>rs,Followsets:()=>Ss,ForumThread:()=>go,GenericRepost:()=>vo,Genericlists:()=>ks,GeocacheListing:()=>ma,GeocacheLog:()=>vi,GeocacheLogEntry:()=>ba,GeocacheProofOfFind:()=>Ei,GiftWrap:()=>Mo,GitPullRequest:()=>Go,GitPullRequestUpdate:()=>Zo,GoodWikiAuthorList:()=>os,GoodWikiRelayList:()=>is,GroupMetadata:()=>Sa,HTTPAuth:()=>xs,Handlerinformation:()=>ha,Handlerrecommendation:()=>da,Highlights:()=>Ci,InteractiveRoom:()=>Ks,InterestsList:()=>Gi,Interestsets:()=>Ls,Issue:()=>Jo,JobFeedback:()=>yi,JobRequest:()=>pi,JobResult:()=>gi,Label:()=>ii,LegacyNsiteFile:()=>pa,LightningPubRPC:()=>ys,LinkSet:()=>oa,LiveChatMessage:()=>Wo,LiveEvent:()=>zs,LongFormArticle:()=>$s,MarketplaceUI:()=>Ns,MediaFollows:()=>Ji,MediaStarterPacks:()=>Ba,MergeRequests:()=>Uo,Metadata:()=>ro,ModularArticleContent:()=>Hs,ModularArticleHeader:()=>Ds,MuteSets:()=>Bs,Mutelist:()=>$i,NWCWalletInfo:()=>fs,NWCWalletRequest:()=>ms,NWCWalletResponse:()=>bs,NormalVideo:()=>So,NostrConnect:()=>vs,NsiteNamed:()=>wa,NsiteRoot:()=>ps,NutZap:()=>Li,NutZapInfo:()=>Zi,OpenTimestamps:()=>$o,Patch:()=>Ko,PeerToPeerOrderEvents:()=>xa,Photo:()=>xo,Pinlist:()=>Mi,PodcastEpisode:()=>Po,PodcastMetadata:()=>ss,Poll:()=>Do,PollResponse:()=>_o,PrivateDirectMessage:()=>mo,PrivateEventRelayList:()=>Ki,ProblemTracker:()=>ni,ProductSoldAsAuction:()=>Cs,ProfileBadges:()=>Ts,ProxyAnnouncement:()=>ds,PublicChatsList:()=>qi,PublicMessage:()=>Ao,Reaction:()=>uo,ReactionToWebsite:()=>Eo,RecommendRelay:()=>io,Redirects:()=>na,RelayDiscovery:()=>Vs,RelayList:()=>Fi,RelayMonitorAnnouncement:()=>cs,RelayReview:()=>ua,RelayReviews:()=>si,Relaysets:()=>As,ReleaseArtifactSets:()=>qs,Reply:()=>Xo,Report:()=>ri,Reporting:()=>oi,RepositoryAnnouncement:()=>Qs,RepositoryState:()=>ea,Repost:()=>lo,ReservedCashuWalletTokens:()=>wi,RoomPresence:()=>ls,Scroll:()=>jo,Seal:()=>wo,SearchRelaysList:()=>Vi,ShortTextNote:()=>oo,ShortVideo:()=>ko,SimpleGroupAdmins:()=>ka,SimpleGroupCreateGroup:()=>Ri,SimpleGroupCreateInvite:()=>Ii,SimpleGroupDeleteEvent:()=>Ai,SimpleGroupDeleteGroup:()=>Oi,SimpleGroupEditMetadata:()=>ki,SimpleGroupJoinRequest:()=>Bi,SimpleGroupLeaveRequest:()=>Ti,SimpleGroupList:()=>Wi,SimpleGroupLiveKitParticipants:()=>Oa,SimpleGroupMembers:()=>Aa,SimpleGroupPutUser:()=>xi,SimpleGroupRemoveUser:()=>Si,SimpleGroupReply:()=>yo,SimpleGroupRoles:()=>Ra,SimpleGroupThreadedReply:()=>po,SlideSet:()=>Js,SoftwareApplication:()=>fa,StarterPacks:()=>Ia,StatusApplied:()=>Qo,StatusClosed:()=>ei,StatusDraft:()=>ti,StatusOpen:()=>Yo,TidalLogin:()=>Ui,Time:()=>aa,Torrent:()=>ci,TorrentComment:()=>li,TransportMethodAnnouncement:()=>hs,UserEmojiList:()=>Yi,UserGraspList:()=>us,UserStatuses:()=>Zs,VideoViewEvent:()=>ga,Voice:()=>qo,VoiceComment:()=>Vo,WebBookmarks:()=>Ta,WikiArticle:()=>ta,Zap:()=>Ni,ZapGoal:()=>Pi,ZapRequest:()=>_i,classifyKind:()=>to,isAddressableKind:()=>eo,isEphemeralKind:()=>Qr,isKind:()=>no,isRegularKind:()=>Xr,isReplaceableKind:()=>Yr});var ro=0,oo=1,io=2,so=3,ao=4,co=5,lo=6,uo=7,ho=8,fo=9,po=10,go=11,yo=12,wo=13,mo=14,bo=15,vo=16,Eo=17,xo=20,So=21,ko=22,Ao=24,Ro=40,Oo=41,Io=42,Bo=43,To=44,Po=54,Lo=64,Uo=818,_o=1018,No=1021,Co=1022,$o=1040,Mo=1059,Fo=1063,Do=1068,Ho=1111,qo=1222,jo=1227,Vo=1244,Wo=1311,zo=1337,Ko=1617,Go=1618,Zo=1619,Jo=1621,Xo=1622,Yo=1630,Qo=1631,ei=1632,ti=1633,ni=1971,ri=1984,oi=1984,ii=1985,si=1986,ai=1987,ci=2003,li=2004,ui=2022,di=4454,hi=4455,fi=4550,pi=5999,gi=6999,yi=7e3,wi=7374,mi=7375,bi=7376,vi=7516,Ei=7517,xi=9e3,Si=9001,ki=9002,Ai=9005,Ri=9007,Oi=9008,Ii=9009,Bi=9021,Ti=9022,Pi=9041,Li=9321,Ui=9467,_i=9734,Ni=9735,Ci=9802,$i=1e4,Mi=10001,Fi=10002,Di=10003,Hi=10004,qi=10005,ji=10006,Vi=10007,Wi=10009,zi=10012,Ki=10013,Gi=10015,Zi=10019,Ji=10020,Xi=10021,Yi=10030,Qi=10044,es=10050,ts=10054,ns=10063,rs=10096,os=10101,is=10102,ss=10154,as=10164,cs=10166,ls=10312,us=10317,ds=10377,hs=11111,fs=13194,ps=15128,gs=17375,ys=21e3,ws=22242,ms=23194,bs=23195,vs=24133,Es=24242,xs=27235,Ss=3e4,ks=30001,As=30002,Rs=30003,Os=30004,Is=30005,Bs=30007,Ts=30008,Ps=30009,Ls=30015,Us=30017,_s=30018,Ns=30019,Cs=30020,$s=30023,Ms=30024,Fs=30030,Ds=30040,Hs=30041,qs=30063,js=30078,Vs=30166,Ws=30267,zs=30311,Ks=30312,Gs=30313,Zs=30315,Js=30388,Xs=30402,Ys=30403,Qs=30617,ea=30618,ta=30818,na=30819,ra=31234,oa=31388,ia=31890,sa=31922,aa=31923,ca=31924,la=31925,ua=31987,da=31989,ha=31990,fa=32267,pa=34128,ga=34237,ya=34550,wa=35128,ma=37515,ba=37516,va=38172,Ea=38173,xa=38383,Sa=39e3,ka=39001,Aa=39002,Ra=39003,Oa=39004,Ia=39089,Ba=39092,Ta=39701;function Pa(e,t){if(e.ids&&-1===e.ids.indexOf(t.id))return!1;if(e.kinds&&-1===e.kinds.indexOf(t.kind))return!1;if(e.authors&&-1===e.authors.indexOf(t.pubkey))return!1;for(let n in e)if("#"===n[0]){let r=e[`#${n.slice(1)}`];if(r&&!t.tags.find((([e,t])=>e===n.slice(1)&&-1!==r.indexOf(t))))return!1}return!(e.since&&t.created_at<e.since)&&!(e.until&&t.created_at>e.until)}function La(e,t){for(let n=0;n<e.length;n++)if(Pa(e[n],t))return!0;return!1}function Ua(...e){let t={};for(let n=0;n<e.length;n++){let r=e[n];Object.entries(r).forEach((([e,n])=>{if("kinds"===e||"ids"===e||"authors"===e||"#"===e[0]){t[e]=t[e]||[];for(let r=0;r<n.length;r++){let o=n[r];t[e].includes(o)||t[e].push(o)}}})),r.limit&&(!t.limit||r.limit>t.limit)&&(t.limit=r.limit),r.until&&(!t.until||r.until>t.until)&&(t.until=r.until),r.since&&(!t.since||r.since<t.since)&&(t.since=r.since)}return t}function _a(e){if(e.ids&&!e.ids.length)return 0;if(e.kinds&&!e.kinds.length)return 0;if(e.authors&&!e.authors.length)return 0;for(const[t,n]of Object.entries(e))if("#"===t[0]&&Array.isArray(n)&&!n.length)return 0;return Math.min(Math.max(0,e.limit??1/0),e.ids?.length??1/0,e.authors?.length&&e.kinds?.every((e=>Yr(e)))?e.authors.length*e.kinds.length:1/0,e.authors?.length&&e.kinds?.every((e=>eo(e)))&&e["#d"]?.length?e.authors.length*e.kinds.length*e["#d"].length:1/0)}var Na={};function Ca(e,t){let n=t.length+3,r=e.indexOf(`"${t}":`)+n,o=e.slice(r).indexOf('"')+r+1;return e.slice(o,o+64)}function $a(e,t){let n=t.length,r=e.indexOf(`"${t}":`)+n+3,o=e.slice(r),i=Math.min(o.indexOf(","),o.indexOf("}"));return parseInt(o.slice(0,i),10)}function Ma(e){let t=e.slice(0,22).indexOf('"EVENT"');if(-1===t)return null;let n=e.slice(t+7+1).indexOf('"');if(-1===n)return null;let r=t+7+1+n,o=e.slice(r+1,80).indexOf('"');if(-1===o)return null;let i=r+1+o;return e.slice(r+1,i)}function Fa(e,t){return t===Ca(e,"id")}function Da(e,t){return t===Ca(e,"pubkey")}function Ha(e,t){return t===$a(e,"kind")}Br(Na,{getHex64:()=>Ca,getInt:()=>$a,getSubscriptionId:()=>Ma,matchEventId:()=>Fa,matchEventKind:()=>Ha,matchEventPubkey:()=>Da});var qa={};function ja(e,t){return{kind:ws,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",t]],content:""}}Br(qa,{makeAuthEvent:()=>ja});var Va,Wa=class extends Error{constructor(e,t){super(`Tried to send message '${e} on a closed connection to ${t}.`),this.name="SendingOnClosedConnection"}},za=class{url;_connected=!1;onclose=null;onnotice=e=>console.debug(`NOTICE from ${this.url}: ${e}`);onauth;baseEoseTimeout=4400;publishTimeout=4400;pingFrequency=29e3;pingTimeout=2e4;resubscribeBackoff=[1e4,1e4,1e4,2e4,2e4,3e4,6e4];openSubs=new Map;enablePing;enableReconnect;idleTimeout=0;idleSince=Date.now();ongoingOperations=0;reconnectTimeoutHandle;pingIntervalHandle;reconnectAttempts=0;skipReconnection=!1;idleTimeoutHandle;connectionPromise;openCountRequests=new Map;openEventPublishes=new Map;ws;challenge;authPromise;serial=0;verifyEvent;_WebSocket;constructor(e,t){this.url=Ur(e),this.verifyEvent=t.verifyEvent,this._WebSocket=t.websocketImplementation||WebSocket,this.enablePing=t.enablePing,this.enableReconnect=t.enableReconnect||!1,t.idleTimeout&&(this.idleTimeout=t.idleTimeout)}static async connect(e,t){const n=new za(e,t);return await n.connect(t),n}closeAllSubscriptions(e){for(let[t,n]of this.openSubs)n.close(e);this.openSubs.clear();for(let[t,n]of this.openEventPublishes)n.reject(new Error(e));this.openEventPublishes.clear();for(let[t,n]of this.openCountRequests)n.reject(new Error(e));this.openCountRequests.clear()}get connected(){return this._connected}clearIdleTimeout(){this.idleTimeoutHandle&&(clearTimeout(this.idleTimeoutHandle),this.idleTimeoutHandle=void 0)}scheduleIdleClose(){this.clearIdleTimeout(),this.idleTimeout>0&&(this.idleTimeoutHandle=setTimeout((()=>{0===this.ongoingOperations&&this.idleSince&&this.close()}),this.idleTimeout))}async reconnect(){const e=this.resubscribeBackoff[Math.min(this.reconnectAttempts,this.resubscribeBackoff.length-1)];this.reconnectAttempts++,this.reconnectTimeoutHandle=setTimeout((async()=>{try{await this.connect()}catch(e){}}),e)}handleHardClose(e){this.ws&&(this.ws.onopen=null,this.ws.onerror=null,this.ws.onclose=null),this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this._connected=!1,this.connectionPromise=void 0,this.idleSince=void 0,this.clearIdleTimeout(),this.enableReconnect&&!this.skipReconnection?this.reconnect():(this.onclose?.(),this.closeAllSubscriptions(e))}async connect(e){let t;return this.connectionPromise||(this.challenge=void 0,this.authPromise=void 0,this.skipReconnection=!1,this.connectionPromise=new Promise(((n,r)=>{e?.timeout&&(t=setTimeout((()=>{r("connection timed out"),this.connectionPromise=void 0,0===this.reconnectAttempts&&(this.skipReconnection=!0),this.handleHardClose("relay connection timed out")}),e.timeout)),e?.abort&&(e.abort.onabort=r);try{this.ws=new this._WebSocket(this.url)}catch(e){return clearTimeout(t),void r(e)}this.ws.onopen=()=>{this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),clearTimeout(t),this._connected=!0;const e=this.reconnectAttempts>0;this.reconnectAttempts=0;for(const t of this.openSubs.values()){if(t.eosed=!1,e)for(let e=0;e<t.filters.length;e++)t.lastEmitted&&(t.filters[e].since=t.lastEmitted+1);t.fire()}this.enablePing&&(this.pingIntervalHandle=setInterval((()=>this.pingpong()),this.pingFrequency)),n()},this.ws.onerror=()=>{clearTimeout(t),r("connection failed"),this.connectionPromise=void 0,0===this.reconnectAttempts&&(this.skipReconnection=!0),this.handleHardClose("relay connection failed")},this.ws.onclose=e=>{clearTimeout(t),r(e.message||"websocket closed"),this.handleHardClose("relay connection closed")},this.ws.onmessage=this._onmessage.bind(this)}))),this.connectionPromise}waitForPingPong(){return new Promise((e=>{this.ws.once("pong",(()=>e(!0))),this.ws.ping()}))}waitForDummyReq(){return new Promise(((e,t)=>{if(!this.connectionPromise)return t(new Error(`no connection to ${this.url}, can't ping`));try{const t=this.subscribe([{ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0}],{label:"<forced-ping>",oneose:()=>{e(!0),t.close()},onclose(){e(!0)},eoseTimeout:this.pingTimeout+1e3})}catch(e){t(e)}}))}async pingpong(){if(1===this.ws?.readyState){await Promise.any([this.ws&&this.ws.ping&&this.ws.once?this.waitForPingPong():this.waitForDummyReq(),new Promise((e=>setTimeout((()=>e(!1)),this.pingTimeout)))])||this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close()}}async send(e){if(!this.connectionPromise)throw new Wa(e,this.url);this.connectionPromise.then((()=>{this.ws?.send(e)}))}async auth(e){const t=this.challenge;if(!t)throw new Error("can't perform auth, no challenge was received");return this.authPromise||(this.authPromise=new Promise((async(n,r)=>{try{let o=await e(ja(this.url,t)),i=setTimeout((()=>{let e=this.openEventPublishes.get(o.id);e&&(e.reject(new Error("auth timed out")),this.openEventPublishes.delete(o.id))}),this.publishTimeout);this.openEventPublishes.set(o.id,{resolve:n,reject:r,timeout:i}),this.send('["AUTH",'+JSON.stringify(o)+"]")}catch(e){console.warn("subscribe auth function failed:",e)}}))),this.authPromise}async publish(e){this.idleSince=void 0,this.clearIdleTimeout(),this.ongoingOperations++;const t=new Promise(((t,n)=>{const r=setTimeout((()=>{const t=this.openEventPublishes.get(e.id);t&&(t.reject(new Error("publish timed out")),this.openEventPublishes.delete(e.id))}),this.publishTimeout);this.openEventPublishes.set(e.id,{resolve:t,reject:n,timeout:r})}));try{await this.send('["EVENT",'+JSON.stringify(e)+"]")}catch(t){const n=this.openEventPublishes.get(e.id);n&&(n.reject(t),this.openEventPublishes.delete(e.id))}return this.ongoingOperations--,0===this.ongoingOperations&&(this.idleSince=Date.now(),this.scheduleIdleClose()),t}async count(e,t){return(await this.countWithHLL(e,t)).count}async countWithHLL(e,t){this.serial++;const n=t?.id||"count:"+this.serial,r=new Promise(((e,t)=>{this.openCountRequests.set(n,{resolve:e,reject:t})}));try{await this.send('["COUNT","'+n+'",'+JSON.stringify(e).substring(1))}catch(e){const t=this.openCountRequests.get(n);t&&(t.reject(e),this.openCountRequests.delete(n))}return r}subscribe(e,t){"<forced-ping>"!==t.label&&(this.idleSince=void 0,this.clearIdleTimeout(),this.ongoingOperations++);const n=this.prepareSubscription(e,t);return n.fire(),t.abort&&(t.abort.onabort=()=>n.close(String(t.abort.reason||"<aborted>"))),n}prepareSubscription(e,t){this.serial++;const n=t.id||(t.label?t.label+":":"sub:")+this.serial,r=new Ka(this,n,e,t);return this.openSubs.set(n,r),r}close(){this.skipReconnection=!0,this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,this.connectionPromise=void 0,this.idleSince=void 0,this.clearIdleTimeout(),this.onclose?.(),this.ws&&(this.ws.onopen=null,this.ws.onerror=null,this.ws.onclose=null,this.ws.readyState!==this._WebSocket.CLOSING&&this.ws.readyState!==this._WebSocket.CLOSED&&this.ws.close())}_onmessage(e){const t=e.data;if(!t)return;const n=Ma(t);if(n){const e=this.openSubs.get(n);if(!e)return;const r=Ca(t,"id"),o=e.alreadyHaveEvent?.(r);if(e.receivedEvent?.(this,r),o)return}try{let e=JSON.parse(t);switch(e[0]){case"EVENT":{const t=this.openSubs.get(e[1]),n=e[2];return La(t.filters,n)&&this.verifyEvent(n,this.url)?t.onevent(n):t.oninvalidevent?.(n),void((!t.lastEmitted||t.lastEmitted<n.created_at)&&(t.lastEmitted=n.created_at))}case"COUNT":{const t=e[1],n=e[2],r=this.openCountRequests.get(t);return void(r&&(r.resolve(n),this.openCountRequests.delete(t)))}case"EOSE":{const t=this.openSubs.get(e[1]);if(!t)return;return void t.receivedEose()}case"OK":{const t=e[1],n=e[2],r=e[3],o=this.openEventPublishes.get(t);return void(o&&(clearTimeout(o.timeout),n?o.resolve(r):o.reject(new Error(r)),this.openEventPublishes.delete(t)))}case"CLOSED":{const t=e[1],n=this.openSubs.get(t);if(!n){const n=this.openCountRequests.get(t);return void(n&&(n.reject(new Error(e[2])),this.openCountRequests.delete(t)))}return n.closed=!0,void n.close(e[2])}case"NOTICE":return void this.onnotice(e[1]);case"AUTH":return this.challenge=e[1],void(this.onauth&&this.auth(this.onauth).catch((e=>{if(!(e instanceof Wa))throw e})));default:{const t=this.openSubs.get(e[1]);return void t?.oncustom?.(e)}}}catch(e){try{const[n,r,o]=JSON.parse(t);console.warn(`[nostr] relay ${this.url} error processing message:`,e,o)}catch(t){console.warn(`[nostr] relay ${this.url} error processing message:`,e)}return}}},Ka=class{relay;id;lastEmitted;closed=!1;eosed=!1;filters;alreadyHaveEvent;receivedEvent;onevent;oninvalidevent;oneose;onclose;oncustom;eoseTimeout;eoseTimeoutHandle;constructor(e,t,n,r){if(0===n.length)throw new Error("subscription can't be created with zero filters");this.relay=e,this.filters=n,this.id=t,this.alreadyHaveEvent=r.alreadyHaveEvent,this.receivedEvent=r.receivedEvent,this.eoseTimeout=r.eoseTimeout||e.baseEoseTimeout,this.oneose=r.oneose,this.onclose=r.onclose,this.oninvalidevent=r.oninvalidevent,this.onevent=r.onevent||(e=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,e)})}fire(){this.relay.send('["REQ","'+this.id+'",'+JSON.stringify(this.filters).substring(1)),this.eoseTimeoutHandle=setTimeout(this.receivedEose.bind(this),this.eoseTimeout)}receivedEose(){this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,this.oneose?.())}close(e="closed by caller"){if(!this.closed&&this.relay.connected){try{this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]")}catch(e){if(!(e instanceof Wa))throw e}this.closed=!0}this.relay.openSubs.delete(this.id),this.relay.ongoingOperations--,0===this.relay.ongoingOperations&&(this.relay.idleSince=Date.now(),this.relay.scheduleIdleClose()),this.onclose?.(e)}};try{Va=WebSocket}catch{}var Ga=class extends za{constructor(e,t){super(e,{verifyEvent:Zr,websocketImplementation:Va,...t})}static async connect(e,t){const n=new Ga(e,t);return await n.connect(),n}},Za=256;new TextEncoder;function Ja(e){if(512!==e.length||!/^[0-9a-f]+$/.test(e))return;const t=new Uint8Array(Za);for(let n=0;n<Za;n++)t[n]=parseInt(e.slice(2*n,2*n+2),16);return t}function Xa(e){if(e.length!==Za)throw new Error(`invalid number of registers ${e.length}`);let t="";for(let n=0;n<Za;n++)t+=e[n].toString(16).padStart(2,"0");return t}function Ya(e,t){if(0===e.length&&(e=new Uint8Array(Za)),e.length!==Za)throw new Error(`invalid number of registers ${e.length}`);if(t.length!==Za)throw new Error(`invalid number of registers ${t.length}`);for(let n=0;n<Za;n++)t[n]>e[n]&&(e[n]=t[n]);return e}var Qa,ec=class{relays=new Map;seenOn=new Map;trackRelays=!1;verifyEvent;enablePing;enableReconnect;idleTimeout=2e4;automaticallyAuth;onRelayConnectionFailure;onRelayConnectionSuccess;allowConnectingToRelay;maxWaitForConnection;_WebSocket;constructor(e){this.verifyEvent=e.verifyEvent,this._WebSocket=e.websocketImplementation,this.enablePing=e.enablePing,this.enableReconnect=e.enableReconnect||!1,e.idleTimeout&&(this.idleTimeout=e.idleTimeout),this.automaticallyAuth=e.automaticallyAuth,this.onRelayConnectionFailure=e.onRelayConnectionFailure,this.onRelayConnectionSuccess=e.onRelayConnectionSuccess,this.allowConnectingToRelay=e.allowConnectingToRelay,this.maxWaitForConnection=e.maxWaitForConnection||3e3}async ensureRelay(e,t){e=Ur(e);let n=this.relays.get(e);if(n||(n=new za(e,{verifyEvent:this.verifyEvent,websocketImplementation:this._WebSocket,enablePing:this.enablePing,enableReconnect:this.enableReconnect,idleTimeout:this.idleTimeout}),n.onclose=()=>{this.relays.delete(e)},this.relays.set(e,n)),this.automaticallyAuth){const t=this.automaticallyAuth(e);t&&(n.onauth=t)}try{await n.connect({timeout:t?.connectionTimeout,abort:t?.abort})}catch(t){throw this.relays.delete(e),t}return n}close(e){e.map(Ur).forEach((e=>{this.relays.get(e)?.close(),this.relays.delete(e)}))}subscribe(e,t,n){const r=[],o=[];for(let n=0;n<e.length;n++){const i=Ur(e[n]);r.find((e=>e.url===i))||-1===o.indexOf(i)&&(o.push(i),r.push({url:i,filter:t}))}return this.subscribeMap(r,n)}subscribeMany(e,t,n){return this.subscribe(e,t,n)}subscribeMap(e,t){const n=new Map;for(const t of e){const{url:e,filter:r}=t;n.has(e)||n.set(e,[]),n.get(e).push(r)}const r=Array.from(n.entries()).map((([e,t])=>({url:e,filters:t})));this.trackRelays&&(t.receivedEvent=(e,t)=>{let n=this.seenOn.get(t);n||(n=new Set,this.seenOn.set(t,n)),n.add(e)});const o=new Set,i=[],s=[];let a=e=>{s[e]||(s[e]=!0,s.filter((e=>e)).length===r.length&&(t.oneose?.(),a=()=>{}))};const c=[];let l=(e,n,o)=>{c[e]||(a(e),c[e]={url:n,reason:o},c.filter((e=>e)).length===r.length&&(t.onclose?.(c),l=()=>{}))};const u=e=>{if(t.alreadyHaveEvent?.(e))return!0;const n=o.has(e);return o.add(e),n},d=Promise.all(r.map((async({url:e,filters:n},r)=>{if(!1===this.allowConnectingToRelay?.(e,["read",n]))return void l(r,e,"connection skipped by allowConnectingToRelay");let o;try{o=await this.ensureRelay(e,{connectionTimeout:this.maxWaitForConnection<(t.maxWait||0)?Math.max(.8*t.maxWait,t.maxWait-1e3):this.maxWaitForConnection,abort:t.abort})}catch(t){return this.onRelayConnectionFailure?.(e),void l(r,e,t?.message||String(t))}this.onRelayConnectionSuccess?.(e);let s=o.subscribe(n,{...t,oneose:()=>a(r),onclose:i=>{i.startsWith("auth-required: ")&&t.onauth?o.auth(t.onauth).then((()=>{o.subscribe(n,{...t,oneose:()=>a(r),onclose:t=>{l(r,e,t)},alreadyHaveEvent:u,eoseTimeout:t.maxWait,abort:t.abort})})).catch((t=>{l(r,e,`auth was required and attempted, but failed with: ${t}`)})):l(r,e,i)},alreadyHaveEvent:u,eoseTimeout:t.maxWait,abort:t.abort});i.push(s)})));return{async close(e){await d,i.forEach((t=>{t.close(e)}))}}}subscribeEose(e,t,n){let r;return r=this.subscribe(e,t,{...n,oneose(){const t="closed automatically on eose";r?r.close(t):n.onclose?.(e.map((e=>({url:e,reason:t}))))}}),r}subscribeManyEose(e,t,n){return this.subscribeEose(e,t,n)}async querySync(e,t,n){return new Promise((async r=>{const o=[];this.subscribeEose(e,t,{...n,onevent(e){o.push(e)},onclose(e){r(o)}})}))}async get(e,t,n){t.limit=1;const r=await this.querySync(e,t,n);return r.sort(((e,t)=>t.created_at-e.created_at)),r[0]||null}async countMany(e,t,n,r){const o=function(e,t){switch(t){case"reactions":return{"#e":[e],kinds:[7]};case"reposts":return{"#e":[e],kinds:[6]};case"quotes":return{"#q":[e],kinds:[1,1111]};case"replies":return{"#e":[e],kinds:[1]};case"comments":return{"#E":[e],kinds:[1111]};case"followers":return{"#p":[e],kinds:[3]}}}(t,n),i=[];for(let t=0;t<e.length;t++){const n=Ur(e[t]);-1===i.indexOf(n)&&i.push(n)}const s=await Promise.all(i.map((async e=>{if(!1===this.allowConnectingToRelay?.(e,["read",[o]]))return null;let t;try{t=await this.ensureRelay(e,{connectionTimeout:this.maxWaitForConnection<(r?.maxWait||0)?Math.max(.8*r.maxWait,r.maxWait-1e3):this.maxWaitForConnection,abort:r?.abort})}catch(t){return this.onRelayConnectionFailure?.(e),null}return this.onRelayConnectionSuccess?.(e),t.countWithHLL([o],{id:r?.id}).catch((()=>null))})));let a,c=0;for(const e of s){if(!e)continue;if(e.count>c&&(c=e.count),!e.hll||512!==e.hll.length)continue;const t=Ja(e.hll);t&&(a=Ya(a||new Uint8Array(0),t))}return a?{count:c,hll:Xa(a)}:{count:c}}publish(e,t,n){return e.map(Ur).map((async(e,r,o)=>{if(o.indexOf(e)!==r)return Promise.reject("duplicate url");if(!1===this.allowConnectingToRelay?.(e,["write",t]))return Promise.reject("connection skipped by allowConnectingToRelay");let i;try{i=await this.ensureRelay(e,{connectionTimeout:this.maxWaitForConnection<(n?.maxWait||0)?Math.max(.8*n.maxWait,n.maxWait-1e3):this.maxWaitForConnection,abort:n?.abort})}catch(t){return this.onRelayConnectionFailure?.(e),String("connection failure: "+String(t))}return i.publish(t).catch((async e=>{if(e instanceof Error&&e.message.startsWith("auth-required: ")&&n?.onauth)return await i.auth(n.onauth),i.publish(t);throw e})).then((e=>{if(this.trackRelays){let e=this.seenOn.get(t.id);e||(e=new Set,this.seenOn.set(t.id,e)),e.add(i)}return e}))}))}listConnectionStatus(){const e=new Map;return this.relays.forEach(((t,n)=>e.set(n,t.connected))),e}destroy(){this.relays.forEach((e=>e.close())),this.relays=new Map}pruneIdleRelays(e=1e4){const t=[];for(const[n,r]of this.relays)r.idleSince&&Date.now()-r.idleSince>=e&&(this.relays.delete(n),t.push(n),r.close());return t}};try{Qa=WebSocket}catch{}var tc=class extends ec{constructor(e){super({verifyEvent:Zr,websocketImplementation:Qa,maxWaitForConnection:3e3,...e})}},nc={};Br(nc,{BECH32_REGEX:()=>ic,Bech32MaxSize:()=>oc,NostrTypeGuard:()=>rc,decode:()=>ac,decodeNostrURI:()=>sc,encodeBytes:()=>fc,naddrEncode:()=>yc,neventEncode:()=>gc,noteEncode:()=>dc,nprofileEncode:()=>pc,npubEncode:()=>uc,nsecEncode:()=>lc});var rc={isNProfile:e=>/^nprofile1[a-z\d]+$/.test(e||""),isNEvent:e=>/^nevent1[a-z\d]+$/.test(e||""),isNAddr:e=>/^naddr1[a-z\d]+$/.test(e||""),isNSec:e=>/^nsec1[a-z\d]{58}$/.test(e||""),isNPub:e=>/^npub1[a-z\d]{58}$/.test(e||""),isNote:e=>/^note1[a-z\d]+$/.test(e||""),isNcryptsec:e=>/^ncryptsec1[a-z\d]+$/.test(e||"")},oc=5e3,ic=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function sc(e){try{return e.startsWith("nostr:")&&(e=e.substring(6)),ac(e)}catch(e){return{type:"invalid",data:null}}}function ac(e){let{prefix:t,words:n}=nn.decode(e,oc),r=new Uint8Array(nn.fromWords(n));switch(t){case"nprofile":{let e=cc(r);if(!e[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(32!==e[0][0].length)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:f(e[0][0]),relays:e[1]?e[1].map((e=>Pr.decode(e))):[]}}}case"nevent":{let e=cc(r);if(!e[0]?.[0])throw new Error("missing TLV 0 for nevent");if(32!==e[0][0].length)throw new Error("TLV 0 should be 32 bytes");if(e[2]&&32!==e[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(e[3]&&4!==e[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:f(e[0][0]),relays:e[1]?e[1].map((e=>Pr.decode(e))):[],author:e[2]?.[0]?f(e[2][0]):void 0,kind:e[3]?.[0]?parseInt(f(e[3][0]),16):void 0}}}case"naddr":{let e=cc(r);if(!e[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!e[2]?.[0])throw new Error("missing TLV 2 for naddr");if(32!==e[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(!e[3]?.[0])throw new Error("missing TLV 3 for naddr");if(4!==e[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:Pr.decode(e[0][0]),pubkey:f(e[2][0]),kind:parseInt(f(e[3][0]),16),relays:e[1]?e[1].map((e=>Pr.decode(e))):[]}}}case"nsec":return{type:t,data:r};case"npub":case"note":return{type:t,data:f(r)};default:throw new Error(`unknown prefix ${t}`)}}function cc(e){let t={},n=e;for(;n.length>0;){if(n.length<2)throw new Error("not enough data to read TLV");let e=n[0],r=n[1],o=n.slice(2,2+r);if(n=n.slice(2+r),o.length<r)throw new Error(`not enough data to read on TLV ${e}`);t[e]=t[e]||[],t[e].push(o)}return t}function lc(e){return fc("nsec",e)}function uc(e){return fc("npub",E(e))}function dc(e){return fc("note",E(e))}function hc(e,t){let n=nn.toWords(t);return nn.encode(e,n,oc)}function fc(e,t){return hc(e,t)}function pc(e){return hc("nprofile",wc({0:[E(e.pubkey)],1:(e.relays||[]).map((e=>Lr.encode(e)))}))}function gc(e){let t;return void 0!==e.kind&&(t=function(e){const t=new Uint8Array(4);return t[0]=e>>24&255,t[1]=e>>16&255,t[2]=e>>8&255,t[3]=255&e,t}(e.kind)),hc("nevent",wc({0:[E(e.id)],1:(e.relays||[]).map((e=>Lr.encode(e))),2:e.author?[E(e.author)]:[],3:t?[new Uint8Array(t)]:[]}))}function yc(e){let t=new ArrayBuffer(4);return new DataView(t).setUint32(0,e.kind,!1),hc("naddr",wc({0:[Lr.encode(e.identifier)],1:(e.relays||[]).map((e=>Lr.encode(e))),2:[E(e.pubkey)],3:[new Uint8Array(t)]}))}function wc(e){let t=[];return Object.entries(e).reverse().forEach((([e,n])=>{n.forEach((n=>{let r=new Uint8Array(n.length+2);r.set([parseInt(e)],0),r.set([n.length],1),r.set(n,2),t.push(r)}))})),x(...t)}var mc=/\bnostr:((note|npub|naddr|nevent|nprofile)1\w+)\b|#\[(\d+)\]/g;function bc(e){let t=[];for(let n of e.content.matchAll(mc))if(n[2])try{let{type:e,data:r}=ac(n[1]);switch(e){case"npub":t.push({text:n[0],profile:{pubkey:r,relays:[]}});break;case"nprofile":t.push({text:n[0],profile:r});break;case"note":t.push({text:n[0],event:{id:r,relays:[]}});break;case"nevent":t.push({text:n[0],event:r});break;case"naddr":t.push({text:n[0],address:r})}}catch(e){}else if(n[3]){let r=parseInt(n[3],10),o=e.tags[r];if(!o)continue;switch(o[0]){case"p":t.push({text:n[0],profile:{pubkey:o[1],relays:o[2]?[o[2]]:[]}});break;case"e":t.push({text:n[0],event:{id:o[1],relays:o[2]?[o[2]]:[]}});break;case"a":try{let[e,r,i]=o[1].split(":");t.push({text:n[0],address:{identifier:i,pubkey:r,kind:parseInt(e,10),relays:o[2]?[o[2]]:[]}})}catch(e){}}}return t}var vc={};function Ec(e,t,n){const r=e instanceof Uint8Array?e:E(e),o=Sc(st.getSharedSecret(r,E("02"+t)));let i=Uint8Array.from(k(16)),s=Lr.encode(n),a=Jn(o,i).encrypt(s);return`${Wt.encode(new Uint8Array(a))}?iv=${Wt.encode(new Uint8Array(i.buffer))}`}function xc(e,t,n){const r=e instanceof Uint8Array?e:E(e);let[o,i]=n.split("?iv="),s=Sc(st.getSharedSecret(r,E("02"+t))),a=Wt.decode(i),c=Wt.decode(o),l=Jn(s,a).decrypt(c);return Pr.decode(l)}function Sc(e){return e.slice(1,33)}Br(vc,{decrypt:()=>xc,encrypt:()=>Ec});var kc={};Br(kc,{NIP05_REGEX:()=>Rc,isNip05:()=>Oc,isValid:()=>Pc,queryProfile:()=>Tc,searchDomain:()=>Bc,useFetchImplementation:()=>Ic});var Ac,Rc=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,Oc=e=>Rc.test(e||"");try{Ac=fetch}catch(e){}function Ic(e){Ac=e}async function Bc(e,t=""){try{const n=`https://${e}/.well-known/nostr.json?name=${t}`,r=await Ac(n,{redirect:"manual"});if(200!==r.status)throw Error("Wrong response code");return(await r.json()).names}catch(e){return{}}}async function Tc(e){const t=e.match(Rc);if(!t)return null;const[,n="_",r]=t;try{const e=`https://${r}/.well-known/nostr.json?name=${n}`,t=await Ac(e,{redirect:"manual"});if(200!==t.status)throw Error("Wrong response code");const o=await t.json(),i=o.names[n];return i?{pubkey:i,relays:o.relays?.[i]}:null}catch(e){return null}}async function Pc(e,t){const n=await Tc(t);return!!n&&n.pubkey===e}var Lc={};function Uc(e){const t={reply:void 0,root:void 0,mentions:[],profiles:[],quotes:[]};let n,r;for(let o=e.tags.length-1;o>=0;o--){const i=e.tags[o];if("e"===i[0]&&i[1]&&Mr(i[1])){const[e,o,s,a,c]=i,l={id:o,relays:s?[s]:[],author:c&&Mr(c)?c:void 0};if("root"===a){t.root=l;continue}if("reply"===a){t.reply=l;continue}if("mention"===a){t.mentions.push(l);continue}n?r=l:n=l,t.mentions.push(l)}else{if("q"===i[0]&&i[1]&&Mr(i[1])){const[e,n,r]=i;t.quotes.push({id:n,relays:r?[r]:[]})}"p"===i[0]&&i[1]&&Mr(i[1])&&t.profiles.push({pubkey:i[1],relays:i[2]?[i[2]]:[]})}}return t.root||(t.root=r||n||t.reply),t.reply||(t.reply=n||t.root),[t.reply,t.root].forEach((e=>{if(!e)return;let n=t.mentions.indexOf(e);if(-1!==n&&t.mentions.splice(n,1),e.author){let n=t.profiles.find((t=>t.pubkey===e.author));n&&n.relays&&(e.relays||(e.relays=[]),n.relays.forEach((t=>{-1===e.relays?.indexOf(t)&&e.relays.push(t)})),n.relays=e.relays)}})),t.mentions.forEach((e=>{if(e.author){let n=t.profiles.find((t=>t.pubkey===e.author));n&&n.relays&&(e.relays||(e.relays=[]),n.relays.forEach((t=>{-1===e.relays.indexOf(t)&&e.relays.push(t)})),n.relays=e.relays)}})),t}Br(Lc,{parse:()=>Uc});var _c={};Br(_c,{fetchRelayInformation:()=>Cc,useFetchImplementation:()=>Nc});try{fetch}catch{}function Nc(e){0}async function Cc(e){return await(await fetch(e.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var $c={};function Mc(e){let t=0;for(let n=0;n<64;n+=8){const r=parseInt(e.substring(n,n+8),16);if(0!==r){t+=Math.clz32(r);break}t+=32}return t}function Fc(e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];if(0!==r){t+=Math.clz32(r)-24;break}t+=8}return t}function Dc(e,t){let n=0;const r=e,o=["nonce",n.toString(),t.toString()];for(r.tags.push(o);;){const e=Math.floor((new Date).getTime()/1e3);e!==r.created_at&&(n=0,r.created_at=e),o[1]=(++n).toString();const i=U(Lr.encode(JSON.stringify([0,r.pubkey,r.created_at,r.kind,r.tags,r.content])));if(Fc(i)>=t){r.id=f(i);break}}return r}Br($c,{getPow:()=>Mc,minePow:()=>Dc});var Hc={};Br(Hc,{unwrapEvent:()=>yl,unwrapManyEvents:()=>wl,wrapEvent:()=>pl,wrapManyEvents:()=>gl});var qc={};Br(qc,{createRumor:()=>al,createSeal:()=>cl,createWrap:()=>ll,unwrapEvent:()=>hl,unwrapManyEvents:()=>fl,wrapEvent:()=>ul,wrapManyEvents:()=>dl});var jc={};Br(jc,{decrypt:()=>el,encrypt:()=>Qc,getConversationKey:()=>Kc,v2:()=>tl});var Vc=1,Wc=4294967295,zc=65536;function Kc(e,t){const n=st.getSharedSecret(e,E("02"+t)).subarray(1,33);return kr(U,n,Lr.encode("nip44-v2"))}function Gc(e,t){const n=Or(U,e,t,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function Zc(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("expected positive integer");if(e<=32)return 32;const t=2**(Math.floor(Math.log2(e-1))+1),n=t<=256?32:t/8;return n*(Math.floor((e-1)/n)+1)}function Jc(e){const t=Lr.encode(e),n=t.length;if(n<Vc||n>Wc)throw new Error("invalid plaintext size: must be between 1 and 4294967295 bytes");const r=n>=zc?x(new Uint8Array([0,0]),function(e){if(!Number.isSafeInteger(e)||e<zc||e>Wc)throw new Error("invalid plaintext size: must be between 65536 and 4294967295 bytes");const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t}(n)):function(e){if(!Number.isSafeInteger(e)||e<Vc||e>65535)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}(n);return x(r,t,new Uint8Array(Zc(n)-n))}function Xc(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint16(0);let r,o;if(0===n){if(r=t.getUint32(2),r<zc)throw new Error("invalid padding");o=6}else r=n,o=2;const i=e.subarray(o,o+r);if(r<Vc||r>Wc||i.length!==r||e.length!==o+Zc(r))throw new Error("invalid padding");return Pr.decode(i)}function Yc(e,t,n){if(32!==n.length)throw new Error("AAD associated data must be 32 bytes");const r=x(n,t);return Me(U,e,r)}function Qc(e,t,n=k(32)){const{chacha_key:r,chacha_nonce:o,hmac_key:i}=Gc(t,n),s=Jc(e),a=wr(r,o,s),c=Yc(i,a,n);return Wt.encode(x(new Uint8Array([2]),n,a,c))}function el(e,t){const{nonce:n,ciphertext:r,mac:o}=function(e){if("string"!=typeof e)throw new Error("payload must be a valid string");const t=e.length;if(t<132)throw new Error("invalid payload length: "+t);if("#"===e[0])throw new Error("unknown encryption version");let n;try{n=Wt.decode(e)}catch(e){throw new Error("invalid base64: "+e.message)}const r=n.length;if(r<99)throw new Error("invalid data length: "+r);const o=n[0];if(2!==o)throw new Error("unknown encryption version "+o);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}(e),{chacha_key:i,chacha_nonce:s,hmac_key:a}=Gc(t,n);if(!yn(Yc(a,r,n),o))throw new Error("invalid MAC");return Xc(wr(i,s,r))}var tl={utils:{getConversationKey:Kc,calcPaddedLen:Zc,pad:Jc,unpad:Xc},encrypt:Qc,decrypt:el},nl=()=>Math.round(Date.now()/1e3),rl=()=>Math.round(nl()-172800*Math.random()),ol=(e,t)=>Kc(e,t),il=(e,t,n)=>Qc(JSON.stringify(e),ol(t,n)),sl=(e,t)=>JSON.parse(el(e.content,ol(t,e.pubkey)));function al(e,t){const n={created_at:nl(),content:"",tags:[],...e,pubkey:Kr(t)};return n.id=Vr(n),n}function cl(e,t,n){return Gr({kind:wo,content:il(e,t,n),created_at:rl(),tags:[]},t)}function ll(e,t){const n=zr();return Gr({kind:Mo,content:il(e,n,t),created_at:rl(),tags:[["p",t]]},n)}function ul(e,t,n){return ll(cl(al(e,t),t,n),n)}function dl(e,t,n){if(!n||0===n.length)throw new Error("At least one recipient is required.");const r=Kr(t),o=[ul(e,t,r)];return n.forEach((n=>{o.push(ul(e,t,n))})),o}function hl(e,t){const n=sl(e,t);return sl(n,t)}function fl(e,t){let n=[];return e.forEach((e=>{n.push(hl(e,t))})),n.sort(((e,t)=>e.created_at-t.created_at)),n}function pl(e,t,n,r,o){const i=function(e,t,n,r){const o={created_at:Math.ceil(Date.now()/1e3),kind:mo,tags:[],content:t};return(Array.isArray(e)?e:[e]).forEach((({publicKey:e,relayUrl:t})=>{o.tags.push(t?["p",e,t]:["p",e])})),r&&o.tags.push(["e",r.eventId,r.relayUrl||"","reply"]),n&&o.tags.push(["subject",n]),o}(t,n,r,o);return ul(i,e,t.publicKey)}function gl(e,t,n,r,o){if(!t||0===t.length)throw new Error("At least one recipient is required.");return[{publicKey:Kr(e)},...t].map((t=>pl(e,t,n,r,o)))}var yl=hl,wl=fl,ml={};function bl(e,t,n,r){let o;const i=[...e.tags??[],["e",t.id,n],["p",t.pubkey]];return t.kind===oo?o=lo:(o=vo,i.push(["k",String(t.kind)])),Gr({kind:o,tags:i,content:""===e.content||t.tags?.find((e=>"-"===e[0]))?"":JSON.stringify(t),created_at:e.created_at},r)}function vl(e){if(![lo,vo].includes(e.kind))return;let t,n;for(let r=e.tags.length-1;r>=0&&(void 0===t||void 0===n);r--){const o=e.tags[r];o.length>=2&&("e"===o[0]&&void 0===t?t=o:"p"===o[0]&&void 0===n&&(n=o))}return void 0!==t?{id:t[1],relays:[t[2],n?.[2]].filter((e=>"string"==typeof e)),author:n?.[1]}:void 0}function El(e,{skipVerification:t}={}){const n=vl(e);if(void 0===n||""===e.content)return;let r;try{r=JSON.parse(e.content)}catch(e){return}return r.id===n.id&&(t||Zr(r))?r:void 0}Br(ml,{finishRepostEvent:()=>bl,getRepostedEvent:()=>El,getRepostedEventPointer:()=>vl});var xl={};Br(xl,{NOSTR_URI_REGEX:()=>Sl,parse:()=>Al,test:()=>kl});var Sl=new RegExp(`nostr:(${ic.source})`);function kl(e){return"string"==typeof e&&new RegExp(`^${Sl.source}$`).test(e)}function Al(e){const t=e.match(new RegExp(`^${Sl.source}$`));if(!t)throw new Error(`Invalid Nostr URI: ${e}`);return{uri:t[0],value:t[1],decoded:ac(t[1])}}var Rl={};function Ol(e){if(e)return/^\d+$/.test(e)?parseInt(e,10):e}function Il(e,t){const n=e.indexOf(":"),r=e.indexOf(":",n+1);if(-1===n||-1===r)return;const o=parseInt(e.slice(0,n),10);if(Number.isNaN(o))return;const i=e.slice(n+1,r);return Mr(i)?{kind:o,pubkey:i,identifier:e.slice(r+1),relays:t?[t]:[]}:void 0}function Bl(e){switch(e[0]){case"E":case"e":if(!e[1]||!Mr(e[1]))return;return{id:e[1],relays:e[2]?[e[2]]:[],author:e[3]&&Mr(e[3])?e[3]:void 0};case"A":case"a":if(!e[1])return;return Il(e[1],e[2]);case"I":case"i":if(!e[1])return;return{value:e[1],hint:e[2]}}}function Tl(e){if(e[1]){if(e[1].includes(":"))return Il(e[1],e[2]);if(Mr(e[1]))return{id:e[1],relays:e[2]?[e[2]]:[],author:e[3]&&Mr(e[3])?e[3]:void 0}}}function Pl(e){return e.findLast((e=>"A"===e.tagName||"a"===e.tagName))?.pointer||e.findLast((e=>"I"===e.tagName||"i"===e.tagName))?.pointer||e.findLast((e=>"E"===e.tagName||"e"===e.tagName))?.pointer}function Ll(e,t){if(!e||!("id"in e)||!e.author)return;const n=t.find((t=>t.pubkey===e.author));n&&n.relays&&(e.relays||(e.relays=[]),n.relays.forEach((t=>{-1===e.relays.indexOf(t)&&e.relays.push(t)})),n.relays=e.relays)}function Ul(e){const t={root:void 0,rootKind:void 0,reply:void 0,replyKind:void 0,mentions:[],quotes:[],profiles:[]},n=[],r=[];for(const o of e.tags)if("E"!==o[0]&&"A"!==o[0]&&"I"!==o[0]||!o[1])if("e"!==o[0]&&"a"!==o[0]&&"i"!==o[0]||!o[1])if("K"!==o[0])if("k"!==o[0])if("q"!==o[0])("P"===o[0]||"p"===o[0])&&o[1]&&Mr(o[1])&&t.profiles.push({pubkey:o[1],relays:o[2]?[o[2]]:[]});else{const e=Tl(o);e&&t.quotes.push(e)}else t.replyKind=Ol(o[1]);else t.rootKind=Ol(o[1]);else{const e=Bl(o);e&&r.push({tagName:o[0],pointer:e})}else{const e=Bl(o);e&&n.push({tagName:o[0],pointer:e})}return t.root=Pl(n),t.reply=Pl(r),Ll(t.root,t.profiles),Ll(t.reply,t.profiles),t.quotes.forEach((e=>Ll(e,t.profiles))),t}Br(Rl,{parse:()=>Ul});var _l={};function Nl(e,t,n){const r=t.tags.filter((e=>e.length>=2&&("e"===e[0]||"p"===e[0])));return Gr({...e,kind:uo,tags:[...e.tags??[],...r,["e",t.id],["p",t.pubkey]],content:e.content??"+"},n)}function Cl(e){if(e.kind!==uo)return;let t,n;for(let r=e.tags.length-1;r>=0&&(void 0===t||void 0===n);r--){const o=e.tags[r];o.length>=2&&("e"===o[0]&&void 0===t?t=o:"p"===o[0]&&void 0===n&&(n=o))}return void 0!==t&&void 0!==n?{id:t[1],relays:[t[2],n[2]].filter((e=>void 0!==e)),author:n[1]}:void 0}Br(_l,{finishReactionEvent:()=>Nl,getReactedEventPointer:()=>Cl});var $l={};Br($l,{parse:()=>Hl});var Ml=/\W/m,Fl=/[^\w\/] |[^\w\/]$|$|,| /m,Dl=42;function*Hl(e){let t=[];if("string"!=typeof e){for(let n=0;n<e.tags.length;n++){const r=e.tags[n];"emoji"===r[0]&&r.length>=3&&t.push({type:"emoji",shortcode:r[1],url:r[2]})}e=e.content}const n=e.length;let r=0,o=0;e:for(;o<n;){const i=e.indexOf(":",o),s=e.indexOf("#",o);if(-1===i&&-1===s)break e;if(-1===i||s>=0&&s<i){if(0===s||e[s-1].match(Ml)){const t=e.slice(s+1,s+Dl).match(Ml),i=t?s+1+t.index:n;yield{type:"text",text:e.slice(r,s)},yield{type:"hashtag",value:e.slice(s+1,i)},o=i,r=o;continue e}o=s+1}else if("nostr"===e.slice(i-5,i)){const t=e.slice(i+60).match(Ml),s=t?i+60+t.index:n;try{let t,{data:n,type:a}=ac(e.slice(i+1,s));switch(a){case"npub":t={pubkey:n};break;case"note":t={id:n};break;case"nsec":o=s+1;continue;default:t=n}r!==i-5&&(yield{type:"text",text:e.slice(r,i-5)}),yield{type:"reference",pointer:t},o=s,r=o;continue e}catch(e){o=i+1;continue e}}else if("https"===e.slice(i-5,i)||"http"===e.slice(i-4,i)){const t=e.slice(i+4).match(Fl),s=t?i+4+t.index:n,a="s"===e[i-1]?5:4;try{let t=new URL(e.slice(i-a,s));if(-1===t.hostname.indexOf("."))throw new Error("invalid url");if(r!==i-a&&(yield{type:"text",text:e.slice(r,i-a)}),/\.(png|jpe?g|gif|webp|heic|svg)$/i.test(t.pathname)){yield{type:"image",url:t.toString()},o=s,r=o;continue e}if(/\.(mp4|avi|webm|mkv|mov)$/i.test(t.pathname)){yield{type:"video",url:t.toString()},o=s,r=o;continue e}if(/\.(mp3|aac|ogg|opus|wav|flac)$/i.test(t.pathname)){yield{type:"audio",url:t.toString()},o=s,r=o;continue e}yield{type:"url",url:t.toString()},o=s,r=o;continue e}catch(e){o=s+1;continue e}}else{if("wss"!==e.slice(i-3,i)&&"ws"!==e.slice(i-2,i)){for(let n=0;n<t.length;n++){const s=t[n];if(":"===e[i+s.shortcode.length+1]&&e.slice(i+1,i+s.shortcode.length+1)===s.shortcode){r!==i&&(yield{type:"text",text:e.slice(r,i)}),yield s,o=i+s.shortcode.length+2,r=o;continue e}}o=i+1;continue e}{const t=e.slice(i+4).match(Fl),s=t?i+4+t.index:n,a="s"===e[i-1]?3:2;try{let t=new URL(e.slice(i-a,s));if(-1===t.hostname.indexOf("."))throw new Error("invalid ws url");r!==i-a&&(yield{type:"text",text:e.slice(r,i-a)}),yield{type:"relay",url:t.toString()},o=s,r=o;continue e}catch(e){o=s+1;continue e}}}}r!==n&&(yield{type:"text",text:e.slice(r)})}var ql={};Br(ql,{channelCreateEvent:()=>jl,channelHideMessageEvent:()=>zl,channelMessageEvent:()=>Wl,channelMetadataEvent:()=>Vl,channelMuteUserEvent:()=>Kl});var jl=(e,t)=>{let n;if("object"==typeof e.content)n=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;n=e.content}return Gr({kind:Ro,tags:[...e.tags??[]],content:n,created_at:e.created_at},t)},Vl=(e,t)=>{let n;if("object"==typeof e.content)n=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;n=e.content}return Gr({kind:Oo,tags:[["e",e.channel_create_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},Wl=(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"]),Gr({kind:Io,tags:[...n,...e.tags??[]],content:e.content,created_at:e.created_at},t)},zl=(e,t)=>{let n;if("object"==typeof e.content)n=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;n=e.content}return Gr({kind:Bo,tags:[["e",e.channel_message_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},Kl=(e,t)=>{let n;if("object"==typeof e.content)n=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;n=e.content}return Gr({kind:To,tags:[["p",e.pubkey_to_mute],...e.tags??[]],content:n,created_at:e.created_at},t)},Gl={};Br(Gl,{EMOJI_SHORTCODE_REGEX:()=>Zl,matchAll:()=>Xl,regex:()=>Jl,replaceAll:()=>Yl});var Zl=/:(\w+):/,Jl=()=>new RegExp(`\\B${Zl.source}\\B`,"g");function*Xl(e){const t=e.matchAll(Jl());for(const e of t)try{const[t,n]=e;yield{shortcode:t,name:n,start:e.index,end:e.index+t.length}}catch(e){}}function Yl(e,t){return e.replaceAll(Jl(),((e,n)=>t({shortcode:e,name:n})))}var Ql,eu={};Br(eu,{useFetchImplementation:()=>tu,validateGithub:()=>nu});try{Ql=fetch}catch{}function tu(e){Ql=e}async function nu(e,t,n){try{return await(await Ql(`https://gist.github.com/${t}/${n}/raw`)).text()===`Verifying that I control the following Nostr public key: ${e}`}catch(e){return!1}}var ru={};function ou(e){const{host:t,pathname:n,searchParams:r}=new URL(e),o=n||t,i=r.getAll("relay"),s=r.get("secret");if(!o||0===i.length||!s)throw new Error("invalid connection string");return{pubkey:o,relay:i[0],relays:i,secret:s}}async function iu(e,t,n){const r={method:"pay_invoice",params:{invoice:n}},o=Ec(t,e,JSON.stringify(r)),i={kind:ms,created_at:Math.round(Date.now()/1e3),content:o,tags:[["p",e]]};return Gr(i,t)}Br(ru,{makeNwcRequestEvent:()=>iu,parseConnectionString:()=>ou});var su={};function au(e){return e=(e=e.trim().toLowerCase()).normalize("NFKC"),Array.from(e).map((e=>/\p{Letter}/u.test(e)||/\p{Number}/u.test(e)?e:"-")).join("")}Br(su,{normalizeIdentifier:()=>au});var cu,lu={};Br(lu,{getSatoshisAmountFromBolt11:()=>gu,getZapEndpoint:()=>du,makeZapReceipt:()=>pu,makeZapRequest:()=>hu,useFetchImplementation:()=>uu,validateZapRequest:()=>fu});try{cu=fetch}catch{}function uu(e){cu=e}async function du(e){try{let t="",{lud06:n,lud16:r}=JSON.parse(e.content);if(r){let[e,n]=r.split("@");t=new URL(`/.well-known/lnurlp/${e}`,`https://${n}`).toString()}else{if(!n)return null;{let{words:e}=nn.decode(n,1e3),r=nn.fromWords(e);t=Pr.decode(r)}}let o=await cu(t),i=await o.json();if(i.allowsNostr&&i.nostrPubkey)return i.callback}catch(e){}return null}function hu(e){let t={kind:9734,created_at:Math.round(Date.now()/1e3),content:e.comment||"",tags:[["p","pubkey"in e?e.pubkey:e.event.pubkey],["amount",e.amount.toString()],["relays",...e.relays]]};if("event"in e){if(t.tags.push(["e",e.event.id]),Yr(e.event.kind)){const n=["a",`${e.event.kind}:${e.event.pubkey}:`];t.tags.push(n)}else if(eo(e.event.kind)){let n=e.event.tags.find((([e,t])=>"d"===e&&t));if(!n)throw new Error("d tag not found or is empty");const r=["a",`${e.event.kind}:${e.event.pubkey}:${n[1]}`];t.tags.push(r)}t.tags.push(["k",e.event.kind.toString()])}return t}function fu(e){let t;try{t=JSON.parse(e)}catch(e){return"Invalid zap request JSON."}if(!Hr(t))return"Zap request is not a valid Nostr event.";if(!Zr(t))return"Invalid signature on zap request.";let n=t.tags.find((([e,t])=>"p"===e&&t));if(!n)return"Zap request doesn't have a 'p' tag.";if(!Mr(n[1]))return"Zap request 'p' tag is not valid hex.";let r=t.tags.find((([e,t])=>"e"===e&&t));return r&&!Mr(r[1])?"Zap request 'e' tag is not valid hex.":t.tags.find((([e,t])=>"relays"===e&&t))?null:"Zap request doesn't have a 'relays' tag."}function pu({zapRequest:e,preimage:t,bolt11:n,paidAt:r}){let o=JSON.parse(e),i=o.tags.filter((([e])=>"e"===e||"p"===e||"a"===e)),s={kind:9735,created_at:Math.round(r.getTime()/1e3),content:"",tags:[...i,["P",o.pubkey],["bolt11",n],["description",e]]};return t&&s.tags.push(["preimage",t]),s}function gu(e){if(e.length<50)return 0;const t=(e=e.substring(0,50)).lastIndexOf("1");if(-1===t)return 0;const n=e.substring(0,t);if(!n.startsWith("lnbc"))return 0;const r=n.substring(4);if(r.length<1)return 0;const o=r[r.length-1],i=o.charCodeAt(0)-"0".charCodeAt(0),s=i>=0&&i<=9;let a=r.length-1;if(s&&a++,a<1)return 0;const c=parseInt(r.substring(0,a));switch(o){case"m":return 1e5*c;case"u":return 100*c;case"n":return c/10;case"p":return c/1e4;default:return 1e8*c}}var yu={};Br(yu,{Negentropy:()=>Ou,NegentropyStorageVector:()=>Ru,NegentropySync:()=>Tu});var wu=32,mu=0,bu=1,vu=2,Eu=class{_raw;length;constructor(e){"number"==typeof e?(this._raw=new Uint8Array(e),this.length=0):e instanceof Uint8Array?(this._raw=new Uint8Array(e),this.length=e.length):(this._raw=new Uint8Array(512),this.length=0)}unwrap(){return this._raw.subarray(0,this.length)}get capacity(){return this._raw.byteLength}extend(e){if(e instanceof Eu&&(e=e.unwrap()),"number"!=typeof e.length)throw Error("bad length");const t=e.length+this.length;if(this.capacity<t){const e=this._raw,n=Math.max(2*this.capacity,t);this._raw=new Uint8Array(n),this._raw.set(e)}this._raw.set(e,this.length),this.length+=e.length}shift(){const e=this._raw[0];return this._raw=this._raw.subarray(1),this.length--,e}shiftN(e=1){const t=this._raw.subarray(0,e);return this._raw=this._raw.subarray(e),this.length-=e,t}};function xu(e){let t=0;for(;;){if(0===e.length)throw Error("parse ends prematurely");let n=e.shift();if(t=t<<7|127&n,!(128&n))break}return t}function Su(e){if(0===e)return new Eu(new Uint8Array([0]));let t=[];for(;0!==e;)t.push(127&e),e>>>=7;t.reverse();for(let e=0;e<t.length-1;e++)t[e]|=128;return new Eu(new Uint8Array(t))}function ku(e,t){if(e.length<t)throw Error("parse ends prematurely");return e.shiftN(t)}var Au=class{buf;constructor(){this.setToZero()}setToZero(){this.buf=new Uint8Array(wu)}add(e){let t=0,n=0,r=new DataView(this.buf.buffer),o=new DataView(e.buffer);for(let e=0;e<8;e++){let i=4*e,s=r.getUint32(i,!0);s+=t,s+=o.getUint32(i,!0),s>4294967295&&(n=1),r.setUint32(i,4294967295&s,!0),t=n,n=0}}negate(){let e=new DataView(this.buf.buffer);for(let t=0;t<8;t++){let n=4*t;e.setUint32(n,~e.getUint32(n,!0))}let t=new Uint8Array(wu);t[0]=1,this.add(t)}getFingerprint(e){let t=new Eu;return t.extend(this.buf),t.extend(Su(e)),U(t.unwrap()).subarray(0,16)}},Ru=class{items;sealed;constructor(){this.items=[],this.sealed=!1}insert(e,t){if(this.sealed)throw Error("already sealed");const n=E(t);if(n.byteLength!==wu)throw Error("bad id size for added item");this.items.push({timestamp:e,id:n})}seal(){if(this.sealed)throw Error("already sealed");this.sealed=!0,this.items.sort(Bu);for(let e=1;e<this.items.length;e++)if(0===Bu(this.items[e-1],this.items[e]))throw Error("duplicate item inserted")}unseal(){this.sealed=!1}size(){return this._checkSealed(),this.items.length}getItem(e){if(this._checkSealed(),e>=this.items.length)throw Error("out of range");return this.items[e]}iterate(e,t,n){this._checkSealed(),this._checkBounds(e,t);for(let r=e;r<t&&n(this.items[r],r);++r);}findLowerBound(e,t,n){return this._checkSealed(),this._checkBounds(e,t),this._binarySearch(this.items,e,t,(e=>Bu(e,n)<0))}fingerprint(e,t){let n=new Au;return n.setToZero(),this.iterate(e,t,(e=>(n.add(e.id),!0))),n.getFingerprint(t-e)}_checkSealed(){if(!this.sealed)throw Error("not sealed")}_checkBounds(e,t){if(e>t||t>this.items.length)throw Error("bad range")}_binarySearch(e,t,n,r){let o=n-t;for(;o>0;){let n=t,i=Math.floor(o/2);n+=i,r(e[n])?(t=++n,o-=i+1):o=i}return t}},Ou=class{storage;frameSizeLimit;lastTimestampIn;lastTimestampOut;constructor(e,t=6e4){if(t<4096)throw Error("frameSizeLimit too small");this.storage=e,this.frameSizeLimit=t,this.lastTimestampIn=0,this.lastTimestampOut=0}_bound(e,t){return{timestamp:e,id:t||new Uint8Array(0)}}initiate(){let e=new Eu;return e.extend(new Uint8Array([97])),this.splitRange(0,this.storage.size(),this._bound(Number.MAX_VALUE),e),f(e.unwrap())}reconcile(e,t,n){const r=new Eu(E(e));this.lastTimestampIn=this.lastTimestampOut=0;let o=new Eu;o.extend(new Uint8Array([97]));let i=ku(r,1)[0];if(i<96||i>111)throw Error("invalid negentropy protocol version byte");if(97!==i)throw Error("unsupported negentropy protocol version requested: "+(i-96));let s=this.storage.size(),a=this._bound(0),c=0,l=!1;for(;0!==r.length;){let e=new Eu,i=()=>{l&&(l=!1,e.extend(this.encodeBound(a)),e.extend(Su(mu)))},u=this.decodeBound(r),d=xu(r),h=c,p=this.storage.findLowerBound(c,s,u);if(d===mu)l=!0;else if(d===bu){0!==Iu(ku(r,16),this.storage.fingerprint(h,p))?(i(),this.splitRange(h,p,u,e)):l=!0}else{if(d!==vu)throw Error("unexpected mode");{let e=xu(r),o={};for(let t=0;t<e;t++){let e=ku(r,wu);o[f(e)]=e}if(l=!0,this.storage.iterate(h,p,(e=>{let n=e.id;const r=f(n);return o[r]?delete o[f(n)]:t?.(r),!0})),n)for(let e of Object.values(o))n(f(e))}}if(this.exceededFrameSizeLimit(o.length+e.length)){let e=this.storage.fingerprint(p,s);o.extend(this.encodeBound(this._bound(Number.MAX_VALUE))),o.extend(Su(bu)),o.extend(e);break}o.extend(e),c=p,a=u}return 1===o.length?null:f(o.unwrap())}splitRange(e,t,n,r){let o=t-e;if(o<32)r.extend(this.encodeBound(n)),r.extend(Su(vu)),r.extend(Su(o)),this.storage.iterate(e,t,(e=>(r.extend(e.id),!0)));else{let i=Math.floor(o/16),s=o%16,a=e;for(let e=0;e<16;e++){let o,c=i+(e<s?1:0),l=this.storage.fingerprint(a,a+c);if(a+=c,a===t)o=n;else{let e,t;this.storage.iterate(a-1,a+1,((n,r)=>(r===a-1?e=n:t=n,!0))),o=this.getMinimalBound(e,t)}r.extend(this.encodeBound(o)),r.extend(Su(bu)),r.extend(l)}}}exceededFrameSizeLimit(e){return e>this.frameSizeLimit-200}decodeTimestampIn(e){let t=xu(e);return t=0===t?Number.MAX_VALUE:t-1,this.lastTimestampIn===Number.MAX_VALUE||t===Number.MAX_VALUE?(this.lastTimestampIn=Number.MAX_VALUE,Number.MAX_VALUE):(t+=this.lastTimestampIn,this.lastTimestampIn=t,t)}decodeBound(e){let t=this.decodeTimestampIn(e),n=xu(e);if(n>wu)throw Error("bound key too long");return{timestamp:t,id:ku(e,n)}}encodeTimestampOut(e){if(e===Number.MAX_VALUE)return this.lastTimestampOut=Number.MAX_VALUE,Su(0);let t=e;return e-=this.lastTimestampOut,this.lastTimestampOut=t,Su(e+1)}encodeBound(e){let t=new Eu;return t.extend(this.encodeTimestampOut(e.timestamp)),t.extend(Su(e.id.length)),t.extend(e.id),t}getMinimalBound(e,t){if(t.timestamp!==e.timestamp)return this._bound(t.timestamp);{let n=0,r=t.id,o=e.id;for(let e=0;e<wu&&r[e]===o[e];e++)n++;return this._bound(t.timestamp,t.id.subarray(0,n+1))}}};function Iu(e,t){for(let n=0;n<e.byteLength;n++){if(e[n]<t[n])return-1;if(e[n]>t[n])return 1}return e.byteLength>t.byteLength?1:e.byteLength<t.byteLength?-1:0}function Bu(e,t){return e.timestamp===t.timestamp?Iu(e.id,t.id):e.timestamp-t.timestamp}var Tu=class{relay;storage;neg;filter;subscription;onhave;onneed;constructor(e,t,n,r={}){this.relay=e,this.storage=t,this.neg=new Ou(t),this.onhave=r.onhave,this.onneed=r.onneed,this.filter=n,this.subscription=this.relay.prepareSubscription([{}],{label:r.label||"negentropy"}),this.subscription.oncustom=e=>{switch(e[0]){case"NEG-MSG":e.length<3&&console.warn(`got invalid NEG-MSG from ${this.relay.url}: ${e}`);try{const t=this.neg.reconcile(e[2],this.onhave,this.onneed);t?this.relay.send(`["NEG-MSG", "${this.subscription.id}", "${t}"]`):(this.close(),r.onclose?.())}catch(e){console.error("negentropy reconcile error:",e),r?.onclose?.(`reconcile error: ${e}`)}break;case"NEG-CLOSE":{const t=e[2];console.warn("negentropy error:",t),r.onclose?.(t);break}case"NEG-ERR":r.onclose?.()}}}async start(){const e=this.neg.initiate();this.relay.send(`["NEG-OPEN","${this.subscription.id}",${JSON.stringify(this.filter)},"${e}"]`)}close(){this.relay.send(`["NEG-CLOSE","${this.subscription.id}"]`),this.subscription.close()}},Pu={};Br(Pu,{getToken:()=>Uu,hashPayload:()=>Du,unpackEventFromToken:()=>Nu,validateEvent:()=>qu,validateEventKind:()=>$u,validateEventMethodTag:()=>Fu,validateEventPayloadTag:()=>Hu,validateEventTimestamp:()=>Cu,validateEventUrlTag:()=>Mu,validateToken:()=>_u});var Lu="Nostr ";async function Uu(e,t,n,r=!1,o){const i={kind:xs,tags:[["u",e],["method",t]],created_at:Math.round((new Date).getTime()/1e3),content:""};o&&i.tags.push(["payload",Du(o)]);const s=await n(i);return(r?Lu:"")+Wt.encode(Lr.encode(JSON.stringify(s)))}async function _u(e,t,n){const r=await Nu(e).catch((e=>{throw e}));return await qu(r,t,n).catch((e=>{throw e}))}async function Nu(e){if(!e)throw new Error("Missing token");e=e.replace(Lu,"");const t=Pr.decode(Wt.decode(e));if(!t||0===t.length||!t.startsWith("{"))throw new Error("Invalid token");return JSON.parse(t)}function Cu(e){return!!e.created_at&&Math.round((new Date).getTime()/1e3)-e.created_at<60}function $u(e){return e.kind===xs}function Mu(e,t){const n=e.tags.find((e=>"u"===e[0]));return!!n&&(n.length>0&&n[1]===t)}function Fu(e,t){const n=e.tags.find((e=>"method"===e[0]));return!!n&&(n.length>0&&n[1].toLowerCase()===t.toLowerCase())}function Du(e){return f(U(Lr.encode(JSON.stringify(e))))}function Hu(e,t){const n=e.tags.find((e=>"payload"===e[0]));if(!n)return!1;const r=Du(t);return n.length>0&&n[1]===r}async function qu(e,t,n,r){if(!Zr(e))throw new Error("Invalid nostr event, signature invalid");if(!$u(e))throw new Error("Invalid nostr event, kind invalid");if(!Cu(e))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!Mu(e,t))throw new Error("Invalid nostr event, url tag invalid");if(!Fu(e,n))throw new Error("Invalid nostr event, method tag invalid");if(Boolean(r)&&"object"==typeof r&&Object.keys(r).length>0&&!Hu(e,r))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}}},t={};function n(r){var o=t[r];if(void 0!==o)return o.exports;var i=t[r]={exports:{}};return e[r](i,i.exports,n),i.exports}n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};(()=>{var e=r;Object.defineProperty(e,"__esModule",{value:!0}),e.LNDataType=e.PaymentDirection=e.getOutgoingPayments=e.getIncomingPayments=e.getBalance=e.sendPayment=e.checkPayment=e.createInvoice=e.msatToSat=e.startLightning=void 0;var t=n(13);Object.defineProperty(e,"startLightning",{enumerable:!0,get:function(){return t.startLightning}});var o=n(805);Object.defineProperty(e,"msatToSat",{enumerable:!0,get:function(){return o.msatToSat}});var i=n(398);Object.defineProperty(e,"createInvoice",{enumerable:!0,get:function(){return i.createInvoice}}),Object.defineProperty(e,"checkPayment",{enumerable:!0,get:function(){return i.checkPayment}}),Object.defineProperty(e,"sendPayment",{enumerable:!0,get:function(){return i.sendPayment}}),Object.defineProperty(e,"getBalance",{enumerable:!0,get:function(){return i.getBalance}}),Object.defineProperty(e,"getIncomingPayments",{enumerable:!0,get:function(){return i.getIncomingPayments}}),Object.defineProperty(e,"getOutgoingPayments",{enumerable:!0,get:function(){return i.getOutgoingPayments}});var s=n(329);Object.defineProperty(e,"PaymentDirection",{enumerable:!0,get:function(){return s.PaymentDirection}}),Object.defineProperty(e,"LNDataType",{enumerable:!0,get:function(){return s.LNDataType}})})();var o=exports;for(var i in r)o[i]=r[i];r.__esModule&&Object.defineProperty(o,"__esModule",{value:!0})})();
2
+ (()=>{"use strict";var e={13:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.startLightning=void 0;const r=n(421),o=n(24),i=n(534),s=n(329),a=n(805);t.startLightning=({password:e,credentialsPath:t="/root/.phoenix/credentials.json",port:n,cacheDurationMs:c,serverPrvKeyBytes:l,serverPubKeyHex:u,defaultRelays:d,domain:h})=>{const f=`http://localhost:${n}`,p={},g=e||JSON.parse((0,o.readFileSync)(t,"utf-8"))?.password,y=(e,t,n)=>{try{const o=["-s","-u",`:${g}`,"-X",t];let i=`${f}${e}`;if(n){const e=new URLSearchParams(Object.fromEntries(Object.entries(n)?.map((([e,t])=>[e,String(t)])))).toString();"GET"==t?i+=`?${e}`:o.push("-d",e)}o.push(i);const s=(0,r.execFileSync)("curl",o).toString();return s?.startsWith("{")||s?.startsWith("[")?JSON.parse(s):s}catch(t){console.error((0,a.seoDt)(),`Lightning node ${e} failed:`,t instanceof Error?t.message:String(t))}},w=({amountSat:e,description:t=""})=>{try{const n=y("/createinvoice","POST",{amountSat:e,description:t});if(n?.serialized)return{invoiceString:n.serialized,invoiceId:n.paymentHash}}catch(e){console.error((0,a.seoDt)(),"newInvoice failed",e)}},m=({type:e,params:t})=>{try{const n=(0,a.tN)(),r=`${e}${t?JSON.stringify(t):""}`;if(p[r]&&p[r].time>n-c)return p[r].data;const o=y(`/${e}`,"GET",t);return o&&(p[r]={time:n,data:o}),o}catch(e){console.error((0,a.seoDt)(),"nodeQuery failed",e)}},b=({invoiceId:e,type:t})=>{try{const n=m({type:`payments/${t}`,params:{limit:30}});return n?.find((t=>t?.paymentHash==e))}catch(e){console.error((0,a.seoDt)(),"checkInvoice failed",e)}},v=({nostr:e,bolt11:t})=>{try{const n=(0,a.parseNostrEvent)(e);if(!n)return;const r={kind:9735,content:n.content||"",created_at:Math.round((0,a.tN)()/1e3),pubkey:u,tags:[...n.tags.filter((e=>["e","a","p","k"].includes(e[0]))),["bolt11",t],["description",JSON.stringify(n)],["P",n.pubkey]]},o=(0,i.finalizeEvent)(r,l);return(0,i.verifyEvent)(o)?{signedReceipt:o,relays:(0,a.eventRelays)(n)}:void console.error((0,a.seoDt)(),"zapSign verification failed",JSON.stringify(r))}catch(e){console.error((0,a.seoDt)(),"zapSign failed",e)}};return{newInvoice:w,checkInvoice:b,payInvoice:({amountSat:e,address:t})=>{try{if("number"!=typeof e||!t)return;const n=a.lightningAddressRegex.test(t),r=y(`/${n?"paylnaddress":"sendtoaddress"}`,"POST",{address:t,amountSat:e,...n?{}:{feerateSatByte:5}});if(r?.recipientAmountSat)return r}catch(e){console.error((0,a.seoDt)(),"payInvoice failed",e)}},nodeQuery:m,zapSign:v,zapPublish:async({nostr:e,bolt11:t,invoiceId:n})=>{try{const r=200,o=async()=>{const{signedReceipt:n,relays:r}=v({nostr:e,bolt11:t})||{};if(!n)return;const o=new i.SimplePool,s=(r||[]).concat(d).filter(((e,t,n)=>n.indexOf(e)===t));await Promise.allSettled(o.publish(s,n)),o.close(d)};let c=r;for(let e=0;e<30;e++){await(0,a.delayCode)(c);const e=b({invoiceId:n,type:s.PaymentDirection.Incoming});if(e?.isPaid)return void o();c+=r}}catch(e){console.error((0,a.seoDt)(),"zapPublish failed",e)}},payRequest:({user:e,amountMsat:t,nostr:n})=>{const r=(0,a.msatToSat)(t);if("number"!=typeof r||r<1)return;const o=`${e}@${h}`,{invoiceString:i="",invoiceId:s=""}=w({amountSat:r,description:`${n?"Zap":"Payment"} to ${o}`})||{};if(!i)return;const c={pr:i,routes:[]};if(n){const{signedReceipt:e}=v({nostr:n,bolt11:i})||{};if(!e)return}return{invoice:c,invoiceId:s}}}}},398:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getOutgoingPayments=t.getIncomingPayments=t.getBalance=t.sendPayment=t.checkPayment=t.createInvoice=void 0;t.createInvoice=({client:e,amountSat:t,description:n})=>e.newInvoice({amountSat:t,description:n});t.checkPayment=({client:e,invoiceId:t,type:n})=>e.checkInvoice({invoiceId:t,type:n});t.sendPayment=({client:e,amountSat:t,address:n})=>e.payInvoice({amountSat:t,address:n});t.getBalance=({client:e})=>e.nodeQuery({type:"getbalance"});t.getIncomingPayments=({client:e,limit:t=30})=>e.nodeQuery({type:"payments/incoming",params:{limit:t}});t.getOutgoingPayments=({client:e,limit:t=30})=>e.nodeQuery({type:"payments/outgoing",params:{limit:t}})},329:(e,t)=>{var n,r;Object.defineProperty(t,"__esModule",{value:!0}),t.LNDataType=t.PaymentDirection=void 0,function(e){e.Incoming="incoming",e.Outgoing="outgoing"}(n||(t.PaymentDirection=n={})),function(e){e.GetBalance="getbalance",e.GetInfo="getinfo",e.PaymentsIncoming="payments/incoming",e.PaymentsOutgoing="payments/outgoing"}(r||(t.LNDataType=r={}))},805:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.eventRelays=t.parseNostrEvent=t.msatToSat=t.delayCode=t.seoDt=t.tN=t.lightningAddressRegex=void 0;const n=()=>(new Date).toISOString();t.lightningAddressRegex=/^[a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,}$/i,t.tN=()=>Date.now(),t.seoDt=n,t.delayCode=e=>new Promise((t=>setTimeout(t,e)));t.msatToSat=e=>{try{return Math.round(Number(BigInt(e)/1000n))}catch{return 0}};t.parseNostrEvent=e=>{try{const t=e?.includes("{")?e:Buffer.from(e,"base64").toString("utf-8");return JSON.parse(t)}catch(e){console.error(n(),"parseNostrEvent failed",e)}};t.eventRelays=e=>{try{return e?.tags?.find((e=>"relays"==e?.[0]))?.slice(1,10)?.map((e=>e.lastIndexOf("/")==e.length-1?e.slice(0,e.length-1):e))||[]}catch(e){console.error(n(),"eventRelays failed",e)}return[]}},421:e=>{e.exports=require("node:child_process")},24:e=>{e.exports=require("node:fs")},534:(e,t,n)=>{function r(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function o(e,t=""){if(!Number.isSafeInteger(e)||e<0){throw new Error(`${t&&`"${t}" `}expected integer >= 0, got ${e}`)}}function i(e,t,n=""){const o=r(e),i=e?.length,s=void 0!==t;if(!o||s&&i!==t){throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(o?`length=${i}`:"type="+typeof e))}return e}function s(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash must wrapped by utils.createHasher");o(e.outputLen),o(e.blockLen)}function a(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 c(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function l(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function u(e,t){return e<<32-t|e>>>t}n.r(t),n.d(t,{Relay:()=>Ga,SimplePool:()=>tc,finalizeEvent:()=>Gr,fj:()=>Na,generateSecretKey:()=>zr,getEventHash:()=>Vr,getFilterLimit:()=>Ua,getPublicKey:()=>Kr,kinds:()=>Jr,matchFilter:()=>La,matchFilters:()=>Pa,mergeFilters:()=>_a,nip04:()=>vc,nip05:()=>kc,nip10:()=>Pc,nip11:()=>Uc,nip13:()=>$c,nip17:()=>Hc,nip18:()=>ml,nip19:()=>nc,nip21:()=>xl,nip22:()=>Rl,nip25:()=>Ul,nip27:()=>$l,nip28:()=>ql,nip30:()=>Gl,nip39:()=>eu,nip42:()=>qa,nip44:()=>jc,nip47:()=>ru,nip54:()=>su,nip57:()=>lu,nip59:()=>qc,nip77:()=>yu,nip98:()=>Lu,parseReferences:()=>bc,serializeEvent:()=>jr,sortEvents:()=>qr,utils:()=>Tr,validateEvent:()=>Hr,verifiedSymbol:()=>Fr,verifyEvent:()=>Zr});const d=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),h=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function f(e){if(i(e),d)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=h[e[n]];return t}const p=48,g=57,y=65,w=70,m=97,b=102;function v(e){return e>=p&&e<=g?e-p:e>=y&&e<=w?e-(y-10):e>=m&&e<=b?e-(m-10):void 0}function E(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(d)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,o=0;t<n;t++,o+=2){const n=v(e.charCodeAt(o)),i=v(e.charCodeAt(o+1));if(void 0===n||void 0===i){const t=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+o)}r[t]=16*n+i}return r}function x(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];i(r),t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const o=e[t];n.set(o,r),r+=o.length}return n}function S(e,t={}){const n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}function k(e=32){const t="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof t?.getRandomValues)throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}const A=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function R(e,t,n){return e&t^e&n^t&n}class O{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=l(this.buffer)}update(e){a(this),i(e);const{view:t,buffer:n,blockLen:r}=this,o=e.length;for(let i=0;i<o;){const s=Math.min(r-this.pos,o-i);if(s!==r)n.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===r&&(this.process(t,0),this.pos=0);else{const t=l(e);for(;r<=o-i;i+=r)this.process(t,i)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){a(this),function(e,t){i(e,void 0,"digestInto() output");const n=t.outputLen;if(e.length<n)throw new Error('"digestInto() output" expected to be of length >='+n)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:o}=this;let{pos:s}=this;t[s++]=128,c(this.buffer.subarray(s)),this.padOffset>r-s&&(this.process(n,0),s=0);for(let e=s;e<r;e++)t[e]=0;n.setBigUint64(r-8,BigInt(8*this.length),o),this.process(n,0);const u=l(e),d=this.outputLen;if(d%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const h=d/4,f=this.get();if(h>f.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<h;e++)u.setUint32(4*e,f[e],o)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:o,destroyed:i,pos:s}=this;return e.destroyed=i,e.finished=o,e.length=r,e.pos=s,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const I=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);const B=Uint32Array.from([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]),T=new Uint32Array(64);class L extends O{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:t,C:n,D:r,E:o,F:i,G:s,H:a}=this;return[e,t,n,r,o,i,s,a]}set(e,t,n,r,o,i,s,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|o,this.F=0|i,this.G=0|s,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)T[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=T[e-15],n=T[e-2],r=u(t,7)^u(t,18)^t>>>3,o=u(n,17)^u(n,19)^n>>>10;T[e]=o+T[e-7]+r+T[e-16]|0}let{A:n,B:r,C:o,D:i,E:s,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(u(s,6)^u(s,11)^u(s,25))+((d=s)&a^~d&c)+B[e]+T[e]|0,h=(u(n,2)^u(n,13)^u(n,22))+R(n,r,o)|0;l=c,c=a,a=s,s=i+t|0,i=o,o=r,r=n,n=t+h|0}var d;n=n+this.A|0,r=r+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,o,i,s,a,c,l)}roundClean(){c(T)}destroy(){this.set(0,0,0,0,0,0,0,0),c(this.buffer)}}class P extends L{A=0|I[0];B=0|I[1];C=0|I[2];D=0|I[3];E=0|I[4];F=0|I[5];G=0|I[6];H=0|I[7];constructor(){super(32)}}const _=S((()=>new P),A(1)),U=BigInt(0),N=BigInt(1);function C(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}" `)+"expected boolean, got type="+typeof e)}return e}function $(e){if("bigint"==typeof e){if(!W(e))throw new Error("positive bigint expected, got "+e)}else o(e);return e}function M(e){const t=$(e).toString(16);return 1&t.length?"0"+t:t}function F(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?U:BigInt("0x"+e)}function D(e){return F(f(e))}function H(e){return F(f(function(e){return Uint8Array.from(e)}(i(e)).reverse()))}function q(e,t){o(t);const n=E((e=$(e)).toString(16).padStart(2*t,"0"));if(n.length!==t)throw new Error("number too large");return n}function j(e,t){return q(e,t).reverse()}function V(e){return Uint8Array.from(e,((t,n)=>{const r=t.charCodeAt(0);if(1!==t.length||r>127)throw new Error(`string contains non-ASCII character "${e[n]}" with code ${r} at position ${n}`);return r}))}const W=e=>"bigint"==typeof e&&U<=e;function z(e,t,n,r){if(!function(e,t,n){return W(e)&&W(t)&&W(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}const K=e=>(N<<BigInt(e))-N;function G(e,t={},n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");const r=(t,n)=>Object.entries(t).forEach((([t,r])=>function(t,n,r){const o=e[t];if(r&&void 0===o)return;const i=typeof o;if(i!==n||null===o)throw new Error(`param "${t}" is invalid: expected ${n}, got ${i}`)}(t,r,n)));r(t,!1),r(n,!0)}function Z(e){const t=new WeakMap;return(n,...r)=>{const o=t.get(n);if(void 0!==o)return o;const i=e(n,...r);return t.set(n,i),i}}const J=BigInt(0),X=BigInt(1),Y=BigInt(2),Q=BigInt(3),ee=BigInt(4),te=BigInt(5),ne=BigInt(7),re=BigInt(8),oe=BigInt(9),ie=BigInt(16);function se(e,t){const n=e%t;return n>=J?n:t+n}function ae(e,t,n){let r=e;for(;t-- >J;)r*=r,r%=n;return r}function ce(e,t){if(e===J)throw new Error("invert: expected non-zero number");if(t<=J)throw new Error("invert: expected positive modulus, got "+t);let n=se(e,t),r=t,o=J,i=X,s=X,a=J;for(;n!==J;){const e=r/n,t=r%n,c=o-s*e,l=i-a*e;r=n,n=t,o=s,i=a,s=c,a=l}if(r!==X)throw new Error("invert: does not exist");return se(o,t)}function le(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function ue(e,t){const n=(e.ORDER+X)/ee,r=e.pow(t,n);return le(e,r,t),r}function de(e,t){const n=(e.ORDER-te)/re,r=e.mul(t,Y),o=e.pow(r,n),i=e.mul(t,o),s=e.mul(e.mul(i,Y),o),a=e.mul(i,e.sub(s,e.ONE));return le(e,a,t),a}function he(e){if(e<Q)throw new Error("sqrt is not defined for small field");let t=e-X,n=0;for(;t%Y===J;)t/=Y,n++;let r=Y;const o=be(e);for(;1===we(o,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return ue;let i=o.pow(r,t);const s=(t+X)/Y;return function(e,r){if(e.is0(r))return r;if(1!==we(e,r))throw new Error("Cannot find square root");let o=n,a=e.mul(e.ONE,i),c=e.pow(r,t),l=e.pow(r,s);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===o)throw new Error("Cannot find square root");const r=X<<BigInt(o-t-1),i=e.pow(a,r);o=t,a=e.sqr(i),c=e.mul(c,a),l=e.mul(l,i)}return l}}function fe(e){return e%ee===Q?ue:e%re===te?de:e%ie===oe?function(e){const t=be(e),n=he(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+ne)/ie;return(e,t)=>{let n=e.pow(t,s),a=e.mul(n,r);const c=e.mul(n,o),l=e.mul(n,i),u=e.eql(e.sqr(a),t),d=e.eql(e.sqr(c),t);n=e.cmov(n,a,u),a=e.cmov(l,c,d);const h=e.eql(e.sqr(a),t),f=e.cmov(n,a,h);return le(e,f,t),f}}(e):he(e)}const pe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ge(e,t,n){if(n<J)throw new Error("invalid exponent, negatives unsupported");if(n===J)return e.ONE;if(n===X)return t;let r=e.ONE,o=t;for(;n>J;)n&X&&(r=e.mul(r,o)),o=e.sqr(o),n>>=X;return r}function ye(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),o=t.reduce(((t,n,o)=>e.is0(n)?t:(r[o]=t,e.mul(t,n))),e.ONE),i=e.inv(o);return t.reduceRight(((t,n,o)=>e.is0(n)?t:(r[o]=e.mul(t,r[o]),e.mul(t,n))),i),r}function we(e,t){const n=(e.ORDER-X)/Y,r=e.pow(t,n),o=e.eql(r,e.ONE),i=e.eql(r,e.ZERO),s=e.eql(r,e.neg(e.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}class me{ORDER;BITS;BYTES;isLE;ZERO=J;ONE=X;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=J)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,null!=t&&"object"==typeof t&&("number"==typeof t.BITS&&(n=t.BITS),"function"==typeof t.sqrt&&(this.sqrt=t.sqrt),"boolean"==typeof t.isLE&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),"boolean"==typeof t.modFromBytes&&(this._mod=t.modFromBytes));const{nBitLength:r,nByteLength:i}=function(e,t){void 0!==t&&o(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}(e,n);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=r,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return se(e,this.ORDER)}isValid(e){if("bigint"!=typeof e)throw new Error("invalid field element: expected bigint, got "+typeof e);return J<=e&&e<this.ORDER}is0(e){return e===J}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&X)===X}neg(e){return se(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return se(e*e,this.ORDER)}add(e,t){return se(e+t,this.ORDER)}sub(e,t){return se(e-t,this.ORDER)}mul(e,t){return se(e*t,this.ORDER)}pow(e,t){return ge(this,e,t)}div(e,t){return se(e*ce(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return ce(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=fe(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?j(e,this.BYTES):q(e,this.BYTES)}fromBytes(e,t=!1){i(e);const{_lengths:n,BYTES:r,isLE:o,ORDER:s,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>r)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);const t=new Uint8Array(r);t.set(e,o?0:t.length-e.length),e=t}if(e.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=o?H(e):D(e);if(a&&(c=se(c,s)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return ye(this,e)}cmov(e,t,n){return n?t:e}}function be(e,t={}){return new me(e,t)}function ve(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Ee(e){const t=ve(e);return t+Math.ceil(t/2)}function xe(e,t,n=!1){i(e);const r=e.length,o=ve(t),s=Ee(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const a=se(n?H(e):D(e),t-X)+X;return n?j(a,o):q(a,o)}const Se=BigInt(0),ke=BigInt(1);function Ae(e,t){const n=t.negate();return e?n:t}function Re(e,t){const n=ye(e.Fp,t.map((e=>e.Z)));return t.map(((t,r)=>e.fromAffine(t.toAffine(n[r]))))}function Oe(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Ie(e,t){Oe(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:K(e),maxNumber:n,shiftBy:BigInt(e)}}function Be(e,t,n){const{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n;let a=Number(e&o),c=e>>s;a>r&&(a-=i,c+=ke);const l=t*r;return{nextN:c,offset:l+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:l}}const Te=new WeakMap,Le=new WeakMap;function Pe(e){return Le.get(e)||1}function _e(e){if(e!==Se)throw new Error("invalid wNAF")}class Ue{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>Se;)t&ke&&(n=n.add(r)),r=r.double(),t>>=ke;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=Ie(t,this.bits),o=[];let i=e,s=i;for(let e=0;e<n;e++){s=i,o.push(s);for(let e=1;e<r;e++)s=s.add(i),o.push(s);i=s.double()}return o}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,o=this.BASE;const i=Ie(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:s,offset:a,isZero:c,isNeg:l,isNegF:u,offsetF:d}=Be(n,e,i);n=s,c?o=o.add(Ae(u,t[d])):r=r.add(Ae(l,t[a]))}return _e(n),{p:r,f:o}}wNAFUnsafe(e,t,n,r=this.ZERO){const o=Ie(e,this.bits);for(let e=0;e<o.windows&&n!==Se;e++){const{nextN:i,offset:s,isZero:a,isNeg:c}=Be(n,e,o);if(n=i,!a){const e=t[s];r=r.add(c?e.negate():e)}}return _e(n),r}getPrecomputes(e,t,n){let r=Te.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),Te.set(t,r))),r}cached(e,t,n){const r=Pe(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const o=Pe(e);return 1===o?this._unsafeLadder(e,t,r):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,r)}createCache(e,t){Oe(t,this.bits),Le.set(e,t),Te.delete(e)}hasCache(e){return 1!==Pe(e)}}function Ne(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){G(e,pe.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return be(e,{isLE:n})}function Ce(e,t){return function(n){const r=e(n);return{secretKey:r,publicKey:t(r)}}}V("HashToScalar-");class $e{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(s(e),i(t,void 0,"key"),this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),c(r)}update(e){return a(this),this.iHash.update(e),this}digestInto(e){a(this),i(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});const{oHash:t,iHash:n,finished:r,destroyed:o,blockLen:i,outputLen:s}=this;return e.finished=r,e.destroyed=o,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Me=(e,t,n)=>new $e(e,t).update(n).digest();Me.create=(e,t)=>new $e(e,t);const Fe=(e,t)=>(e+(e>=0?t:-t)/Ke)/t;function De(e,t,n){const[[r,o],[i,s]]=t,a=Fe(s*e,n),c=Fe(-o*e,n);let l=e-a*r-c*i,u=-a*o-c*s;const d=l<We,h=u<We;d&&(l=-l),h&&(u=-u);const f=K(Math.ceil(function(e){let t;for(t=0;e>U;e>>=N,t+=1);return t}(n)/2))+ze;if(l<We||l>=f||u<We||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:l,k2neg:h,k2:u}}function He(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function qe(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return C(n.lowS,"lowS"),C(n.prehash,"prehash"),void 0!==n.format&&He(n.format),n}class je extends Error{constructor(e=""){super(e)}}const Ve={Err:je,_tlv:{encode:(e,t)=>{const{Err:n}=Ve;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(1&t.length)throw new n("tlv.encode: unpadded data");const r=t.length/2,o=M(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?M(o.length/2|128):"";return M(e)+i+o+t},decode(e,t){const{Err:n}=Ve;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const o=t[r++];let i=0;if(!!(128&o)){const e=127&o;if(!e)throw new n("tlv.decode(long): indefinite length not supported");if(e>4)throw new n("tlv.decode(long): byte length is too big");const s=t.subarray(r,r+e);if(s.length!==e)throw new n("tlv.decode: length bytes not complete");if(0===s[0])throw new n("tlv.decode(long): zero leftmost byte");for(const e of s)i=i<<8|e;if(r+=e,i<128)throw new n("tlv.decode(long): not minimal encoding")}else i=o;const s=t.subarray(r,r+i);if(s.length!==i)throw new n("tlv.decode: wrong value length");return{v:s,l:t.subarray(r+i)}}},_int:{encode(e){const{Err:t}=Ve;if(e<We)throw new t("integer: negative integers are not allowed");let n=M(e);if(8&Number.parseInt(n[0],16)&&(n="00"+n),1&n.length)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=Ve;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return D(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=Ve,o=i(e,void 0,"signature"),{v:s,l:a}=r.decode(48,o);if(a.length)throw new t("invalid signature: left bytes after parsing");const{v:c,l}=r.decode(2,s),{v:u,l:d}=r.decode(2,l);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(c),s:n.decode(u)}},hexFromSig(e){const{_tlv:t,_int:n}=Ve,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},We=BigInt(0),ze=BigInt(1),Ke=BigInt(2),Ge=BigInt(3),Ze=BigInt(4);function Je(e,t={}){const n=function(e,t,n={},r){if(void 0===r&&(r="edwards"===e),!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const n=t[e];if(!("bigint"==typeof n&&n>Se))throw new Error(`CURVE.${e} must be positive bigint`)}const o=Ne(t.p,n.Fp,r),i=Ne(t.n,n.Fn,r),s=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of s)if(!o.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:o,Fn:i}}("weierstrass",e,t),{Fp:r,Fn:o}=n;let s=n.CURVE;const{h:a,n:c}=s;G(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:l}=t;if(l&&(!r.is0(s.a)||"bigint"!=typeof l.beta||!Array.isArray(l.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=Ye(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const h=t.toBytes||function(e,t,n){const{x:o,y:i}=t.toAffine(),s=r.toBytes(o);if(C(n,"isCompressed"),n){d();return x(Xe(!r.isOdd(i)),s)}return x(Uint8Array.of(4),s,r.toBytes(i))},p=t.fromBytes||function(e){i(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=u,o=e.length,s=e[0],a=e.subarray(1);if(o!==t||2!==s&&3!==s){if(o===n&&4===s){const e=r.BYTES,t=r.fromBytes(a.subarray(0,e)),n=r.fromBytes(a.subarray(e,2*e));if(!y(t,n))throw new Error("bad point: is not on curve");return{x:t,y:n}}throw new Error(`bad point: got length ${o}, expected compressed=${t} or uncompressed=${n}`)}{const e=r.fromBytes(a);if(!r.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=g(e);let n;try{n=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("bad point: is not on curve, sqrt error"+t)}d();return!(1&~s)!==r.isOdd(n)&&(n=r.neg(n)),{x:e,y:n}}};function g(e){const t=r.sqr(e),n=r.mul(t,e);return r.add(r.add(n,r.mul(e,s.a)),s.b)}function y(e,t){const n=r.sqr(t),o=g(e);return r.eql(n,o)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const w=r.mul(r.pow(s.a,Ge),Ze),m=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(w,m)))throw new Error("bad curve params: a or b");function b(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function v(e){if(!(e instanceof O))throw new Error("Weierstrass Point expected")}function S(e){if(!l||!l.basises)throw new Error("no endo");return De(e,l.basises,o.ORDER)}const k=Z(((e,t)=>{const{X:n,Y:o,Z:i}=e;if(r.eql(i,r.ONE))return{x:n,y:o};const s=e.is0();null==t&&(t=s?r.ONE:r.inv(i));const a=r.mul(n,t),c=r.mul(o,t),l=r.mul(i,t);if(s)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw new Error("invZ was invalid");return{x:a,y:c}})),A=Z((e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:n,y:o}=e.toAffine();if(!r.isValid(n)||!r.isValid(o))throw new Error("bad point: x or y not field elements");if(!y(n,o))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0}));function R(e,t,n,o,i){return n=new O(r.mul(n.X,e),n.Y,n.Z),t=Ae(o,t),n=Ae(i,n),t.add(n)}class O{static BASE=new O(s.Gx,s.Gy,r.ONE);static ZERO=new O(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=o;X;Y;Z;constructor(e,t,n){this.X=b("x",e),this.Y=b("y",t,!0),this.Z=b("z",n),Object.freeze(this)}static CURVE(){return s}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw new Error("invalid affine point");if(e instanceof O)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?O.ZERO:new O(t,n,r.ONE)}static fromBytes(e){const t=O.fromAffine(p(i(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return O.fromBytes(E(e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return B.createCache(this,e),t||this.multiply(Ge),this}assertValidity(){A(this)}hasEvenY(){const{y:e}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(e)}equals(e){v(e);const{X:t,Y:n,Z:o}=this,{X:i,Y:s,Z:a}=e,c=r.eql(r.mul(t,a),r.mul(i,o)),l=r.eql(r.mul(n,a),r.mul(s,o));return c&&l}negate(){return new O(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=s,n=r.mul(t,Ge),{X:o,Y:i,Z:a}=this;let c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(o,o),h=r.mul(i,i),f=r.mul(a,a),p=r.mul(o,i);return p=r.add(p,p),u=r.mul(o,a),u=r.add(u,u),c=r.mul(e,u),l=r.mul(n,f),l=r.add(c,l),c=r.sub(h,l),l=r.add(h,l),l=r.mul(c,l),c=r.mul(p,c),u=r.mul(n,u),f=r.mul(e,f),p=r.sub(d,f),p=r.mul(e,p),p=r.add(p,u),u=r.add(d,d),d=r.add(u,d),d=r.add(d,f),d=r.mul(d,p),l=r.add(l,d),f=r.mul(i,a),f=r.add(f,f),d=r.mul(f,p),c=r.sub(c,d),u=r.mul(f,h),u=r.add(u,u),u=r.add(u,u),new O(c,l,u)}add(e){v(e);const{X:t,Y:n,Z:o}=this,{X:i,Y:a,Z:c}=e;let l=r.ZERO,u=r.ZERO,d=r.ZERO;const h=s.a,f=r.mul(s.b,Ge);let p=r.mul(t,i),g=r.mul(n,a),y=r.mul(o,c),w=r.add(t,n),m=r.add(i,a);w=r.mul(w,m),m=r.add(p,g),w=r.sub(w,m),m=r.add(t,o);let b=r.add(i,c);return m=r.mul(m,b),b=r.add(p,y),m=r.sub(m,b),b=r.add(n,o),l=r.add(a,c),b=r.mul(b,l),l=r.add(g,y),b=r.sub(b,l),d=r.mul(h,m),l=r.mul(f,y),d=r.add(l,d),l=r.sub(g,d),d=r.add(g,d),u=r.mul(l,d),g=r.add(p,p),g=r.add(g,p),y=r.mul(h,y),m=r.mul(f,m),g=r.add(g,y),y=r.sub(p,y),y=r.mul(h,y),m=r.add(m,y),p=r.mul(g,m),u=r.add(u,p),p=r.mul(b,m),l=r.mul(w,l),l=r.sub(l,p),p=r.mul(w,g),d=r.mul(b,d),d=r.add(d,p),new O(l,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(O.ZERO)}multiply(e){const{endo:n}=t;if(!o.isValidNot0(e))throw new Error("invalid scalar: out of range");let r,i;const s=e=>B.cached(this,e,(e=>Re(O,e)));if(n){const{k1neg:t,k1:o,k2neg:a,k2:c}=S(e),{p:l,f:u}=s(o),{p:d,f:h}=s(c);i=u.add(h),r=R(n.beta,l,d,t,a)}else{const{p:t,f:n}=s(e);r=t,i=n}return Re(O,[r,i])[0]}multiplyUnsafe(e){const{endo:n}=t,r=this;if(!o.isValid(e))throw new Error("invalid scalar: out of range");if(e===We||r.is0())return O.ZERO;if(e===ze)return r;if(B.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:o,k2neg:i,k2:s}=S(e),{p1:a,p2:c}=function(e,t,n,r){let o=t,i=e.ZERO,s=e.ZERO;for(;n>Se||r>Se;)n&ke&&(i=i.add(o)),r&ke&&(s=s.add(o)),o=o.double(),n>>=ke,r>>=ke;return{p1:i,p2:s}}(O,r,o,s);return R(n.beta,a,c,t,i)}return B.unsafe(r,e)}toAffine(e){return k(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return a===ze||(e?e(O,this):B.unsafe(this,c).is0())}clearCofactor(){const{clearCofactor:e}=t;return a===ze?this:e?e(O,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(e=!0){return C(e,"isCompressed"),this.assertValidity(),h(O,this,e)}toHex(e=!0){return f(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const I=o.BITS,B=new Ue(O,t.endo?Math.ceil(I/2):I);return O.BASE.precompute(8),O}function Xe(e){return Uint8Array.of(e?2:3)}function Ye(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Qe(e,t,n={}){s(t),G(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const a=(n=Object.assign({},n)).randomBytes||k,c=n.hmac||((e,n)=>Me(t,e,n)),{Fp:l,Fn:u}=e,{ORDER:d,BITS:h}=u,{keygen:p,getPublicKey:g,getSharedSecret:y,utils:w,lengths:m}=function(e,t={}){const{Fn:n}=e,o=t.randomBytes||k,s=Object.assign(Ye(e.Fp,n),{seed:Ee(n.ORDER)});function a(e=o(s.seed)){return xe(i(e,s.seed,"seed"),n.ORDER)}function c(t,r=!0){return e.BASE.multiply(n.fromBytes(t)).toBytes(r)}function l(e){const{secretKey:t,publicKey:o,publicKeyUncompressed:a}=s;if(!r(e))return;if("_lengths"in n&&n._lengths||t===o)return;const c=i(e,void 0,"key").length;return c===o||c===a}const u={isValidSecretKey:function(e){try{const t=n.fromBytes(e);return n.isValidNot0(t)}catch(e){return!1}},isValidPublicKey:function(t,n){const{publicKey:r,publicKeyUncompressed:o}=s;try{const i=t.length;return!(!0===n&&i!==r||!1===n&&i!==o||!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:a},d=Ce(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:function(t,r,o=!0){if(!0===l(t))throw new Error("first arg must be private key");if(!1===l(r))throw new Error("second arg must be public key");const i=n.fromBytes(t);return e.fromBytes(r).multiply(i).toBytes(o)},keygen:d,Point:e,utils:u,lengths:s})}(e,n),b={prehash:!0,lowS:"boolean"!=typeof n.lowS||n.lowS,format:"compact",extraEntropy:!1},v=d*Ke<l.ORDER;function S(e){return e>d>>ze}function A(e,t){if(!u.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}function R(){if(v)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function O(e,t){He(t);const n=m.signature;return i(e,"compact"===t?n:"recovered"===t?n+1:void 0)}class I{r;s;recovery;constructor(e,t,n){if(this.r=A("r",e),this.s=A("s",t),null!=n){if(R(),![0,1,2,3].includes(n))throw new Error("invalid recovery id");this.recovery=n}Object.freeze(this)}static fromBytes(e,t=b.format){let n;if(O(e,t),"der"===t){const{r:t,s:n}=Ve.toSig(i(e));return new I(t,n)}"recovered"===t&&(n=e[0],t="compact",e=e.subarray(1));const r=m.signature/2,o=e.subarray(0,r),s=e.subarray(r,2*r);return new I(u.fromBytes(o),u.fromBytes(s),n)}static fromHex(e,t){return this.fromBytes(E(e),t)}assertRecovery(){const{recovery:e}=this;if(null==e)throw new Error("invalid recovery id: must be present");return e}addRecoveryBit(e){return new I(this.r,this.s,e)}recoverPublicKey(t){const{r:n,s:r}=this,o=this.assertRecovery(),s=2===o||3===o?n+d:n;if(!l.isValid(s))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const a=l.toBytes(s),c=e.fromBytes(x(Xe(!(1&o)),a)),h=u.inv(s),f=T(i(t,void 0,"msgHash")),p=u.create(-f*h),g=u.create(r*h),y=e.BASE.multiplyUnsafe(p).add(c.multiplyUnsafe(g));if(y.is0())throw new Error("invalid recovery: point at infinify");return y.assertValidity(),y}hasHighS(){return S(this.s)}toBytes(e=b.format){if(He(e),"der"===e)return E(Ve.hexFromSig(this));const{r:t,s:n}=this,r=u.toBytes(t),o=u.toBytes(n);return"recovered"===e?(R(),x(Uint8Array.of(this.assertRecovery()),r,o)):x(r,o)}toHex(e){return f(this.toBytes(e))}}const B=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=D(e),n=8*e.length-h;return n>0?t>>BigInt(n):t},T=n.bits2int_modN||function(e){return u.create(B(e))},L=K(h);function P(e){return z("num < 2^"+h,e,We,L),u.toBytes(e)}function _(e,n){return i(e,void 0,"message"),n?i(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:p,getPublicKey:g,getSharedSecret:y,utils:w,lengths:m,Point:e,sign:function(n,r,s={}){const{seed:l,k2sig:d}=function(t,n,r){const{lowS:o,prehash:s,extraEntropy:c}=qe(r,b);t=_(t,s);const l=T(t),d=u.fromBytes(n);if(!u.isValidNot0(d))throw new Error("invalid private key");const h=[P(d),P(l)];if(null!=c&&!1!==c){const e=!0===c?a(m.secretKey):c;h.push(i(e,void 0,"extraEntropy"))}const f=x(...h),p=l;return{seed:f,k2sig:function(t){const n=B(t);if(!u.isValidNot0(n))return;const r=u.inv(n),i=e.BASE.multiply(n).toAffine(),s=u.create(i.x);if(s===We)return;const a=u.create(r*u.create(p+s*d));if(a===We)return;let c=(i.x===s?0:2)|Number(i.y&ze),l=a;return o&&S(a)&&(l=u.neg(a),c^=1),new I(s,l,v?void 0:c)}}}(n,r,s),h=function(e,t,n){if(o(e,"hashLen"),o(t,"qByteLen"),"function"!=typeof n)throw new Error("hmacFn must be a function");const r=e=>new Uint8Array(e),i=Uint8Array.of(),s=Uint8Array.of(0),a=Uint8Array.of(1);let c=r(e),l=r(e),u=0;const d=()=>{c.fill(1),l.fill(0),u=0},h=(...e)=>n(l,x(c,...e)),f=(e=i)=>{l=h(s,e),c=h(),0!==e.length&&(l=h(a,e),c=h())},p=()=>{if(u++>=1e3)throw new Error("drbg: tried max amount of iterations");let e=0;const n=[];for(;e<t;){c=h();const t=c.slice();n.push(t),e+=c.length}return x(...n)};return(e,t)=>{let n;for(d(),f(e);!(n=t(p()));)f();return d(),n}}(t.outputLen,u.BYTES,c);return h(l,d).toBytes(s.format)},verify:function(t,n,o,s={}){const{lowS:a,prehash:c,format:l}=qe(s,b);if(o=i(o,void 0,"publicKey"),n=_(n,c),!r(t)){throw new Error("verify expects Uint8Array signature"+(t instanceof I?", use sig.toBytes()":""))}O(t,l);try{const r=I.fromBytes(t,l),i=e.fromBytes(o);if(a&&r.hasHighS())return!1;const{r:s,s:c}=r,d=T(n),h=u.inv(c),f=u.create(d*h),p=u.create(s*h),g=e.BASE.multiplyUnsafe(f).add(i.multiplyUnsafe(p));if(g.is0())return!1;return u.create(g.x)===s}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:r}=qe(n,b);return t=_(t,r),I.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:I,hash:t})}const et={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},tt={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},nt=BigInt(0),rt=BigInt(2);const ot=be(et.p,{sqrt:function(e){const t=et.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=ae(u,n,t)*u%t,h=ae(d,n,t)*u%t,f=ae(h,rt,t)*l%t,p=ae(f,o,t)*f%t,g=ae(p,i,t)*p%t,y=ae(g,a,t)*g%t,w=ae(y,c,t)*y%t,m=ae(w,a,t)*g%t,b=ae(m,n,t)*u%t,v=ae(b,s,t)*p%t,E=ae(v,r,t)*l%t,x=ae(E,rt,t);if(!ot.eql(ot.sqr(x),e))throw new Error("Cannot find square root");return x}}),it=Je(et,{Fp:ot,endo:tt}),st=Qe(it,_),at={};function ct(e,...t){let n=at[e];if(void 0===n){const t=_(V(e));n=x(t,t),at[e]=n}return _(x(n,...t))}const lt=e=>e.toBytes(!0).slice(1),ut=e=>e%rt===nt;function dt(e){const{Fn:t,BASE:n}=it,r=t.fromBytes(e),o=n.multiply(r);return{scalar:ut(o.y)?r:t.neg(r),bytes:lt(o)}}function ht(e){const t=ot;if(!t.isValidNot0(e))throw new Error("invalid x: Fail if x ≥ p");const n=t.create(e*e),r=t.create(n*e+BigInt(7));let o=t.sqrt(r);ut(o)||(o=t.neg(o));const i=it.fromAffine({x:e,y:o});return i.assertValidity(),i}const ft=D;function pt(...e){return it.Fn.create(ft(ct("BIP0340/challenge",...e)))}function gt(e){return dt(e).bytes}function yt(e,t,n=k(32)){const{Fn:r}=it,o=i(e,void 0,"message"),{bytes:s,scalar:a}=dt(t),c=i(n,32,"auxRand"),l=r.toBytes(a^ft(ct("BIP0340/aux",c))),u=ct("BIP0340/nonce",l,s,o),{bytes:d,scalar:h}=dt(u),f=pt(d,s,o),p=new Uint8Array(64);if(p.set(d,0),p.set(r.toBytes(r.create(h+f*a)),32),!wt(p,o,s))throw new Error("sign: Invalid signature produced");return p}function wt(e,t,n){const{Fp:r,Fn:o,BASE:s}=it,a=i(e,64,"signature"),c=i(t,void 0,"message"),l=i(n,32,"publicKey");try{const e=ht(ft(l)),t=ft(a.subarray(0,32));if(!r.isValidNot0(t))return!1;const n=ft(a.subarray(32,64));if(!o.isValidNot0(n))return!1;const i=pt(o.toBytes(t),lt(e),c),u=s.multiplyUnsafe(n).add(e.multiplyUnsafe(o.neg(i))),{x:d,y:h}=u.toAffine();return!(u.is0()||!ut(h)||d!==t)}catch(e){return!1}}const mt=(()=>{const e=(e=k(48))=>xe(e,et.n);return{keygen:Ce(e,gt),getPublicKey:gt,sign:yt,verify:wt,Point:it,utils:{randomSecretKey:e,taggedHash:ct,lift_x:ht,pointToBytes:lt},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();function bt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function vt(e){if(!bt(e))throw new Error("Uint8Array expected")}function Et(e,t){return!!Array.isArray(t)&&(0===t.length||(e?t.every((e=>"string"==typeof e)):t.every((e=>Number.isSafeInteger(e)))))}function xt(e){if("function"!=typeof e)throw new Error("function expected");return!0}function St(e,t){if("string"!=typeof t)throw new Error(`${e}: string expected`);return!0}function kt(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function At(e){if(!Array.isArray(e))throw new Error("array expected")}function Rt(e,t){if(!Et(!0,t))throw new Error(`${e}: array of strings expected`)}function Ot(e,t){if(!Et(!1,t))throw new Error(`${e}: array of numbers expected`)}function It(...e){const t=e=>e,n=(e,t)=>n=>e(t(n));return{encode:e.map((e=>e.encode)).reduceRight(n,t),decode:e.map((e=>e.decode)).reduce(n,t)}}function Bt(e){const t="string"==typeof e?e.split(""):e,n=t.length;Rt("alphabet",t);const r=new Map(t.map(((e,t)=>[e,t])));return{encode:r=>(At(r),r.map((r=>{if(!Number.isSafeInteger(r)||r<0||r>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${r}". Allowed: ${e}`);return t[r]}))),decode:t=>(At(t),t.map((t=>{St("alphabet.decode",t);const n=r.get(t);if(void 0===n)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return n})))}}function Tt(e=""){return St("join",e),{encode:t=>(Rt("join.decode",t),t.join(e)),decode:t=>(St("join.decode",t),t.split(e))}}function Lt(e,t="="){return kt(e),St("padding",t),{encode(n){for(Rt("padding.encode",n);n.length*e%8;)n.push(t);return n},decode(n){Rt("padding.decode",n);let r=n.length;if(r*e%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===t;r--){if((r-1)*e%8==0)throw new Error("padding: invalid, string has too much padding")}return n.slice(0,r)}}}function Pt(e){return xt(e),{encode:e=>e,decode:t=>e(t)}}function _t(e,t,n){if(t<2)throw new Error(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: invalid to=${n}, base cannot be less than 2`);if(At(e),!e.length)return[];let r=0;const o=[],i=Array.from(e,(e=>{if(kt(e),e<0||e>=t)throw new Error(`invalid integer: ${e}`);return e})),s=i.length;for(;;){let e=0,a=!0;for(let o=r;o<s;o++){const s=i[o],c=t*e,l=c+s;if(!Number.isSafeInteger(l)||c/t!==e||l-s!==c)throw new Error("convertRadix: carry overflow");const u=l/n;e=l%n;const d=Math.floor(u);if(i[o]=d,!Number.isSafeInteger(d)||d*n+e!==l)throw new Error("convertRadix: carry overflow");a&&(d?a=!1:r=o)}if(o.push(e),a)break}for(let t=0;t<e.length-1&&0===e[t];t++)o.push(0);return o.reverse()}const Ut=(e,t)=>0===t?e:Ut(t,e%t),Nt=(e,t)=>e+(t-Ut(e,t)),Ct=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function $t(e,t,n,r){if(At(e),t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(Nt(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${Nt(t,n)}`);let o=0,i=0;const s=Ct[t],a=Ct[n]-1,c=[];for(const r of e){if(kt(r),r>=s)throw new Error(`convertRadix2: invalid data word=${r} from=${t}`);if(o=o<<t|r,i+t>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${t}`);for(i+=t;i>=n;i-=n)c.push((o>>i-n&a)>>>0);const e=Ct[i];if(void 0===e)throw new Error("invalid carry");o&=e-1}if(o=o<<n-i&a,!r&&i>=t)throw new Error("Excess padding");if(!r&&o>0)throw new Error(`Non-zero padding: ${o}`);return r&&i>0&&c.push(o>>>0),c}function Mt(e){kt(e);return{encode:t=>{if(!bt(t))throw new Error("radix.encode input should be Uint8Array");return _t(Array.from(t),256,e)},decode:t=>(Ot("radix.decode",t),Uint8Array.from(_t(t,e,256)))}}function Ft(e,t=!1){if(kt(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(Nt(8,e)>32||Nt(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!bt(n))throw new Error("radix2.encode input should be Uint8Array");return $t(Array.from(n),8,e,!t)},decode:n=>(Ot("radix2.decode",n),Uint8Array.from($t(n,e,8,t)))}}function Dt(e){return xt(e),function(...t){try{return e.apply(null,t)}catch(e){}}}const Ht=It(Ft(4),Bt("0123456789ABCDEF"),Tt("")),qt=It(Ft(5),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Lt(5),Tt("")),jt=(It(Ft(5),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Tt("")),It(Ft(5),Bt("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Lt(5),Tt("")),It(Ft(5),Bt("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Tt("")),It(Ft(5),Bt("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),Tt(""),Pt((e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")))),(()=>"function"==typeof Uint8Array.from([]).toBase64&&"function"==typeof Uint8Array.fromBase64)()),Vt=(e,t)=>{St("base64",e);const n=t?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,r=t?"base64url":"base64";if(e.length>0&&!n.test(e))throw new Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:r,lastChunkHandling:"strict"})},Wt=jt?{encode:e=>(vt(e),e.toBase64()),decode:e=>Vt(e,!1)}:It(Ft(6),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Lt(6),Tt("")),zt=(It(Ft(6),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Tt("")),jt?{encode:e=>(vt(e),e.toBase64({alphabet:"base64url"})),decode:e=>Vt(e,!0)}:It(Ft(6),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Lt(6),Tt(""))),Kt=(It(Ft(6),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Tt("")),e=>It(Mt(58),Bt(e),Tt(""))),Gt=Kt("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),Zt=(Kt("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),Kt("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"),[0,2,3,5,6,7,9,10,11]),Jt={encode(e){let t="";for(let n=0;n<e.length;n+=8){const r=e.subarray(n,n+8);t+=Gt.encode(r).padStart(Zt[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),o=Zt.indexOf(r.length),i=Gt.decode(r);for(let e=0;e<i.length-o;e++)if(0!==i[e])throw new Error("base58xmr: wrong padding");t=t.concat(Array.from(i.slice(i.length-o)))}return Uint8Array.from(t)}},Xt=It(Bt("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Tt("")),Yt=[996825010,642813549,513874426,1027748829,705979059];function Qt(e){const t=e>>25;let n=(33554431&e)<<5;for(let e=0;e<Yt.length;e++)1==(t>>e&1)&&(n^=Yt[e]);return n}function en(e,t,n=1){const r=e.length;let o=1;for(let t=0;t<r;t++){const n=e.charCodeAt(t);if(n<33||n>126)throw new Error(`Invalid prefix (${e})`);o=Qt(o)^n>>5}o=Qt(o);for(let t=0;t<r;t++)o=Qt(o)^31&e.charCodeAt(t);for(let e of t)o=Qt(o)^e;for(let e=0;e<6;e++)o=Qt(o);return o^=n,Xt.encode($t([o%Ct[30]],30,5,!1))}function tn(e){const t="bech32"===e?1:734539939,n=Ft(5),r=n.decode,o=n.encode,i=Dt(r);function s(e,n,r=90){St("bech32.encode prefix",e),bt(n)&&(n=Array.from(n)),Ot("bech32.encode",n);const o=e.length;if(0===o)throw new TypeError(`Invalid prefix length ${o}`);const i=o+7+n.length;if(!1!==r&&i>r)throw new TypeError(`Length ${i} exceeds limit ${r}`);const s=e.toLowerCase(),a=en(s,n,t);return`${s}1${Xt.encode(n)}${a}`}function a(e,n=90){St("bech32.decode input",e);const r=e.length;if(r<8||!1!==n&&r>n)throw new TypeError(`invalid string length: ${r} (${e}). Expected (8..${n})`);const o=e.toLowerCase();if(e!==o&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const i=o.lastIndexOf("1");if(0===i||-1===i)throw new Error('Letter "1" must be present between prefix and data only');const s=o.slice(0,i),a=o.slice(i+1);if(a.length<6)throw new Error("Data must be at least 6 characters long");const c=Xt.decode(a).slice(0,-6),l=en(s,c,t);if(!a.endsWith(l))throw new Error(`Invalid checksum in ${e}: expected "${l}"`);return{prefix:s,words:c}}return{encode:s,decode:a,encodeFromBytes:function(e,t){return s(e,o(t))},decodeToBytes:function(e){const{prefix:t,words:n}=a(e,!1);return{prefix:t,words:n,bytes:r(n)}},decodeUnsafe:Dt(a),fromWords:r,fromWordsUnsafe:i,toWords:o}}const nn=tn("bech32"),rn=(tn("bech32m"),{encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)});(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)()||It(Ft(4),Bt("0123456789abcdef"),Tt(""),Pt((e=>{if("string"!=typeof e||e.length%2!=0)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()})));function on(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function sn(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function an(e,t,n=""){const r=(o=e)instanceof Uint8Array||ArrayBuffer.isView(o)&&"Uint8Array"===o.constructor.name;var o;const i=e?.length,s=void 0!==t;if(!r||s&&i!==t){throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(r?`length=${i}`:"type="+typeof e))}return e}function cn(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 ln(e,t){an(e,void 0,"output");const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function un(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function dn(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function hn(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}const fn=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function pn(e,t){return e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function gn(e,t){if(pn(e,t)&&e.byteOffset<t.byteOffset)throw new Error("complex overlap of input and output is not supported")}function yn(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 0===n}const wn=(e,t)=>{function n(n,...r){if(an(n,void 0,"key"),!fn)throw new Error("Non little-endian hardware is not yet supported");if(void 0!==e.nonceLength){an(r[0],e.varSizeNonce?void 0:e.nonceLength,"nonce")}const o=e.tagLength;o&&void 0!==r[1]&&an(r[1],void 0,"AAD");const i=t(n,...r),s=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");an(t,void 0,"output")}};let a=!1;return{encrypt(e,t){if(a)throw new Error("cannot encrypt() twice with same key + nonce");return a=!0,an(e),s(i.encrypt.length,t),i.encrypt(e,t)},decrypt(e,t){if(an(e),o&&e.length<o)throw new Error('"ciphertext" expected length bigger than tagLength='+o);return s(i.decrypt.length,t),i.decrypt(e,t)}}}return Object.assign(n,e),n};function mn(e,t,n=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw new Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(n&&!vn(t))throw new Error("invalid output, must be aligned");return t}function bn(e,t,n){on(n);const r=new Uint8Array(16),o=hn(r);return o.setBigUint64(0,BigInt(t),n),o.setBigUint64(8,BigInt(e),n),r}function vn(e){return e.byteOffset%4==0}function En(e){return Uint8Array.from(e)}const xn=16,Sn=new Uint8Array(16),kn=un(Sn),An=e=>(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255;class Rn{blockLen=xn;outputLen=xn;s0=0;s1=0;s2=0;s3=0;finished=!1;t;W;windowSize;constructor(e,t){an(e,16,"key");const n=hn(e=En(e));let r=n.getUint32(0,!1),o=n.getUint32(4,!1),i=n.getUint32(8,!1),s=n.getUint32(12,!1);const a=[];for(let e=0;e<128;e++)a.push({s0:An(r),s1:An(o),s2:An(i),s3:An(s)}),({s0:r,s1:o,s2:i,s3:s}={s3:(u=i)<<31|(d=s)>>>1,s2:(l=o)<<31|u>>>1,s1:(c=r)<<31|l>>>1,s0:c>>>1^225<<24&-(1&d)});var c,l,u,d;const h=(e=>e>65536?8:e>1024?4:2)(t||1024);if(![1,2,4,8].includes(h))throw new Error("ghash: invalid window size, expected 2, 4 or 8");this.W=h;const f=128/h,p=this.windowSize=2**h,g=[];for(let e=0;e<f;e++)for(let t=0;t<p;t++){let n=0,r=0,o=0,i=0;for(let s=0;s<h;s++){if(!(t>>>h-s-1&1))continue;const{s0:c,s1:l,s2:u,s3:d}=a[h*e+s];n^=c,r^=l,o^=u,i^=d}g.push({s0:n,s1:r,s2:o,s3:i})}this.t=g}_updateBlock(e,t,n,r){e^=this.s0,t^=this.s1,n^=this.s2,r^=this.s3;const{W:o,t:i,windowSize:s}=this;let a=0,c=0,l=0,u=0;const d=(1<<o)-1;let h=0;for(const f of[e,t,n,r])for(let e=0;e<4;e++){const t=f>>>8*e&255;for(let e=8/o-1;e>=0;e--){const n=t>>>o*e&d,{s0:r,s1:f,s2:p,s3:g}=i[h*s+n];a^=r,c^=f,l^=p,u^=g,h+=1}}this.s0=a,this.s1=c,this.s2=l,this.s3=u}update(e){cn(this),an(e);const t=un(e=En(e)),n=Math.floor(e.length/xn),r=e.length%xn;for(let e=0;e<n;e++)this._updateBlock(t[4*e+0],t[4*e+1],t[4*e+2],t[4*e+3]);return r&&(Sn.set(e.subarray(n*xn)),this._updateBlock(kn[0],kn[1],kn[2],kn[3]),dn(kn)),this}destroy(){const{t:e}=this;for(const t of e)t.s0=0,t.s1=0,t.s2=0,t.s3=0}digestInto(e){cn(this),ln(e,this),this.finished=!0;const{s0:t,s1:n,s2:r,s3:o}=this,i=un(e);return i[0]=t,i[1]=n,i[2]=r,i[3]=o,e}digest(){const e=new Uint8Array(xn);return this.digestInto(e),this.destroy(),e}}class On extends Rn{constructor(e,t){an(e);const n=function(e){e.reverse();const t=1&e[15];let n=0;for(let t=0;t<e.length;t++){const r=e[t];e[t]=r>>>1|n,n=(1&r)<<7}return e[0]^=225&-t,e}(En(e));super(n,t),dn(n)}update(e){cn(this),an(e);const t=un(e=En(e)),n=e.length%xn,r=Math.floor(e.length/xn);for(let e=0;e<r;e++)this._updateBlock(An(t[4*e+3]),An(t[4*e+2]),An(t[4*e+1]),An(t[4*e+0]));return n&&(Sn.set(e.subarray(r*xn)),this._updateBlock(An(kn[3]),An(kn[2]),An(kn[1]),An(kn[0])),dn(kn)),this}digestInto(e){cn(this),ln(e,this),this.finished=!0;const{s0:t,s1:n,s2:r,s3:o}=this,i=un(e);return i[0]=t,i[1]=n,i[2]=r,i[3]=o,e.reverse()}}function In(e){const t=(t,n)=>e(n,t.length).update(t).digest(),n=e(new Uint8Array(16),0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=(t,n)=>e(t,n),t}In(((e,t)=>new Rn(e,t))),In(((e,t)=>new On(e,t)));const Bn=16;function Tn(e){if(![16,24,32].includes(e.length))throw new Error('"aes key" expected Uint8Array of length 16/24/32, got length='+e.length)}function Ln(e){return e<<1^283&-(e>>7)}function Pn(e,t){let n=0;for(;t>0;t>>=1)n^=e&-(1&t),e=Ln(e);return n}const _n=(()=>{const e=new Uint8Array(256);for(let t=0,n=1;t<256;t++,n^=Ln(n))e[t]=n;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]]=255&(r^r>>4^r>>5^r>>6^r>>7^99)}return dn(e),t})(),Un=_n.map(((e,t)=>_n.indexOf(t))),Nn=e=>e<<8|e>>>24;function Cn(e,t){if(256!==e.length)throw new Error("Wrong sbox length");const n=new Uint32Array(256).map(((n,r)=>t(e[r]))),r=n.map(Nn),o=r.map(Nn),i=o.map(Nn),s=new Uint32Array(65536),a=new Uint32Array(65536),c=new Uint16Array(65536);for(let t=0;t<256;t++)for(let l=0;l<256;l++){const u=256*t+l;s[u]=n[t]^r[l],a[u]=o[t]^i[l],c[u]=e[t]<<8|e[l]}return{sbox:e,sbox2:c,T0:n,T1:r,T2:o,T3:i,T01:s,T23:a}}const $n=Cn(_n,(e=>Pn(e,3)<<24|e<<16|e<<8|Pn(e,2))),Mn=Cn(Un,(e=>Pn(e,11)<<24|Pn(e,13)<<16|Pn(e,9)<<8|Pn(e,14))),Fn=(()=>{const e=new Uint8Array(16);for(let t=0,n=1;t<16;t++,n=Ln(n))e[t]=n;return e})();function Dn(e){an(e);const t=e.length;Tn(e);const{sbox2:n}=$n,r=[];vn(e)||r.push(e=En(e));const o=un(e),i=o.length,s=e=>jn(n,e,e,e,e),a=new Uint32Array(t+28);a.set(o);for(let e=i;e<a.length;e++){let t=a[e-1];e%i==0?t=s((c=t)<<24|c>>>8)^Fn[e/i-1]:i>6&&e%i==4&&(t=s(t)),a[e]=a[e-i]^t}var c;return dn(...r),a}function Hn(e){const t=Dn(e),n=t.slice(),r=t.length,{sbox2:o}=$n,{T0:i,T1:s,T2:a,T3:c}=Mn;for(let e=0;e<r;e+=4)for(let o=0;o<4;o++)n[e+o]=t[r-e-4+o];dn(t);for(let e=4;e<r-4;e++){const t=n[e],r=jn(o,t,t,t,t);n[e]=i[255&r]^s[r>>>8&255]^a[r>>>16&255]^c[r>>>24]}return n}function qn(e,t,n,r,o,i){return e[n<<8&65280|r>>>8&255]^t[o>>>8&65280|i>>>24&255]}function jn(e,t,n,r,o){return e[255&t|65280&n]|e[r>>>16&255|o>>>16&65280]<<16}function Vn(e,t,n,r,o){const{sbox2:i,T01:s,T23:a}=$n;let c=0;t^=e[c++],n^=e[c++],r^=e[c++],o^=e[c++];const l=e.length/4-2;for(let i=0;i<l;i++){const i=e[c++]^qn(s,a,t,n,r,o),l=e[c++]^qn(s,a,n,r,o,t),u=e[c++]^qn(s,a,r,o,t,n),d=e[c++]^qn(s,a,o,t,n,r);t=i,n=l,r=u,o=d}return{s0:e[c++]^jn(i,t,n,r,o),s1:e[c++]^jn(i,n,r,o,t),s2:e[c++]^jn(i,r,o,t,n),s3:e[c++]^jn(i,o,t,n,r)}}function Wn(e,t,n,r,o){const{sbox2:i,T01:s,T23:a}=Mn;let c=0;t^=e[c++],n^=e[c++],r^=e[c++],o^=e[c++];const l=e.length/4-2;for(let i=0;i<l;i++){const i=e[c++]^qn(s,a,t,o,r,n),l=e[c++]^qn(s,a,n,t,o,r),u=e[c++]^qn(s,a,r,n,t,o),d=e[c++]^qn(s,a,o,r,n,t);t=i,n=l,r=u,o=d}return{s0:e[c++]^jn(i,t,o,r,n),s1:e[c++]^jn(i,n,t,o,r),s2:e[c++]^jn(i,r,n,t,o),s3:e[c++]^jn(i,o,r,n,t)}}function zn(e){if(an(e),e.length%Bn!=0)throw new Error("aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size 16")}function Kn(e,t,n){an(e);let r=e.length;const o=r%Bn;if(!t&&0!==o)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");vn(e)||(e=En(e));const i=un(e);if(t){let e=Bn-o;e||(e=Bn),r+=e}gn(e,n=mn(r,n));return{b:i,o:un(n),out:n}}function Gn(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");const o=e.subarray(0,-r);for(let t=0;t<r;t++)if(e[n-t-1]!==r)throw new Error("aes/pcks5: wrong padding");return o}function Zn(e){const t=new Uint8Array(16),n=un(t);t.set(e);const r=Bn-e.length;for(let e=Bn-r;e<Bn;e++)t[e]=r;return n}const Jn=wn({blockSize:16,nonceLength:16},(function(e,t,n={}){const r=!n.disablePadding;return{encrypt(n,o){const i=Dn(e),{b:s,o:a,out:c}=Kn(n,r,o);let l=t;const u=[i];vn(l)||u.push(l=En(l));const d=un(l);let h=d[0],f=d[1],p=d[2],g=d[3],y=0;for(;y+4<=s.length;)h^=s[y+0],f^=s[y+1],p^=s[y+2],g^=s[y+3],({s0:h,s1:f,s2:p,s3:g}=Vn(i,h,f,p,g)),a[y++]=h,a[y++]=f,a[y++]=p,a[y++]=g;if(r){const e=Zn(n.subarray(4*y));h^=e[0],f^=e[1],p^=e[2],g^=e[3],({s0:h,s1:f,s2:p,s3:g}=Vn(i,h,f,p,g)),a[y++]=h,a[y++]=f,a[y++]=p,a[y++]=g}return dn(...u),c},decrypt(n,o){zn(n);const i=Hn(e);let s=t;const a=[i];vn(s)||a.push(s=En(s));const c=un(s);o=mn(n.length,o),vn(n)||a.push(n=En(n)),gn(n,o);const l=un(n),u=un(o);let d=c[0],h=c[1],f=c[2],p=c[3];for(let e=0;e+4<=l.length;){const t=d,n=h,r=f,o=p;d=l[e+0],h=l[e+1],f=l[e+2],p=l[e+3];const{s0:s,s1:a,s2:c,s3:g}=Wn(i,d,h,f,p);u[e++]=s^t,u[e++]=a^n,u[e++]=c^r,u[e++]=g^o}return dn(...a),Gn(o,r)}}}));function Xn(e){return e instanceof Uint32Array||ArrayBuffer.isView(e)&&"Uint32Array"===e.constructor.name}function Yn(e,t){if(an(t,16,"block"),!Xn(e))throw new Error("_encryptBlock accepts result of expandKeyLE");const n=un(t);let{s0:r,s1:o,s2:i,s3:s}=Vn(e,n[0],n[1],n[2],n[3]);return n[0]=r,n[1]=o,n[2]=i,n[3]=s,t}function Qn(e){let t=0;for(let n=15;n>=0;n--){const r=(128&e[n])>>>7;e[n]=e[n]<<1|t,t=r}return t&&(e[15]^=135),e}function er(e,t){if(e.length!==t.length)throw new Error("xorBlock: blocks must have same length");for(let n=0;n<e.length;n++)e[n]=e[n]^t[n];return e}class tr{buffer;destroyed;k1;k2;xk;constructor(e){an(e),Tn(e),this.xk=Dn(e),this.buffer=new Uint8Array(0),this.destroyed=!1;const t=new Uint8Array(Bn);Yn(this.xk,t),this.k1=Qn(t),this.k2=Qn(new Uint8Array(this.k1))}update(e){const{destroyed:t,buffer:n}=this;if(t)throw new Error("CMAC instance was destroyed");an(e);const r=new Uint8Array(n.length+e.length);return r.set(n),r.set(e,n.length),this.buffer=r,this}digest(){if(this.destroyed)throw new Error("CMAC instance was destroyed");const{buffer:e}=this,t=e.length;let n,r=Math.ceil(t/Bn);0===r?(r=1,n=!1):n=t%Bn==0;const o=(r-1)*Bn,i=e.subarray(o);let s;if(n)s=er(new Uint8Array(i),this.k1);else{const e=new Uint8Array(Bn);e.set(i),e[i.length]=128,s=er(e,this.k2)}let a=new Uint8Array(Bn);for(let t=0;t<r-1;t++){er(a,e.subarray(t*Bn,(t+1)*Bn)),Yn(this.xk,a)}return er(a,s),Yn(this.xk,a),dn(s),a}destroy(){const{buffer:e,destroyed:t,xk:n,k1:r,k2:o}=this;t||(this.destroyed=!0,dn(e,n,r,o))}}const nr=(e,t)=>new tr(e).update(t).digest();nr.create=e=>new tr(e);const rr=e=>Uint8Array.from(e.split(""),(e=>e.charCodeAt(0))),or=rr("expand 16-byte k"),ir=rr("expand 32-byte k"),sr=un(or),ar=un(ir);function cr(e,t){return e<<t|e>>>32-t}function lr(e){return e.byteOffset%4==0}const ur=2**32-1,dr=Uint32Array.of();function hr(e,t){const{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:i,rounds:s}=function(e,t){if(null==t||"object"!=typeof t)throw new Error("options must be defined");return Object.assign(e,t)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if("function"!=typeof e)throw new Error("core must be a function");return sn(o),sn(s),on(i),on(n),(t,a,c,l,u=0)=>{an(t,void 0,"key"),an(a,void 0,"nonce"),an(c,void 0,"data");const d=c.length;if(void 0===l&&(l=new Uint8Array(d)),an(l,void 0,"output"),sn(u),u<0||u>=ur)throw new Error("arx: counter overflow");if(l.length<d)throw new Error(`arx: output (${l.length}) is shorter than data (${d})`);const h=[];let f,p,g=t.length;if(32===g)h.push(f=En(t)),p=ar;else{if(16!==g||!n)throw an(t,32,"arx key"),new Error("invalid key size");f=new Uint8Array(32),f.set(t),f.set(t,16),p=sr,h.push(f)}lr(a)||h.push(a=En(a));const y=un(f);if(r){if(24!==a.length)throw new Error("arx: extended nonce must be 24 bytes");r(p,y,un(a.subarray(0,16)),y),a=a.subarray(16)}const w=16-o;if(w!==a.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(12!==w){const e=new Uint8Array(12);e.set(a,i?0:12-a.length),a=e,h.push(a)}const m=un(a);return function(e,t,n,r,o,i,s,a){const c=o.length,l=new Uint8Array(64),u=un(l),d=lr(o)&&lr(i),h=d?un(o):dr,f=d?un(i):dr;for(let p=0;p<c;s++){if(e(t,n,r,u,s,a),s>=ur)throw new Error("arx: counter overflow");const g=Math.min(64,c-p);if(d&&64===g){const e=p/4;if(p%4!=0)throw new Error("arx: invalid block position");for(let t,n=0;n<16;n++)t=e+n,f[t]=h[t]^u[n];p+=64}else{for(let e,t=0;t<g;t++)e=p+t,i[e]=o[e]^l[t];p+=g}}}(e,p,y,m,c,l,u,s),dn(...h),l}}function fr(e,t){return 255&e[t++]|(255&e[t++])<<8}class pr{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;constructor(e){const t=fr(e=En(an(e,32,"key")),0),n=fr(e,2),r=fr(e,4),o=fr(e,6),i=fr(e,8),s=fr(e,10),a=fr(e,12),c=fr(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|n<<3),this.r[2]=7939&(n>>>10|r<<6),this.r[3]=8191&(r>>>7|o<<9),this.r[4]=255&(o>>>4|i<<12),this.r[5]=i>>>1&8190,this.r[6]=8191&(i>>>14|s<<2),this.r[7]=8065&(s>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=fr(e,16+2*t)}process(e,t,n=!1){const r=n?0:2048,{h:o,r:i}=this,s=i[0],a=i[1],c=i[2],l=i[3],u=i[4],d=i[5],h=i[6],f=i[7],p=i[8],g=i[9],y=fr(e,t+0),w=fr(e,t+2),m=fr(e,t+4),b=fr(e,t+6),v=fr(e,t+8),E=fr(e,t+10),x=fr(e,t+12),S=fr(e,t+14);let k=o[0]+(8191&y),A=o[1]+(8191&(y>>>13|w<<3)),R=o[2]+(8191&(w>>>10|m<<6)),O=o[3]+(8191&(m>>>7|b<<9)),I=o[4]+(8191&(b>>>4|v<<12)),B=o[5]+(v>>>1&8191),T=o[6]+(8191&(v>>>14|E<<2)),L=o[7]+(8191&(E>>>11|x<<5)),P=o[8]+(8191&(x>>>8|S<<8)),_=o[9]+(S>>>5|r),U=0,N=U+k*s+A*(5*g)+R*(5*p)+O*(5*f)+I*(5*h);U=N>>>13,N&=8191,N+=B*(5*d)+T*(5*u)+L*(5*l)+P*(5*c)+_*(5*a),U+=N>>>13,N&=8191;let C=U+k*a+A*s+R*(5*g)+O*(5*p)+I*(5*f);U=C>>>13,C&=8191,C+=B*(5*h)+T*(5*d)+L*(5*u)+P*(5*l)+_*(5*c),U+=C>>>13,C&=8191;let $=U+k*c+A*a+R*s+O*(5*g)+I*(5*p);U=$>>>13,$&=8191,$+=B*(5*f)+T*(5*h)+L*(5*d)+P*(5*u)+_*(5*l),U+=$>>>13,$&=8191;let M=U+k*l+A*c+R*a+O*s+I*(5*g);U=M>>>13,M&=8191,M+=B*(5*p)+T*(5*f)+L*(5*h)+P*(5*d)+_*(5*u),U+=M>>>13,M&=8191;let F=U+k*u+A*l+R*c+O*a+I*s;U=F>>>13,F&=8191,F+=B*(5*g)+T*(5*p)+L*(5*f)+P*(5*h)+_*(5*d),U+=F>>>13,F&=8191;let D=U+k*d+A*u+R*l+O*c+I*a;U=D>>>13,D&=8191,D+=B*s+T*(5*g)+L*(5*p)+P*(5*f)+_*(5*h),U+=D>>>13,D&=8191;let H=U+k*h+A*d+R*u+O*l+I*c;U=H>>>13,H&=8191,H+=B*a+T*s+L*(5*g)+P*(5*p)+_*(5*f),U+=H>>>13,H&=8191;let q=U+k*f+A*h+R*d+O*u+I*l;U=q>>>13,q&=8191,q+=B*c+T*a+L*s+P*(5*g)+_*(5*p),U+=q>>>13,q&=8191;let j=U+k*p+A*f+R*h+O*d+I*u;U=j>>>13,j&=8191,j+=B*l+T*c+L*a+P*s+_*(5*g),U+=j>>>13,j&=8191;let V=U+k*g+A*p+R*f+O*h+I*d;U=V>>>13,V&=8191,V+=B*u+T*l+L*c+P*a+_*s,U+=V>>>13,V&=8191,U=(U<<2)+U|0,U=U+N|0,N=8191&U,U>>>=13,C+=U,o[0]=N,o[1]=C,o[2]=$,o[3]=M,o[4]=F,o[5]=D,o[6]=H,o[7]=q,o[8]=j,o[9]=V}finalize(){const{h:e,pad:t}=this,n=new Uint16Array(10);let r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=5*r,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let o=(1^r)-1;for(let e=0;e<10;e++)n[e]&=o;o=~o;for(let t=0;t<10;t++)e[t]=e[t]&o|n[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let i=e[0]+t[0];e[0]=65535&i;for(let n=1;n<8;n++)i=(e[n]+t[n]|0)+(i>>>16)|0,e[n]=65535&i;dn(n)}update(e){cn(this),an(e),e=En(e);const{buffer:t,blockLen:n}=this,r=e.length;for(let o=0;o<r;){const i=Math.min(n-this.pos,r-o);if(i!==n)t.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===n&&(this.process(t,0,!1),this.pos=0);else for(;n<=r-o;o+=n)this.process(e,o)}return this}destroy(){dn(this.h,this.r,this.buffer,this.pad)}digestInto(e){cn(this),ln(e,this),this.finished=!0;const{buffer:t,h:n}=this;let{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let o=0;for(let t=0;t<8;t++)e[o++]=n[t]>>>0,e[o++]=n[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}}const gr=(()=>function(e){const t=(t,n)=>e(n).update(t).digest(),n=e(new Uint8Array(32));return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t}((e=>new pr(e))))();function yr(e,t,n,r,o,i=20){let s=e[0],a=e[1],c=e[2],l=e[3],u=t[0],d=t[1],h=t[2],f=t[3],p=t[4],g=t[5],y=t[6],w=t[7],m=o,b=n[0],v=n[1],E=n[2],x=s,S=a,k=c,A=l,R=u,O=d,I=h,B=f,T=p,L=g,P=y,_=w,U=m,N=b,C=v,$=E;for(let e=0;e<i;e+=2)x=x+R|0,U=cr(U^x,16),T=T+U|0,R=cr(R^T,12),x=x+R|0,U=cr(U^x,8),T=T+U|0,R=cr(R^T,7),S=S+O|0,N=cr(N^S,16),L=L+N|0,O=cr(O^L,12),S=S+O|0,N=cr(N^S,8),L=L+N|0,O=cr(O^L,7),k=k+I|0,C=cr(C^k,16),P=P+C|0,I=cr(I^P,12),k=k+I|0,C=cr(C^k,8),P=P+C|0,I=cr(I^P,7),A=A+B|0,$=cr($^A,16),_=_+$|0,B=cr(B^_,12),A=A+B|0,$=cr($^A,8),_=_+$|0,B=cr(B^_,7),x=x+O|0,$=cr($^x,16),P=P+$|0,O=cr(O^P,12),x=x+O|0,$=cr($^x,8),P=P+$|0,O=cr(O^P,7),S=S+I|0,U=cr(U^S,16),_=_+U|0,I=cr(I^_,12),S=S+I|0,U=cr(U^S,8),_=_+U|0,I=cr(I^_,7),k=k+B|0,N=cr(N^k,16),T=T+N|0,B=cr(B^T,12),k=k+B|0,N=cr(N^k,8),T=T+N|0,B=cr(B^T,7),A=A+R|0,C=cr(C^A,16),L=L+C|0,R=cr(R^L,12),A=A+R|0,C=cr(C^A,8),L=L+C|0,R=cr(R^L,7);let M=0;r[M++]=s+x|0,r[M++]=a+S|0,r[M++]=c+k|0,r[M++]=l+A|0,r[M++]=u+R|0,r[M++]=d+O|0,r[M++]=h+I|0,r[M++]=f+B|0,r[M++]=p+T|0,r[M++]=g+L|0,r[M++]=y+P|0,r[M++]=w+_|0,r[M++]=m+U|0,r[M++]=b+N|0,r[M++]=v+C|0,r[M++]=E+$|0}const wr=hr(yr,{counterRight:!1,counterLength:4,allowShortKeys:!1}),mr=hr(yr,{counterRight:!1,counterLength:8,extendNonceFn:function(e,t,n,r){let o=e[0],i=e[1],s=e[2],a=e[3],c=t[0],l=t[1],u=t[2],d=t[3],h=t[4],f=t[5],p=t[6],g=t[7],y=n[0],w=n[1],m=n[2],b=n[3];for(let e=0;e<20;e+=2)o=o+c|0,y=cr(y^o,16),h=h+y|0,c=cr(c^h,12),o=o+c|0,y=cr(y^o,8),h=h+y|0,c=cr(c^h,7),i=i+l|0,w=cr(w^i,16),f=f+w|0,l=cr(l^f,12),i=i+l|0,w=cr(w^i,8),f=f+w|0,l=cr(l^f,7),s=s+u|0,m=cr(m^s,16),p=p+m|0,u=cr(u^p,12),s=s+u|0,m=cr(m^s,8),p=p+m|0,u=cr(u^p,7),a=a+d|0,b=cr(b^a,16),g=g+b|0,d=cr(d^g,12),a=a+d|0,b=cr(b^a,8),g=g+b|0,d=cr(d^g,7),o=o+l|0,b=cr(b^o,16),p=p+b|0,l=cr(l^p,12),o=o+l|0,b=cr(b^o,8),p=p+b|0,l=cr(l^p,7),i=i+u|0,y=cr(y^i,16),g=g+y|0,u=cr(u^g,12),i=i+u|0,y=cr(y^i,8),g=g+y|0,u=cr(u^g,7),s=s+d|0,w=cr(w^s,16),h=h+w|0,d=cr(d^h,12),s=s+d|0,w=cr(w^s,8),h=h+w|0,d=cr(d^h,7),a=a+c|0,m=cr(m^a,16),f=f+m|0,c=cr(c^f,12),a=a+c|0,m=cr(m^a,8),f=f+m|0,c=cr(c^f,7);let v=0;r[v++]=o,r[v++]=i,r[v++]=s,r[v++]=a,r[v++]=y,r[v++]=w,r[v++]=m,r[v++]=b},allowShortKeys:!1}),br=new Uint8Array(16),vr=(e,t)=>{e.update(t);const n=t.length%16;n&&e.update(br.subarray(n))},Er=new Uint8Array(32);function xr(e,t,n,r,o){void 0!==o&&an(o,void 0,"AAD");const i=e(t,n,Er),s=bn(r.length,o?o.length:0,!0),a=gr.create(i);o&&vr(a,o),vr(a,r),a.update(s);const c=a.digest();return dn(i,s),c}const Sr=e=>(t,n,r)=>{const o=16;return{encrypt(i,s){const a=i.length;(s=mn(a+o,s,!1)).set(i);const c=s.subarray(0,-16);e(t,n,c,c,1);const l=xr(e,t,n,c,r);return s.set(l,a),dn(l),s},decrypt(i,s){s=mn(i.length-o,s,!1);const a=i.subarray(0,-16),c=i.subarray(-16),l=xr(e,t,n,a,r);if(!yn(c,l))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),e(t,n,s,s,1),dn(l),s}}};Sr(wr),Sr(mr);function kr(e,t,n){return s(e),void 0===n&&(n=new Uint8Array(e.outputLen)),Me(e,n,t)}const Ar=Uint8Array.of(0),Rr=Uint8Array.of();function Or(e,t,n,r=32){s(e),o(r,"length");const a=e.outputLen;if(r>255*a)throw new Error("Length must be <= 255*HashLen");const l=Math.ceil(r/a);void 0===n?n=Rr:i(n,void 0,"info");const u=new Uint8Array(l*a),d=Me.create(e,t),h=d._cloneInto(),f=new Uint8Array(d.outputLen);for(let e=0;e<l;e++)Ar[0]=e+1,h.update(0===e?Rr:f).update(n).update(Ar).digestInto(f),u.set(f,a*e),d._cloneInto(h);return d.destroy(),h.destroy(),c(f,Ar),u.slice(0,r)}var Ir=Object.defineProperty,Br=(e,t)=>{for(var n in t)Ir(e,n,{get:t[n],enumerable:!0})},Tr={};Br(Tr,{binarySearch:()=>Cr,bytesToHex:()=>f,hexToBytes:()=>E,insertEventIntoAscendingList:()=>Nr,insertEventIntoDescendingList:()=>Ur,isHex32:()=>Mr,mergeReverseSortedLists:()=>$r,normalizeURL:()=>_r,utf8Decoder:()=>Lr,utf8Encoder:()=>Pr});var Lr=new TextDecoder("utf-8"),Pr=new TextEncoder;function _r(e){try{-1===e.indexOf("://")&&(e="wss://"+e);let t=new URL(e);return"http:"===t.protocol?t.protocol="ws:":"https:"===t.protocol&&(t.protocol="wss:"),t.pathname=t.pathname.replace(/\/+/g,"/"),t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),("80"===t.port&&"ws:"===t.protocol||"443"===t.port&&"wss:"===t.protocol)&&(t.port=""),t.searchParams.sort(),t.hash="",t.toString()}catch(t){throw new Error(`Invalid URL: ${e}`)}}function Ur(e,t){const[n,r]=Cr(e,(e=>t.id===e.id?0:t.created_at===e.created_at?-1:e.created_at-t.created_at));return r||e.splice(n,0,t),e}function Nr(e,t){const[n,r]=Cr(e,(e=>t.id===e.id?0:t.created_at===e.created_at?-1:t.created_at-e.created_at));return r||e.splice(n,0,t),e}function Cr(e,t){let n=0,r=e.length-1;for(;n<=r;){const o=Math.floor((n+r)/2),i=t(e[o]);if(0===i)return[o,!0];i<0?r=o-1:n=o+1}return[n,!1]}function $r(e,t){const n=new Array(e.length+t.length);n.length=0;let r=0,o=0,i=[];for(;r<e.length&&o<t.length;){let s;if(e[r]?.created_at>t[o]?.created_at?(s=e[r],r++):(s=t[o],o++),n.length>0&&n[n.length-1].created_at===s.created_at){if(i.includes(s.id))continue}else i.length=0;n.push(s),i.push(s.id)}for(;r<e.length;){const t=e[r];if(r++,n.length>0&&n[n.length-1].created_at===t.created_at){if(i.includes(t.id))continue}else i.length=0;n.push(t),i.push(t.id)}for(;o<t.length;){const e=t[o];if(o++,n.length>0&&n[n.length-1].created_at===e.created_at){if(i.includes(e.id))continue}else i.length=0;n.push(e),i.push(e.id)}return n}function Mr(e){for(let t=0;t<64;t++){let n=e.charCodeAt(t);if(isNaN(n)||n<48||n>102||n>57&&n<97)return!1}return!0}var Fr=Symbol("verified"),Dr=e=>e instanceof Object;function Hr(e){if(!Dr(e))return!1;if("number"!=typeof e.kind)return!1;if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if("string"!=typeof e.pubkey)return!1;if(!Mr(e.pubkey))return!1;if(!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 e=0;e<n.length;e++)if("string"!=typeof n[e])return!1}return!0}function qr(e){return e.sort(((e,t)=>e.created_at!==t.created_at?t.created_at-e.created_at:e.id.localeCompare(t.id)))}function jr(e){if(!Hr(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 Vr(e){return f(_(Pr.encode(jr(e))))}var Wr=new class{generateSecretKey(){return mt.utils.randomSecretKey()}getPublicKey(e){return f(mt.getPublicKey(e))}finalizeEvent(e,t){const n=e;return n.pubkey=f(mt.getPublicKey(t)),n.id=Vr(n),n.sig=f(mt.sign(E(Vr(n)),t)),n[Fr]=!0,n}verifyEvent(e){if("boolean"==typeof e[Fr])return e[Fr];try{const t=Vr(e);if(t!==e.id)return e[Fr]=!1,!1;const n=mt.verify(E(e.sig),E(t),E(e.pubkey));return e[Fr]=n,n}catch(t){return e[Fr]=!1,!1}}},zr=Wr.generateSecretKey,Kr=Wr.getPublicKey,Gr=Wr.finalizeEvent,Zr=Wr.verifyEvent,Jr={};function Xr(e){return e<1e4&&0!==e&&3!==e}function Yr(e){return 0===e||3===e||1e4<=e&&e<2e4}function Qr(e){return 2e4<=e&&e<3e4}function eo(e){return 3e4<=e&&e<4e4}function to(e){return Xr(e)?"regular":Yr(e)?"replaceable":Qr(e)?"ephemeral":eo(e)?"parameterized":"unknown"}function no(e,t){const n=t instanceof Array?t:[t];return Hr(e)&&n.includes(e.kind)||!1}Br(Jr,{AIEmbeddings:()=>ai,AppCurationSet:()=>Ws,Application:()=>js,AuthoredPodcasts:()=>as,BadgeAward:()=>ho,BadgeDefinition:()=>Ls,Bid:()=>No,BidConfirmation:()=>Co,BlobsAuth:()=>Es,BlockedRelaysList:()=>ji,BlossomServerList:()=>ns,BookmarkList:()=>Di,Bookmarksets:()=>Rs,Calendar:()=>ca,CalendarEventRSVP:()=>la,CashuMintAnnouncement:()=>va,CashuWalletEvent:()=>gs,CashuWalletHistory:()=>bi,CashuWalletTokens:()=>mi,ChannelCreation:()=>Ro,ChannelHideMessage:()=>Bo,ChannelMessage:()=>Io,ChannelMetadata:()=>Oo,ChannelMuteUser:()=>To,ChatMessage:()=>fo,Chess:()=>Po,ClassifiedListing:()=>Xs,ClientAuth:()=>ws,CodeSnippet:()=>zo,CoinjoinPool:()=>ui,Comment:()=>Ho,CommunitiesList:()=>Hi,CommunityDefinition:()=>ya,CommunityPostApproval:()=>fi,ConferenceEvent:()=>Gs,Contacts:()=>so,CreateOrUpdateProduct:()=>Us,CreateOrUpdateStall:()=>_s,CuratedVideoSets:()=>Is,Curationsets:()=>Os,Date:()=>sa,DecoupledEncryptionKeyDistribution:()=>hi,DecoupledKeyAnnouncement:()=>Qi,DecoupledKeyClientAnnouncement:()=>di,DirectMessageRelaysList:()=>es,DraftClassifiedListing:()=>Ys,DraftEvent:()=>ra,DraftLong:()=>Ms,Emojisets:()=>Fs,EncryptedDirectMessage:()=>ao,EventDeletion:()=>co,FavoriteFollowSets:()=>Xi,FavoritePodcasts:()=>ts,FavoriteRelays:()=>zi,FedimintAnnouncement:()=>Ea,Feed:()=>ia,FileMessage:()=>bo,FileMetadata:()=>Fo,FileServerPreference:()=>rs,Followsets:()=>Ss,ForumThread:()=>go,GenericRepost:()=>vo,Genericlists:()=>ks,GeocacheListing:()=>ma,GeocacheLog:()=>vi,GeocacheLogEntry:()=>ba,GeocacheProofOfFind:()=>Ei,GiftWrap:()=>Mo,GitPullRequest:()=>Go,GitPullRequestUpdate:()=>Zo,GoodWikiAuthorList:()=>os,GoodWikiRelayList:()=>is,GroupMetadata:()=>Sa,HTTPAuth:()=>xs,Handlerinformation:()=>ha,Handlerrecommendation:()=>da,Highlights:()=>Ci,InteractiveRoom:()=>Ks,InterestsList:()=>Gi,Interestsets:()=>Ps,Issue:()=>Jo,JobFeedback:()=>yi,JobRequest:()=>pi,JobResult:()=>gi,Label:()=>ii,LegacyNsiteFile:()=>pa,LightningPubRPC:()=>ys,LinkSet:()=>oa,LiveChatMessage:()=>Wo,LiveEvent:()=>zs,LongFormArticle:()=>$s,MarketplaceUI:()=>Ns,MediaFollows:()=>Ji,MediaStarterPacks:()=>Ba,MergeRequests:()=>_o,Metadata:()=>ro,ModularArticleContent:()=>Hs,ModularArticleHeader:()=>Ds,MuteSets:()=>Bs,Mutelist:()=>$i,NWCWalletInfo:()=>fs,NWCWalletRequest:()=>ms,NWCWalletResponse:()=>bs,NormalVideo:()=>So,NostrConnect:()=>vs,NsiteNamed:()=>wa,NsiteRoot:()=>ps,NutZap:()=>Pi,NutZapInfo:()=>Zi,OpenTimestamps:()=>$o,Patch:()=>Ko,PeerToPeerOrderEvents:()=>xa,Photo:()=>xo,Pinlist:()=>Mi,PodcastEpisode:()=>Lo,PodcastMetadata:()=>ss,Poll:()=>Do,PollResponse:()=>Uo,PrivateDirectMessage:()=>mo,PrivateEventRelayList:()=>Ki,ProblemTracker:()=>ni,ProductSoldAsAuction:()=>Cs,ProfileBadges:()=>Ts,ProxyAnnouncement:()=>ds,PublicChatsList:()=>qi,PublicMessage:()=>Ao,Reaction:()=>uo,ReactionToWebsite:()=>Eo,RecommendRelay:()=>io,Redirects:()=>na,RelayDiscovery:()=>Vs,RelayList:()=>Fi,RelayMonitorAnnouncement:()=>cs,RelayReview:()=>ua,RelayReviews:()=>si,Relaysets:()=>As,ReleaseArtifactSets:()=>qs,Reply:()=>Xo,Report:()=>ri,Reporting:()=>oi,RepositoryAnnouncement:()=>Qs,RepositoryState:()=>ea,Repost:()=>lo,ReservedCashuWalletTokens:()=>wi,RoomPresence:()=>ls,Scroll:()=>jo,Seal:()=>wo,SearchRelaysList:()=>Vi,ShortTextNote:()=>oo,ShortVideo:()=>ko,SimpleGroupAdmins:()=>ka,SimpleGroupCreateGroup:()=>Ri,SimpleGroupCreateInvite:()=>Ii,SimpleGroupDeleteEvent:()=>Ai,SimpleGroupDeleteGroup:()=>Oi,SimpleGroupEditMetadata:()=>ki,SimpleGroupJoinRequest:()=>Bi,SimpleGroupLeaveRequest:()=>Ti,SimpleGroupList:()=>Wi,SimpleGroupLiveKitParticipants:()=>Oa,SimpleGroupMembers:()=>Aa,SimpleGroupPutUser:()=>xi,SimpleGroupRemoveUser:()=>Si,SimpleGroupReply:()=>yo,SimpleGroupRoles:()=>Ra,SimpleGroupThreadedReply:()=>po,SlideSet:()=>Js,SoftwareApplication:()=>fa,StarterPacks:()=>Ia,StatusApplied:()=>Qo,StatusClosed:()=>ei,StatusDraft:()=>ti,StatusOpen:()=>Yo,TidalLogin:()=>_i,Time:()=>aa,Torrent:()=>ci,TorrentComment:()=>li,TransportMethodAnnouncement:()=>hs,UserEmojiList:()=>Yi,UserGraspList:()=>us,UserStatuses:()=>Zs,VideoViewEvent:()=>ga,Voice:()=>qo,VoiceComment:()=>Vo,WebBookmarks:()=>Ta,WikiArticle:()=>ta,Zap:()=>Ni,ZapGoal:()=>Li,ZapRequest:()=>Ui,classifyKind:()=>to,isAddressableKind:()=>eo,isEphemeralKind:()=>Qr,isKind:()=>no,isRegularKind:()=>Xr,isReplaceableKind:()=>Yr});var ro=0,oo=1,io=2,so=3,ao=4,co=5,lo=6,uo=7,ho=8,fo=9,po=10,go=11,yo=12,wo=13,mo=14,bo=15,vo=16,Eo=17,xo=20,So=21,ko=22,Ao=24,Ro=40,Oo=41,Io=42,Bo=43,To=44,Lo=54,Po=64,_o=818,Uo=1018,No=1021,Co=1022,$o=1040,Mo=1059,Fo=1063,Do=1068,Ho=1111,qo=1222,jo=1227,Vo=1244,Wo=1311,zo=1337,Ko=1617,Go=1618,Zo=1619,Jo=1621,Xo=1622,Yo=1630,Qo=1631,ei=1632,ti=1633,ni=1971,ri=1984,oi=1984,ii=1985,si=1986,ai=1987,ci=2003,li=2004,ui=2022,di=4454,hi=4455,fi=4550,pi=5999,gi=6999,yi=7e3,wi=7374,mi=7375,bi=7376,vi=7516,Ei=7517,xi=9e3,Si=9001,ki=9002,Ai=9005,Ri=9007,Oi=9008,Ii=9009,Bi=9021,Ti=9022,Li=9041,Pi=9321,_i=9467,Ui=9734,Ni=9735,Ci=9802,$i=1e4,Mi=10001,Fi=10002,Di=10003,Hi=10004,qi=10005,ji=10006,Vi=10007,Wi=10009,zi=10012,Ki=10013,Gi=10015,Zi=10019,Ji=10020,Xi=10021,Yi=10030,Qi=10044,es=10050,ts=10054,ns=10063,rs=10096,os=10101,is=10102,ss=10154,as=10164,cs=10166,ls=10312,us=10317,ds=10377,hs=11111,fs=13194,ps=15128,gs=17375,ys=21e3,ws=22242,ms=23194,bs=23195,vs=24133,Es=24242,xs=27235,Ss=3e4,ks=30001,As=30002,Rs=30003,Os=30004,Is=30005,Bs=30007,Ts=30008,Ls=30009,Ps=30015,_s=30017,Us=30018,Ns=30019,Cs=30020,$s=30023,Ms=30024,Fs=30030,Ds=30040,Hs=30041,qs=30063,js=30078,Vs=30166,Ws=30267,zs=30311,Ks=30312,Gs=30313,Zs=30315,Js=30388,Xs=30402,Ys=30403,Qs=30617,ea=30618,ta=30818,na=30819,ra=31234,oa=31388,ia=31890,sa=31922,aa=31923,ca=31924,la=31925,ua=31987,da=31989,ha=31990,fa=32267,pa=34128,ga=34237,ya=34550,wa=35128,ma=37515,ba=37516,va=38172,Ea=38173,xa=38383,Sa=39e3,ka=39001,Aa=39002,Ra=39003,Oa=39004,Ia=39089,Ba=39092,Ta=39701;function La(e,t){if(e.ids&&-1===e.ids.indexOf(t.id))return!1;if(e.kinds&&-1===e.kinds.indexOf(t.kind))return!1;if(e.authors&&-1===e.authors.indexOf(t.pubkey))return!1;for(let n in e)if("#"===n[0]){let r=e[`#${n.slice(1)}`];if(r&&!t.tags.find((([e,t])=>e===n.slice(1)&&-1!==r.indexOf(t))))return!1}return!(e.since&&t.created_at<e.since)&&!(e.until&&t.created_at>e.until)}function Pa(e,t){for(let n=0;n<e.length;n++)if(La(e[n],t))return!0;return!1}function _a(...e){let t={};for(let n=0;n<e.length;n++){let r=e[n];Object.entries(r).forEach((([e,n])=>{if("kinds"===e||"ids"===e||"authors"===e||"#"===e[0]){t[e]=t[e]||[];for(let r=0;r<n.length;r++){let o=n[r];t[e].includes(o)||t[e].push(o)}}})),r.limit&&(!t.limit||r.limit>t.limit)&&(t.limit=r.limit),r.until&&(!t.until||r.until>t.until)&&(t.until=r.until),r.since&&(!t.since||r.since<t.since)&&(t.since=r.since)}return t}function Ua(e){if(e.ids&&!e.ids.length)return 0;if(e.kinds&&!e.kinds.length)return 0;if(e.authors&&!e.authors.length)return 0;for(const[t,n]of Object.entries(e))if("#"===t[0]&&Array.isArray(n)&&!n.length)return 0;return Math.min(Math.max(0,e.limit??1/0),e.ids?.length??1/0,e.authors?.length&&e.kinds?.every((e=>Yr(e)))?e.authors.length*e.kinds.length:1/0,e.authors?.length&&e.kinds?.every((e=>eo(e)))&&e["#d"]?.length?e.authors.length*e.kinds.length*e["#d"].length:1/0)}var Na={};function Ca(e,t){let n=t.length+3,r=e.indexOf(`"${t}":`)+n,o=e.slice(r).indexOf('"')+r+1;return e.slice(o,o+64)}function $a(e,t){let n=t.length,r=e.indexOf(`"${t}":`)+n+3,o=e.slice(r),i=Math.min(o.indexOf(","),o.indexOf("}"));return parseInt(o.slice(0,i),10)}function Ma(e){let t=e.slice(0,22).indexOf('"EVENT"');if(-1===t)return null;let n=e.slice(t+7+1).indexOf('"');if(-1===n)return null;let r=t+7+1+n,o=e.slice(r+1,80).indexOf('"');if(-1===o)return null;let i=r+1+o;return e.slice(r+1,i)}function Fa(e,t){return t===Ca(e,"id")}function Da(e,t){return t===Ca(e,"pubkey")}function Ha(e,t){return t===$a(e,"kind")}Br(Na,{getHex64:()=>Ca,getInt:()=>$a,getSubscriptionId:()=>Ma,matchEventId:()=>Fa,matchEventKind:()=>Ha,matchEventPubkey:()=>Da});var qa={};function ja(e,t){return{kind:ws,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",t]],content:""}}Br(qa,{makeAuthEvent:()=>ja});var Va,Wa=class extends Error{constructor(e,t){super(`Tried to send message '${e} on a closed connection to ${t}.`),this.name="SendingOnClosedConnection"}},za=class{url;_connected=!1;onclose=null;onnotice=e=>console.debug(`NOTICE from ${this.url}: ${e}`);onauth;baseEoseTimeout=4400;publishTimeout=4400;pingFrequency=29e3;pingTimeout=2e4;resubscribeBackoff=[1e4,1e4,1e4,2e4,2e4,3e4,6e4];openSubs=new Map;enablePing;enableReconnect;idleTimeout=0;idleSince=Date.now();ongoingOperations=0;reconnectTimeoutHandle;pingIntervalHandle;reconnectAttempts=0;skipReconnection=!1;idleTimeoutHandle;connectionPromise;openCountRequests=new Map;openEventPublishes=new Map;ws;challenge;authPromise;serial=0;verifyEvent;_WebSocket;constructor(e,t){this.url=_r(e),this.verifyEvent=t.verifyEvent,this._WebSocket=t.websocketImplementation||WebSocket,this.enablePing=t.enablePing,this.enableReconnect=t.enableReconnect||!1,t.idleTimeout&&(this.idleTimeout=t.idleTimeout)}static async connect(e,t){const n=new za(e,t);return await n.connect(t),n}closeAllSubscriptions(e){for(let[t,n]of this.openSubs)n.close(e);this.openSubs.clear();for(let[t,n]of this.openEventPublishes)n.reject(new Error(e));this.openEventPublishes.clear();for(let[t,n]of this.openCountRequests)n.reject(new Error(e));this.openCountRequests.clear()}get connected(){return this._connected}clearIdleTimeout(){this.idleTimeoutHandle&&(clearTimeout(this.idleTimeoutHandle),this.idleTimeoutHandle=void 0)}scheduleIdleClose(){this.clearIdleTimeout(),this.idleTimeout>0&&(this.idleTimeoutHandle=setTimeout((()=>{0===this.ongoingOperations&&this.idleSince&&this.close()}),this.idleTimeout))}async reconnect(){const e=this.resubscribeBackoff[Math.min(this.reconnectAttempts,this.resubscribeBackoff.length-1)];this.reconnectAttempts++,this.reconnectTimeoutHandle=setTimeout((async()=>{try{await this.connect()}catch(e){}}),e)}handleHardClose(e){this.ws&&(this.ws.onopen=null,this.ws.onerror=null,this.ws.onclose=null),this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this._connected=!1,this.connectionPromise=void 0,this.idleSince=void 0,this.clearIdleTimeout(),this.enableReconnect&&!this.skipReconnection?this.reconnect():(this.onclose?.(),this.closeAllSubscriptions(e))}async connect(e){let t;return this.connectionPromise||(this.challenge=void 0,this.authPromise=void 0,this.skipReconnection=!1,this.connectionPromise=new Promise(((n,r)=>{e?.timeout&&(t=setTimeout((()=>{r("connection timed out"),this.connectionPromise=void 0,0===this.reconnectAttempts&&(this.skipReconnection=!0),this.handleHardClose("relay connection timed out")}),e.timeout)),e?.abort&&(e.abort.onabort=r);try{this.ws=new this._WebSocket(this.url)}catch(e){return clearTimeout(t),void r(e)}this.ws.onopen=()=>{this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),clearTimeout(t),this._connected=!0;const e=this.reconnectAttempts>0;this.reconnectAttempts=0;for(const t of this.openSubs.values()){if(t.eosed=!1,e)for(let e=0;e<t.filters.length;e++)t.lastEmitted&&(t.filters[e].since=t.lastEmitted+1);t.fire()}this.enablePing&&(this.pingIntervalHandle=setInterval((()=>this.pingpong()),this.pingFrequency)),n()},this.ws.onerror=()=>{clearTimeout(t),r("connection failed"),this.connectionPromise=void 0,0===this.reconnectAttempts&&(this.skipReconnection=!0),this.handleHardClose("relay connection failed")},this.ws.onclose=e=>{clearTimeout(t),r(e.message||"websocket closed"),this.handleHardClose("relay connection closed")},this.ws.onmessage=this._onmessage.bind(this)}))),this.connectionPromise}waitForPingPong(){return new Promise((e=>{this.ws.once("pong",(()=>e(!0))),this.ws.ping()}))}waitForDummyReq(){return new Promise(((e,t)=>{if(!this.connectionPromise)return t(new Error(`no connection to ${this.url}, can't ping`));try{const t=this.subscribe([{ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0}],{label:"<forced-ping>",oneose:()=>{e(!0),t.close()},onclose(){e(!0)},eoseTimeout:this.pingTimeout+1e3})}catch(e){t(e)}}))}async pingpong(){if(1===this.ws?.readyState){await Promise.any([this.ws&&this.ws.ping&&this.ws.once?this.waitForPingPong():this.waitForDummyReq(),new Promise((e=>setTimeout((()=>e(!1)),this.pingTimeout)))])||this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close()}}async send(e){if(!this.connectionPromise)throw new Wa(e,this.url);this.connectionPromise.then((()=>{this.ws?.send(e)}))}async auth(e){const t=this.challenge;if(!t)throw new Error("can't perform auth, no challenge was received");return this.authPromise||(this.authPromise=new Promise((async(n,r)=>{try{let o=await e(ja(this.url,t)),i=setTimeout((()=>{let e=this.openEventPublishes.get(o.id);e&&(e.reject(new Error("auth timed out")),this.openEventPublishes.delete(o.id))}),this.publishTimeout);this.openEventPublishes.set(o.id,{resolve:n,reject:r,timeout:i}),this.send('["AUTH",'+JSON.stringify(o)+"]")}catch(e){console.warn("subscribe auth function failed:",e)}}))),this.authPromise}async publish(e){this.idleSince=void 0,this.clearIdleTimeout(),this.ongoingOperations++;const t=new Promise(((t,n)=>{const r=setTimeout((()=>{const t=this.openEventPublishes.get(e.id);t&&(t.reject(new Error("publish timed out")),this.openEventPublishes.delete(e.id))}),this.publishTimeout);this.openEventPublishes.set(e.id,{resolve:t,reject:n,timeout:r})}));try{await this.send('["EVENT",'+JSON.stringify(e)+"]")}catch(t){const n=this.openEventPublishes.get(e.id);n&&(n.reject(t),this.openEventPublishes.delete(e.id))}return this.ongoingOperations--,0===this.ongoingOperations&&(this.idleSince=Date.now(),this.scheduleIdleClose()),t}async count(e,t){return(await this.countWithHLL(e,t)).count}async countWithHLL(e,t){this.serial++;const n=t?.id||"count:"+this.serial,r=new Promise(((e,t)=>{this.openCountRequests.set(n,{resolve:e,reject:t})}));try{await this.send('["COUNT","'+n+'",'+JSON.stringify(e).substring(1))}catch(e){const t=this.openCountRequests.get(n);t&&(t.reject(e),this.openCountRequests.delete(n))}return r}subscribe(e,t){"<forced-ping>"!==t.label&&(this.idleSince=void 0,this.clearIdleTimeout(),this.ongoingOperations++);const n=this.prepareSubscription(e,t);return n.fire(),t.abort&&(t.abort.onabort=()=>n.close(String(t.abort.reason||"<aborted>"))),n}prepareSubscription(e,t){this.serial++;const n=t.id||(t.label?t.label+":":"sub:")+this.serial,r=new Ka(this,n,e,t);return this.openSubs.set(n,r),r}close(){this.skipReconnection=!0,this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,this.connectionPromise=void 0,this.idleSince=void 0,this.clearIdleTimeout(),this.onclose?.(),this.ws&&(this.ws.onopen=null,this.ws.onerror=null,this.ws.onclose=null,this.ws.readyState!==this._WebSocket.CLOSING&&this.ws.readyState!==this._WebSocket.CLOSED&&this.ws.close())}_onmessage(e){const t=e.data;if(!t)return;const n=Ma(t);if(n){const e=this.openSubs.get(n);if(!e)return;const r=Ca(t,"id"),o=e.alreadyHaveEvent?.(r);if(e.receivedEvent?.(this,r),o)return}try{let e=JSON.parse(t);switch(e[0]){case"EVENT":{const t=this.openSubs.get(e[1]),n=e[2];return Pa(t.filters,n)&&this.verifyEvent(n,this.url)?t.onevent(n):t.oninvalidevent?.(n),void((!t.lastEmitted||t.lastEmitted<n.created_at)&&(t.lastEmitted=n.created_at))}case"COUNT":{const t=e[1],n=e[2],r=this.openCountRequests.get(t);return void(r&&(r.resolve(n),this.openCountRequests.delete(t)))}case"EOSE":{const t=this.openSubs.get(e[1]);if(!t)return;return void t.receivedEose()}case"OK":{const t=e[1],n=e[2],r=e[3],o=this.openEventPublishes.get(t);return void(o&&(clearTimeout(o.timeout),n?o.resolve(r):o.reject(new Error(r)),this.openEventPublishes.delete(t)))}case"CLOSED":{const t=e[1],n=this.openSubs.get(t);if(!n){const n=this.openCountRequests.get(t);return void(n&&(n.reject(new Error(e[2])),this.openCountRequests.delete(t)))}return n.closed=!0,void n.close(e[2])}case"NOTICE":return void this.onnotice(e[1]);case"AUTH":return this.challenge=e[1],void(this.onauth&&this.auth(this.onauth).catch((e=>{if(!(e instanceof Wa))throw e})));default:{const t=this.openSubs.get(e[1]);return void t?.oncustom?.(e)}}}catch(e){try{const[n,r,o]=JSON.parse(t);console.warn(`[nostr] relay ${this.url} error processing message:`,e,o)}catch(t){console.warn(`[nostr] relay ${this.url} error processing message:`,e)}return}}},Ka=class{relay;id;lastEmitted;closed=!1;eosed=!1;filters;alreadyHaveEvent;receivedEvent;onevent;oninvalidevent;oneose;onclose;oncustom;eoseTimeout;eoseTimeoutHandle;constructor(e,t,n,r){if(0===n.length)throw new Error("subscription can't be created with zero filters");this.relay=e,this.filters=n,this.id=t,this.alreadyHaveEvent=r.alreadyHaveEvent,this.receivedEvent=r.receivedEvent,this.eoseTimeout=r.eoseTimeout||e.baseEoseTimeout,this.oneose=r.oneose,this.onclose=r.onclose,this.oninvalidevent=r.oninvalidevent,this.onevent=r.onevent||(e=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,e)})}fire(){this.relay.send('["REQ","'+this.id+'",'+JSON.stringify(this.filters).substring(1)),this.eoseTimeoutHandle=setTimeout(this.receivedEose.bind(this),this.eoseTimeout)}receivedEose(){this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,this.oneose?.())}close(e="closed by caller"){if(!this.closed&&this.relay.connected){try{this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]")}catch(e){if(!(e instanceof Wa))throw e}this.closed=!0}this.relay.openSubs.delete(this.id),this.relay.ongoingOperations--,0===this.relay.ongoingOperations&&(this.relay.idleSince=Date.now(),this.relay.scheduleIdleClose()),this.onclose?.(e)}};try{Va=WebSocket}catch{}var Ga=class extends za{constructor(e,t){super(e,{verifyEvent:Zr,websocketImplementation:Va,...t})}static async connect(e,t){const n=new Ga(e,t);return await n.connect(),n}},Za=256;new TextEncoder;function Ja(e){if(512!==e.length||!/^[0-9a-f]+$/.test(e))return;const t=new Uint8Array(Za);for(let n=0;n<Za;n++)t[n]=parseInt(e.slice(2*n,2*n+2),16);return t}function Xa(e){if(e.length!==Za)throw new Error(`invalid number of registers ${e.length}`);let t="";for(let n=0;n<Za;n++)t+=e[n].toString(16).padStart(2,"0");return t}function Ya(e,t){if(0===e.length&&(e=new Uint8Array(Za)),e.length!==Za)throw new Error(`invalid number of registers ${e.length}`);if(t.length!==Za)throw new Error(`invalid number of registers ${t.length}`);for(let n=0;n<Za;n++)t[n]>e[n]&&(e[n]=t[n]);return e}var Qa,ec=class{relays=new Map;seenOn=new Map;trackRelays=!1;verifyEvent;enablePing;enableReconnect;idleTimeout=2e4;automaticallyAuth;onRelayConnectionFailure;onRelayConnectionSuccess;allowConnectingToRelay;maxWaitForConnection;_WebSocket;constructor(e){this.verifyEvent=e.verifyEvent,this._WebSocket=e.websocketImplementation,this.enablePing=e.enablePing,this.enableReconnect=e.enableReconnect||!1,e.idleTimeout&&(this.idleTimeout=e.idleTimeout),this.automaticallyAuth=e.automaticallyAuth,this.onRelayConnectionFailure=e.onRelayConnectionFailure,this.onRelayConnectionSuccess=e.onRelayConnectionSuccess,this.allowConnectingToRelay=e.allowConnectingToRelay,this.maxWaitForConnection=e.maxWaitForConnection||3e3}async ensureRelay(e,t){e=_r(e);let n=this.relays.get(e);if(n||(n=new za(e,{verifyEvent:this.verifyEvent,websocketImplementation:this._WebSocket,enablePing:this.enablePing,enableReconnect:this.enableReconnect,idleTimeout:this.idleTimeout}),n.onclose=()=>{this.relays.delete(e)},this.relays.set(e,n)),this.automaticallyAuth){const t=this.automaticallyAuth(e);t&&(n.onauth=t)}try{await n.connect({timeout:t?.connectionTimeout,abort:t?.abort})}catch(t){throw this.relays.delete(e),t}return n}close(e){e.map(_r).forEach((e=>{this.relays.get(e)?.close(),this.relays.delete(e)}))}subscribe(e,t,n){const r=[],o=[];for(let n=0;n<e.length;n++){const i=_r(e[n]);r.find((e=>e.url===i))||-1===o.indexOf(i)&&(o.push(i),r.push({url:i,filter:t}))}return this.subscribeMap(r,n)}subscribeMany(e,t,n){return this.subscribe(e,t,n)}subscribeMap(e,t){const n=new Map;for(const t of e){const{url:e,filter:r}=t;n.has(e)||n.set(e,[]),n.get(e).push(r)}const r=Array.from(n.entries()).map((([e,t])=>({url:e,filters:t})));this.trackRelays&&(t.receivedEvent=(e,t)=>{let n=this.seenOn.get(t);n||(n=new Set,this.seenOn.set(t,n)),n.add(e)});const o=new Set,i=[],s=[];let a=e=>{s[e]||(s[e]=!0,s.filter((e=>e)).length===r.length&&(t.oneose?.(),a=()=>{}))};const c=[];let l=(e,n,o)=>{c[e]||(a(e),c[e]={url:n,reason:o},c.filter((e=>e)).length===r.length&&(t.onclose?.(c),l=()=>{}))};const u=e=>{if(t.alreadyHaveEvent?.(e))return!0;const n=o.has(e);return o.add(e),n},d=Promise.all(r.map((async({url:e,filters:n},r)=>{if(!1===this.allowConnectingToRelay?.(e,["read",n]))return void l(r,e,"connection skipped by allowConnectingToRelay");let o;try{o=await this.ensureRelay(e,{connectionTimeout:this.maxWaitForConnection<(t.maxWait||0)?Math.max(.8*t.maxWait,t.maxWait-1e3):this.maxWaitForConnection,abort:t.abort})}catch(t){return this.onRelayConnectionFailure?.(e),void l(r,e,t?.message||String(t))}this.onRelayConnectionSuccess?.(e);let s=o.subscribe(n,{...t,oneose:()=>a(r),onclose:i=>{i.startsWith("auth-required: ")&&t.onauth?o.auth(t.onauth).then((()=>{o.subscribe(n,{...t,oneose:()=>a(r),onclose:t=>{l(r,e,t)},alreadyHaveEvent:u,eoseTimeout:t.maxWait,abort:t.abort})})).catch((t=>{l(r,e,`auth was required and attempted, but failed with: ${t}`)})):l(r,e,i)},alreadyHaveEvent:u,eoseTimeout:t.maxWait,abort:t.abort});i.push(s)})));return{async close(e){await d,i.forEach((t=>{t.close(e)}))}}}subscribeEose(e,t,n){let r;return r=this.subscribe(e,t,{...n,oneose(){const t="closed automatically on eose";r?r.close(t):n.onclose?.(e.map((e=>({url:e,reason:t}))))}}),r}subscribeManyEose(e,t,n){return this.subscribeEose(e,t,n)}async querySync(e,t,n){return new Promise((async r=>{const o=[];this.subscribeEose(e,t,{...n,onevent(e){o.push(e)},onclose(e){r(o)}})}))}async get(e,t,n){t.limit=1;const r=await this.querySync(e,t,n);return r.sort(((e,t)=>t.created_at-e.created_at)),r[0]||null}async countMany(e,t,n,r){const o=function(e,t){switch(t){case"reactions":return{"#e":[e],kinds:[7]};case"reposts":return{"#e":[e],kinds:[6]};case"quotes":return{"#q":[e],kinds:[1,1111]};case"replies":return{"#e":[e],kinds:[1]};case"comments":return{"#E":[e],kinds:[1111]};case"followers":return{"#p":[e],kinds:[3]}}}(t,n),i=[];for(let t=0;t<e.length;t++){const n=_r(e[t]);-1===i.indexOf(n)&&i.push(n)}const s=await Promise.all(i.map((async e=>{if(!1===this.allowConnectingToRelay?.(e,["read",[o]]))return null;let t;try{t=await this.ensureRelay(e,{connectionTimeout:this.maxWaitForConnection<(r?.maxWait||0)?Math.max(.8*r.maxWait,r.maxWait-1e3):this.maxWaitForConnection,abort:r?.abort})}catch(t){return this.onRelayConnectionFailure?.(e),null}return this.onRelayConnectionSuccess?.(e),t.countWithHLL([o],{id:r?.id}).catch((()=>null))})));let a,c=0;for(const e of s){if(!e)continue;if(e.count>c&&(c=e.count),!e.hll||512!==e.hll.length)continue;const t=Ja(e.hll);t&&(a=Ya(a||new Uint8Array(0),t))}return a?{count:c,hll:Xa(a)}:{count:c}}publish(e,t,n){return e.map(_r).map((async(e,r,o)=>{if(o.indexOf(e)!==r)return Promise.reject("duplicate url");if(!1===this.allowConnectingToRelay?.(e,["write",t]))return Promise.reject("connection skipped by allowConnectingToRelay");let i;try{i=await this.ensureRelay(e,{connectionTimeout:this.maxWaitForConnection<(n?.maxWait||0)?Math.max(.8*n.maxWait,n.maxWait-1e3):this.maxWaitForConnection,abort:n?.abort})}catch(t){return this.onRelayConnectionFailure?.(e),String("connection failure: "+String(t))}return i.publish(t).catch((async e=>{if(e instanceof Error&&e.message.startsWith("auth-required: ")&&n?.onauth)return await i.auth(n.onauth),i.publish(t);throw e})).then((e=>{if(this.trackRelays){let e=this.seenOn.get(t.id);e||(e=new Set,this.seenOn.set(t.id,e)),e.add(i)}return e}))}))}listConnectionStatus(){const e=new Map;return this.relays.forEach(((t,n)=>e.set(n,t.connected))),e}destroy(){this.relays.forEach((e=>e.close())),this.relays=new Map}pruneIdleRelays(e=1e4){const t=[];for(const[n,r]of this.relays)r.idleSince&&Date.now()-r.idleSince>=e&&(this.relays.delete(n),t.push(n),r.close());return t}};try{Qa=WebSocket}catch{}var tc=class extends ec{constructor(e){super({verifyEvent:Zr,websocketImplementation:Qa,maxWaitForConnection:3e3,...e})}},nc={};Br(nc,{BECH32_REGEX:()=>ic,Bech32MaxSize:()=>oc,NostrTypeGuard:()=>rc,decode:()=>ac,decodeNostrURI:()=>sc,encodeBytes:()=>fc,naddrEncode:()=>yc,neventEncode:()=>gc,noteEncode:()=>dc,nprofileEncode:()=>pc,npubEncode:()=>uc,nsecEncode:()=>lc});var rc={isNProfile:e=>/^nprofile1[a-z\d]+$/.test(e||""),isNEvent:e=>/^nevent1[a-z\d]+$/.test(e||""),isNAddr:e=>/^naddr1[a-z\d]+$/.test(e||""),isNSec:e=>/^nsec1[a-z\d]{58}$/.test(e||""),isNPub:e=>/^npub1[a-z\d]{58}$/.test(e||""),isNote:e=>/^note1[a-z\d]+$/.test(e||""),isNcryptsec:e=>/^ncryptsec1[a-z\d]+$/.test(e||"")},oc=5e3,ic=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function sc(e){try{return e.startsWith("nostr:")&&(e=e.substring(6)),ac(e)}catch(e){return{type:"invalid",data:null}}}function ac(e){let{prefix:t,words:n}=nn.decode(e,oc),r=new Uint8Array(nn.fromWords(n));switch(t){case"nprofile":{let e=cc(r);if(!e[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(32!==e[0][0].length)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:f(e[0][0]),relays:e[1]?e[1].map((e=>Lr.decode(e))):[]}}}case"nevent":{let e=cc(r);if(!e[0]?.[0])throw new Error("missing TLV 0 for nevent");if(32!==e[0][0].length)throw new Error("TLV 0 should be 32 bytes");if(e[2]&&32!==e[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(e[3]&&4!==e[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:f(e[0][0]),relays:e[1]?e[1].map((e=>Lr.decode(e))):[],author:e[2]?.[0]?f(e[2][0]):void 0,kind:e[3]?.[0]?parseInt(f(e[3][0]),16):void 0}}}case"naddr":{let e=cc(r);if(!e[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!e[2]?.[0])throw new Error("missing TLV 2 for naddr");if(32!==e[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(!e[3]?.[0])throw new Error("missing TLV 3 for naddr");if(4!==e[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:Lr.decode(e[0][0]),pubkey:f(e[2][0]),kind:parseInt(f(e[3][0]),16),relays:e[1]?e[1].map((e=>Lr.decode(e))):[]}}}case"nsec":return{type:t,data:r};case"npub":case"note":return{type:t,data:f(r)};default:throw new Error(`unknown prefix ${t}`)}}function cc(e){let t={},n=e;for(;n.length>0;){if(n.length<2)throw new Error("not enough data to read TLV");let e=n[0],r=n[1],o=n.slice(2,2+r);if(n=n.slice(2+r),o.length<r)throw new Error(`not enough data to read on TLV ${e}`);t[e]=t[e]||[],t[e].push(o)}return t}function lc(e){return fc("nsec",e)}function uc(e){return fc("npub",E(e))}function dc(e){return fc("note",E(e))}function hc(e,t){let n=nn.toWords(t);return nn.encode(e,n,oc)}function fc(e,t){return hc(e,t)}function pc(e){return hc("nprofile",wc({0:[E(e.pubkey)],1:(e.relays||[]).map((e=>Pr.encode(e)))}))}function gc(e){let t;return void 0!==e.kind&&(t=function(e){const t=new Uint8Array(4);return t[0]=e>>24&255,t[1]=e>>16&255,t[2]=e>>8&255,t[3]=255&e,t}(e.kind)),hc("nevent",wc({0:[E(e.id)],1:(e.relays||[]).map((e=>Pr.encode(e))),2:e.author?[E(e.author)]:[],3:t?[new Uint8Array(t)]:[]}))}function yc(e){let t=new ArrayBuffer(4);return new DataView(t).setUint32(0,e.kind,!1),hc("naddr",wc({0:[Pr.encode(e.identifier)],1:(e.relays||[]).map((e=>Pr.encode(e))),2:[E(e.pubkey)],3:[new Uint8Array(t)]}))}function wc(e){let t=[];return Object.entries(e).reverse().forEach((([e,n])=>{n.forEach((n=>{let r=new Uint8Array(n.length+2);r.set([parseInt(e)],0),r.set([n.length],1),r.set(n,2),t.push(r)}))})),x(...t)}var mc=/\bnostr:((note|npub|naddr|nevent|nprofile)1\w+)\b|#\[(\d+)\]/g;function bc(e){let t=[];for(let n of e.content.matchAll(mc))if(n[2])try{let{type:e,data:r}=ac(n[1]);switch(e){case"npub":t.push({text:n[0],profile:{pubkey:r,relays:[]}});break;case"nprofile":t.push({text:n[0],profile:r});break;case"note":t.push({text:n[0],event:{id:r,relays:[]}});break;case"nevent":t.push({text:n[0],event:r});break;case"naddr":t.push({text:n[0],address:r})}}catch(e){}else if(n[3]){let r=parseInt(n[3],10),o=e.tags[r];if(!o)continue;switch(o[0]){case"p":t.push({text:n[0],profile:{pubkey:o[1],relays:o[2]?[o[2]]:[]}});break;case"e":t.push({text:n[0],event:{id:o[1],relays:o[2]?[o[2]]:[]}});break;case"a":try{let[e,r,i]=o[1].split(":");t.push({text:n[0],address:{identifier:i,pubkey:r,kind:parseInt(e,10),relays:o[2]?[o[2]]:[]}})}catch(e){}}}return t}var vc={};function Ec(e,t,n){const r=e instanceof Uint8Array?e:E(e),o=Sc(st.getSharedSecret(r,E("02"+t)));let i=Uint8Array.from(k(16)),s=Pr.encode(n),a=Jn(o,i).encrypt(s);return`${Wt.encode(new Uint8Array(a))}?iv=${Wt.encode(new Uint8Array(i.buffer))}`}function xc(e,t,n){const r=e instanceof Uint8Array?e:E(e);let[o,i]=n.split("?iv="),s=Sc(st.getSharedSecret(r,E("02"+t))),a=Wt.decode(i),c=Wt.decode(o),l=Jn(s,a).decrypt(c);return Lr.decode(l)}function Sc(e){return e.slice(1,33)}Br(vc,{decrypt:()=>xc,encrypt:()=>Ec});var kc={};Br(kc,{NIP05_REGEX:()=>Rc,isNip05:()=>Oc,isValid:()=>Lc,queryProfile:()=>Tc,searchDomain:()=>Bc,useFetchImplementation:()=>Ic});var Ac,Rc=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,Oc=e=>Rc.test(e||"");try{Ac=fetch}catch(e){}function Ic(e){Ac=e}async function Bc(e,t=""){try{const n=`https://${e}/.well-known/nostr.json?name=${t}`,r=await Ac(n,{redirect:"manual"});if(200!==r.status)throw Error("Wrong response code");return(await r.json()).names}catch(e){return{}}}async function Tc(e){const t=e.match(Rc);if(!t)return null;const[,n="_",r]=t;try{const e=`https://${r}/.well-known/nostr.json?name=${n}`,t=await Ac(e,{redirect:"manual"});if(200!==t.status)throw Error("Wrong response code");const o=await t.json(),i=o.names[n];return i?{pubkey:i,relays:o.relays?.[i]}:null}catch(e){return null}}async function Lc(e,t){const n=await Tc(t);return!!n&&n.pubkey===e}var Pc={};function _c(e){const t={reply:void 0,root:void 0,mentions:[],profiles:[],quotes:[]};let n,r;for(let o=e.tags.length-1;o>=0;o--){const i=e.tags[o];if("e"===i[0]&&i[1]&&Mr(i[1])){const[e,o,s,a,c]=i,l={id:o,relays:s?[s]:[],author:c&&Mr(c)?c:void 0};if("root"===a){t.root=l;continue}if("reply"===a){t.reply=l;continue}if("mention"===a){t.mentions.push(l);continue}n?r=l:n=l,t.mentions.push(l)}else{if("q"===i[0]&&i[1]&&Mr(i[1])){const[e,n,r]=i;t.quotes.push({id:n,relays:r?[r]:[]})}"p"===i[0]&&i[1]&&Mr(i[1])&&t.profiles.push({pubkey:i[1],relays:i[2]?[i[2]]:[]})}}return t.root||(t.root=r||n||t.reply),t.reply||(t.reply=n||t.root),[t.reply,t.root].forEach((e=>{if(!e)return;let n=t.mentions.indexOf(e);if(-1!==n&&t.mentions.splice(n,1),e.author){let n=t.profiles.find((t=>t.pubkey===e.author));n&&n.relays&&(e.relays||(e.relays=[]),n.relays.forEach((t=>{-1===e.relays?.indexOf(t)&&e.relays.push(t)})),n.relays=e.relays)}})),t.mentions.forEach((e=>{if(e.author){let n=t.profiles.find((t=>t.pubkey===e.author));n&&n.relays&&(e.relays||(e.relays=[]),n.relays.forEach((t=>{-1===e.relays.indexOf(t)&&e.relays.push(t)})),n.relays=e.relays)}})),t}Br(Pc,{parse:()=>_c});var Uc={};Br(Uc,{fetchRelayInformation:()=>Cc,useFetchImplementation:()=>Nc});try{fetch}catch{}function Nc(e){0}async function Cc(e){return await(await fetch(e.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var $c={};function Mc(e){let t=0;for(let n=0;n<64;n+=8){const r=parseInt(e.substring(n,n+8),16);if(0!==r){t+=Math.clz32(r);break}t+=32}return t}function Fc(e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];if(0!==r){t+=Math.clz32(r)-24;break}t+=8}return t}function Dc(e,t){let n=0;const r=e,o=["nonce",n.toString(),t.toString()];for(r.tags.push(o);;){const e=Math.floor((new Date).getTime()/1e3);e!==r.created_at&&(n=0,r.created_at=e),o[1]=(++n).toString();const i=_(Pr.encode(JSON.stringify([0,r.pubkey,r.created_at,r.kind,r.tags,r.content])));if(Fc(i)>=t){r.id=f(i);break}}return r}Br($c,{getPow:()=>Mc,minePow:()=>Dc});var Hc={};Br(Hc,{unwrapEvent:()=>yl,unwrapManyEvents:()=>wl,wrapEvent:()=>pl,wrapManyEvents:()=>gl});var qc={};Br(qc,{createRumor:()=>al,createSeal:()=>cl,createWrap:()=>ll,unwrapEvent:()=>hl,unwrapManyEvents:()=>fl,wrapEvent:()=>ul,wrapManyEvents:()=>dl});var jc={};Br(jc,{decrypt:()=>el,encrypt:()=>Qc,getConversationKey:()=>Kc,v2:()=>tl});var Vc=1,Wc=4294967295,zc=65536;function Kc(e,t){const n=st.getSharedSecret(e,E("02"+t)).subarray(1,33);return kr(_,n,Pr.encode("nip44-v2"))}function Gc(e,t){const n=Or(_,e,t,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function Zc(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("expected positive integer");if(e<=32)return 32;const t=2**(Math.floor(Math.log2(e-1))+1),n=t<=256?32:t/8;return n*(Math.floor((e-1)/n)+1)}function Jc(e){const t=Pr.encode(e),n=t.length;if(n<Vc||n>Wc)throw new Error("invalid plaintext size: must be between 1 and 4294967295 bytes");const r=n>=zc?x(new Uint8Array([0,0]),function(e){if(!Number.isSafeInteger(e)||e<zc||e>Wc)throw new Error("invalid plaintext size: must be between 65536 and 4294967295 bytes");const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t}(n)):function(e){if(!Number.isSafeInteger(e)||e<Vc||e>65535)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}(n);return x(r,t,new Uint8Array(Zc(n)-n))}function Xc(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint16(0);let r,o;if(0===n){if(r=t.getUint32(2),r<zc)throw new Error("invalid padding");o=6}else r=n,o=2;const i=e.subarray(o,o+r);if(r<Vc||r>Wc||i.length!==r||e.length!==o+Zc(r))throw new Error("invalid padding");return Lr.decode(i)}function Yc(e,t,n){if(32!==n.length)throw new Error("AAD associated data must be 32 bytes");const r=x(n,t);return Me(_,e,r)}function Qc(e,t,n=k(32)){const{chacha_key:r,chacha_nonce:o,hmac_key:i}=Gc(t,n),s=Jc(e),a=wr(r,o,s),c=Yc(i,a,n);return Wt.encode(x(new Uint8Array([2]),n,a,c))}function el(e,t){const{nonce:n,ciphertext:r,mac:o}=function(e){if("string"!=typeof e)throw new Error("payload must be a valid string");const t=e.length;if(t<132)throw new Error("invalid payload length: "+t);if("#"===e[0])throw new Error("unknown encryption version");let n;try{n=Wt.decode(e)}catch(e){throw new Error("invalid base64: "+e.message)}const r=n.length;if(r<99)throw new Error("invalid data length: "+r);const o=n[0];if(2!==o)throw new Error("unknown encryption version "+o);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}(e),{chacha_key:i,chacha_nonce:s,hmac_key:a}=Gc(t,n);if(!yn(Yc(a,r,n),o))throw new Error("invalid MAC");return Xc(wr(i,s,r))}var tl={utils:{getConversationKey:Kc,calcPaddedLen:Zc,pad:Jc,unpad:Xc},encrypt:Qc,decrypt:el},nl=()=>Math.round(Date.now()/1e3),rl=()=>Math.round(nl()-172800*Math.random()),ol=(e,t)=>Kc(e,t),il=(e,t,n)=>Qc(JSON.stringify(e),ol(t,n)),sl=(e,t)=>JSON.parse(el(e.content,ol(t,e.pubkey)));function al(e,t){const n={created_at:nl(),content:"",tags:[],...e,pubkey:Kr(t)};return n.id=Vr(n),n}function cl(e,t,n){return Gr({kind:wo,content:il(e,t,n),created_at:rl(),tags:[]},t)}function ll(e,t){const n=zr();return Gr({kind:Mo,content:il(e,n,t),created_at:rl(),tags:[["p",t]]},n)}function ul(e,t,n){return ll(cl(al(e,t),t,n),n)}function dl(e,t,n){if(!n||0===n.length)throw new Error("At least one recipient is required.");const r=Kr(t),o=[ul(e,t,r)];return n.forEach((n=>{o.push(ul(e,t,n))})),o}function hl(e,t){const n=sl(e,t);return sl(n,t)}function fl(e,t){let n=[];return e.forEach((e=>{n.push(hl(e,t))})),n.sort(((e,t)=>e.created_at-t.created_at)),n}function pl(e,t,n,r,o){const i=function(e,t,n,r){const o={created_at:Math.ceil(Date.now()/1e3),kind:mo,tags:[],content:t};return(Array.isArray(e)?e:[e]).forEach((({publicKey:e,relayUrl:t})=>{o.tags.push(t?["p",e,t]:["p",e])})),r&&o.tags.push(["e",r.eventId,r.relayUrl||"","reply"]),n&&o.tags.push(["subject",n]),o}(t,n,r,o);return ul(i,e,t.publicKey)}function gl(e,t,n,r,o){if(!t||0===t.length)throw new Error("At least one recipient is required.");return[{publicKey:Kr(e)},...t].map((t=>pl(e,t,n,r,o)))}var yl=hl,wl=fl,ml={};function bl(e,t,n,r){let o;const i=[...e.tags??[],["e",t.id,n],["p",t.pubkey]];return t.kind===oo?o=lo:(o=vo,i.push(["k",String(t.kind)])),Gr({kind:o,tags:i,content:""===e.content||t.tags?.find((e=>"-"===e[0]))?"":JSON.stringify(t),created_at:e.created_at},r)}function vl(e){if(![lo,vo].includes(e.kind))return;let t,n;for(let r=e.tags.length-1;r>=0&&(void 0===t||void 0===n);r--){const o=e.tags[r];o.length>=2&&("e"===o[0]&&void 0===t?t=o:"p"===o[0]&&void 0===n&&(n=o))}return void 0!==t?{id:t[1],relays:[t[2],n?.[2]].filter((e=>"string"==typeof e)),author:n?.[1]}:void 0}function El(e,{skipVerification:t}={}){const n=vl(e);if(void 0===n||""===e.content)return;let r;try{r=JSON.parse(e.content)}catch(e){return}return r.id===n.id&&(t||Zr(r))?r:void 0}Br(ml,{finishRepostEvent:()=>bl,getRepostedEvent:()=>El,getRepostedEventPointer:()=>vl});var xl={};Br(xl,{NOSTR_URI_REGEX:()=>Sl,parse:()=>Al,test:()=>kl});var Sl=new RegExp(`nostr:(${ic.source})`);function kl(e){return"string"==typeof e&&new RegExp(`^${Sl.source}$`).test(e)}function Al(e){const t=e.match(new RegExp(`^${Sl.source}$`));if(!t)throw new Error(`Invalid Nostr URI: ${e}`);return{uri:t[0],value:t[1],decoded:ac(t[1])}}var Rl={};function Ol(e){if(e)return/^\d+$/.test(e)?parseInt(e,10):e}function Il(e,t){const n=e.indexOf(":"),r=e.indexOf(":",n+1);if(-1===n||-1===r)return;const o=parseInt(e.slice(0,n),10);if(Number.isNaN(o))return;const i=e.slice(n+1,r);return Mr(i)?{kind:o,pubkey:i,identifier:e.slice(r+1),relays:t?[t]:[]}:void 0}function Bl(e){switch(e[0]){case"E":case"e":if(!e[1]||!Mr(e[1]))return;return{id:e[1],relays:e[2]?[e[2]]:[],author:e[3]&&Mr(e[3])?e[3]:void 0};case"A":case"a":if(!e[1])return;return Il(e[1],e[2]);case"I":case"i":if(!e[1])return;return{value:e[1],hint:e[2]}}}function Tl(e){if(e[1]){if(e[1].includes(":"))return Il(e[1],e[2]);if(Mr(e[1]))return{id:e[1],relays:e[2]?[e[2]]:[],author:e[3]&&Mr(e[3])?e[3]:void 0}}}function Ll(e){return e.findLast((e=>"A"===e.tagName||"a"===e.tagName))?.pointer||e.findLast((e=>"I"===e.tagName||"i"===e.tagName))?.pointer||e.findLast((e=>"E"===e.tagName||"e"===e.tagName))?.pointer}function Pl(e,t){if(!e||!("id"in e)||!e.author)return;const n=t.find((t=>t.pubkey===e.author));n&&n.relays&&(e.relays||(e.relays=[]),n.relays.forEach((t=>{-1===e.relays.indexOf(t)&&e.relays.push(t)})),n.relays=e.relays)}function _l(e){const t={root:void 0,rootKind:void 0,reply:void 0,replyKind:void 0,mentions:[],quotes:[],profiles:[]},n=[],r=[];for(const o of e.tags)if("E"!==o[0]&&"A"!==o[0]&&"I"!==o[0]||!o[1])if("e"!==o[0]&&"a"!==o[0]&&"i"!==o[0]||!o[1])if("K"!==o[0])if("k"!==o[0])if("q"!==o[0])("P"===o[0]||"p"===o[0])&&o[1]&&Mr(o[1])&&t.profiles.push({pubkey:o[1],relays:o[2]?[o[2]]:[]});else{const e=Tl(o);e&&t.quotes.push(e)}else t.replyKind=Ol(o[1]);else t.rootKind=Ol(o[1]);else{const e=Bl(o);e&&r.push({tagName:o[0],pointer:e})}else{const e=Bl(o);e&&n.push({tagName:o[0],pointer:e})}return t.root=Ll(n),t.reply=Ll(r),Pl(t.root,t.profiles),Pl(t.reply,t.profiles),t.quotes.forEach((e=>Pl(e,t.profiles))),t}Br(Rl,{parse:()=>_l});var Ul={};function Nl(e,t,n){const r=t.tags.filter((e=>e.length>=2&&("e"===e[0]||"p"===e[0])));return Gr({...e,kind:uo,tags:[...e.tags??[],...r,["e",t.id],["p",t.pubkey]],content:e.content??"+"},n)}function Cl(e){if(e.kind!==uo)return;let t,n;for(let r=e.tags.length-1;r>=0&&(void 0===t||void 0===n);r--){const o=e.tags[r];o.length>=2&&("e"===o[0]&&void 0===t?t=o:"p"===o[0]&&void 0===n&&(n=o))}return void 0!==t&&void 0!==n?{id:t[1],relays:[t[2],n[2]].filter((e=>void 0!==e)),author:n[1]}:void 0}Br(Ul,{finishReactionEvent:()=>Nl,getReactedEventPointer:()=>Cl});var $l={};Br($l,{parse:()=>Hl});var Ml=/\W/m,Fl=/[^\w\/] |[^\w\/]$|$|,| /m,Dl=42;function*Hl(e){let t=[];if("string"!=typeof e){for(let n=0;n<e.tags.length;n++){const r=e.tags[n];"emoji"===r[0]&&r.length>=3&&t.push({type:"emoji",shortcode:r[1],url:r[2]})}e=e.content}const n=e.length;let r=0,o=0;e:for(;o<n;){const i=e.indexOf(":",o),s=e.indexOf("#",o);if(-1===i&&-1===s)break e;if(-1===i||s>=0&&s<i){if(0===s||e[s-1].match(Ml)){const t=e.slice(s+1,s+Dl).match(Ml),i=t?s+1+t.index:n;yield{type:"text",text:e.slice(r,s)},yield{type:"hashtag",value:e.slice(s+1,i)},o=i,r=o;continue e}o=s+1}else if("nostr"===e.slice(i-5,i)){const t=e.slice(i+60).match(Ml),s=t?i+60+t.index:n;try{let t,{data:n,type:a}=ac(e.slice(i+1,s));switch(a){case"npub":t={pubkey:n};break;case"note":t={id:n};break;case"nsec":o=s+1;continue;default:t=n}r!==i-5&&(yield{type:"text",text:e.slice(r,i-5)}),yield{type:"reference",pointer:t},o=s,r=o;continue e}catch(e){o=i+1;continue e}}else if("https"===e.slice(i-5,i)||"http"===e.slice(i-4,i)){const t=e.slice(i+4).match(Fl),s=t?i+4+t.index:n,a="s"===e[i-1]?5:4;try{let t=new URL(e.slice(i-a,s));if(-1===t.hostname.indexOf("."))throw new Error("invalid url");if(r!==i-a&&(yield{type:"text",text:e.slice(r,i-a)}),/\.(png|jpe?g|gif|webp|heic|svg)$/i.test(t.pathname)){yield{type:"image",url:t.toString()},o=s,r=o;continue e}if(/\.(mp4|avi|webm|mkv|mov)$/i.test(t.pathname)){yield{type:"video",url:t.toString()},o=s,r=o;continue e}if(/\.(mp3|aac|ogg|opus|wav|flac)$/i.test(t.pathname)){yield{type:"audio",url:t.toString()},o=s,r=o;continue e}yield{type:"url",url:t.toString()},o=s,r=o;continue e}catch(e){o=s+1;continue e}}else{if("wss"!==e.slice(i-3,i)&&"ws"!==e.slice(i-2,i)){for(let n=0;n<t.length;n++){const s=t[n];if(":"===e[i+s.shortcode.length+1]&&e.slice(i+1,i+s.shortcode.length+1)===s.shortcode){r!==i&&(yield{type:"text",text:e.slice(r,i)}),yield s,o=i+s.shortcode.length+2,r=o;continue e}}o=i+1;continue e}{const t=e.slice(i+4).match(Fl),s=t?i+4+t.index:n,a="s"===e[i-1]?3:2;try{let t=new URL(e.slice(i-a,s));if(-1===t.hostname.indexOf("."))throw new Error("invalid ws url");r!==i-a&&(yield{type:"text",text:e.slice(r,i-a)}),yield{type:"relay",url:t.toString()},o=s,r=o;continue e}catch(e){o=s+1;continue e}}}}r!==n&&(yield{type:"text",text:e.slice(r)})}var ql={};Br(ql,{channelCreateEvent:()=>jl,channelHideMessageEvent:()=>zl,channelMessageEvent:()=>Wl,channelMetadataEvent:()=>Vl,channelMuteUserEvent:()=>Kl});var jl=(e,t)=>{let n;if("object"==typeof e.content)n=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;n=e.content}return Gr({kind:Ro,tags:[...e.tags??[]],content:n,created_at:e.created_at},t)},Vl=(e,t)=>{let n;if("object"==typeof e.content)n=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;n=e.content}return Gr({kind:Oo,tags:[["e",e.channel_create_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},Wl=(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"]),Gr({kind:Io,tags:[...n,...e.tags??[]],content:e.content,created_at:e.created_at},t)},zl=(e,t)=>{let n;if("object"==typeof e.content)n=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;n=e.content}return Gr({kind:Bo,tags:[["e",e.channel_message_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},Kl=(e,t)=>{let n;if("object"==typeof e.content)n=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;n=e.content}return Gr({kind:To,tags:[["p",e.pubkey_to_mute],...e.tags??[]],content:n,created_at:e.created_at},t)},Gl={};Br(Gl,{EMOJI_SHORTCODE_REGEX:()=>Zl,matchAll:()=>Xl,regex:()=>Jl,replaceAll:()=>Yl});var Zl=/:(\w+):/,Jl=()=>new RegExp(`\\B${Zl.source}\\B`,"g");function*Xl(e){const t=e.matchAll(Jl());for(const e of t)try{const[t,n]=e;yield{shortcode:t,name:n,start:e.index,end:e.index+t.length}}catch(e){}}function Yl(e,t){return e.replaceAll(Jl(),((e,n)=>t({shortcode:e,name:n})))}var Ql,eu={};Br(eu,{useFetchImplementation:()=>tu,validateGithub:()=>nu});try{Ql=fetch}catch{}function tu(e){Ql=e}async function nu(e,t,n){try{return await(await Ql(`https://gist.github.com/${t}/${n}/raw`)).text()===`Verifying that I control the following Nostr public key: ${e}`}catch(e){return!1}}var ru={};function ou(e){const{host:t,pathname:n,searchParams:r}=new URL(e),o=n||t,i=r.getAll("relay"),s=r.get("secret");if(!o||0===i.length||!s)throw new Error("invalid connection string");return{pubkey:o,relay:i[0],relays:i,secret:s}}async function iu(e,t,n){const r={method:"pay_invoice",params:{invoice:n}},o=Ec(t,e,JSON.stringify(r)),i={kind:ms,created_at:Math.round(Date.now()/1e3),content:o,tags:[["p",e]]};return Gr(i,t)}Br(ru,{makeNwcRequestEvent:()=>iu,parseConnectionString:()=>ou});var su={};function au(e){return e=(e=e.trim().toLowerCase()).normalize("NFKC"),Array.from(e).map((e=>/\p{Letter}/u.test(e)||/\p{Number}/u.test(e)?e:"-")).join("")}Br(su,{normalizeIdentifier:()=>au});var cu,lu={};Br(lu,{getSatoshisAmountFromBolt11:()=>gu,getZapEndpoint:()=>du,makeZapReceipt:()=>pu,makeZapRequest:()=>hu,useFetchImplementation:()=>uu,validateZapRequest:()=>fu});try{cu=fetch}catch{}function uu(e){cu=e}async function du(e){try{let t="",{lud06:n,lud16:r}=JSON.parse(e.content);if(r){let[e,n]=r.split("@");t=new URL(`/.well-known/lnurlp/${e}`,`https://${n}`).toString()}else{if(!n)return null;{let{words:e}=nn.decode(n,1e3),r=nn.fromWords(e);t=Lr.decode(r)}}let o=await cu(t),i=await o.json();if(i.allowsNostr&&i.nostrPubkey)return i.callback}catch(e){}return null}function hu(e){let t={kind:9734,created_at:Math.round(Date.now()/1e3),content:e.comment||"",tags:[["p","pubkey"in e?e.pubkey:e.event.pubkey],["amount",e.amount.toString()],["relays",...e.relays]]};if("event"in e){if(t.tags.push(["e",e.event.id]),Yr(e.event.kind)){const n=["a",`${e.event.kind}:${e.event.pubkey}:`];t.tags.push(n)}else if(eo(e.event.kind)){let n=e.event.tags.find((([e,t])=>"d"===e&&t));if(!n)throw new Error("d tag not found or is empty");const r=["a",`${e.event.kind}:${e.event.pubkey}:${n[1]}`];t.tags.push(r)}t.tags.push(["k",e.event.kind.toString()])}return t}function fu(e){let t;try{t=JSON.parse(e)}catch(e){return"Invalid zap request JSON."}if(!Hr(t))return"Zap request is not a valid Nostr event.";if(!Zr(t))return"Invalid signature on zap request.";let n=t.tags.find((([e,t])=>"p"===e&&t));if(!n)return"Zap request doesn't have a 'p' tag.";if(!Mr(n[1]))return"Zap request 'p' tag is not valid hex.";let r=t.tags.find((([e,t])=>"e"===e&&t));return r&&!Mr(r[1])?"Zap request 'e' tag is not valid hex.":t.tags.find((([e,t])=>"relays"===e&&t))?null:"Zap request doesn't have a 'relays' tag."}function pu({zapRequest:e,preimage:t,bolt11:n,paidAt:r}){let o=JSON.parse(e),i=o.tags.filter((([e])=>"e"===e||"p"===e||"a"===e)),s={kind:9735,created_at:Math.round(r.getTime()/1e3),content:"",tags:[...i,["P",o.pubkey],["bolt11",n],["description",e]]};return t&&s.tags.push(["preimage",t]),s}function gu(e){if(e.length<50)return 0;const t=(e=e.substring(0,50)).lastIndexOf("1");if(-1===t)return 0;const n=e.substring(0,t);if(!n.startsWith("lnbc"))return 0;const r=n.substring(4);if(r.length<1)return 0;const o=r[r.length-1],i=o.charCodeAt(0)-"0".charCodeAt(0),s=i>=0&&i<=9;let a=r.length-1;if(s&&a++,a<1)return 0;const c=parseInt(r.substring(0,a));switch(o){case"m":return 1e5*c;case"u":return 100*c;case"n":return c/10;case"p":return c/1e4;default:return 1e8*c}}var yu={};Br(yu,{Negentropy:()=>Ou,NegentropyStorageVector:()=>Ru,NegentropySync:()=>Tu});var wu=32,mu=0,bu=1,vu=2,Eu=class{_raw;length;constructor(e){"number"==typeof e?(this._raw=new Uint8Array(e),this.length=0):e instanceof Uint8Array?(this._raw=new Uint8Array(e),this.length=e.length):(this._raw=new Uint8Array(512),this.length=0)}unwrap(){return this._raw.subarray(0,this.length)}get capacity(){return this._raw.byteLength}extend(e){if(e instanceof Eu&&(e=e.unwrap()),"number"!=typeof e.length)throw Error("bad length");const t=e.length+this.length;if(this.capacity<t){const e=this._raw,n=Math.max(2*this.capacity,t);this._raw=new Uint8Array(n),this._raw.set(e)}this._raw.set(e,this.length),this.length+=e.length}shift(){const e=this._raw[0];return this._raw=this._raw.subarray(1),this.length--,e}shiftN(e=1){const t=this._raw.subarray(0,e);return this._raw=this._raw.subarray(e),this.length-=e,t}};function xu(e){let t=0;for(;;){if(0===e.length)throw Error("parse ends prematurely");let n=e.shift();if(t=t<<7|127&n,!(128&n))break}return t}function Su(e){if(0===e)return new Eu(new Uint8Array([0]));let t=[];for(;0!==e;)t.push(127&e),e>>>=7;t.reverse();for(let e=0;e<t.length-1;e++)t[e]|=128;return new Eu(new Uint8Array(t))}function ku(e,t){if(e.length<t)throw Error("parse ends prematurely");return e.shiftN(t)}var Au=class{buf;constructor(){this.setToZero()}setToZero(){this.buf=new Uint8Array(wu)}add(e){let t=0,n=0,r=new DataView(this.buf.buffer),o=new DataView(e.buffer);for(let e=0;e<8;e++){let i=4*e,s=r.getUint32(i,!0);s+=t,s+=o.getUint32(i,!0),s>4294967295&&(n=1),r.setUint32(i,4294967295&s,!0),t=n,n=0}}negate(){let e=new DataView(this.buf.buffer);for(let t=0;t<8;t++){let n=4*t;e.setUint32(n,~e.getUint32(n,!0))}let t=new Uint8Array(wu);t[0]=1,this.add(t)}getFingerprint(e){let t=new Eu;return t.extend(this.buf),t.extend(Su(e)),_(t.unwrap()).subarray(0,16)}},Ru=class{items;sealed;constructor(){this.items=[],this.sealed=!1}insert(e,t){if(this.sealed)throw Error("already sealed");const n=E(t);if(n.byteLength!==wu)throw Error("bad id size for added item");this.items.push({timestamp:e,id:n})}seal(){if(this.sealed)throw Error("already sealed");this.sealed=!0,this.items.sort(Bu);for(let e=1;e<this.items.length;e++)if(0===Bu(this.items[e-1],this.items[e]))throw Error("duplicate item inserted")}unseal(){this.sealed=!1}size(){return this._checkSealed(),this.items.length}getItem(e){if(this._checkSealed(),e>=this.items.length)throw Error("out of range");return this.items[e]}iterate(e,t,n){this._checkSealed(),this._checkBounds(e,t);for(let r=e;r<t&&n(this.items[r],r);++r);}findLowerBound(e,t,n){return this._checkSealed(),this._checkBounds(e,t),this._binarySearch(this.items,e,t,(e=>Bu(e,n)<0))}fingerprint(e,t){let n=new Au;return n.setToZero(),this.iterate(e,t,(e=>(n.add(e.id),!0))),n.getFingerprint(t-e)}_checkSealed(){if(!this.sealed)throw Error("not sealed")}_checkBounds(e,t){if(e>t||t>this.items.length)throw Error("bad range")}_binarySearch(e,t,n,r){let o=n-t;for(;o>0;){let n=t,i=Math.floor(o/2);n+=i,r(e[n])?(t=++n,o-=i+1):o=i}return t}},Ou=class{storage;frameSizeLimit;lastTimestampIn;lastTimestampOut;constructor(e,t=6e4){if(t<4096)throw Error("frameSizeLimit too small");this.storage=e,this.frameSizeLimit=t,this.lastTimestampIn=0,this.lastTimestampOut=0}_bound(e,t){return{timestamp:e,id:t||new Uint8Array(0)}}initiate(){let e=new Eu;return e.extend(new Uint8Array([97])),this.splitRange(0,this.storage.size(),this._bound(Number.MAX_VALUE),e),f(e.unwrap())}reconcile(e,t,n){const r=new Eu(E(e));this.lastTimestampIn=this.lastTimestampOut=0;let o=new Eu;o.extend(new Uint8Array([97]));let i=ku(r,1)[0];if(i<96||i>111)throw Error("invalid negentropy protocol version byte");if(97!==i)throw Error("unsupported negentropy protocol version requested: "+(i-96));let s=this.storage.size(),a=this._bound(0),c=0,l=!1;for(;0!==r.length;){let e=new Eu,i=()=>{l&&(l=!1,e.extend(this.encodeBound(a)),e.extend(Su(mu)))},u=this.decodeBound(r),d=xu(r),h=c,p=this.storage.findLowerBound(c,s,u);if(d===mu)l=!0;else if(d===bu){0!==Iu(ku(r,16),this.storage.fingerprint(h,p))?(i(),this.splitRange(h,p,u,e)):l=!0}else{if(d!==vu)throw Error("unexpected mode");{let e=xu(r),o={};for(let t=0;t<e;t++){let e=ku(r,wu);o[f(e)]=e}if(l=!0,this.storage.iterate(h,p,(e=>{let n=e.id;const r=f(n);return o[r]?delete o[f(n)]:t?.(r),!0})),n)for(let e of Object.values(o))n(f(e))}}if(this.exceededFrameSizeLimit(o.length+e.length)){let e=this.storage.fingerprint(p,s);o.extend(this.encodeBound(this._bound(Number.MAX_VALUE))),o.extend(Su(bu)),o.extend(e);break}o.extend(e),c=p,a=u}return 1===o.length?null:f(o.unwrap())}splitRange(e,t,n,r){let o=t-e;if(o<32)r.extend(this.encodeBound(n)),r.extend(Su(vu)),r.extend(Su(o)),this.storage.iterate(e,t,(e=>(r.extend(e.id),!0)));else{let i=Math.floor(o/16),s=o%16,a=e;for(let e=0;e<16;e++){let o,c=i+(e<s?1:0),l=this.storage.fingerprint(a,a+c);if(a+=c,a===t)o=n;else{let e,t;this.storage.iterate(a-1,a+1,((n,r)=>(r===a-1?e=n:t=n,!0))),o=this.getMinimalBound(e,t)}r.extend(this.encodeBound(o)),r.extend(Su(bu)),r.extend(l)}}}exceededFrameSizeLimit(e){return e>this.frameSizeLimit-200}decodeTimestampIn(e){let t=xu(e);return t=0===t?Number.MAX_VALUE:t-1,this.lastTimestampIn===Number.MAX_VALUE||t===Number.MAX_VALUE?(this.lastTimestampIn=Number.MAX_VALUE,Number.MAX_VALUE):(t+=this.lastTimestampIn,this.lastTimestampIn=t,t)}decodeBound(e){let t=this.decodeTimestampIn(e),n=xu(e);if(n>wu)throw Error("bound key too long");return{timestamp:t,id:ku(e,n)}}encodeTimestampOut(e){if(e===Number.MAX_VALUE)return this.lastTimestampOut=Number.MAX_VALUE,Su(0);let t=e;return e-=this.lastTimestampOut,this.lastTimestampOut=t,Su(e+1)}encodeBound(e){let t=new Eu;return t.extend(this.encodeTimestampOut(e.timestamp)),t.extend(Su(e.id.length)),t.extend(e.id),t}getMinimalBound(e,t){if(t.timestamp!==e.timestamp)return this._bound(t.timestamp);{let n=0,r=t.id,o=e.id;for(let e=0;e<wu&&r[e]===o[e];e++)n++;return this._bound(t.timestamp,t.id.subarray(0,n+1))}}};function Iu(e,t){for(let n=0;n<e.byteLength;n++){if(e[n]<t[n])return-1;if(e[n]>t[n])return 1}return e.byteLength>t.byteLength?1:e.byteLength<t.byteLength?-1:0}function Bu(e,t){return e.timestamp===t.timestamp?Iu(e.id,t.id):e.timestamp-t.timestamp}var Tu=class{relay;storage;neg;filter;subscription;onhave;onneed;constructor(e,t,n,r={}){this.relay=e,this.storage=t,this.neg=new Ou(t),this.onhave=r.onhave,this.onneed=r.onneed,this.filter=n,this.subscription=this.relay.prepareSubscription([{}],{label:r.label||"negentropy"}),this.subscription.oncustom=e=>{switch(e[0]){case"NEG-MSG":e.length<3&&console.warn(`got invalid NEG-MSG from ${this.relay.url}: ${e}`);try{const t=this.neg.reconcile(e[2],this.onhave,this.onneed);t?this.relay.send(`["NEG-MSG", "${this.subscription.id}", "${t}"]`):(this.close(),r.onclose?.())}catch(e){console.error("negentropy reconcile error:",e),r?.onclose?.(`reconcile error: ${e}`)}break;case"NEG-CLOSE":{const t=e[2];console.warn("negentropy error:",t),r.onclose?.(t);break}case"NEG-ERR":r.onclose?.()}}}async start(){const e=this.neg.initiate();this.relay.send(`["NEG-OPEN","${this.subscription.id}",${JSON.stringify(this.filter)},"${e}"]`)}close(){this.relay.send(`["NEG-CLOSE","${this.subscription.id}"]`),this.subscription.close()}},Lu={};Br(Lu,{getToken:()=>_u,hashPayload:()=>Du,unpackEventFromToken:()=>Nu,validateEvent:()=>qu,validateEventKind:()=>$u,validateEventMethodTag:()=>Fu,validateEventPayloadTag:()=>Hu,validateEventTimestamp:()=>Cu,validateEventUrlTag:()=>Mu,validateToken:()=>Uu});var Pu="Nostr ";async function _u(e,t,n,r=!1,o){const i={kind:xs,tags:[["u",e],["method",t]],created_at:Math.round((new Date).getTime()/1e3),content:""};o&&i.tags.push(["payload",Du(o)]);const s=await n(i);return(r?Pu:"")+Wt.encode(Pr.encode(JSON.stringify(s)))}async function Uu(e,t,n){const r=await Nu(e).catch((e=>{throw e}));return await qu(r,t,n).catch((e=>{throw e}))}async function Nu(e){if(!e)throw new Error("Missing token");e=e.replace(Pu,"");const t=Lr.decode(Wt.decode(e));if(!t||0===t.length||!t.startsWith("{"))throw new Error("Invalid token");return JSON.parse(t)}function Cu(e){return!!e.created_at&&Math.round((new Date).getTime()/1e3)-e.created_at<60}function $u(e){return e.kind===xs}function Mu(e,t){const n=e.tags.find((e=>"u"===e[0]));return!!n&&(n.length>0&&n[1]===t)}function Fu(e,t){const n=e.tags.find((e=>"method"===e[0]));return!!n&&(n.length>0&&n[1].toLowerCase()===t.toLowerCase())}function Du(e){return f(_(Pr.encode(JSON.stringify(e))))}function Hu(e,t){const n=e.tags.find((e=>"payload"===e[0]));if(!n)return!1;const r=Du(t);return n.length>0&&n[1]===r}async function qu(e,t,n,r){if(!Zr(e))throw new Error("Invalid nostr event, signature invalid");if(!$u(e))throw new Error("Invalid nostr event, kind invalid");if(!Cu(e))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!Mu(e,t))throw new Error("Invalid nostr event, url tag invalid");if(!Fu(e,n))throw new Error("Invalid nostr event, method tag invalid");if(Boolean(r)&&"object"==typeof r&&Object.keys(r).length>0&&!Hu(e,r))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}}},t={};function n(r){var o=t[r];if(void 0!==o)return o.exports;var i=t[r]={exports:{}};return e[r](i,i.exports,n),i.exports}n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};(()=>{var e=r;Object.defineProperty(e,"__esModule",{value:!0}),e.LNDataType=e.PaymentDirection=e.getOutgoingPayments=e.getIncomingPayments=e.getBalance=e.sendPayment=e.checkPayment=e.createInvoice=e.msatToSat=e.startLightning=void 0;var t=n(13);Object.defineProperty(e,"startLightning",{enumerable:!0,get:function(){return t.startLightning}});var o=n(805);Object.defineProperty(e,"msatToSat",{enumerable:!0,get:function(){return o.msatToSat}});var i=n(398);Object.defineProperty(e,"createInvoice",{enumerable:!0,get:function(){return i.createInvoice}}),Object.defineProperty(e,"checkPayment",{enumerable:!0,get:function(){return i.checkPayment}}),Object.defineProperty(e,"sendPayment",{enumerable:!0,get:function(){return i.sendPayment}}),Object.defineProperty(e,"getBalance",{enumerable:!0,get:function(){return i.getBalance}}),Object.defineProperty(e,"getIncomingPayments",{enumerable:!0,get:function(){return i.getIncomingPayments}}),Object.defineProperty(e,"getOutgoingPayments",{enumerable:!0,get:function(){return i.getOutgoingPayments}});var s=n(329);Object.defineProperty(e,"PaymentDirection",{enumerable:!0,get:function(){return s.PaymentDirection}}),Object.defineProperty(e,"LNDataType",{enumerable:!0,get:function(){return s.LNDataType}})})();var o=exports;for(var i in r)o[i]=r[i];r.__esModule&&Object.defineProperty(o,"__esModule",{value:!0})})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coinexams/lightning",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "CoinExams Lightning Payment SDK - A standalone Lightning Network client module that wraps a local Phoenixd node REST API.",
5
5
  "main": "dist/node/lightning.node.min.js",
6
6
  "module": "dist/node/lightning.node.min.js",