aboutsummaryrefslogtreecommitdiffstats
path: root/lib/sync.js
blob: 4aa8d40d8b6b50e9752d86c18231dabd0e448f0c (plain) (blame)
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
import db from "$db/db";
import app from "$app";
import { differenceInDays } from "date-fns";
import fs from "fs";
import read from "./read";
import { Op } from "@sequelize/core";
import store from "./store";
import { l, err, warn } from "./logging";
import lnd from "./lnd";
import { getInvoices } from "lightning";
import bc from "./bitcoin";
import lq from "./liquid";

const init = async () => {
  try {
    read(fs.createReadStream("exceptions"), data =>
      store.exceptions.push(data)
    );
  } catch (e) {
    warn("couldn't read exceptions file", e.message);
  }

  try {
    const thirtyDays = new Date(new Date().setDate(new Date().getDate() - 30));

    (
      await db.Invoice.findAll({
        where: {
          createdAt: {
            [Op.gt]: thirtyDays
          }
        },
        include: {
          model: db.User,
          as: "user"
        }
      })
    ).map(({ address, user, unconfidential }) => {
      if (address && user) store.addresses[address] = user.username;
      if (unconfidential && user)
        store.addresses[unconfidential] = user.username;
    });
  } catch (e) {
    console.log(e);
  }

  store.payments = (
    await db.Payment.findAll({
      attributes: ["hash"]
    })
  ).map(p => p.hash);
};

init();

const sync = async () => {
  const twoWeeksAgo = new Date(new Date().setDate(new Date().getDate() - 14));

  try {
    const payments = await db.Payment.findAll({
      attributes: ["hash", "confirmed", "preimage"],
      where: { createdAt: { [Op.gt]: twoWeeksAgo } },
      include: [
        {
          model: db.Account,
          as: "account"
        },
        {
          model: db.User,
          as: "user"
        }
      ]
    });

    let { invoices } = await getInvoices({ lnd, limit: 200 });

    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];
      if (!text.length) continue;

      try {
        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("lightning missing from account", account.id, amount);
          }
        }
      } catch (e) {
        err(
          "problem syncing lightning payment",
          JSON.stringify(missed[i]),
          e.message,
          e.stack
        );
      }
    }

    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("*", 500)),
      ...(await lq.listTransactions("*", 500))
    ].filter(
      tx =>
        ["send", "receive"].includes(tx.category) &&
        new Date(tx.time * 1000) > twoWeeksAgo
    );

    missed = transactions.filter(
      tx =>
        tx.category === "receive" &&
        tx.confirmations > 2 &&
        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;

      try {
        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("unconfirmed tx", p.user_id, p.hash, p.address);
      } catch (e) {
        err("problem confirming payment", p, e.message, e.stack);
      }
    }

    store.unaccounted = [];

    transactions.map(tx => {
      if (
        !payments.find(p => p.hash === tx.txid) &&
        !store.exceptions.includes(tx.txid) &&
        !store.unaccounted.find(a => a.txid === tx.txid) &&
        new Date(tx.blocktime * 1000) >= twoWeeksAgo
      ) {
        store.unaccounted.push(tx);
      }
    });

    if (store.unaccounted.length)
      warn(
        "wallet transactions missing from database",
        store.unaccounted.map(tx => tx.txid)
      );

    let receipts = store.unaccounted
      .filter(
        tx =>
          tx.category === "receive" &&
          (!tx.asset || 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];

      l("unaccounted", address);

      let pending = store.unaccounted.filter(
        tx => tx.address === address || tx.address === unconfidential
      );

      for (let i = 0; i < pending.length; i++) {
        let { amount, txid: hash } = pending[i];

        amount = toSats(amount);

        try {
          await db.transaction(async transaction => {
            l("found pending transaction", user.username, amount, hash);
            store.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);
          });
        } catch (e) {
          err("problem updating pending transaction", hash, e.message, e.stack);
        }
      }
    }
  } catch (e) {
    console.log(e);
    err("sync check failed", e.message, e.stack);
  }

  setTimeout(sync, 300000);
};

setTimeout(sync, 5000);

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"]
    })
  ).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))
  );
});