Decoding data from raw tx

118 Views Asked by At

Suppose, I need to get data from the object tx that normally looks like this:

 {
  ins: [
    {
      hash: <Buffer c4 37 9e 8c 55 93 98 f1 e6 68 83 c8 cf f4 45 90 59 0d 64 e8 c8 93 c3 e4 59 3d bf 6d 25 19 e0 dc>,
      index: 1,
      script: <Buffer >,
      sequence: 4294967280,
      witness: [Array]
    }
  ],
  outs: [
    {
      value: 1000000,
      script: <Buffer a9 14 c6 95 36 cc 29 d8 7f 20 3e 0f 8f 4e 9e 1a 21 a1 47 14 d9 00 87>
    },
    {
      value: 240536,
      script: <Buffer 00 14 01 8d 87 11 fa ff 3d ed 55 e7 61 4f 87 80 c2 f6 08 a7 8d d3>
    },
    {
      value: 0,
      script: <Buffer 6a 17 68 74 74 70 73 3a 2f 2f 74 62 74 63 2e 62 69 74 61 70 73 2e 63 6f 6d>
    }
  ]
 }

Generally, what I need to to is:

  1. Extract address param from script using special library.

  2. Check that this address is corresponding to an address that I'm interested in.

  3. Get value for this address.

  4. Send both address and value to the next step.

There are cases in which library can't decode address from script and raise an error. That's why I am using try-catch to skip those cases.

Simplу my code looks like this:

for (i = 0; i < tx.outs.length; i++) {
  try {
    const address = bitcoin.address.fromOutputScript(tx.outs[i].script, network).toString();

    if (!checkAddress(address)) {
        return;
    }

    let txValue = tx.outs[i].value;

    confirmTx(address, txValue);

  } catch (e) {
    logger.error(e)
  }
}

Imagine I have tx with several objects inside outs array, one of which stores the address I'm looking for. Most of the time, everything works well and confirmTx is called as expected (only for that address and value).

But the problem is that it can happen when confirmTx is called with other address and value (and that address shouldn't pass checkAddress(address)).

What can cause the problem?

0

There are 0 best solutions below