@coinexams/lightning 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,244 @@
1
+ # CoinExams Lightning Payment SDK
2
+
3
+ A standalone Lightning Network client module that wraps a local Phoenixd node REST API. It provides invoice creation, payment sending, balance queries, LNURL-pay request handling, and Nostr Zap receipt signing/publishing.
4
+
5
+ ## Change Log
6
+ [Change Log](changes.md)
7
+
8
+ ## Architecture
9
+
10
+ ```
11
+ lightning/
12
+ ├── README.md
13
+ ├── index.ts # Public barrel exports
14
+ └── code/
15
+ ├── client.ts # startLightning() factory → LightningClient
16
+ ├── payment.ts # Convenience wrappers (optional DI)
17
+ ├── types.ts # All type definitions
18
+ └── utils.ts # Helpers (regex, timers, nostr parsing)
19
+ ```
20
+
21
+ ## Getting Started
22
+
23
+ ### 1. Create a client
24
+
25
+ ```ts
26
+ import { startLightning } from "./lightning";
27
+
28
+ const client = startLightning({
29
+ port: 9740,
30
+ cacheDurationMs: 1000,
31
+ serverPrvKeyBytes: new Uint8Array([...]),
32
+ serverPubKeyHex: "abc123...",
33
+ defaultRelays: ["wss://relay.damus.io"],
34
+ domain: "example.com",
35
+ });
36
+ ```
37
+
38
+ ### 2. Use the client
39
+
40
+ #### Create an invoice
41
+
42
+ ```ts
43
+ const invoice = client.newInvoice({ amountSat: 1000, description: "test" });
44
+ // → { invoiceString: "lnbc1...", invoiceId: "abc..." }
45
+ ```
46
+
47
+ #### Check payment status
48
+
49
+ ```ts
50
+ import { PaymentDirection } from "./lightning";
51
+
52
+ const payment = client.checkInvoice({
53
+ invoiceId: "abc...",
54
+ type: PaymentDirection.Incoming,
55
+ });
56
+ // → IncomingPayment | undefined
57
+ ```
58
+
59
+ #### Send a payment
60
+
61
+ ```ts
62
+ const sent = client.payInvoice({
63
+ amountSat: 500,
64
+ lightningAddress: "user@example.com",
65
+ });
66
+ // → { recipientAmountSat: 500, paymentHash: "...", ... }
67
+
68
+ // On-chain:
69
+ const onchain = client.payInvoice({
70
+ amountSat: 10000,
71
+ onChain: true,
72
+ onChainAddress: "bc1...",
73
+ });
74
+ ```
75
+
76
+ #### Query balance or payment history
77
+
78
+ ```ts
79
+ const balance = client.nodeQuery({ type: "getbalance" });
80
+ // → { balanceSat: 50000, feeCreditSat: 100 }
81
+
82
+ const incoming = client.nodeQuery({
83
+ type: "payments/incoming",
84
+ params: { limit: 10 },
85
+ });
86
+ // → IncomingPayment[]
87
+ ```
88
+
89
+ #### Handle LNURL-pay (with optional zap)
90
+
91
+ ```ts
92
+ const result = client.payRequest({
93
+ user: "alice",
94
+ amountMsat: 100000, // 100 sats
95
+ nostr: "<zap-request-json-or-base64>", // optional
96
+ });
97
+ // → { invoice: { pr: "lnbc...", routes: [] }, invoiceId: "..." }
98
+ ```
99
+
100
+ #### Zap receipt signing & publishing
101
+
102
+ ```ts
103
+ await client.zapPublish({
104
+ nostr: "<zap-request>",
105
+ bolt11: "lnbc...",
106
+ invoiceId: "abc...",
107
+ });
108
+ // Polls until paid, then signs & publishes a kind-9735 receipt
109
+ ```
110
+
111
+ ## Convenience Wrappers (optional)
112
+
113
+ The `payment.ts` file exports stateless function wrappers if you prefer functional style:
114
+
115
+ ```ts
116
+ import {
117
+ createInvoice,
118
+ checkPayment,
119
+ sendPayment,
120
+ getBalance,
121
+ } from "./lightning";
122
+
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);
127
+ ```
128
+
129
+ ## Environment Variables (example)
130
+
131
+ When wiring up from a server entry point:
132
+
133
+ ```env
134
+ PHOENIX_SERVER_PORT=9740
135
+ ADDRESS_LIGHTNING=bob@example.com
136
+ ADDRESS_ONCHAIN=bc1...
137
+ SERVER_PRV_KEY=<hex-encoded-key>
138
+ SERVER_PUB_KEY=<hex-encoded-pubkey>
139
+ ADMIN_USERNAME=admin
140
+ SERVER_USERNAME=server
141
+ ADMIN_PASSWORD=<admin-pw>
142
+ ```
143
+
144
+ ## Error Handling
145
+
146
+ All client methods return `undefined` on failure and log the error via `console.error` with an ISO timestamp prefix. Check for `undefined` to detect failures:
147
+
148
+ ```ts
149
+ const invoice = client.newInvoice({ amountSat: 100 });
150
+ if (!invoice) {
151
+ // handle error
152
+ }
153
+ ```
154
+
155
+ ## Dependency Setup: Phoenixd
156
+
157
+ Run this on a root-access server to install and configure Phoenixd as a systemd service:
158
+
159
+ ```bash
160
+ #!/bin/bash
161
+
162
+ # ssh root@IP 'bash -s' < ./server/phoenix/setup.sh
163
+
164
+ # Leave empty to generate a new wallet or paste your 12 words
165
+ SEED=""
166
+
167
+ # --- 1. CONFIGURATION ---
168
+ PHOENIX_VERSION="0.7.1"
169
+ PORT="9740"
170
+ BIND_IP="127.0.0.1"
171
+ DATADIR="/root/.phoenix"
172
+ OUTPUT_FILE="$DATADIR/credentials.json"
173
+ INSTALL_DIR="/opt/phoenix-setup"
174
+
175
+ mkdir -p "$INSTALL_DIR" "$DATADIR"
176
+ cd "$INSTALL_DIR"
177
+
178
+ # --- 2. INSTALL DEPENDENCIES ---
179
+ apt-get update && apt-get install -y wget unzip curl jq
180
+
181
+ # --- 3. DOWNLOAD ---
182
+ wget -q "https://github.com/ACINQ/phoenixd/releases/download/v$PHOENIX_VERSION/phoenixd-$PHOENIX_VERSION-linux-x64.zip"
183
+ unzip -o "phoenixd-$PHOENIX_VERSION-linux-x64.zip"
184
+ find . -name "phoenixd" -exec mv {} "$INSTALL_DIR/phoenixd" \;
185
+ chmod +x "$INSTALL_DIR/phoenixd"
186
+
187
+ # --- 4. INITIALIZE ---
188
+ echo "Initializing phoenixd..."
189
+ export PHOENIX_DATADIR="$DATADIR"
190
+
191
+ if [ -z "$SEED" ]; then
192
+ "$INSTALL_DIR/phoenixd" > /dev/null 2>&1 &
193
+ else
194
+ "$INSTALL_DIR/phoenixd" --seed "$SEED" > /dev/null 2>&1 &
195
+ fi
196
+
197
+ PHOENIX_PID=$!
198
+
199
+ for i in {1..20}; do
200
+ [ -f "$DATADIR/phoenix.conf" ] && break
201
+ sleep 1
202
+ done
203
+
204
+ kill $PHOENIX_PID 2>/dev/null || true
205
+ sleep 2
206
+
207
+ # --- 5. CREATE SYSTEMD SERVICE ---
208
+ cat > /etc/systemd/system/phoenixd.service <<EOF
209
+ [Unit]
210
+ Description=Phoenixd Lightning Service
211
+ After=network.target
212
+
213
+ [Service]
214
+ Environment=PHOENIX_DATADIR=$DATADIR
215
+ ExecStart=$INSTALL_DIR/phoenixd --http-bind-ip $BIND_IP --http-bind-port $PORT
216
+ User=root
217
+ Restart=always
218
+ WorkingDirectory=$INSTALL_DIR
219
+
220
+ [Install]
221
+ WantedBy=multi-user.target
222
+ EOF
223
+
224
+ # --- 6. START & SAVE ---
225
+ systemctl daemon-reload
226
+ systemctl enable --now phoenixd
227
+
228
+ API_PASSWORD=$(grep "^http-password=" "$DATADIR/phoenix.conf" | cut -d'=' -f2 | tr -d '[:space:]')
229
+ jq -n --arg pw "$API_PASSWORD" --arg port "$PORT" \
230
+ '{password: $pw, port: $port}' > "$OUTPUT_FILE"
231
+ chmod 600 "$OUTPUT_FILE"
232
+ ```
233
+
234
+ After setup, the password and port are saved in `/root/.phoenix/credentials.json` — pass them to `startLightning()`.
235
+
236
+ ## Installation
237
+
238
+ ```bash
239
+ npm install @coinexams/lightning
240
+ ```
241
+
242
+ ## Change Log
243
+
244
+ See [changes.md](changes.md).
@@ -0,0 +1,12 @@
1
+ import { LightningClient } from "./types";
2
+ declare const startLightning: ({ password: directPassword, credentialsPath, port, cacheDurationMs, serverPrvKeyBytes, serverPubKeyHex, defaultRelays, domain, }: {
3
+ password?: string;
4
+ credentialsPath?: string;
5
+ port: number;
6
+ cacheDurationMs: number;
7
+ serverPrvKeyBytes: Uint8Array;
8
+ serverPubKeyHex: string;
9
+ defaultRelays: string[];
10
+ domain: string;
11
+ }) => LightningClient;
12
+ export { startLightning };
@@ -0,0 +1,32 @@
1
+ import { PaymentInvoiceDetails, IncomingPayment, OutgoingPaymentLN, SentPayment, LNBalance, LightningClient, PaymentDirection } from "./types";
2
+ declare const createInvoice: ({ client, amountSat, description, }: {
3
+ client: LightningClient;
4
+ amountSat: number;
5
+ description?: string;
6
+ }) => PaymentInvoiceDetails | undefined;
7
+ declare const checkPayment: ({ client, invoiceId, type, }: {
8
+ client: LightningClient;
9
+ invoiceId: string;
10
+ type: PaymentDirection;
11
+ }) => IncomingPayment | OutgoingPaymentLN | undefined;
12
+ declare const sendPayment: ({ client, amountSat, opts, }: {
13
+ client: LightningClient;
14
+ amountSat: number;
15
+ opts?: {
16
+ onChain?: boolean;
17
+ lightningAddress?: string;
18
+ onChainAddress?: string;
19
+ };
20
+ }) => SentPayment | undefined;
21
+ declare const getBalance: ({ client, }: {
22
+ client: LightningClient;
23
+ }) => LNBalance | undefined;
24
+ declare const getIncomingPayments: ({ client, limit, }: {
25
+ client: LightningClient;
26
+ limit?: number;
27
+ }) => IncomingPayment[] | undefined;
28
+ declare const getOutgoingPayments: ({ client, limit, }: {
29
+ client: LightningClient;
30
+ limit?: number;
31
+ }) => OutgoingPaymentLN[] | undefined;
32
+ export { createInvoice, checkPayment, sendPayment, getBalance, getIncomingPayments, getOutgoingPayments, };
@@ -0,0 +1,152 @@
1
+ import { VerifiedEvent } from "nostr-tools";
2
+ interface PaymentMakeRequest {
3
+ amountSat: number;
4
+ onChain?: boolean;
5
+ }
6
+ interface PaymentNewRequest {
7
+ amountSat: number;
8
+ description?: string;
9
+ }
10
+ interface PaymentInvoiceDetails {
11
+ invoiceString: string;
12
+ invoiceId: string;
13
+ }
14
+ declare enum PaymentDirection {
15
+ Incoming = "incoming",
16
+ Outgoing = "outgoing"
17
+ }
18
+ interface PaymentCheck {
19
+ invoiceId: string;
20
+ type: PaymentDirection;
21
+ }
22
+ declare enum LNDataType {
23
+ GetBalance = "getbalance",
24
+ GetInfo = "getinfo",
25
+ PaymentsIncoming = "payments/incoming",
26
+ PaymentsOutgoing = "payments/outgoing"
27
+ }
28
+ interface LNDataParams {
29
+ limit?: number;
30
+ offset?: number;
31
+ }
32
+ interface LNDataRequest {
33
+ type: string;
34
+ params?: Record<string, string | number>;
35
+ }
36
+ interface LNBalance {
37
+ balanceSat: number;
38
+ feeCreditSat: number;
39
+ }
40
+ interface IncomingPayment {
41
+ type: `incoming_payment`;
42
+ subType: `lightning`;
43
+ paymentHash: string;
44
+ preimage: string;
45
+ description: string;
46
+ invoice: string;
47
+ isPaid: boolean;
48
+ isExpired: boolean;
49
+ requestedSat: number;
50
+ receivedSat: number;
51
+ fees: number;
52
+ expiresAt: number;
53
+ completedAt: number;
54
+ createdAt: number;
55
+ }
56
+ interface OutgoingPaymentBase {
57
+ type: `outgoing_payment`;
58
+ isPaid: boolean;
59
+ sent: number;
60
+ fees: number;
61
+ completedAt: number;
62
+ createdAt: number;
63
+ }
64
+ interface OutgoingPaymentLN extends OutgoingPaymentBase {
65
+ subType: `lightning`;
66
+ invoice: string;
67
+ paymentHash: string;
68
+ preimage: string;
69
+ }
70
+ interface OutgoingPaymentLiquidity extends OutgoingPaymentBase {
71
+ subType: `auto_liquidity`;
72
+ txId: string;
73
+ }
74
+ interface NodeInfo {
75
+ nodeId: string;
76
+ channels: object[];
77
+ chain: string;
78
+ blockHeight: number;
79
+ version: string;
80
+ }
81
+ interface SentPayment {
82
+ recipientAmountSat: number;
83
+ routingFeeSat: number;
84
+ paymentId: string;
85
+ paymentHash: string;
86
+ paymentPreimage: string;
87
+ }
88
+ interface PaymentDoneResponse {
89
+ recipientAmountSat: number;
90
+ routingFeeSat: number;
91
+ paymentId: string;
92
+ paymentHash: string;
93
+ paymentPreimage: string;
94
+ }
95
+ interface NewInvoiceResponse {
96
+ amountSat: number;
97
+ paymentHash: string;
98
+ serialized: string;
99
+ }
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;
128
+ }
129
+ interface LnurlPayRequest {
130
+ callback: string;
131
+ maxSendable: number;
132
+ minSendable: number;
133
+ metadata: string;
134
+ tag: 'payRequest';
135
+ }
136
+ interface LnurlPayResponse {
137
+ pr: string;
138
+ routes: object[];
139
+ }
140
+ interface UserStoredPayment {
141
+ text: string;
142
+ sats: number;
143
+ time: number;
144
+ }
145
+ interface UserSeverData {
146
+ pass: string;
147
+ username: string;
148
+ payments: UserStoredPayment[];
149
+ }
150
+ type CacheData = LNBalance | NewInvoiceResponse | PaymentDoneResponse | (IncomingPayment | OutgoingPaymentLN)[] | NodeInfo | SentPayment | string;
151
+ 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, };
@@ -0,0 +1,6 @@
1
+ import { NostrEvent } from "nostr-tools";
2
+ declare const lightningAddressRegex: RegExp, tN: () => number, seoDt: () => string, delayCode: (ms: number) => Promise<unknown>;
3
+ declare const msatToSat: (msat: number | string | bigint) => number;
4
+ declare const parseNostrEvent: (nostr: string) => NostrEvent | undefined;
5
+ declare const eventRelays: (event: NostrEvent) => string[];
6
+ export { lightningAddressRegex, tN, seoDt, delayCode, msatToSat, parseNostrEvent, eventRelays, };
@@ -0,0 +1,3 @@
1
+ export { startLightning } from "./code/client";
2
+ export { createInvoice, checkPayment, sendPayment, getBalance, getIncomingPayments, getOutgoingPayments, } from "./code/payment";
3
+ export type { PaymentDirection, IncomingPayment, UserStoredPayment, UserSeverData, } from "./code/types";
@@ -0,0 +1,2 @@
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:()=>jr,getFilterLimit:()=>Pa,getPublicKey:()=>Kr,kinds:()=>Jr,matchFilter:()=>Ua,matchFilters:()=>_a,mergeFilters:()=>La,nip04:()=>vc,nip05:()=>kc,nip10:()=>_c,nip11:()=>Pc,nip13:()=>$c,nip17:()=>qc,nip18:()=>ml,nip19:()=>nc,nip21:()=>xl,nip22:()=>Rl,nip25:()=>Pl,nip27:()=>$l,nip28:()=>Dl,nip30:()=>Gl,nip39:()=>eu,nip42:()=>Da,nip44:()=>Vc,nip47:()=>ru,nip54:()=>su,nip57:()=>lu,nip59:()=>Dc,nip77:()=>yu,nip98:()=>Uu,parseReferences:()=>bc,serializeEvent:()=>Vr,sortEvents:()=>Dr,utils:()=>Tr,validateEvent:()=>qr,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 U 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 _ extends U{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 L=S((()=>new _),A(1)),P=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?P:BigInt("0x"+e)}function H(e){return F(f(e))}function q(e){return F(f(function(e){return Uint8Array.from(e)}(i(e)).reverse()))}function D(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 V(e,t){return D(e,t).reverse()}function j(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&&P<=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?V(e,this.BYTES):D(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?q(e):H(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?q(e):H(e),t-X)+X;return n?V(a,o):D(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,Ue=new WeakMap;function _e(e){return Ue.get(e)||1}function Le(e){if(e!==Se)throw new Error("invalid wNAF")}class Pe{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 Le(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 Le(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=_e(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const o=_e(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),Ue.set(e,t),Te.delete(e)}hasCache(e){return 1!==_e(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)}}}j("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 He(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>P;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 qe(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function De(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&&qe(n.format),n}class Ve extends Error{constructor(e=""){super(e)}}const je={Err:Ve,_tlv:{encode:(e,t)=>{const{Err:n}=je;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}=je;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}=je;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}=je;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 H(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=je,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}=je,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 He(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 Pe(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){qe(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}=je.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(qe(e),"der"===e)return E(je.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=H(e),n=8*e.length-h;return n>0?t>>BigInt(n):t},T=n.bits2int_modN||function(e){return u.create(B(e))},U=K(h);function _(e){return z("num < 2^"+h,e,We,U),u.toBytes(e)}function L(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}=De(r,b);t=L(t,s);const l=T(t),d=u.fromBytes(n);if(!u.isValidNot0(d))throw new Error("invalid private key");const h=[_(d),_(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}=De(s,b);if(o=i(o,void 0,"publicKey"),n=L(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}=De(n,b);return t=L(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,L),at={};function ct(e,...t){let n=at[e];if(void 0===n){const t=L(j(e));n=x(t,t),at[e]=n}return L(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=H;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 Ut(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 _t(e){return xt(e),{encode:e=>e,decode:t=>e(t)}}function Lt(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 Pt=(e,t)=>0===t?e:Pt(t,e%t),Nt=(e,t)=>e+(t-Pt(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 Lt(Array.from(t),256,e)},decode:t=>(Ot("radix.decode",t),Uint8Array.from(Lt(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 Ht(e){return xt(e),function(...t){try{return e.apply(null,t)}catch(e){}}}const qt=It(Ft(4),Bt("0123456789ABCDEF"),Tt("")),Dt=It(Ft(5),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Ut(5),Tt("")),Vt=(It(Ft(5),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Tt("")),It(Ft(5),Bt("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Ut(5),Tt("")),It(Ft(5),Bt("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Tt("")),It(Ft(5),Bt("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),Tt(""),_t((e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")))),(()=>"function"==typeof Uint8Array.from([]).toBase64&&"function"==typeof Uint8Array.fromBase64)()),jt=(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=Vt?{encode:e=>(vt(e),e.toBase64()),decode:e=>jt(e,!1)}:It(Ft(6),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Ut(6),Tt("")),zt=(It(Ft(6),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Tt("")),Vt?{encode:e=>(vt(e),e.toBase64({alphabet:"base64url"})),decode:e=>jt(e,!0)}:It(Ft(6),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Ut(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=Ht(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:Ht(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(""),_t((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 Un(e){return e<<1^283&-(e>>7)}function _n(e,t){let n=0;for(;t>0;t>>=1)n^=e&-(1&t),e=Un(e);return n}const Ln=(()=>{const e=new Uint8Array(256);for(let t=0,n=1;t<256;t++,n^=Un(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})(),Pn=Ln.map(((e,t)=>Ln.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(Ln,(e=>_n(e,3)<<24|e<<16|e<<8|_n(e,2))),Mn=Cn(Pn,(e=>_n(e,11)<<24|_n(e,13)<<16|_n(e,9)<<8|_n(e,14))),Fn=(()=>{const e=new Uint8Array(16);for(let t=0,n=1;t<16;t++,n=Un(n))e[t]=n;return e})();function Hn(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=>Vn(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 qn(e){const t=Hn(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=Vn(o,t,t,t,t);n[e]=i[255&r]^s[r>>>8&255]^a[r>>>16&255]^c[r>>>24]}return n}function Dn(e,t,n,r,o,i){return e[n<<8&65280|r>>>8&255]^t[o>>>8&65280|i>>>24&255]}function Vn(e,t,n,r,o){return e[255&t|65280&n]|e[r>>>16&255|o>>>16&65280]<<16}function jn(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++]^Dn(s,a,t,n,r,o),l=e[c++]^Dn(s,a,n,r,o,t),u=e[c++]^Dn(s,a,r,o,t,n),d=e[c++]^Dn(s,a,o,t,n,r);t=i,n=l,r=u,o=d}return{s0:e[c++]^Vn(i,t,n,r,o),s1:e[c++]^Vn(i,n,r,o,t),s2:e[c++]^Vn(i,r,o,t,n),s3:e[c++]^Vn(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++]^Dn(s,a,t,o,r,n),l=e[c++]^Dn(s,a,n,t,o,r),u=e[c++]^Dn(s,a,r,n,t,o),d=e[c++]^Dn(s,a,o,r,n,t);t=i,n=l,r=u,o=d}return{s0:e[c++]^Vn(i,t,o,r,n),s1:e[c++]^Vn(i,n,t,o,r),s2:e[c++]^Vn(i,r,n,t,o),s3:e[c++]^Vn(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=Hn(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}=jn(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}=jn(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=qn(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}=jn(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=Hn(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)),U=o[7]+(8191&(E>>>11|x<<5)),_=o[8]+(8191&(x>>>8|S<<8)),L=o[9]+(S>>>5|r),P=0,N=P+k*s+A*(5*g)+R*(5*p)+O*(5*f)+I*(5*h);P=N>>>13,N&=8191,N+=B*(5*d)+T*(5*u)+U*(5*l)+_*(5*c)+L*(5*a),P+=N>>>13,N&=8191;let C=P+k*a+A*s+R*(5*g)+O*(5*p)+I*(5*f);P=C>>>13,C&=8191,C+=B*(5*h)+T*(5*d)+U*(5*u)+_*(5*l)+L*(5*c),P+=C>>>13,C&=8191;let $=P+k*c+A*a+R*s+O*(5*g)+I*(5*p);P=$>>>13,$&=8191,$+=B*(5*f)+T*(5*h)+U*(5*d)+_*(5*u)+L*(5*l),P+=$>>>13,$&=8191;let M=P+k*l+A*c+R*a+O*s+I*(5*g);P=M>>>13,M&=8191,M+=B*(5*p)+T*(5*f)+U*(5*h)+_*(5*d)+L*(5*u),P+=M>>>13,M&=8191;let F=P+k*u+A*l+R*c+O*a+I*s;P=F>>>13,F&=8191,F+=B*(5*g)+T*(5*p)+U*(5*f)+_*(5*h)+L*(5*d),P+=F>>>13,F&=8191;let H=P+k*d+A*u+R*l+O*c+I*a;P=H>>>13,H&=8191,H+=B*s+T*(5*g)+U*(5*p)+_*(5*f)+L*(5*h),P+=H>>>13,H&=8191;let q=P+k*h+A*d+R*u+O*l+I*c;P=q>>>13,q&=8191,q+=B*a+T*s+U*(5*g)+_*(5*p)+L*(5*f),P+=q>>>13,q&=8191;let D=P+k*f+A*h+R*d+O*u+I*l;P=D>>>13,D&=8191,D+=B*c+T*a+U*s+_*(5*g)+L*(5*p),P+=D>>>13,D&=8191;let V=P+k*p+A*f+R*h+O*d+I*u;P=V>>>13,V&=8191,V+=B*l+T*c+U*a+_*s+L*(5*g),P+=V>>>13,V&=8191;let j=P+k*g+A*p+R*f+O*h+I*d;P=j>>>13,j&=8191,j+=B*u+T*l+U*c+_*a+L*s,P+=j>>>13,j&=8191,P=(P<<2)+P|0,P=P+N|0,N=8191&P,P>>>=13,C+=P,o[0]=N,o[1]=C,o[2]=$,o[3]=M,o[4]=F,o[5]=H,o[6]=q,o[7]=D,o[8]=V,o[9]=j}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,U=g,_=y,L=w,P=m,N=b,C=v,$=E;for(let e=0;e<i;e+=2)x=x+R|0,P=cr(P^x,16),T=T+P|0,R=cr(R^T,12),x=x+R|0,P=cr(P^x,8),T=T+P|0,R=cr(R^T,7),S=S+O|0,N=cr(N^S,16),U=U+N|0,O=cr(O^U,12),S=S+O|0,N=cr(N^S,8),U=U+N|0,O=cr(O^U,7),k=k+I|0,C=cr(C^k,16),_=_+C|0,I=cr(I^_,12),k=k+I|0,C=cr(C^k,8),_=_+C|0,I=cr(I^_,7),A=A+B|0,$=cr($^A,16),L=L+$|0,B=cr(B^L,12),A=A+B|0,$=cr($^A,8),L=L+$|0,B=cr(B^L,7),x=x+O|0,$=cr($^x,16),_=_+$|0,O=cr(O^_,12),x=x+O|0,$=cr($^x,8),_=_+$|0,O=cr(O^_,7),S=S+I|0,P=cr(P^S,16),L=L+P|0,I=cr(I^L,12),S=S+I|0,P=cr(P^S,8),L=L+P|0,I=cr(I^L,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),U=U+C|0,R=cr(R^U,12),A=A+R|0,C=cr(C^A,8),U=U+C|0,R=cr(R^U,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+U|0,r[M++]=y+_|0,r[M++]=w+L|0,r[M++]=m+P|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:()=>Pr,isHex32:()=>Mr,mergeReverseSortedLists:()=>$r,normalizeURL:()=>Lr,utf8Decoder:()=>Ur,utf8Encoder:()=>_r});var Ur=new TextDecoder("utf-8"),_r=new TextEncoder;function Lr(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 Pr(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"),Hr=e=>e instanceof Object;function qr(e){if(!Hr(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 Dr(e){return e.sort(((e,t)=>e.created_at!==t.created_at?t.created_at-e.created_at:e.id.localeCompare(t.id)))}function Vr(e){if(!qr(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 jr(e){return f(L(_r.encode(Vr(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=jr(n),n.sig=f(mt.sign(E(jr(n)),t)),n[Fr]=!0,n}verifyEvent(e){if("boolean"==typeof e[Fr])return e[Fr];try{const t=jr(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 qr(e)&&n.includes(e.kind)||!1}Br(Jr,{AIEmbeddings:()=>ai,AppCurationSet:()=>Ws,Application:()=>Vs,AuthoredPodcasts:()=>as,BadgeAward:()=>ho,BadgeDefinition:()=>Us,Bid:()=>No,BidConfirmation:()=>Co,BlobsAuth:()=>Es,BlockedRelaysList:()=>Vi,BlossomServerList:()=>ns,BookmarkList:()=>Hi,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:()=>_o,ClassifiedListing:()=>Xs,ClientAuth:()=>ws,CodeSnippet:()=>zo,CoinjoinPool:()=>ui,Comment:()=>qo,CommunitiesList:()=>qi,CommunityDefinition:()=>ya,CommunityPostApproval:()=>fi,ConferenceEvent:()=>Gs,Contacts:()=>so,CreateOrUpdateProduct:()=>Ps,CreateOrUpdateStall:()=>Ls,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:()=>_s,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:()=>Lo,Metadata:()=>ro,ModularArticleContent:()=>qs,ModularArticleHeader:()=>Hs,MuteSets:()=>Bs,Mutelist:()=>$i,NWCWalletInfo:()=>fs,NWCWalletRequest:()=>ms,NWCWalletResponse:()=>bs,NormalVideo:()=>So,NostrConnect:()=>vs,NsiteNamed:()=>wa,NsiteRoot:()=>ps,NutZap:()=>_i,NutZapInfo:()=>Zi,OpenTimestamps:()=>$o,Patch:()=>Ko,PeerToPeerOrderEvents:()=>xa,Photo:()=>xo,Pinlist:()=>Mi,PodcastEpisode:()=>Uo,PodcastMetadata:()=>ss,Poll:()=>Ho,PollResponse:()=>Po,PrivateDirectMessage:()=>mo,PrivateEventRelayList:()=>Ki,ProblemTracker:()=>ni,ProductSoldAsAuction:()=>Cs,ProfileBadges:()=>Ts,ProxyAnnouncement:()=>ds,PublicChatsList:()=>Di,PublicMessage:()=>Ao,Reaction:()=>uo,ReactionToWebsite:()=>Eo,RecommendRelay:()=>io,Redirects:()=>na,RelayDiscovery:()=>js,RelayList:()=>Fi,RelayMonitorAnnouncement:()=>cs,RelayReview:()=>ua,RelayReviews:()=>si,Relaysets:()=>As,ReleaseArtifactSets:()=>Ds,Reply:()=>Xo,Report:()=>ri,Reporting:()=>oi,RepositoryAnnouncement:()=>Qs,RepositoryState:()=>ea,Repost:()=>lo,ReservedCashuWalletTokens:()=>wi,RoomPresence:()=>ls,Scroll:()=>Vo,Seal:()=>wo,SearchRelaysList:()=>ji,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:()=>Li,Time:()=>aa,Torrent:()=>ci,TorrentComment:()=>li,TransportMethodAnnouncement:()=>hs,UserEmojiList:()=>Yi,UserGraspList:()=>us,UserStatuses:()=>Zs,VideoViewEvent:()=>ga,Voice:()=>Do,VoiceComment:()=>jo,WebBookmarks:()=>Ta,WikiArticle:()=>ta,Zap:()=>Ni,ZapGoal:()=>Ui,ZapRequest:()=>Pi,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,Uo=54,_o=64,Lo=818,Po=1018,No=1021,Co=1022,$o=1040,Mo=1059,Fo=1063,Ho=1068,qo=1111,Do=1222,Vo=1227,jo=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,Ui=9041,_i=9321,Li=9467,Pi=9734,Ni=9735,Ci=9802,$i=1e4,Mi=10001,Fi=10002,Hi=10003,qi=10004,Di=10005,Vi=10006,ji=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,Us=30009,_s=30015,Ls=30017,Ps=30018,Ns=30019,Cs=30020,$s=30023,Ms=30024,Fs=30030,Hs=30040,qs=30041,Ds=30063,Vs=30078,js=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 Ua(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 _a(e,t){for(let n=0;n<e.length;n++)if(Ua(e[n],t))return!0;return!1}function La(...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 Pa(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 Ha(e,t){return t===Ca(e,"pubkey")}function qa(e,t){return t===$a(e,"kind")}Br(Na,{getHex64:()=>Ca,getInt:()=>$a,getSubscriptionId:()=>Ma,matchEventId:()=>Fa,matchEventKind:()=>qa,matchEventPubkey:()=>Ha});var Da={};function Va(e,t){return{kind:ws,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",t]],content:""}}Br(Da,{makeAuthEvent:()=>Va});var ja,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=Lr(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(Va(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 _a(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{ja=WebSocket}catch{}var Ga=class extends za{constructor(e,t){super(e,{verifyEvent:Zr,websocketImplementation:ja,...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=Lr(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(Lr).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=Lr(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=Lr(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(Lr).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=>Ur.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=>Ur.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:Ur.decode(e[0][0]),pubkey:f(e[2][0]),kind:parseInt(f(e[3][0]),16),relays:e[1]?e[1].map((e=>Ur.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=>_r.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=>_r.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:[_r.encode(e.identifier)],1:(e.relays||[]).map((e=>_r.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=_r.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 Ur.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:()=>Uc,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 Uc(e,t){const n=await Tc(t);return!!n&&n.pubkey===e}var _c={};function Lc(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(_c,{parse:()=>Lc});var Pc={};Br(Pc,{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 Hc(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=L(_r.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:()=>Hc});var qc={};Br(qc,{unwrapEvent:()=>yl,unwrapManyEvents:()=>wl,wrapEvent:()=>pl,wrapManyEvents:()=>gl});var Dc={};Br(Dc,{createRumor:()=>al,createSeal:()=>cl,createWrap:()=>ll,unwrapEvent:()=>hl,unwrapManyEvents:()=>fl,wrapEvent:()=>ul,wrapManyEvents:()=>dl});var Vc={};Br(Vc,{decrypt:()=>el,encrypt:()=>Qc,getConversationKey:()=>Kc,v2:()=>tl});var jc=1,Wc=4294967295,zc=65536;function Kc(e,t){const n=st.getSharedSecret(e,E("02"+t)).subarray(1,33);return kr(L,n,_r.encode("nip44-v2"))}function Gc(e,t){const n=Or(L,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=_r.encode(e),n=t.length;if(n<jc||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<jc||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<jc||r>Wc||i.length!==r||e.length!==o+Zc(r))throw new Error("invalid padding");return Ur.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(L,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=jr(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 Ul(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 _l(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 Ll(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=Ul(n),t.reply=Ul(r),_l(t.root,t.profiles),_l(t.reply,t.profiles),t.quotes.forEach((e=>_l(e,t.profiles))),t}Br(Rl,{parse:()=>Ll});var Pl={};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(Pl,{finishReactionEvent:()=>Nl,getReactedEventPointer:()=>Cl});var $l={};Br($l,{parse:()=>ql});var Ml=/\W/m,Fl=/[^\w\/] |[^\w\/]$|$|,| /m,Hl=42;function*ql(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+Hl).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 Dl={};Br(Dl,{channelCreateEvent:()=>Vl,channelHideMessageEvent:()=>zl,channelMessageEvent:()=>Wl,channelMetadataEvent:()=>jl,channelMuteUserEvent:()=>Kl});var 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:Ro,tags:[...e.tags??[]],content:n,created_at:e.created_at},t)},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: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=Ur.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(!qr(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)),L(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()}},Uu={};Br(Uu,{getToken:()=>Lu,hashPayload:()=>Hu,unpackEventFromToken:()=>Nu,validateEvent:()=>Du,validateEventKind:()=>$u,validateEventMethodTag:()=>Fu,validateEventPayloadTag:()=>qu,validateEventTimestamp:()=>Cu,validateEventUrlTag:()=>Mu,validateToken:()=>Pu});var _u="Nostr ";async function Lu(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",Hu(o)]);const s=await n(i);return(r?_u:"")+Wt.encode(_r.encode(JSON.stringify(s)))}async function Pu(e,t,n){const r=await Nu(e).catch((e=>{throw e}));return await Du(r,t,n).catch((e=>{throw e}))}async function Nu(e){if(!e)throw new Error("Missing token");e=e.replace(_u,"");const t=Ur.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 Hu(e){return f(L(_r.encode(JSON.stringify(e))))}function qu(e,t){const n=e.tags.find((e=>"payload"===e[0]));if(!n)return!1;const r=Hu(t);return n.length>0&&n[1]===r}async function Du(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&&!qu(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.getOutgoingPayments=e.getIncomingPayments=e.getBalance=e.sendPayment=e.checkPayment=e.createInvoice=e.startLightning=void 0;var t=n(13);Object.defineProperty(e,"startLightning",{enumerable:!0,get:function(){return t.startLightning}});var o=n(398);Object.defineProperty(e,"createInvoice",{enumerable:!0,get:function(){return o.createInvoice}}),Object.defineProperty(e,"checkPayment",{enumerable:!0,get:function(){return o.checkPayment}}),Object.defineProperty(e,"sendPayment",{enumerable:!0,get:function(){return o.sendPayment}}),Object.defineProperty(e,"getBalance",{enumerable:!0,get:function(){return o.getBalance}}),Object.defineProperty(e,"getIncomingPayments",{enumerable:!0,get:function(){return o.getIncomingPayments}}),Object.defineProperty(e,"getOutgoingPayments",{enumerable:!0,get:function(){return o.getOutgoingPayments}})})();var o=exports;for(var i in r)o[i]=r[i];r.__esModule&&Object.defineProperty(o,"__esModule",{value:!0})})();
@@ -0,0 +1,9 @@
1
+ /*! MIT License. CoinExams Lightning Payment SDK used in accordance with terms https://coinexams.com/terms */
2
+
3
+ /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
4
+
5
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6
+
7
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
8
+
9
+ /*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@coinexams/lightning",
3
+ "version": "1.0.0",
4
+ "description": "CoinExams Lightning Payment SDK - A standalone Lightning Network client module that wraps a local Phoenixd node REST API.",
5
+ "main": "dist/node/lightning.node.min.js",
6
+ "module": "dist/node/lightning.node.min.js",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "webpack"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/CoinExams/CE_Lightning.git"
14
+ },
15
+ "keywords": [
16
+ "CoinExams",
17
+ "Lightning Network",
18
+ "Phoenixd",
19
+ "LNURL",
20
+ "Nostr",
21
+ "Zap",
22
+ "Bitcoin"
23
+ ],
24
+ "author": "CoinExams",
25
+ "license": "MIT",
26
+ "bugs": {
27
+ "url": "https://github.com/CoinExams/CE_Lightning/issues"
28
+ },
29
+ "homepage": "https://github.com/CoinExams/CE_Lightning#readme",
30
+ "devDependencies": {
31
+ "@types/node": "^22.10.2",
32
+ "esbuild": "^0.24.2",
33
+ "terser-webpack-plugin": "^5.3.11",
34
+ "ts-loader": "^9.5.1",
35
+ "ts-node": "^10.9.2",
36
+ "typescript": "^5.7.2",
37
+ "webpack": "^5.97.1",
38
+ "webpack-cli": "^6.0.1"
39
+ },
40
+ "files": [
41
+ "dist/"
42
+ ],
43
+ "dependencies": {
44
+ "nostr-tools": "^2.24.1"
45
+ }
46
+ }