aboutsummaryrefslogtreecommitdiffstats
path: root/lib/send.js
blob: 660fcae4dd8b2b39c7b5051784bb448011a1e7b9 (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
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888 } /* Comment */
.highlight .err { color: #A61717; background-color: #E3D2D2 } /* Error */
.highlight .k { color: #080; font-weight: bold } /* Keyword */
.highlight .ch { color: #888 } /* Comment.Hashbang */
.highlight .cm { color: #888 } /* Comment.Multiline */
.highlight .cp { color: #C00; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888 } /* Comment.Single */
.highlight .cs { color: #C00; font-weight: bold; background-color: #FFF0F0 } /* Comment.Special */
.highlight .gd { color: #000; background-color: #FDD } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #A00 } /* Generic.Error */
.highlight .gh { color: #333 } /* Generic.Heading */
.highlight .gi { color: #000; background-color: #DFD } /* Generic.Inserted */
.highlight .go { color: #888 } /* Generic.Output */
.highlight .gp { color: #555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666 } /* Generic.Subheading */
.highlight .gt { color: #A00 } /* Generic.Traceback */
.highlight .kc { color: #080; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #080; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #080; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #080 } /* Keyword.Pseudo */
.highlight .kr { color: #080; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #00D; font-weight: bold } /* Literal.Number */
.highlight .s { color: #D20; background-color: #FFF0F0 } /* Literal.String */
.highlight .na { color: #369 } /* Name.Attribute */
.highlight .nb { color: #038 } /* Name.Builtin */
.highlight .nc { color: #B06; font-weight: bold } /* Name.Class */
.highlight .no { color: #036; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555 } /* Name.Decorator */
.highlight .ne { color: #B06; font-weight: bold } /* N
const bolt11 = require("bolt11");
const { Op } = require("sequelize");

send = async (amount, memo, hash, user) => {
  let payreq = bolt11.decode(hash);
  let routingInfo = payreq.tags.find(t => t.tagName === "routing_info");
  if (
    routingInfo &&
    routingInfo.data.find(d => d.fee_proportional_millionths > 100)
  )
    throw new Error("Fee rate too high");

  if (!amount || payreq.satoshis > amount) amount = payreq.satoshis;

  if (seen.includes(hash)) {
    l.warn("attempted to pay a paid invoice", user.username);
    throw new Error("Invoice has been paid, can't pay again");
  }

  let error, fee, total, preimage, payment;

  await db.transaction(async transaction => {
    let account = await db.Account.findOne({
      where: {
        user_id: user.id,
        asset: config.liquid.btcasset,
        pubkey: null,
        balance: {
          [Op.gte]: amount
        }
      },
      lock: transaction.LOCK.UPDATE,
      transaction
    });

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

    await account.decrement({ balance: amount }, { transaction });
    await account.reload({ transaction });

    if (config.lna.clightning) {
      let m = await lna.pay(hash);
      let sent;
      ({
        msatoshi: total,
        msatoshi_sent: sent,
        payment_preimage: preimage
      } = m);

      fee = parseInt((sent - total) / 1000);
      total = parseInt(total / 1000);
    } else {
      let m = await lna.sendPaymentSync({
        amt: amount,
        payment_request: hash,
        max_parts: 10,
        fee_limit: { fixed: Math.min(10000, account.balance) },
      });

      if (m.payment_error) throw new Error(m.payment_error);

      ({
        payment_route: { total_fees: fee, total_amt: total },
        payment_preimage: preimage
      } = m);
    }

    preimage = preimage.toString("hex");

    if (seen.includes(preimage)) {
      l.warn("duplicate payment detected", preimage);
      throw new Error("Duplicate payment detected");
    }
  });

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

    total = parseInt(total);
    fee = parseInt(fee);

    await account.decrement({ balance: fee }, { transaction });
    await account.reload({ transaction });

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

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

    emit(user.username, "account", payment.account);
    emit(user.username, "payment", payment);

    seen.push(preimage);
    seen.push(hash);

    l.info("sent lightning", user.username, total - fee, fee);
  });

  return payment;
};