aboutsummaryrefslogtreecommitdiffstats
path: root/apidoc/utils/send_sample_request_utils.js
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2023-02-28 18:06:52 +0000
committerAdam Soltys <[email protected]>2023-02-28 18:07:05 +0000
commit80fe35caae77ab6551c35f340a18007e2bfb9750 (patch)
treeb7868bd413900556fd966a505b6eeb97cf60461f /apidoc/utils/send_sample_request_utils.js
parentea794b2a1c7679bcd0e053ef623c234ad3700fb0 (diff)
downloadcoinos-server-80fe35caae77ab6551c35f340a18007e2bfb9750.tar.gz
coinos-server-80fe35caae77ab6551c35f340a18007e2bfb9750.zip
bail if event not found
Diffstat (limited to 'apidoc/utils/send_sample_request_utils.js')
0 files changed, 0 insertions, 0 deletions
id='n128' href='#n128'>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
const reverse = require("buffer-reverse");
const zmq = require("zeromq");
const { Op } = require("sequelize");

const bitcoin = require("bitcoinjs-lib");

const zmqRawBlock = zmq.socket("sub");
zmqRawBlock.connect(config.bitcoin.zmqrawblock);
zmqRawBlock.subscribe("rawblock");

const zmqRawTx = zmq.socket("sub");
zmqRawTx.connect(config.bitcoin.zmqrawtx);
zmqRawTx.subscribe("rawtx");

const network =
  bitcoin.networks[
    config.bitcoin.network === "mainnet" ? "bitcoin" : config.bitcoin.network
  ];

zmqRawTx.on("message", async (topic, message, sequence) => {
  const hex = message.toString("hex");
  let tx = bitcoin.Transaction.fromHex(message);
  let hash = reverse(tx.getHash()).toString("hex");

  if (payments.includes(hash)) return;

  Promise.all(
    tx.outs.map(async o => {
      const { value } = o;

      let address;
      try {
        address = bitcoin.address.fromOutputScript(o.script, network);
      } catch (e) {
        return;
      }

      if (Object.keys(addresses).includes(address)) {
        payments.push(hash);

        let user = await db.User.findOne({
          where: {
            username: addresses[address]
          }
        });

        const invoice = await db.Invoice.findOne({
          where: {
            user_id: user.id,
            network: "BTC"
          },
          order: [["id", "DESC"]]
        });

        const currency = invoice ? invoice.currency : user.currency;
        const rate = invoice ? invoice.rate : app.get("rates")[user.currency];
        const tip = invoice ? invoice.tip : 0;

        let confirmed = false;

        const account = await db.Account.findOne({
          where: {
            user_id: user.id,
            asset: config.liquid.btcasset
          }
        });

        account.pending += value;
        await account.save();

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

        user.address = await bc.getNewAddress("", "bech32");
        await user.save();

        addresses[user.address] = user.username;

        let totalOutputs = tx.outs.reduce((a, b) => a + b.value, 0);
        let totalInputs = 0;
        for (let i = 0; i < tx.ins.length; i++) {
          let { hash, index } = tx.ins[i];
          hash = reverse(hash).toString("hex");
          let hex = await bc.getRawTransaction(hash.toString("hex"));
          let inputTx = bitcoin.Transaction.fromHex(hex);
          totalInputs += inputTx.outs[index].value;
        }
        let fee = totalInputs - totalOutputs;

        let payment = await db.Payment.create({
          account_id: account.id,
          user_id: user.id,
          hash,
          fee,
          amount: value - tip,
          currency,
          rate,
          received: true,
          tip,
          confirmed,
          address,
          network: "BTC"
        });
        payment = payment.get({ plain: true });
        payment.account = account.get({ plain: true });

        emit(user.username, "account", account);
        emit(user.username, "payment", payment);
        l.info("bitcoin detected", user.username, o.value);
      }
    })
  );
});

let queue = {};

zmqRawBlock.on("message", async (topic, message, sequence) => {
  const payments = await db.Payment.findAll({
    where: { confirmed: false }
  });

  let block = bitcoin.Block.fromHex(message.toString("hex"));
  block.transactions.map(tx => {
    let hash = reverse(tx.getHash()).toString("hex");
    if (payments.find(p => p.hash === hash)) queue[hash] = 1;
  });
});

setInterval(async () => {
  try {
    const arr = Object.keys(queue);
    for (let i = 0; i < arr.length; i++) {
      const hash = arr[i];

      const p = await db.Payment.findOne({
        where: { hash, confirmed: 0, received: 1 },
        include: [
          {
            model: db.Account,
            as: "account"
          },
          {
            model: db.User,
            as: "user"
          }
        ]
      });

      const { user } = p;

      if (p) {
        p.confirmed = 1;
        p.account.balance += p.amount + p.tip;
        p.account.pending -= Math.min(p.account.pending, p.amount + p.tip);

        await p.account.save();
        await p.save();

        emit(user.username, "account", p.account);
        emit(user.username, "payment", p);
        l.info("bitcoin confirmed", user.username, p.amount, p.tip);
      } else {
        l.warn("couldn't find payment", hash);
      }

      delete queue[hash];
    }
  } catch (e) {
    l.error("problem processing queued bitcoin transaction", e.message);
  }
}, 1000);