aboutsummaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/binance.js2
-rw-r--r--lib/bitcoin.js3
-rw-r--r--lib/buildliquidtx.js7
-rw-r--r--lib/buildtx.js3
-rw-r--r--lib/liquid.js4
-rw-r--r--lib/ln.js25
-rw-r--r--lib/logging.js24
-rw-r--r--lib/mail.js62
-rw-r--r--lib/notifications.js3
-rw-r--r--lib/passport.js63
-rw-r--r--lib/rates.js18
-rw-r--r--lib/register.js4
-rw-r--r--lib/rpc.js18
-rw-r--r--lib/send.js4
-rw-r--r--lib/sockets.js289
-rw-r--r--lib/store.js14
-rw-r--r--lib/sync.js72
-rw-r--r--lib/upload.js21
-rw-r--r--lib/utils.js14
-rw-r--r--lib/webhooks.js2
-rw-r--r--lib/whitelist.js2
21 files changed, 373 insertions, 281 deletions
diff --git a/lib/binance.js b/lib/binance.js
index 4aa678a9..0f91ce8c 100644
--- a/lib/binance.js
+++ b/lib/binance.js
@@ -1,7 +1,7 @@
import WebSocket from 'ws';
export default () => {
- binance = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@ticker");
+ const binance = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@ticker");
binance.onmessage = async function (event) {
try {
diff --git a/lib/bitcoin.js b/lib/bitcoin.js
new file mode 100644
index 00000000..275abc04
--- /dev/null
+++ b/lib/bitcoin.js
@@ -0,0 +1,3 @@
+import config from "../config/index.js";
+import rpc from "./rpc.js";
+export default rpc(config.bitcoin);
diff --git a/lib/buildliquidtx.js b/lib/buildliquidtx.js
index ff0557b4..014b026c 100644
--- a/lib/buildliquidtx.js
+++ b/lib/buildliquidtx.js
@@ -1,13 +1,14 @@
+import { prod } from "./utils.js";
import axios from 'axios';
-import liquid from 'liquidjs-lib';
+// import liquid from 'liquidjs-lib';
import coinselect from 'coinselect';
-import split from 'coinselect/split';
+import split from 'coinselect/split.js';
const api = prod
? "https://blockstream.info/liquid/api"
: "http://localhost:3002";
const SATS = 100000000;
const network = prod ? liquid.networks["liquid"] : liquid.networks["regtest"];
-import { Op } from 'sequelize';
+import { Op } from '@sequelize/core';
export default async ({
address,
diff --git a/lib/buildtx.js b/lib/buildtx.js
index 970a17e3..a696062c 100644
--- a/lib/buildtx.js
+++ b/lib/buildtx.js
@@ -1,7 +1,8 @@
+import { prod } from "./utils.js";
import axios from 'axios';
import bitcoin from 'bitcoinjs-lib';
import coinselect from 'coinselect';
-import split from 'coinselect/split';
+import split from 'coinselect/split.js';
const api = prod ? "https://blockstream.info/api" : "http://electrsb:3095";
const SATS = 100000000;
const network = prod
diff --git a/lib/liquid.js b/lib/liquid.js
new file mode 100644
index 00000000..d93bb5a1
--- /dev/null
+++ b/lib/liquid.js
@@ -0,0 +1,4 @@
+import config from "../config/index.js";
+import rpc from "./rpc.js";
+export default rpc(config.liquid);
+
diff --git a/lib/ln.js b/lib/ln.js
new file mode 100644
index 00000000..91a704e9
--- /dev/null
+++ b/lib/ln.js
@@ -0,0 +1,25 @@
+import config from "../config/index.js";
+let ln;
+
+if (config.lna.clightning) {
+ ln = (await import("clightning-client"))(config.lna.dir);
+} else {
+ let lnd = await import("../lib/lnd");
+ ln = [
+ "addInvoice",
+ "channelBalance",
+ "connectPeer",
+ "decodePayReq",
+ "getInfo",
+ "listInvoices",
+ "listPayments",
+ "sendPaymentSync",
+ "walletBalance"
+ ].reduce(
+ (a, b) =>
+ (a[b] = args => new Promise(r => lnd[b](args, (e, v) => r(v)))) && a,
+ {}
+ );
+}
+
+export default ln;
diff --git a/lib/logging.js b/lib/logging.js
index 2e40e1b7..95e48514 100644
--- a/lib/logging.js
+++ b/lib/logging.js
@@ -1,21 +1,5 @@
-import pino from 'pino';
-import expressPinoFactory from 'express-pino-logger';
+import pino from "pino";
-const expressPino = expressPinoFactory({
- logger: pino("./logs/requests.log"),
- serializers: {
- res: res => {},
- req: req => ({
- method: req.method,
- url: req.url
- })
- }
-});
-
-l = {
- info: (...msgs) => pino().info(msgs.join(" ")),
- warn: (...msgs) => pino().warn(msgs.join(" ")),
- error: (...msgs) => pino().error(msgs.join(" "))
-};
-
-app.use(expressPino);
+ export const l = (...msgs) => pino().info(msgs.join(" "))
+ export const warn = (...msgs) => pino().warn(msgs.join(" "))
+ export const err = (...msgs) => pino().error(msgs.join(" "))
diff --git a/lib/mail.js b/lib/mail.js
index b8242f9c..9d2ff7fc 100644
--- a/lib/mail.js
+++ b/lib/mail.js
@@ -1,7 +1,9 @@
-import fs from 'fs';
-import Imap from 'imap';
-import { inspect } from 'util';
-import persist from './persist';
+import app from "../app.js";
+import config from "../config/index.js";
+import fs from "fs";
+import Imap from "imap";
+import { inspect } from "util";
+import persist from "./persist.js";
const emails = persist("data/emails.json");
let imap = new Imap(config.imap);
@@ -9,37 +11,31 @@ function openInbox(cb) {
imap.openBox("INBOX", true, cb);
}
-app.post(
- "/contact-sil",
- ah((req, res) => {
- const mailgun = require("mailgun-js")(config.mailgun);
- let data = {
- subject: "Contact form",
- text: JSON.stringify(req.body),
- };
+app.post("/contact-sil", (req, res) => {
+ const mailgun = require("mailgun-js")(config.mailgun);
+ let data = {
+ subject: "Contact form",
+ text: JSON.stringify(req.body),
+ };
- mailgun.messages().send(data);
- res.send(req.body);
- })
-);
+ mailgun.messages().send(data);
+ res.send(req.body);
+});
-app.post(
- "/contact",
- ah((req, res) => {
- const mailgun = require("mailgun-js")(config.mailgun);
- let data = {
- subject: "Contact form",
- text: JSON.stringify(req.body),
- };
+app.post("/contact", (req, res) => {
+ const mailgun = require("mailgun-js")(config.mailgun);
+ let data = {
+ subject: "Contact form",
+ text: JSON.stringify(req.body),
+ };
- mailgun.messages().send(data);
- res.send(req.body);
- })
-);
+ mailgun.messages().send(data);
+ res.send(req.body);
+});
imap.once("ready", function() {
openInbox(function(err, box) {
@@ -55,7 +51,7 @@ imap.once("ready", function() {
msg.on("body", function(stream, info) {
let buffer = "";
stream.on("data", function(chunk) {
- //stream.pipe(fs.createWriteStream('msg-' + seqno + '-body.txt', {flags:'a+'}));
+ //stream.pipe(fs.createWriteStream('msg-' + seqno + '-body.txt', {flags:'a+'});
buffer += chunk.toString("utf8");
});
stream.once("end", async function() {
diff --git a/lib/notifications.js b/lib/notifications.js
index 1ec1ff69..c931f09c 100644
--- a/lib/notifications.js
+++ b/lib/notifications.js
@@ -1,3 +1,4 @@
+import config from "../config/index.js";
import webpush from 'web-push';
if (config.vapid) {
@@ -8,7 +9,7 @@ if (config.vapid) {
);
}
-notify = (user, payload) => {
+export const notify = (user, payload) => {
let { subscriptions } = user;
if (subscriptions) {
diff --git a/lib/passport.js b/lib/passport.js
index 8da82b8e..16deef6e 100644
--- a/lib/passport.js
+++ b/lib/passport.js
@@ -1,6 +1,19 @@
-import Passport from 'passport';
-import jwt from 'passport-jwt';
-import { Op } from 'sequelize';
+import app from "../app.js";
+import Passport from "passport";
+import jwt from "passport-jwt";
+import { Op } from "@sequelize/core";
+import fastifyPassport from "@fastify/passport";
+import fastifySecureSession from '@fastify/secure-session'
+import config from "../config/index.js";
+import fs from "fs";
+import path from "path";
+
+app.register(fastifySecureSession, {
+ key: fs.readFileSync(config.jwt)
+});
+
+app.register(fastifyPassport.initialize());
+app.register(fastifyPassport.secureSession());
function cookieExtractor(req) {
if (req && req.cookies) {
@@ -9,7 +22,8 @@ function cookieExtractor(req) {
return null;
}
-passport = Passport.use(
+fastifyPassport.use(
+ "jwt",
new jwt.Strategy(
{
jwtFromRequest: jwt.ExtractJwt.fromExtractors([
@@ -40,21 +54,32 @@ passport = Passport.use(
)
);
-auth = passport.authenticate("jwt", { session: false });
-
-optionalAuth = function(req, res, next) {
- passport.authenticate("jwt", { session: false }, function(err, user, info) {
- req.user = user;
- next();
- })(req, res, next);
+export const optionalAuth = {
+ preValidation: fastifyPassport.authenticate(
+ "jwt",
+ { session: false },
+ function(err, user, info) {
+ req.user = user;
+ next();
+ }
+ )
};
-adminAuth = ah((req, res, next) => {
- passport.authenticate("jwt", { session: false }, function(err, user, info) {
- if (!(user && user.admin)) return res.status(401).send("Unauthorized")
- req.user = user;
- next();
- })(req, res, next);
-});
+export const adminAuth = {
+ preValidation: fastifyPassport.authenticate(
+ "jwt",
+ { session: false },
+ function(err, user, info) {
+ if (!(user && user.admin)) return res.status(401).send("Unauthorized");
+ req.user = user;
+ next();
+ }
+ )
+};
-app.use(passport.initialize());
+export const auth = {
+ preValidation: fastifyPassport.authenticate("jwt", {
+ authInfo: false,
+ session: false
+ })
+};
diff --git a/lib/rates.js b/lib/rates.js
index 745c4212..48c87aa7 100644
--- a/lib/rates.js
+++ b/lib/rates.js
@@ -1,6 +1,7 @@
-import axios from 'axios';
-import fs from 'fs';
-import binanceFactory from './binance';
+import app from "../app.js";
+import axios from "axios";
+import fs from "fs";
+import binanceFactory from "./binance.js";
const binance = binanceFactory();
let fetchRates;
@@ -9,7 +10,7 @@ let fetchRates;
try {
({ date, fx } = JSON.parse(fs.readFileSync("fx")));
- } catch(e) {
+ } catch (e) {
l.warn("Failed to read fx file");
}
@@ -47,12 +48,9 @@ let fetchRates;
setTimeout(fetchRates, 7200000);
})();
-app.get(
- "/rates",
- ah(async (req, res, next) => {
- res.send(app.get("rates"));
- })
-);
+app.get("/rates", async (req, res, next) => {
+ res.send(app.get("rates"));
+});
setInterval(() => {
broadcast("rate", app.get("last"));
diff --git a/lib/register.js b/lib/register.js
index 0f7032b3..3dc259f5 100644
--- a/lib/register.js
+++ b/lib/register.js
@@ -2,7 +2,7 @@ import { authenticator } from 'otplib';
import axios from 'axios';
import bcrypt from 'bcrypt';
-register = ah(async (user, ip, requireChallenge) => {
+export const register = async (user, ip, requireChallenge) => {
if (!(user && user.username)) throw new Error("Username required");
user.username = user.username.replace(/ /g, "");
@@ -60,4 +60,4 @@ register = ah(async (user, ip, requireChallenge) => {
await user.save();
l.info("new user", user.username, ip);
return user;
-});
+}
diff --git a/lib/rpc.js b/lib/rpc.js
new file mode 100644
index 00000000..72d1ee73
--- /dev/null
+++ b/lib/rpc.js
@@ -0,0 +1,18 @@
+export default ({ host, port, wallet, user, password }) =>
+ new Proxy(
+ {},
+ {
+ get: (target, prop) => (...params) =>
+ ((method, ...params) =>
+ wretch()
+ .url(`http://${host}:${port}/wallet/${wallet}`)
+ .auth(
+ `Basic ${Buffer.from(`${user}:${password}`).toString("base64")}`
+ )
+ .post({
+ method,
+ params
+ })
+ .json(({ result }) => result))(prop.toLowerCase(), ...params)
+ }
+ );
diff --git a/lib/send.js b/lib/send.js
index e30f0c4b..e589ca6b 100644
--- a/lib/send.js
+++ b/lib/send.js
@@ -1,8 +1,8 @@
import bolt11 from 'bolt11';
-import { Op } from 'sequelize';
+import { Op } from '@sequelize/core';
import { computeConversionFee, conversionFeeReceiver } from '../routes/lightning/conversionFee.js';
-send = async (amount, memo, hash, user) => {
+export const send = async (amount, memo, hash, user) => {
l.info("attempting lightning payment", user.username, amount, hash);
let payreq = bolt11.decode(hash);
diff --git a/lib/sockets.js b/lib/sockets.js
index 91d9636c..dcb8a840 100644
--- a/lib/sockets.js
+++ b/lib/sockets.js
@@ -1,11 +1,14 @@
-import jwt from 'jsonwebtoken';
-import { v4 as uuidv4 } from 'uuid';
-import WebSocket from 'ws';
-import { differenceInSeconds, subSeconds } from 'date-fns';
-const code = 1000;
+import app from "../app.js";
+import jwt from "jsonwebtoken";
+import { v4 as uuidv4 } from "uuid";
+import WebSocket from "ws";
+import { differenceInSeconds, subSeconds } from "date-fns";
+import fastifyWs from "@fastify/websocket";
+import whitelist from "./whitelist.js";
+const code = 1000;
-wss = new WebSocket.Server({ clientTracking: false, noServer: true });
+const wss = new WebSocket.Server({ clientTracking: false, noServer: true });
/* eslint-disable-next-line */
const pick = (O, ...K) => K.reduce((o, k) => ((o[k] = O[k]), o), {});
@@ -13,14 +16,13 @@ const all = {};
const subscriptions = [];
const lastSeen = {};
-emit = (username, type, data) => {
+export const emit = (username, type, data) => {
if (data.username !== undefined) data = pick(data, ...whitelist);
-
if (type === "payment" && data.amount > 0) {
for (let i = subscriptions.length - 1; i >= 0; i--) {
let s = subscriptions[i];
-
+
if (
s.invoice.amount === data.amount ||
(data.address && s.invoice.address === data.address) ||
@@ -39,7 +41,7 @@ emit = (username, type, data) => {
}
};
-broadcast = (type, data) => {
+export const broadcast = (type, data) => {
const sent = [];
for (const username in sockets) {
for (const id in sockets[username]) {
@@ -54,152 +56,163 @@ broadcast = (type, data) => {
});
};
-server.on("upgrade", function(req, socket, head) {
- wss.handleUpgrade(req, socket, head, function(ws) {
- wss.emit("connection", ws, req);
- });
-});
+app.register(fastifyWs);
+app.register(async function(app) {
+ app.get("/ws", { websocket: true }, ({ socket: ws }, req) => {
+ const id = uuidv4();
+ ws.id = id;
+ ws.beats = 0;
+ ws.send(JSON.stringify({ type: "connected", data: id }));
+ all[id] = ws;
-const names = {};
+ ws.on("message", async message => {
+ let type, data;
+ try {
+ ({ type, data } = JSON.parse(message));
+ } catch (e) {
+ l.error("coudn't parse socket message");
+ }
-setInterval(() => {
- for (const username in sockets) {
- for (const id in sockets[username]) {
- let ws = sockets[username][id];
- ws.beats++;
- if (ws.beats > 10) ws.close(code, `${username} ${id} lost heartbeat`);
- }
- }
-}, 2000);
+ switch (type) {
+ case "heartbeat":
+ ws.beats = 0;
+ if (ws.user) emit(ws.user.username, "id", ws.id);
+ break;
-wss.on("connection", function(ws, req) {
- const id = uuidv4();
- ws.id = id;
- ws.beats = 0;
- ws.send(JSON.stringify({ type: "connected", data: id }));
- all[id] = ws;
+ case "login":
+ let token = data;
- ws.on("message", async message => {
- let type, data;
- try {
- ({ type, data } = JSON.parse(message));
- } catch (e) {
- l.error("coudn't parse socket message");
- }
+ // if (differenceInSeconds(new Date(), lastSeen[token]) < 5) return;
+ lastSeen[token] = new Date();
- switch (type) {
- case "heartbeat":
- ws.beats = 0;
- if (ws.user) emit(ws.user.username, "id", ws.id);
- break;
+ try {
+ if (!token || token === "null" || !jwt.decode(token))
+ return ws.close(code, `bad token ${token}`);
+ const username = jwt.decode(token).username;
+ if (!username) throw new Error("Invalid JWT token");
- case "login":
- let token = data;
+ if (!sockets[username]) sockets[username] = {};
+ const existing = Object.keys(sockets[username]);
+ if (existing.length > 4) {
+ const p = existing.find(sid => sid !== id);
+ sockets[username][p].send(JSON.stringify({ type: "logout" }));
+ setTimeout(() => {
+ if (sockets[username][p])
+ sockets[username][p].close(code, "too many sockets");
+ }, 5000);
+ }
+ sockets[username][id] = ws;
+ names[id] = username;
- // if (differenceInSeconds(new Date(), lastSeen[token]) < 5) return;
- lastSeen[token] = new Date();
+ let user = await getUser(username);
+ if (user.locked) throw new Error("Account is locked");
+ let payments = await user.getPayments({
+ where: {
+ account_id: user.account_id
+ },
+ order: [["id", "DESC"]],
+ limit: 12,
+ include: [
+ {
+ model: db.Account,
+ as: "account"
+ },
+ {
+ model: db.Payment,
+ as: "fee_payment"
+ }
+ ]
+ });
- try {
- if (!token || token === "null" || !jwt.decode(token)) return ws.close(code, `bad token ${token}`);
- const username = jwt.decode(token).username;
- if (!username) throw new Error("Invalid JWT token");
+ let accounts = await user.getAccounts();
+ let keys = await user.getKeys();
+ user = user.get({ plain: true });
+ user.accounts = accounts;
+ user.keys = keys;
+ user.payments = payments;
- if (!sockets[username]) sockets[username] = {};
- const existing = Object.keys(sockets[username]);
- if (existing.length > 4) {
- const p = existing.find(sid => sid !== id);
- sockets[username][p].send(JSON.stringify({ type: "logout" }));
- setTimeout(() => {
- if (sockets[username][p]) sockets[username][p].close(code, "too many sockets");
- }, 5000);
+ ws.user = user;
+ ws.send(JSON.stringify({ type: "login", data: user }));
+ ws.send(
+ JSON.stringify({ type: "version", data: config.clientVersion })
+ );
+ } catch (e) {
+ l.error("caught socket error", e.message);
+ if (e.message.includes("locked")) {
+ ws.send(JSON.stringify({ type: "locked" }));
+ ws.send(JSON.stringify({ type: "logout" }));
+ }
+ if (e.message.includes("not found"))
+ ws.send(JSON.stringify({ type: "logout" }));
+ setTimeout(
+ () => ws && ws.close(code, `closing due to error ${e.message}`),
+ 1000
+ );
}
- sockets[username][id] = ws;
- names[id] = username;
-
- let user = await getUser(username);
- if (user.locked) throw new Error("Account is locked");
- let payments = await user.getPayments({
+ break;
+ case "token":
+ if (!ws.user) return;
+ ws.token = data;
+ break;
+ case "lnurl":
+ sessions[data] = ws;
+ break;
+ case "updateMemo":
+ const payment = await db.Payment.findOne({
where: {
- account_id: user.account_id
+ user_id: ws.user.id,
+ id: data.id
},
- order: [["id", "DESC"]],
- limit: 12,
- include: [{
+ include: {
model: db.Account,
as: "account"
- },
- {
- model: db.Payment,
- as: "fee_payment"
- }]
+ }
});
-
- let accounts = await user.getAccounts();
- let keys = await user.getKeys();
- user = user.get({ plain: true });
- user.accounts = accounts;
- user.keys = keys;
- user.payments = payments;
-
- ws.user = user;
- ws.send(JSON.stringify({ type: "login", data: user }));
- ws.send(
- JSON.stringify({ type: "version", data: config.clientVersion })
- );
- } catch (e) {
- l.error("caught socket error", e.message);
- if (e.message.includes("locked")) {
- ws.send(JSON.stringify({ type: "locked" }));
- ws.send(JSON.stringify({ type: "logout" }));
+ if (payment) {
+ payment.memo = data.memo;
+ await payment.save();
+ emit(ws.user.username, "payment", payment);
}
- if (e.message.includes("not found"))
- ws.send(JSON.stringify({ type: "logout" }));
- setTimeout(() => ws && ws.close(code, `closing due to error ${e.message}`), 1000);
- }
- break;
- case "token":
- if (!ws.user) return;
- ws.token = data;
- break;
- case "lnurl":
- sessions[data] = ws;
- break;
- case "updateMemo":
- const payment = await db.Payment.findOne({
- where: {
- user_id: ws.user.id,
- id: data.id
- },
- include: {
- model: db.Account,
- as: "account"
- }
- });
- if (payment) {
- payment.memo = data.memo;
- await payment.save();
- emit(ws.user.username, "payment", payment);
+ break;
+ case "subscribe":
+ subscriptions.push({ invoice: data, ws });
+ break;
+ default:
+ l.warn("received socket message of unknown type", type, data);
+ }
+ });
+
+ ws.on("close", function(code, reason) {
+ // if (reason) console.log("closing socket", reason);
+ try {
+ const username = names[id];
+ if (sockets[username] && sockets[username][id]) {
+ delete sockets[username][id];
}
- break;
- case "subscribe":
- subscriptions.push({ invoice: data, ws });
- break;
- default:
- l.warn("received socket message of unknown type", type, data);
- }
- });
- ws.on("close", function(code, reason) {
- // if (reason) console.log("closing socket", reason);
- try {
- const username = names[id];
- if (sockets[username] && sockets[username][id]) {
- delete sockets[username][id];
+ if (all[id]) delete all[id];
+ } catch (e) {
+ l.error("problem closing socket", e.message);
}
-
- if (all[id]) delete all[id];
- } catch (e) {
- l.error("problem closing socket", e.message);
- }
+ });
});
});
+
+app.listen({ port: 3000 }, err => {
+ if (err) {
+ fastify.log.error(err);
+ process.exit(1);
+ }
+});
+
+const names = {};
+
+setInterval(() => {
+ for (const username in sockets) {
+ for (const id in sockets[username]) {
+ let ws = sockets[username][id];
+ ws.beats++;
+ if (ws.beats > 10) ws.close(code, `${username} ${id} lost heartbeat`);
+ }
+ }
+}, 2000);
diff --git a/lib/store.js b/lib/store.js
new file mode 100644
index 00000000..fae3e65a
--- /dev/null
+++ b/lib/store.js
@@ -0,0 +1,14 @@
+import persist from "./persist.js";
+
+export const addresses = {};
+export const challenge = {};
+export const change = [];
+export const exceptions = [];
+export const issuances = {};
+export const logins = {};
+export const seen = [];
+export const sessions = {};
+export const sockets = {};
+export const unaccounted = [];
+export const networks = [];
+export const convert = persist("data/conversions.json");
diff --git a/lib/sync.js b/lib/sync.js
index ab1e81f0..1a98c121 100644
--- a/lib/sync.js
+++ b/lib/sync.js
@@ -1,7 +1,9 @@
-import { differenceInDays } from 'date-fns';
-import fs from 'fs';
-import read from '../lib/read.js';
-import { Op } from 'sequelize';
+import db from "../db/index.js";
+import app from "../app.js";
+import { differenceInDays } from "date-fns";
+import fs from "fs";
+import read from "../lib/read.js";
+import { Op } from "@sequelize/core";
const init = async () => {
try {
@@ -134,7 +136,12 @@ const sync = async () => {
}
}
} catch (e) {
- l.error("problem syncing lightning payment", JSON.stringify(missed[i]), e.message, e.stack);
+ l.error(
+ "problem syncing lightning payment",
+ JSON.stringify(missed[i]),
+ e.message,
+ e.stack
+ );
}
}
@@ -311,34 +318,31 @@ const sync = async () => {
setTimeout(sync, 5000);
-app.get(
- "/conversions",
- ah(async (req, res) => {
- const transactions = [
- ...(await bc.listTransactions("*", 500)),
- ...(await lq.listTransactions("*", 500))
- ].filter(tx => ["receive"].includes(tx.category));
+app.get("/conversions", async (req, res) => {
+ const transactions = [
+ ...(await bc.listTransactions("*", 500)),
+ ...(await lq.listTransactions("*", 500))
+ ].filter(tx => ["receive"].includes(tx.category));
- const { addr } = req.query;
- const { invoices } = require("./invoices");
- const persist = require("./persist");
- let conversions = persist("data/conversions.json");
- const payments = (
- await db.Payment.findAll({
- attributes: ["hash"]
+ const { addr } = req.query;
+ const { invoices } = require("./invoices");
+ const persist = require("./persist");
+ let conversions = persist("data/conversions.json");
+ const payments = (
+ await db.Payment.findAll({
+ attributes: ["hash"]
+ })
+ ).map(p => p.hash);
+ res.send(
+ Object.keys(conversions)
+ .filter(c => conversions[c].address === addr)
+ .filter(c => {
+ return (
+ invoices.find(
+ i => i.payment_request === c && i.state === "SETTLED"
+ ) || transactions.find(tx => tx.txid === c)
+ );
})
- ).map(p => p.hash);
- res.send(
- Object.keys(conversions)
- .filter(c => conversions[c].address === addr)
- .filter(c => {
- return (
- invoices.find(
- i => i.payment_request === c && i.state === "SETTLED"
- ) || transactions.find(tx => tx.txid === c)
- );
- })
- .filter(c => !payments.includes(c))
- );
- })
-);
+ .filter(c => !payments.includes(c))
+ );
+});
diff --git a/lib/upload.js b/lib/upload.js
index 2cd99bc3..f48a3d94 100644
--- a/lib/upload.js
+++ b/lib/upload.js
@@ -1,4 +1,6 @@
-import multer from 'multer';
+import { auth } from "./passport.js";
+import app from "../app.js";
+import multer from "multer";
const storage = multer.diskStorage({
destination: (req, file, cb) => {
@@ -11,10 +13,10 @@ const storage = multer.diskStorage({
}
});
-upload = multer({
+export const upload = multer({
storage,
onFileUploadStart: (file, req, res) => {
- console.log("CHECKING SIZE")
+ console.log("CHECKING SIZE");
const maxSize = 32 * 1000 * 1000;
if (req.files.file.length > maxSize) {
return false;
@@ -22,12 +24,7 @@ upload = multer({
}
});
-app.post(
- "/profile",
- auth,
- upload.single("squirt"),
- ah(async (req, res) => {
- let { filename } = req.file;
- res.send({ filename });
- })
-);
+app.post("/profile", auth, upload.single("squirt"), async (req, res) => {
+ let { filename } = req.file;
+ res.send({ filename });
+});
diff --git a/lib/utils.js b/lib/utils.js
index 1de8ffeb..af50d7ec 100644
--- a/lib/utils.js
+++ b/lib/utils.js
@@ -1,7 +1,7 @@
-import sequelize from 'sequelize';
+import sequelize from '@sequelize/core';
const { Op } = sequelize;
-getUser = async (username, transaction) => {
+export const getUser = async (username, transaction) => {
let params = {
include: [
{
@@ -25,7 +25,7 @@ getUser = async (username, transaction) => {
return user;
};
-getUserById = async (id, transaction) => {
+export const getUserById = async (id, transaction) => {
let params = {
include: [
{
@@ -46,3 +46,11 @@ getUserById = async (id, transaction) => {
return user;
};
+
+export const prod = process.env.NODE_ENV === "production";
+export const fail = msg => {
+ throw new Error(msg);
+};
+
+export const SATS = 100000000;
+export const toSats = n => Math.round(n * SATS);
diff --git a/lib/webhooks.js b/lib/webhooks.js
index 0dc1df52..ccebc024 100644
--- a/lib/webhooks.js
+++ b/lib/webhooks.js
@@ -2,7 +2,7 @@ import wretch from 'wretch';
import fetch from 'node-fetch';
wretch().polyfills({ fetch });
-callWebhook = (invoice, payment) => {
+export const callWebhook = (invoice, payment) => {
if (!invoice || !payment) return;
let { address, text, webhook } = invoice;
diff --git a/lib/whitelist.js b/lib/whitelist.js
index 39d1fb0f..229f2682 100644
--- a/lib/whitelist.js
+++ b/lib/whitelist.js
@@ -1,4 +1,4 @@
-whitelist = [
+export default [
"id",
"account",
"account_id",