1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
|
import config from "$config";
import { archive, db, g, gf } from "$lib/db";
import { generate } from "$lib/invoices";
import ln from "$lib/ln";
import { err, l, warn } from "$lib/logging";
import {
handleZap,
serverPubkey,
serverPubkey2,
serverSecret,
serverSecret2,
} from "$lib/nostr";
import { sendInternal, sendKeysend, sendLightning } from "$lib/payments";
import { fail, getInvoice, sleep } from "$lib/utils";
import rpc from "@coinos/rpc";
import { hexToBytes } from "@noble/hashes/utils";
import { Relay } from "nostr";
import { finalizeEvent, nip04 } from "nostr-tools";
import type { UnsignedEvent } from "nostr-tools";
const serverKeys = {
[serverPubkey]: serverSecret,
[serverPubkey2]: serverSecret2,
};
const result = (result) => ({ result });
const error = (error) => ({ error });
const bc = rpc(config.bitcoin);
const methods = [
"pay_keysend",
"pay_invoice",
"get_balance",
"get_info",
"make_invoice",
"lookup_invoice",
"list_transactions",
];
const week = 7 * 24 * 60 * 60;
const nwcEventMaxAgeSeconds = 5 * 60;
const handledKey = "handled:nwc";
const handledMaxSize = 200000;
export default () => {
let r: any;
function connect() {
r = new Relay("ws://sf:7777", { reconnect: false });
r.on("open", async (_) => {
l("nwc connected to strfry");
r.subscribe("nwc", { kinds: [23194], "#p": [serverPubkey, serverPubkey2] });
const info = await finalizeEvent(
{
created_at: Math.floor(Date.now() / 1000),
kind: 13194,
tags: [
["p", serverPubkey],
["notifications", "payment_received payment_sent"],
],
content: methods.join(" "),
},
hexToBytes(serverSecret),
);
r.send(["EVENT", info]);
const info2 = await finalizeEvent(
{
created_at: Math.floor(Date.now() / 1000),
kind: 13194,
tags: [
["p", serverPubkey2],
["notifications", "payment_received payment_sent"],
],
content: methods.join(" "),
},
hexToBytes(serverSecret2),
);
r.send(["EVENT", info2]);
});
r.on("close", () => {
warn("nwc strfry connection lost, reconnecting in 5s");
setTimeout(connect, 5000);
});
r.on("error", () => {});
r.on("event", async (sub, ev) => {
try {
if (sub !== "nwc") return;
const now = Math.floor(Date.now() / 1000);
if (ev.created_at && now - ev.created_at > nwcEventMaxAgeSeconds) return;
if (await db.zScore(handledKey, ev.id)) return;
db.zAdd(handledKey, { score: now, value: ev.id });
db.zRemRangeByScore(handledKey, 0, now - nwcEventMaxAgeSeconds);
const size = await db.zCard(handledKey);
if (size > handledMaxSize) {
await db.zRemRangeByRank(handledKey, 0, size - handledMaxSize - 1);
}
let { content, pubkey } = ev;
const pk = ev.tags.find((t) => t[0] === "p")[1];
const sk = serverKeys[pk];
const { params, method } = JSON.parse(
await nip04.decrypt(sk, pubkey, content),
);
// console.log("nwc", method, params, pubkey);
if (!methods.includes(method)) return;
try {
const app = await g(`app:${pubkey}`);
if (!app) fail("pubkey not found");
const user = await g(`user:${app.uid}`);
const result = await handle(method, params, ev, app, user);
const payload = JSON.stringify({ result_type: method, ...result });
content = await nip04.encrypt(sk, pubkey, payload);
let response: UnsignedEvent = {
created_at: Math.floor(Date.now() / 1000),
kind: 23195,
pubkey: serverPubkey,
tags: [
["p", pubkey],
["e", ev.id],
],
content,
};
response = await finalizeEvent(response, hexToBytes(sk));
r.send(["EVENT", response]);
} catch (e) {
// err(
// "problem with nwc",
// pubkey,
// method,
// JSON.stringify(params),
// e.message,
// );
}
} catch (e) {
// err("problem with nwc", e.message);
}
});
}
connect();
};
const handle = (method, params, ev, app, user) =>
({
async pay_invoice() {
const { invoice: pr, metadata } = params;
const { amount_msat, payee } = await ln.decode(pr);
const { id } = await ln.getinfo();
const amount = Math.round(amount_msat / 1000);
const { max_amount, max_fee, budget_renewal, pubkey, created } = app;
const periods = {
daily: 60 * 60 * 24 * 1000,
weekly: 60 * 60 * 24 * 7 * 1000,
monthly: 60 * 60 * 24 * 30 * 1000,
yearly: 60 * 60 * 24 * 365 * 1000,
never: 60 * 60 * 24 * 365 * 10 * 1000,
};
const pids = await db.lRange(`${pubkey}:payments`, 0, -1);
let payments = await Promise.all(pids.map((pid) => g(`payment:${pid}`)));
payments = payments.filter(
(p) => p?.created > Date.now() - periods[budget_renewal],
);
const spent = payments.reduce(
(a, b) =>
a +
(Math.abs(Number.parseInt(b.amount || 0)) +
Number.parseInt(b.tip || 0) +
Number.parseInt(b.fee || 0) +
Number.parseInt(b.ourfee || 0)),
0,
);
if (!created) {
return error({
code: "UNAUTHORIZED",
message: `This NWC connection is no longer valid please create a new one at https://coinos.io/settings/nostr`,
});
}
if (max_amount > 0 && spent + amount > max_amount) {
// warn(
// "budget exceeded",
// pubkey,
// user?.username,
// spent,
// amount,
// max_amount,
// );
return error({
code: "QUOTA_EXCEEDED",
message: `Budget exceeded: ${spent + amount} of ${max_amount}`,
});
}
if (payee === id) {
const invoice = await getInvoice(pr);
const recipient = await g(`user:${invoice.uid}`);
if (recipient?.username !== "mint") {
const { id: pid } = await sendInternal({
amount,
invoice,
recipient,
sender: user,
});
const preimage = pid;
if (pubkey !== user.pubkey) await db.lPush(`${pubkey}:payments`, pid);
if (invoice.memo?.includes("9734")) {
const { invoices } = await ln.listinvoices({ invstring: pr });
const inv = invoices[0];
inv.payment_preimage = preimage;
inv.paid_at = Math.floor(Date.now() / 1000);
try {
await handleZap(inv, user.pubkey);
} catch (e) {
console.log("zap receipt failed", e);
}
}
return result({ preimage });
}
}
try {
const { id: pid } = await sendLightning({
amount,
fee: max_fee || Math.round(amount * 0.01),
user,
pr,
memo: JSON.stringify(metadata),
});
await db.lPush(`${pubkey}:payments`, pid);
for (let i = 0; i < 10; i++) {
const { pays } = await ln.listpays(pr);
const p = pays.find((p) => p.status === "complete");
if (p) {
const { preimage } = p;
return result({ preimage });
}
await sleep(2000);
}
} catch (e) {
return error({ code: "INTERNAL", message: e.message });
}
return error({ code: "INTERNAL", message: "Payment timed out" });
},
async pay_keysend() {
const { amount: amount_msat, pubkey, tlv_records } = params;
const amount = Math.round(amount_msat / 1000);
const extratlvs = {};
// convert tlv_records to the extratlvs format
// tlv_records: [{ type: 1, value: "asdf" }]
// extratlvs: { "1": "asdf" }
if (tlv_records && tlv_records.length) {
for (const record of tlv_records) {
extratlvs[record.type.toString()] = record.value;
}
}
try {
const { payment_hash } = await sendKeysend({
hash: ev.id,
amount,
pubkey,
user,
extratlvs,
});
for (let i = 0; i < 10; i++) {
const { pays } = await ln.listpays({ payment_hash });
const p = pays.find((p) => p.status === "complete");
if (p) {
const { preimage } = p;
return result({ preimage });
}
await sleep(2000);
}
return error({ code: "INTERNAL", message: "Payment timed out" });
} catch (e) {
return error({ code: "INTERNAL", message: "Keysend payment failed" });
}
},
async get_info() {
const { alias, blockheight, color, id } = await ln.getinfo();
return result({
alias,
block_hash: await bc.getBlockHash(blockheight),
block_height: blockheight,
color,
pubkey: id,
network: "mainnet",
methods,
notifications: ["payment_received", "payment_sent"],
});
},
async get_balance() {
let balance = await g(`balance:${user.id}`);
balance *= 1000;
return result({ balance });
},
async make_invoice() {
const { amount, description, description_hash, expiry } = params;
// l("nwc make_invoice", user.username);
const invoice = {
amount: Math.round(amount / 1000),
type: "lightning",
memo: description,
expiry,
};
const {
hash,
created: created_at,
paymentHash,
} = await generate({ invoice, user });
return result({
type: "incoming",
invoice: hash,
description,
description_hash,
amount,
created_at,
expires_at: created_at + expiry,
fees_paid: 0,
payment_hash: paymentHash,
metadata: {},
});
},
async lookup_invoice() {
let { invoice, payment_hash } = params;
const { invoices } = await ln.listinvoices({
invstring: invoice,
payment_hash,
});
if (invoices.length) {
const {
amount_received_msat: amount,
description,
expires_at,
paid_at: settled_at,
} = invoices[0];
({ bolt11: invoice, payment_hash } = invoices[0]);
const { preimage, settled } = await getInvoice(invoice);
return result({
type: "incoming",
invoice,
description,
preimage,
payment_hash,
amount,
fees_paid: 0,
created_at: expires_at - week,
expires_at,
settled_at: settled_at || Math.round(settled / 1000),
state: settled ? "settled" : "pending",
status: settled ? "paid" : "pending",
});
}
const { pays } = await ln.listpays({ bolt11: invoice, payment_hash });
if (!pays.length)
return error({ code: "NOT_FOUND", message: "Invoice not found" });
const {
amount_msat: amount,
amount_sent_msat,
created_at,
preimage,
completed_at: settled_at,
} = pays[0];
({ bolt11: invoice, payment_hash } = pays[0]);
return result({
type: "outgoing",
invoice,
preimage,
payment_hash,
amount,
fees_paid: amount_sent_msat - amount,
created_at,
settled_at,
});
},
async list_transactions() {
const { from, until, limit = 10, offset = 0, type } = params;
const listKey = `${user.id}:payments`;
const main = (await db.lRange(listKey, 0, -1)) || [];
const archived = (await archive.lRange(listKey, 0, -1)) || [];
const payments = [...new Set([...main, ...archived])];
let transactions = [];
for (const pid of payments) {
const p = await gf(`payment:${pid}`);
if (!p) continue;
const created_at = Math.floor(p.created / 1000);
if (created_at < from || created_at > until) continue;
if (p.amount < 0 && type === "incoming") continue;
if (p.amount > 0 && type === "outgoing") continue;
let payment_hash = p.payment_hash || pid;
if (p.type === "lightning") {
try {
if (p.amount > 0) {
const { invoices } = await ln.listinvoices({ invstring: p.hash });
payment_hash ||= invoices[0].payment_hash;
} else {
const { pays } = await ln.listpays({ bolt11: p.hash });
payment_hash ||= pays[0].payment_hash;
}
} catch (e) {}
}
transactions.push({
type: p.amount > 0 ? "incoming" : "outgoing",
invoice: p.hash,
description: p.memo,
preimage: p.ref,
payment_hash,
amount: (Math.abs(p.amount) + (p.tip || 0)) * 1000,
fees_paid: (p?.fee || 0) * 1000,
created_at,
expires_at: created_at + week,
settled_at: p.amount > 0 ? created_at : undefined,
state: "settled",
metadata: {},
});
}
transactions = transactions.slice(offset, offset + limit);
return result({ transactions });
},
})[method](params);
|