diff options
Diffstat (limited to 'routes')
| -rw-r--r-- | routes/admin.js | 17 | ||||
| -rw-r--r-- | routes/payments.js | 495 | ||||
| -rw-r--r-- | routes/referrals.js | 20 | ||||
| -rw-r--r-- | routes/send.js | 2 | ||||
| -rw-r--r-- | routes/swaps.js | 4 | ||||
| -rw-r--r-- | routes/users.js | 3 |
6 files changed, 111 insertions, 430 deletions
diff --git a/routes/admin.js b/routes/admin.js index d12e3ecf..14f97a19 100644 --- a/routes/admin.js +++ b/routes/admin.js @@ -1,6 +1,5 @@ var express = require('express'); var router = express.Router(); -var debug = require('debug')('debug') const parseInput = require('../scripts/apiParse') @@ -47,7 +46,6 @@ router.get( // }) const found = await users - debug('users: ' + JSON.stringify(found)) return res.send({users: found}) }) ); @@ -104,7 +102,6 @@ router.get( } var found = await referrals - debug('Referrals: ' + JSON.stringify(found)) return res.send({referrals: found}) }) ); @@ -151,7 +148,6 @@ router.get( const found = await queue - debug('Waiting list: ' + JSON.stringify(found)) return res.send({queue: found}) }) ); @@ -195,10 +191,8 @@ router.get( if (timeCondition) accounts = accounts.whereRaw(timeCondition) if (userCondition) accounts = accounts.whereRaw(userCondition) - debug('search ? ' + search) const found = await accounts - debug('accounts: ' + JSON.stringify(found)) return res.send({accounts: found}) }) ); @@ -254,7 +248,6 @@ router.get( if (since) { transactions = transactions .havingRaw('(' + stamp + ' >= ? OR ' + stamp + ' IS NULL)', [since]) - debug(types[i] + ' since ' + since) } } @@ -266,10 +259,8 @@ router.get( transactions = transactions .groupBy('users.id') - debug('search ? ' + search) const found = await transactions - debug('transactions: ' + JSON.stringify(found)) return res.send({transactions: found}) }) ); @@ -327,7 +318,6 @@ router.get( }) var found = await orders - debug('orders: ' + JSON.stringify(found)) return res.send({orders: found}) }) ); @@ -376,7 +366,6 @@ router.get( if (userCondition) invoices = invoices.whereRaw(userCondition) var found = await invoices - debug('invoices: ' + JSON.stringify(found)) return res.send({invoices: found}) }) ); @@ -417,8 +406,6 @@ router.get( .from('deposits') .leftJoin('users', 'deposits.user_id', 'users.id') - debug('dtype: ' + deposits.constructor + ' : ' + typeof(deposits)) - var timeCondition = parseInput.addTimeSearch(req.query, 'deposits.updatedAt') var userCondition = parseInput.addUserSearch(req.query) @@ -426,7 +413,6 @@ router.get( if (userCondition) deposits = deposits.whereRaw(userCondition) var found = await deposits - debug('deposits: ' + JSON.stringify(found)) return res.send({deposits: found}) }) ); @@ -473,7 +459,6 @@ router.get( if (userCondition) withdrawals = withdrawals.whereRaw(userCondition) var found = await withdrawals - debug('withdrawals: ' + JSON.stringify(found)) return res.send({withdrawals: found}) }) ); @@ -522,7 +507,6 @@ router.get( if (userCondition) payments = payments.whereRaw(userCondition) var found = await payments - debug('payments: ' + JSON.stringify(found)) return res.send({payments: found}) }) ); @@ -581,7 +565,6 @@ router.get( var found = await kyc.having('max', '>=', threshold) - debug('payments: ' + JSON.stringify(found)) return res.send({found: found}) }) ); diff --git a/routes/payments.js b/routes/payments.js index 836a6681..261d34f3 100644 --- a/routes/payments.js +++ b/routes/payments.js @@ -1,414 +1,135 @@ +const fs = require("fs"); const BitcoinCore = require("@asoltys/bitcoin-core"); -const { Op } = require("sequelize"); const { join } = require("path"); -const fs = require("fs"); -const read = require("../lib/read"); -const { differenceInDays } = require("date-fns"); - -ah(async () => { - seen = []; - addresses = {}; - change = []; - issuances = {}; - unaccounted = []; - - const exceptions = []; - try { - read(fs.createReadStream("exceptions"), data => exceptions.push(data)); - } catch (e) { - l.warn("couldn't read exceptions file", e.message); - } - try { - const twoDays = new Date(new Date().setDate(new Date().getDate() - 2)); +app.post("/send", auth, require("./send")); +app.get( + "/except", + adminAuth, + ah((req, res) => { + let s = fs.createWriteStream("exceptions", { flags: "a" }); + unaccounted.map(tx => s.write(tx.txid + "\n")); + l.info("updated exceptions"); + res.send("updated exceptions"); + }) +); - ( - await db.Invoice.findAll({ - where: { - createdAt: { - [Op.gt]: twoDays - } - }, - include: { - model: db.User, - as: "user" - } - }) - ).map(({ address, user, unconfidential }) => { - if (address && user) addresses[address] = user.username; - if (unconfidential && user) addresses[unconfidential] = user.username; - }); - } catch (e) { - console.log(e); +if (config.lna) { + if (config.lna.clightning) { + lna = require("clightning-client")(config.lna.dir); + } else { + const lnd = require("../lib/lnd"); + lna = lnd.default; + lnp = [ + "addInvoice", + "channelBalance", + "connectPeer", + "decodePayReq", + "getInfo", + "listInvoices", + "listPayments", + "sendPaymentSync", + "walletBalance" + ].reduce( + (a, b) => + (a[b] = args => new Promise(r => lna[b](args, (e, v) => r(v)))) && a, + {} + ); } - try { - const accounts = await db.Account.findAll({ - where: { pubkey: { [Op.ne]: null } }, - include: { - model: db.User, - as: "user" - } - }); - - accounts.map(({ address, user: { username } }) => { - addresses[address] = username; - }); - } catch (e) { - console.log(e); - } + app.post("/lightning/channel", require("./lightning/channel")); + app.post("/lightning/channelRequest", require("./lightning/channelRequest")); + app.post("/lightning/invoice", require("./lightning/invoice")); + app.post("/lightning/query", auth, require("./lightning/query")); + app.post("/lightning/send", auth, require("./lightning/send")); + app.post("/lightning/withdraw", auth, require("./lightning/withdraw")); + require("./lightning/receive"); +} - payments = ( - await db.Payment.findAll({ - attributes: ["hash"] - }) - ).map(p => p.hash); +if (config.bitcoin) { + bc = new BitcoinCore(config.bitcoin); + app.post("/bitcoin/broadcast", optionalAuth, require("./bitcoin/broadcast")); + app.get("/bitcoin/generate", auth, require("./bitcoin/generate")); + app.post("/bitcoin/sweep", auth, require("./bitcoin/sweep")); + app.post("/bitcoin/fee", auth, require("./bitcoin/fee")); + app.post("/bitcoin/send", auth, require("./bitcoin/send")); + app.post("/bitcoin/withdraw", auth, require("./bitcoin/withdraw")); + require("./bitcoin/receive"); - const sanity = async () => { + setTimeout(async () => { try { - let { invoices } = await lnp.listInvoices({ - reversed: true, - num_max_invoices: 1000 - }); - - let recent = invoices - .filter( - i => - i.settled && - differenceInDays(new Date(), new Date(i.settle_date * 1000)) < 2 - ) - .map(i => ({ - amount: parseInt(i.amt_paid_sat), - preimage: i.r_preimage.toString("hex"), - pr: i.payment_request.toString("hex"), - createdAt: new Date(i.settle_date * 1000) - })); - - const twoDaysAgo = new Date(new Date().setDate(new Date().getDate() - 2)); - let settled = ( - await db.Payment.findAll({ - where: { network: "lightning", createdAt: { [Op.gt]: twoDaysAgo } }, - attributes: ["preimage"] - }) - ).map(p => p.preimage); - - let missed = recent.filter(i => !settled.includes(i.preimage)); - for (let i = 0; i < missed.length; i++) { - let { amount, preimage, pr: text, createdAt } = missed[i]; - let invoice = await db.Invoice.findOne({ - where: { text }, - include: { - model: db.User, - as: "user" - } - }); - - if (invoice && invoice.user_id) { - let account = await db.Account.findOne({ - where: { - user_id: invoice.user_id, - asset: config.liquid.btcasset, - pubkey: null - } - }); - - if (account) { - let payment = await db.Payment.create({ - account_id: account.id, - user_id: invoice.user_id, - hash: text, - amount, - currency: invoice.currency, - preimage, - rate: invoice.rate, - received: true, - confirmed: true, - network: "lightning", - tip: invoice.tip, - invoice_id: invoice.id, - createdAt, - updatedAt: createdAt - }); - - await account.increment({ balance: amount }); - - l.info("rectified account", account.id, amount); - } - } - } - - const unconfirmed = await db.Payment.findAll({ - where: { - confirmed: 0 - }, - include: [ - { - model: db.Account, - as: "account" - }, - { - model: db.User, - as: "user" - } - ] - }); - - let hashes = unconfirmed.map(p => p.hash); - - const transactions = [ - ...(await bc.listTransactions("*", 50)), - ...(await lq.listTransactions("*", 50)) - ].filter(tx => ['send', 'receive'].includes(tx.category)); - - missed = transactions.filter( - tx => - tx.category === "receive" && - tx.confirmations > 0 && - hashes.includes(tx.txid) - ); - - for (let i = 0; i < missed.length; i++) { - let p = unconfirmed.find(p => p.hash === missed[i].txid); - p.confirmed = 1; - - await db.transaction(async transaction => { - await p.save({ transaction }); - - await p.account.increment({ balance: p.amount }, { transaction }); - await p.account.decrement({ pending: p.amount }, { transaction }); - }); - - emit(p.user.username, "account", p.account); - emit(p.user.username, "payment", p); - - l.info("confirmed tx", p.user_id, p.hash, p.address); - } - - unaccounted = []; - - transactions.map(tx => { - if (!payments.includes(tx.txid) && !exceptions.includes(tx.txid)) { - unaccounted.push(tx); - } - }); - - if (unaccounted.length) - l.warn( - "wallet transactions missing from database", - unaccounted.map(tx => tx.txid) - ); - - let receipts = unaccounted - .filter(tx => tx.category === "receive" && tx.asset === config.liquid.btcasset) - .map(tx => tx.address); - - invoices = await db.Invoice.findAll({ - where: { - [Op.or]: { - address: receipts, - unconfidential: receipts - } - }, - include: [ - { - model: db.Account, - as: "account" - }, - { - model: db.User, - as: "user" - } - ] - }); - - for (let i = 0; i < invoices.length; i++) { - let { - address, - unconfidential, - account, - account_id, - currency, - id: invoice_id, - network, - rate, - tip, - user, - user_id - } = invoices[i]; - - let { amount, txid: hash } = unaccounted.find( - tx => tx.address === address || tx.address === unconfidential - ); - - amount = toSats(amount); - - await db.transaction(async transaction => { - payments.push(hash); - let p = await db.Payment.create( - { - account_id, - address: address || unconfidential, - amount, - confirmed: false, - currency, - hash, - invoice_id, - network, - rate, - received: true, - tip, - user_id - }, - { transaction } - ); - - await account.increment({ pending: amount }, { transaction }); - - emit(user.username, "account", account); - emit(user.username, "payment", p); - }); - } + const address = await bc.getNewAddress(); + const { hdkeypath } = await bc.getAddressInfo(address); + const parts = hdkeypath.split("/"); + app.set("bcAddressIndex", parts[parts.length - 1].slice(0, -1)); } catch (e) { - l.error("sanity check failed", e.message, e.stack); + console.error(e); } - }; - - setTimeout(sanity, 5000); - setInterval(sanity, 720000); + }, 50); +} - app.post("/send", auth, require("./send")); - app.get( - "/except", - adminAuth, - ah((req, res) => { - let s = fs.createWriteStream("exceptions", { flags: "a" }); - unaccounted.map(tx => s.write(tx.txid + "\n")); - l.info("updated exceptions"); - res.send("wonderful"); - }) - ); +if (config.liquid) { + lq = new BitcoinCore(config.liquid); + rare = new BitcoinCore(config.rare); + app.post("/liquid/broadcast", optionalAuth, require("./liquid/broadcast")); + app.get("/liquid/generate", auth, require("./liquid/generate")); + app.post("/liquid/fee", auth, require("./liquid/fee")); + app.post("/liquid/send", auth, require("./liquid/send")); + app.post("/liquid/withdraw", auth, require("./liquid/withdraw")); + app.post("/taxi", auth, require("./liquid/taxi")); + require("./liquid/receive"); - if (config.lna) { - if (config.lna.clightning) { - lna = require("clightning-client")(config.lna.dir); - } else { - const lnd = require("../lib/lnd"); - lna = lnd.default; - lnp = [ - "addInvoice", - "channelBalance", - "connectPeer", - "decodePayReq", - "getInfo", - "listInvoices", - "listPayments", - "sendPaymentSync", - "walletBalance" - ].reduce( - (a, b) => - (a[b] = args => new Promise(r => lna[b](args, (e, v) => r(v)))) && a, - {} - ); + setTimeout(async () => { + try { + const address = await lq.getNewAddress(); + const { hdkeypath } = await lq.getAddressInfo(address); + const parts = hdkeypath.split("/"); + app.set("lqAddressIndex", parts[parts.length - 1].slice(0, -1)); + } catch (e) { + l.warn("Problem getting liquid address index", e.message); } + }, 50); +} - app.post("/lightning/channel", require("./lightning/channel")); - app.post( - "/lightning/channelRequest", - require("./lightning/channelRequest") - ); - app.post("/lightning/invoice", require("./lightning/invoice")); - app.post("/lightning/query", auth, require("./lightning/query")); - app.post("/lightning/send", auth, require("./lightning/send")); - require("./lightning/receive"); - } - - if (config.bitcoin) { - bc = new BitcoinCore(config.bitcoin); - app.post( - "/bitcoin/broadcast", - optionalAuth, - require("./bitcoin/broadcast") - ); - app.get("/bitcoin/generate", auth, require("./bitcoin/generate")); - app.post("/bitcoin/sweep", auth, require("./bitcoin/sweep")); - app.post("/bitcoin/fee", auth, require("./bitcoin/fee")); - app.post("/bitcoin/send", auth, require("./bitcoin/send")); - require("./bitcoin/receive"); - - setTimeout(async () => { - try { - const address = await bc.getNewAddress(); - const { hdkeypath } = await bc.getAddressInfo(address); - const parts = hdkeypath.split("/"); - app.set("bcAddressIndex", parts[parts.length - 1].slice(0, -1)); - } catch (e) { - console.error(e); +app.get( + "/payments", + auth, + ah(async (req, res) => { + let payments = await req.user.getPayments({ + where: { + account_id: req.user.account_id + }, + order: [["id", "DESC"]], + include: { + model: db.Account, + as: "account" } - }, 50); - } - - if (config.liquid) { - lq = new BitcoinCore(config.liquid); - rare = new BitcoinCore(config.rare); - app.post("/liquid/broadcast", optionalAuth, require("./liquid/broadcast")); - app.get("/liquid/generate", auth, require("./liquid/generate")); - app.post("/liquid/fee", auth, require("./liquid/fee")); - app.post("/liquid/send", auth, require("./liquid/send")); - app.post("/taxi", auth, require("./liquid/taxi")); - require("./liquid/receive"); + }); - setTimeout(async () => { - try { - const address = await lq.getNewAddress(); - const { hdkeypath } = await lq.getAddressInfo(address); - const parts = hdkeypath.split("/"); - app.set("lqAddressIndex", parts[parts.length - 1].slice(0, -1)); - } catch (e) { - l.warn("Problem getting liquid address index", e.message); - } - }, 50); - } + res.send(payments); + }) +); - app.get( - "/payments", - auth, - ah(async (req, res) => { - let payments = await req.user.getPayments({ +app.get( + "/payment/:redeemcode", + ah(async (req, res) => { + try { + const { redeemcode } = req.params; + let payment = await db.Payment.findOne({ where: { - account_id: req.user.account_id + redeemcode }, - order: [["id", "DESC"]], include: { model: db.Account, as: "account" } }); - res.send(payments); - }) - ); - - app.get( - "/payment/:redeemcode", - ah(async (req, res) => { - try { - const { redeemcode } = req.params; - let payment = await db.Payment.findOne({ - where: { - redeemcode - }, - include: { - model: db.Account, - as: "account" - } - }); + if (!payment) fail("invalid code"); - if (!payment) fail("invalid code"); - - res.send(payment); - } catch (e) { - res.status(500).send(e.message); - } - }) - ); -})(); + res.send(payment); + } catch (e) { + res.status(500).send(e.message); + } + }) +); diff --git a/routes/referrals.js b/routes/referrals.js index 11cf8590..185b0928 100644 --- a/routes/referrals.js +++ b/routes/referrals.js @@ -1,6 +1,5 @@ var express = require('express'); var router = express.Router(); -var debug = require('debug')('debug') const { v4: uuidv4 } = require('uuid'); @@ -45,9 +44,7 @@ router.post( auth, ah(async (req, res) => { const {sponsor_id, expiry} = req.body - debug('grant token..') var token = uuidv4() - debug('generated token: ' + token + ' sponsored by ' + sponsor_id) var ref = await knex.table('referrals') .insert({ @@ -57,7 +54,6 @@ router.post( } ) - debug('generated referral: ' + JSON.stringify(ref)) return res.send({token: token, status: 'available', expiry: expiry}) }) ); @@ -89,9 +85,7 @@ router.get( auth, ah(async (req, res) => { const {sponsor_id, expiry} = req.query - debug('grant token..') var token = uuidv4() - debug('Generated token: ' + token + ' sponsored by ' + sponsor_id) var ref = await knex.table('referrals') .insert({ @@ -101,7 +95,6 @@ router.get( } ) - debug('generated referral: ' + JSON.stringify(ref)) return res.send({token: token, status: 'available', expiry: expiry}) }) ); @@ -153,8 +146,6 @@ router.get( if (status && status !== 'all') tokens = tokens.where('status', 'like', status) const found = await tokens - debug('my tokens: ' + JSON.stringify(found)) - return res.send({tokens: found}) }) ); @@ -187,8 +178,6 @@ router.get( ah(async (req, res) => { const { user_id, token } = req.params; - debug('verify token: ' + token) - const found = await knex .select('status') .from('referrals') @@ -196,7 +185,6 @@ router.get( .whereNull('user_id') if (found && found.length) { - debug('found referral: ' + JSON.stringify(found)) if (found[0].status === 'available') { await knex('referrals') @@ -242,10 +230,6 @@ router.post( ah(async (req, res) => { const { email, phone, user_id } = req.body; - debug('email: ' + email) - debug('phone: ' + phone) - debug('user_id: ' + user_id) - await knex.table('waiting_list') .insert({ email: email, @@ -262,10 +246,6 @@ router.get( ah(async (req, res) => { const {email, phone, user_id} = req.query; - debug('email: ' + email) - debug('phone: ' + phone) - debug('user: ' + user_id) - await knex('waiting_list') .insert({ email: email, diff --git a/routes/send.js b/routes/send.js index c00e485a..59b30d57 100644 --- a/routes/send.js +++ b/routes/send.js @@ -1,5 +1,5 @@ const axios = require("axios"); -const uuidv4 = require("uuid/v4"); +const { v4: uuidv4 } = require("uuid"); module.exports = ah(async (req, res, next) => { let { diff --git a/routes/swaps.js b/routes/swaps.js index f20f98fa..9438ee86 100644 --- a/routes/swaps.js +++ b/routes/swaps.js @@ -3,9 +3,7 @@ const crypto = require("crypto"); const fs = require("fs"); const getAccount = require("../lib/account"); const { Op, col } = require("sequelize"); -const uuidv4 = require("uuid/v4"); - -const debug = require('debug')('debug') +const { v4: uuidv4 } = require("uuid"); const shallow = a => { let b = {}; diff --git a/routes/users.js b/routes/users.js index c8427213..0c258155 100644 --- a/routes/users.js +++ b/routes/users.js @@ -766,7 +766,6 @@ app.get( let invoices = await db.Invoice.findAll({ where: { user_id: req.user.id } }); - res.send(invoices); + res.send(invoices); }) - ); |
