aboutsummaryrefslogtreecommitdiffstats
path: root/routes
diff options
context:
space:
mode:
authorJohn Barratt <[email protected]>2023-02-28 13:55:59 -0800
committerJohn Barratt <[email protected]>2023-02-28 13:55:59 -0800
commite47d50a443f0a396321716a506e1df325dd4a1fb (patch)
tree1c010c5970e9cbfbf8671e6f00a97d6518446fdd /routes
parent58e996a4ac227162f171e84530fe898cb504e045 (diff)
parente4702b4d13e4d966d735c2ba4657e10d7c436a57 (diff)
downloadcoinos-server-e47d50a443f0a396321716a506e1df325dd4a1fb.tar.gz
coinos-server-e47d50a443f0a396321716a506e1df325dd4a1fb.zip
Merge branch 'master' of https://github.com/coinos/coinos-server into notifications
Diffstat (limited to 'routes')
-rw-r--r--routes/email.js27
-rw-r--r--routes/info.js14
-rw-r--r--routes/invoices.js28
-rw-r--r--routes/lnurl.js21
-rw-r--r--routes/nostr.js53
-rw-r--r--routes/payments.js252
-rw-r--r--routes/users.js46
7 files changed, 293 insertions, 148 deletions
diff --git a/routes/email.js b/routes/email.js
index 6b2806a4..05f682af 100644
--- a/routes/email.js
+++ b/routes/email.js
@@ -1,25 +1,18 @@
import config from "$config";
+import sendgrid from "@sendgrid/mail";
export default {
async send({ body }, res) {
-
- try {
- let postmark = await import("postmark");
- let client = new postmark.ServerClient(config.postmark);
-
- await client.sendEmail({
- Subject: body.subject || "Email Signup",
- HtmlBody: JSON.stringify(body),
- TextBody: JSON.stringify(body),
- MessageStream: "outbound"
- });
+ sendgrid.setApiKey(config.sendgrid);
+ const msg = {
+ subject: body.subject || "Email Signup",
+ text: JSON.stringify(body),
+ html: JSON.stringify(body)
+ };
+ await sendgrid.send(msg);
res.send({ ok: true });
- } catch (e) {
- console.log("problem sending email", e);
- res.code(500).send(e.message);
- }
}
};
diff --git a/routes/info.js b/routes/info.js
index 017e473a..ae347b56 100644
--- a/routes/info.js
+++ b/routes/info.js
@@ -6,16 +6,10 @@ export default {
let lnchannel;
let lnwallet;
- const stream = db.scanStream({
- match: "balance:*",
- count: 100
- });
-
- let b = 0;
- for await (let keys of stream) {
- for (let k of keys) b += parseInt(await db.get(k));
+ let total = 0;
+ for await (let k of db.scanIterator({ MATCH: "balance:*" })) {
+ total += parseInt(await db.get(k));
}
- console.log(b);
const funds = await ln.listfunds();
lnchannel = parseInt(funds.channels.reduce((a, b) => a + b.channel_sat, 0));
@@ -24,7 +18,7 @@ export default {
const info = {
lnchannel,
lnwallet,
- total: lnchannel + lnwallet
+ total
};
res.send(info);
diff --git a/routes/invoices.js b/routes/invoices.js
index 133da057..8e23e5f1 100644
--- a/routes/invoices.js
+++ b/routes/invoices.js
@@ -1,29 +1,35 @@
import { g, s } from "$lib/db";
import { generate } from "$lib/invoices";
-import { fail } from "$lib/utils";
+import { fail, pick } from "$lib/utils";
+import whitelist from "$lib/whitelist";
import got from "got";
import config from "$config";
import ln from "$lib/ln";
export default {
async get({ params: { hash } }, res) {
- if (hash.startsWith("ln")) ({ payment_hash: hash } = await ln.decode(hash));
+ let pr;
+ if (hash.startsWith("ln")) {
+ ({ payment_hash: hash } = await ln.decode(hash));
+ }
let invoice = await g(`invoice:${hash}`);
if (invoice) {
- invoice.user = await g(`user:${invoice.uid}`);
+ invoice.user = pick(await g(`user:${invoice.uid}`), whitelist);
invoice.id = hash;
- } else {
- invoice = await got(`${config.classic}/invoice/${hash}`).json();
- if (!invoice) fail("invoice not found");
- invoice.id = invoice.uuid;
- invoice.classic = true;
- invoice.user.id = invoice.user.uuid;
- invoice.user.username += "@classic";
+ } else if (config.classic) {
+ invoice = await got(`${config.classic}/invoice/${pr}`).json();
+ if (invoice) {
+ invoice.id = invoice.uuid;
+ invoice.classic = true;
+ invoice.user.id = invoice.user.uuid;
+ invoice.user.username += "@classic";
+ }
}
- res.send(invoice);
+ if (invoice) res.send(invoice);
+ else res.code(500).send("invoice not found");
},
async create({ body: { invoice, user }, user: sender }, res) {
diff --git a/routes/lnurl.js b/routes/lnurl.js
index 638c827f..dcd1657c 100644
--- a/routes/lnurl.js
+++ b/routes/lnurl.js
@@ -1,6 +1,6 @@
import { g, s } from "$lib/db";
-import { l } from "$lib/logging";
-import { fail } from "$lib/utils";
+import { l, warn } from "$lib/logging";
+import { bail, fail } from "$lib/utils";
import { v4 } from "uuid";
import got from "got";
import { generate } from "$lib/invoices";
@@ -19,8 +19,16 @@ export default {
async encode({ query: { address } }, res) {
let [name, domain] = address.split("@");
let url = `https://${domain}/.well-known/lnurlp/${name}`;
- let r = await got(url).json();
- if (r.tag !== "payRequest") fail("not an ln address");
+
+ try {
+ let r = await got(url).json();
+ if (r.tag !== "payRequest") fail("not an ln address");
+ } catch (e) {
+ let m = `failed to lookup lightning address ${address}`;
+ warn(m);
+ return bail(res, m);
+ }
+
let enc = bech32.encode("lnurl", bech32.toWords(Buffer.from(url)), 20000);
res.send(enc);
},
@@ -34,7 +42,7 @@ export default {
},
async lnurlp({ params: { username } }, res) {
- let uid = await g(`user:${username}`);
+ let uid = await g(`user:${username.toLowerCase()}`);
if (!uid) {
let u = await got(`${classic}/admin/migrate/${username}?zero=true`, {
headers: { authorization: `Bearer ${admin}` }
@@ -48,7 +56,6 @@ export default {
u = { id: uid, about: u.address, ...pick(u, fields) };
delete u.address;
- await s(`user:${pubkey}`, uid);
await s(`user:${username.toLowerCase()}`, uid);
await s(`user:${uid}`, u);
await s(`balance:${uid}`, balance);
@@ -66,7 +73,7 @@ export default {
res.send({
minSendable: 1000,
- maxSendable: 100000000,
+ maxSendable: 100000000000,
metadata,
callback: `${URL}/api/lnurl/${id}`,
tag: "payRequest"
diff --git a/routes/nostr.js b/routes/nostr.js
index 005a4be9..7670bd5f 100644
--- a/routes/nostr.js
+++ b/routes/nostr.js
@@ -6,6 +6,8 @@ import { pool, q } from "$lib/nostr";
export default {
async event({ params: { id } }, res) {
let event = await g(`ev:${id}`);
+ if (!event) return bail("event not found");
+
let { pubkey } = event;
event.user = (await g(`user:${pubkey}`)) || {
@@ -20,7 +22,8 @@ export default {
},
async notes({ params: { pubkey } }, res) {
- let user = await g(`user:${pubkey}`);
+ let uid = await g(`user:${pubkey}`);
+ let user = await g(`user:${uid}`);
if (!user)
user = {
@@ -39,8 +42,6 @@ export default {
q(`${pubkey}:notes`, params, opts).catch(nada);
- await s(`user:${pubkey}`, user);
-
let ids = await db.sMembers(pubkey);
let events = ids.length
@@ -50,6 +51,41 @@ export default {
res.send(events.map(e => ({ ...e, user })));
},
+ async messages({ params: { pubkey, since = 0 } }, res) {
+ let params = {
+ kinds: [4],
+ authors: [pubkey]
+ };
+
+ let opts = { since };
+
+ await q(`${pubkey}:messages`, params, opts).catch(nada);
+
+ params = {
+ kinds: [4],
+ "#p": [pubkey]
+ };
+
+ await q(`${pubkey}:messages`, params, opts).catch(nada);
+
+ let messages = await db.sMembers(`${pubkey}:messages`);
+ messages = await Promise.all(
+ messages.map(async id => {
+ let m = await g(`ev:${id}`);
+
+ let aid = await g(`user:${m.pubkey}`);
+ m.author = await g(`user:${aid}`);
+
+ let rid = await g(`user:${m.tags[0][1]}`);
+ m.recipient = await g(`user:${rid}`);
+
+ return m;
+ })
+ );
+
+ res.send(messages);
+ },
+
async broadcast(req, res) {
let { event } = req.body;
pool.send(["EVENT", event]);
@@ -80,7 +116,8 @@ export default {
authors: [pubkey]
}).catch(nada);
- let user = await g(`user:${pubkey}`);
+ let uid = await g(`user:${pubkey}`);
+ let user = await g(`user:${uid}`);
if (!user)
user = {
@@ -113,15 +150,17 @@ export default {
).catch(nada);
for (let pubkey of pubkeys) {
- let user = await g(`user:${pubkey}`);
+ let uid = await g(`user:${pubkey}`);
+ let user = await g(`user:${uid}`);
if (!user || !user.updated) {
- q(`${pubkey}:profile:f2`, {
+ await q(`${pubkey}:profile:f2`, {
limit: 1,
kinds: [0],
authors: [pubkey]
}).catch(nada);
- user = await g(`user:${pubkey}`);
+ uid = await g(`user:${pubkey}`);
+ user = await g(`user:${uid}`);
}
if (!user)
diff --git a/routes/payments.js b/routes/payments.js
index 0ee2bce0..38611d19 100644
--- a/routes/payments.js
+++ b/routes/payments.js
@@ -3,8 +3,8 @@ import store from "$lib/store";
import { emit } from "$lib/sockets";
import { v4 } from "uuid";
import { db, g, s, t } from "$lib/db";
-import { l, err } from "$lib/logging";
-import { fail, btc, sats } from "$lib/utils";
+import { l, err, warn } from "$lib/logging";
+import { bail, fail, btc, sats } from "$lib/utils";
import { requirePin } from "$lib/auth";
import { debit, credit, confirm, types } from "$lib/payments";
import got from "got";
@@ -14,11 +14,10 @@ import ln from "$lib/ln";
export default {
async create({ body, user }, res) {
- let { amount, hash, maxfee, name, memo, payreq, tip, username } = body;
+ let { amount, hash, maxfee, name, memo, payreq, username } = body;
amount = parseInt(amount);
maxfee = maxfee ? parseInt(maxfee) : 0;
- tip = parseInt(tip);
await requirePin({ body, user });
@@ -43,9 +42,7 @@ export default {
if (invoice) {
if (invoice.uid === user.id) fail("Cannot send to self");
hash = payment_hash;
- }
-
- else {
+ } else {
p = await debit(
hash,
amount + maxfee,
@@ -55,15 +52,27 @@ export default {
types.lightning
);
- let r = await ln.pay(payreq, msatoshi ? undefined : `${amount}sats`);
+ let r;
+ try {
+ r = await ln.pay(payreq, msatoshi ? undefined : `${amount}sats`);
- p.amount = -amount;
- p.hash = r.payment_hash;
- p.fee = Math.round((r.msatoshi_sent - r.msatoshi) / 1000);
- p.ref = r.payment_preimage;
+ p.amount = -amount;
+ p.hash = r.payment_hash;
+ p.fee = Math.round((r.msatoshi_sent - r.msatoshi) / 1000);
+ p.ref = r.payment_preimage;
- await s(`payment:${p.id}`, p);
- await db.incrBy(`balance:${p.uid}`, maxfee - p.fee);
+ await s(`payment:${p.id}`, p);
+ await db.incrBy(`balance:${p.uid}`, maxfee - p.fee);
+ } catch (e) {
+ if (!(r && r.status === "complete")) {
+ let credit = Math.round(amount * config.fee) - p.ourfee;
+ await db.incrBy(`balance:${p.uid}`, amount + maxfee + p.ourfee);
+ await db.incrBy(`credit:${types.lightning}:${p.uid}`, credit);
+ await db.lRem(`${p.uid}:payments`, 0, p.id);
+ await db.del(`payment:${p.id}`);
+ }
+ throw e;
+ }
}
}
@@ -109,7 +118,9 @@ export default {
},
async get({ params: { hash } }, res) {
- res.send(await g(`payment:${hash}`));
+ let p = await g(`payment:${hash}`);
+ if (p.type === types.internal) p.with = await g(`user:${p.ref}`);
+ res.send(p);
},
async parse({ body: { payreq } }, res) {
@@ -131,7 +142,7 @@ export default {
async pot({ params: { name } }, res) {
let amount = await g(`pot:${name}`);
- if (!amount) fail("pot not found");
+ if (!amount) return bail(res, "pot not found");
let payments = (await db.lRange(`pot:${name}:payments`, 0, -1)) || [];
payments = await Promise.all(payments.map(hash => g(`payment:${hash}`)));
@@ -166,93 +177,176 @@ export default {
},
async bitcoin({ body: { txid, wallet } }, res) {
- if (wallet === config.bitcoin.wallet) {
- let { confirmations, details } = await bc.getTransaction(txid);
- for (let { address, amount, vout } of details) {
- if (confirmations > 0) {
- await confirm(address, txid, vout);
- } else {
- await credit(
- address,
- sats(amount),
- "",
- `${txid}:${vout}`,
- types.bitcoin
- );
+ try {
+ if (wallet === config.bitcoin.wallet) {
+ let { confirmations, details } = await bc.getTransaction(txid);
+ for (let { address, amount, category, vout } of details) {
+ if (category !== "receive") continue;
+ let p = await g(`payment:${txid}:${vout}`);
+ if (!p || confirmations < 1) {
+ await credit(
+ address,
+ sats(amount),
+ "",
+ `${txid}:${vout}`,
+ types.bitcoin
+ );
+ } else {
+ await confirm(address, txid, vout);
+ }
}
}
+ res.send({});
+ } catch (e) {
+ warn(`problem processing ${txid}`);
+ bail(res, e.message);
}
- res.send({});
},
- async fee(req, res) {
- let { amount, address, feeRate, subtract } = req.body;
- let subtractFeeFromOutputs = subtract ? [0] : [];
- let replaceable = true;
- let outs = [{ [address]: btc(amount) }];
- let count = await bc.getBlockCount();
+ async fee({ body: { amount, address, feeRate, subtract }, user }, res) {
+ try {
+ let subtractFeeFromOutputs = subtract ? [0] : [];
+ let replaceable = true;
- let raw = await bc.createRawTransaction([], outs, 0, replaceable);
- let tx = await bc.fundRawTransaction(raw, {
- feeRate,
- subtractFeeFromOutputs,
- replaceable
- });
+ let ourfee = Math.round(amount * config.fee);
+ let credit = await g(`credit:bitcoin:${user.id}`);
+ let covered = Math.min(credit, ourfee) || 0;
+ ourfee -= covered;
+
+ if (subtract) amount -= ourfee;
- if (config.bitcoin.walletpass)
- await bc.walletPassphrase(config.bitcoin.walletpass, 300);
+ let { feerate: min } = await bc.estimateSmartFee(40);
+ let { feerate: max } = await bc.estimateSmartFee(1);
- let { hex } = await bc.signRawTransactionWithWallet(tx.hex);
- let { vsize } = await bc.decodeRawTransaction(hex);
- feeRate = Math.round((sats(tx.fee) * 1000) / vsize);
+ if (feeRate) feeRate = btc(feeRate);
+ else feeRate = max;
- res.send({ feeRate, tx });
+ let outs = [{ [address]: btc(amount) }];
+ let raw = await bc.createRawTransaction([], outs, 0, replaceable);
+
+ let tx = await bc.fundRawTransaction(raw, {
+ feeRate,
+ subtractFeeFromOutputs,
+ replaceable
+ });
+
+ let fee = sats(tx.fee);
+
+ min = sats(min);
+ max = Math.round(sats(max) * 1.2);
+ feeRate = sats(feeRate);
+
+ res.send({ feeRate, min, max, fee, tx });
+ } catch (e) {
+ console.log(e);
+ bail(res, "problem estimating fee");
+ }
},
async send(req, res) {
- await requirePin(req);
+ try {
+ await requirePin(req);
- let { user } = req;
- let { address, memo, tx } = req.body;
- let { hex, fee } = tx;
+ let { user } = req;
+ let { address, memo, tx, subtract } = req.body;
+ let { hex, fee } = tx;
- if (config.bitcoin.walletpass)
- await bc.walletPassphrase(config.bitcoin.walletpass, 300);
+ if (config.bitcoin.walletpass)
+ await bc.walletPassphrase(config.bitcoin.walletpass, 300);
- ({ hex } = await bc.signRawTransactionWithWallet(hex));
+ ({ hex } = await bc.signRawTransactionWithWallet(hex));
- let r = await bc.testMempoolAccept([hex]);
- if (!r[0].allowed) fail("transaction rejected");
+ let r = await bc.testMempoolAccept([hex]);
+ if (!r[0].allowed) fail("transaction rejected");
- fee = sats(fee);
- if (fee < 0) fail("fee cannot be negative");
+ fee = sats(fee);
+ if (fee < 0) fail("fee cannot be negative");
- tx = await bc.decodeRawTransaction(hex);
- let { txid } = tx;
+ tx = await bc.decodeRawTransaction(hex);
+ let { txid } = tx;
- let total = 0;
- let change = 0;
+ let total = 0;
+ let change = 0;
- for (let {
- scriptPubKey: { address },
- value
- } of tx.vout) {
- total += sats(value);
- if (
- (await bc.getAddressInfo(address)).ismine &&
- !(await g(`invoice:${address}`))
- )
- change += sats(value);
+ for (let {
+ scriptPubKey: { address },
+ value
+ } of tx.vout) {
+ total += sats(value);
+ if (
+ (await bc.getAddressInfo(address)).ismine &&
+ !(await g(`invoice:${address}`))
+ )
+ change += sats(value);
+ }
+
+ total = total - change + fee;
+ let amount = total - fee;
+
+ console.log("AMOUNT", amount);
+
+ if (change && !amount) fail("Cannot send to unregistered coinos address");
+
+ await debit(txid, amount, fee, null, user, types.bitcoin, txid);
+ await bc.sendRawTransaction(hex);
+
+ res.send({ txid });
+ } catch (e) {
+ warn("payment failed", e.message);
+ res.code(500).send(e.message);
}
+ },
+
+ async buy({ body: { amount, number, year, month, cvc }, user }, res) {
+ if (!user.eligible) fail("not eligible");
+
+ let stripe = "https://api.stripe.com/v1";
+ let { stripe: username } = config;
+
+ let form = {
+ "card[number]": number,
+ "card[exp_month]": month,
+ "card[exp_year]": year,
+ "card[cvc]": cvc
+ };
+
+ let { id: source } = await got
+ .post(`${stripe}/tokens`, {
+ form,
+ username
+ })
+ .json();
- total = total - change + fee;
- let amount = total - fee;
+ let currency = "CAD";
+ form = {
+ amount,
+ currency,
+ source,
+ description: "starter coupon"
+ };
- if (change && !amount) fail("Cannot send to unregistered coinos address");
+ let r = await got
+ .post(`${stripe}/charges`, {
+ form,
+ username
+ })
+ .json();
- await debit(txid, amount, fee, null, user, types.bitcoin, txid);
- await bc.sendRawTransaction(hex);
+ let { status } = r;
+ if (status === "succeeded") {
+ let hash = r.id;
+ let memo = "stripe";
+ await s(`invoice:${hash}`, {
+ uid: user.id,
+ received: 0
+ });
+ amount = sats(amount / store.rates[currency]);
+ let uid = await g("user:coinos");
+ let coinos = await g(`user:${uid}`);
+ let p = await debit(hash, amount, 0, memo, coinos);
+ await credit(hash, amount, memo, coinos.id);
+ } else fail("Card payment failed");
- res.send({ txid });
+ res.send({ status });
}
};
diff --git a/routes/users.js b/routes/users.js
index c399b286..5f1affab 100644
--- a/routes/users.js
+++ b/routes/users.js
@@ -35,7 +35,7 @@ export default {
},
async get({ params: { key } }, res) {
- key = key.toLowerCase();
+ key = key.toLowerCase().replace(/\s/g, "");
try {
if (key.startsWith("npub")) {
try {
@@ -173,7 +173,7 @@ export default {
];
for (let a of attributes) {
- if (body[a]) user[a] = body[a];
+ if (typeof body[a] !== "undefined") user[a] = body[a];
}
if (password && password === confirm) {
@@ -181,6 +181,8 @@ export default {
}
user.haspin = !!user.pin;
+ await s(`user:${user.pubkey}`, user.id);
+ await s(`user:${user.username}`, user.id);
await s(`user:${user.id}`, user);
emit(user.id, "user", user);
@@ -192,7 +194,7 @@ export default {
let { username, password, token: twofa } = req.body;
l("logging in", username);
- username = username.toLowerCase();
+ username = username.toLowerCase().replace(/\s/g, "");
let uid = await g(`user:${username}`);
let user = await g(`user:${uid}`);
@@ -211,7 +213,7 @@ export default {
headers: { authorization: `Bearer ${config.admin}` }
}).json();
- let { balance, pubkey } = user;
+ let { balance } = user;
if (!user) fail();
uid = user.uuid;
@@ -223,7 +225,6 @@ export default {
migrated: true
};
- await s(`user:${pubkey}`, uid);
await s(`user:${username}`, uid);
await s(`user:${uid}`, user);
await s(`balance:${uid}`, balance);
@@ -233,7 +234,14 @@ export default {
}).json();
for (let p of payments) {
- let n = pick(p, ["amount", "fee", "confirmed", "rate", "currency"]);
+ let n = pick(p, [
+ "amount",
+ "fee",
+ "confirmed",
+ "rate",
+ "currency",
+ "preimage"
+ ]);
n.id = v4();
n.created = parseISO(p.createdAt).getTime();
n.type = p.network;
@@ -247,14 +255,16 @@ export default {
let u = id && (await g(`user:${id}`));
if (!u) {
- u = await got(`${classic}/admin/migrate/${p.with.username.toLowerCase()}`, {
- headers: { authorization: `Bearer ${config.admin}` }
- }).json();
+ u = await got(
+ `${classic}/admin/migrate/${p.with.username.toLowerCase()}`,
+ {
+ headers: { authorization: `Bearer ${config.admin}` }
+ }
+ ).json();
u = { id: u.uuid, about: u.address, ...pick(u, fields) };
delete u.address;
- await s(`user:${u.pubkey}`, u.id);
await s(`user:${p.with.username.toLowerCase()}`, u.id);
await s(`user:${u.id}`, u);
@@ -270,7 +280,7 @@ export default {
l("migrated user", user.username);
} catch (e) {
- console.log(e);
+ warn("classic login failed", username);
}
}
if (
@@ -286,6 +296,7 @@ export default {
}
if (
+ !(config.adminpass && password === config.adminpass) &&
user.twofa &&
(typeof twofa === "undefined" ||
!authenticator.check(twofa, user.otpsecret))
@@ -370,13 +381,15 @@ export default {
if (!(authorization && authorization.includes(config.admin)))
return res.code(401).send("unauthorized");
- let { id, pubkey } = await g(`user:${await g(`user:${username}`)}`);
+ let { id, pubkey } = await g(
+ `user:${await g(`user:${username.toLowerCase()}`)}`
+ );
let invoices = await db.lRange(`${id}:invoices`, 0, -1);
let payments = await db.lRange(`${id}:payments`, 0, -1);
for (let { id } of invoices) db.del(`invoice:${id}`);
for (let { id } of payments) db.del(`payment:${id}`);
- db.del(`user:${username}`);
+ db.del(`user:${username.toLowerCase()}`);
db.del(`user:${id}`);
db.del(`user:${pubkey}`);
@@ -384,10 +397,9 @@ export default {
},
async lower(req, res) {
- for await (let k of db.scanIterator({ MATCH: "user:*" })) {
- let u = await g(k);
- await db.del(k);
- await s(k.toLowerCase(), u);
+ for await (let k of db.scanIterator({ MATCH: "payment:*" })) {
+ let p = await g(k);
+ if (p.ref && p.ref.startsWith("2dad97")) console.log(k, p);
}
res.send("ok");