aboutsummaryrefslogtreecommitdiffstats
path: root/routes/lnurl.js
blob: f841b87f596c4546be3ebbe8f86ab7e371c2ca70 (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
const axios = require("axios");
const lnurl = require("lnurl");
const jwt = require("jsonwebtoken");

logins = {};
withdrawals = {};

lnurlServer = lnurl.createServer(config.lnurl);

var optionalAuth = function (req, res, next) {
  passport.authenticate("jwt", { session: false }, function (err, user, info) {
    req.user = user;
    next();
  })(req, res, next);
};

app.get("/withdraw", auth, async (req, res) => {
  const { min, max } = req.query;
  try {
    const result = await lnurlServer.generateNewUrl("withdrawRequest", {
      minWithdrawable: min * 1000,
      maxWithdrawable: max * 1000,
      defaultDescription: "coinos withdrawal",
    });

    withdrawals[result.secret] = req.user;

    res.send(result);
  } catch (e) {
    l.error("problem generating withdrawl url", e.message);
    res.status(500).send(e.message);
  }
});

app.post("/withdraw", auth, async (req, res) => {
  const { user } = req;
  const {
    amount: value,
    params: { callback, k1 },
  } = req.body;
  const invoice = await lnb.addInvoice({ value });
  const { payment_request: pr } = invoice;
  const url = `${callback}?k1=${k1}&pr=${pr}`;

  await db.Invoice.create({
    user_id: user.id,
    text: pr,
    rate: app.get("rates")[user.currency],
    currency: user.currency,
    amount: value,
    tip: 0,
    network: "BTC",
  });

  try {
    result = (await axios.get(url)).data;
    res.send(result);
  } catch (e) {
    l.error("failed to withdraw", e.message);
    res.status(500).send(e.message);
  }
});

app.get("/login", optionalAuth, async (req, res) => {
  try {
    const result = await lnurlServer.generateNewUrl("login");

    if (req.user) {
      logins[result.secret] = req.user.username;
    }

    res.send(result);
  } catch (e) {
    l.error("problem generating login url", e.message);
    res.status(500).send(e.message);
  }
});

app.get("/decode", async (req, res) => {
  const { text } = req.query;

  try {
    const decoded = lnurl.decode(text);
    let result = await axios.get(decoded);
    res.send(result.data);
  } catch (e) {
    l.error("problem decoding lnurl", e.message);
    res.status(500).send(e.message);
  }
});

lnurlServer.bindToHook(
  "middleware:signedLnurl:afterCheckSignature",
  async (req, res, next) => {
    let user;
    const { key, tag, pr, k1 } = req.query;

    if (tag === "login") {
      let username = logins[k1];

      if (!username) {
        user = (await db.Key.findOne({
          where: { hex: key },
          include: [{
            model: db.User,
            as: 'user'
          }],
        })).user;

        if (!user) {
          let ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress;
          user = await register({
            username: key.substr(0, 8),
            password: key,
          }, ip);
        }

        ({ username } = user);
      }

      logins[key] = { k1, username };
    }

    if (pr) {
      user = withdrawals[k1];
      if (!user) {
        if (next) next(new Error("withdrawal not found"));
        return;
      }

      try {
        let decoded = await lna.decodePayReq({ pay_req: pr });
        let amount = decoded.num_satoshis;

        await db.transaction(async (transaction) => {
          let account = await db.Account.findOne({
            where: {
              user_id: user.id,
              asset: config.liquid.btcasset,
            },
            lock: transaction.LOCK.UPDATE,
            transaction,
          });

          if (account.balance < amount) {
            throw new Error("Insufficient funds");
          }

          let payment = await db.Payment.create(
            {
              amount: -amount,
              account_id: account.id,
              user_id: user.id,
              hash: pr,
              rate: app.get("rates")[user.currency],
              currency: user.currency,
              confirmed: true,
              network: "LNBTC",
            },
            { transaction }
          );

          setTimeout(async () => {
            try {
              let { payments } = await lna.listPayments({
                include_incomplete: false,
                max_payments: 5,
                reversed: true,
              });

              p = payments.find((p) => p.payment_request === pr);
              if (p) {
                payment.fee = p.fee;
                account.balance -= p.fee;
                await account.save();
                await payment.save();
                payment = payment.get({ plain: true });
                payment.account = account.get({ plain: true });
                emit(user.username, "account", account);
                emit(user.username, "payment", payment);
              } else {
                l.warn("payment not found, fee not set", pr);
              }
            } catch (e) {
              l.error("problem trying to get ln withdrawal payment", e);
            }
          }, 1000);

          account.balance -= amount;
          await account.save({ transaction });

          let p = payment.get({ plain: true });
          p.account = account.get({ plain: true });

          emit(user.username, "account", p.account);
          emit(user.username, "payment", p);
        });
      } catch (e) {
        l.error("failed to process withdrawal", e.message);
        return next(e);
      }
    }

    if (next) next();
  }
);

lnurlServer.bindToHook("login", async (key) => {
  l.info("logging in");
  try {
    const exists = await db.Key.findOne({
      where: { hex: key },
      include: [{ model: db.User, as: "user" }],
    });

    let user;
    if (logins[key] && logins[key] !== "undefined") {
      const { username } = logins[key];
      user = await db.User.findOne({
        where: { username },
      });

      if (user) {
        const k = await db.Key.findOrCreate({
          where: {
            user_id: user.id,
            hex: key,
          }
        });

        l.info("added key", username, k);
        emit(username, "key", k);
      } else {
        l.info("user not found");
        user = await register({
          username: key,
          password: key,
        });
      }
    } else if (exists) ({ user } = exists);

    if (user && user.username) {
      const payload = { username: user.username };
      const token = jwt.sign(payload, config.jwt);
      const ws = sessions[logins[key].k1];
      if (ws && ws.send)
        ws.send(JSON.stringify({ type: "token", data: token }));
    }
  } catch (e) {
    l.error("problem with login hook", e.message);
  }
});