aboutsummaryrefslogtreecommitdiffstats
path: root/routes/bitcoin/send.js
blob: e0756662b0a727a334348cefa0fdd25c4e5f40b0 (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
const decrementAccount = require('./util/decrementacc');
const addPayment = require('./util/addPayment');

module.exports = ah(async (req, res) => {
  let { user } = req;
  let { address, memo, tx } = req.body;
  let { hex } = tx;

  let fee = toSats(tx.fee);
  if (fee < 0) throw new Error("fee cannot be negative");

  const isChange = async address =>
    (await bc.getAddressInfo(address)).ismine &&
    !Object.keys(addresses).includes(address);

  tx = await bc.decodeRawTransaction(hex);

  let total = 0;
  let change = 0;

  for (let i = 0; i < tx.vout.length; i++) {
    let o = tx.vout[i];
    total += toSats(o.value);

    if (o.scriptPubKey.addresses) {
      if (await isChange(o.scriptPubKey.addresses[0])) {
        change += toSats(o.value);
      }
    }
  }

  total = total - change + fee;
  let amount = total - fee;

  let account;
  try {
    account = await decrementAccount(user, amount);

    if (config.bitcoin.walletpass)
      await bc.walletPassphrase(config.bitcoin.walletpass, 300);

    hex = (await bc.signRawTransactionWithWallet(hex)).hex;
    const txid = await bc.sendRawTransaction(hex);

    res.send(await addPayment(account, user, address, amount, memo, txid, fee));
    l.info("sent bitcoin", user.username, total);
  } catch (e) {
    l.error("error sending bitcoin", e.message);
    return res.status(500).send(e.message);
  }
});