paulmillr / scure-btc-signer

Audited & minimal library for creating, signing & decoding Bitcoin transactions.
https://paulmillr.com/noble/#scure
MIT License
135 stars 33 forks source link

Input hash bytes order #11

Closed mahnunchik closed 1 year ago

mahnunchik commented 1 year ago

I've faced with the issue that the byte order is messed up in hash input parameter.

Let's look at the example from the tests: https://github.com/paulmillr/micro-btc-signer/blob/main/test/basic.test.js#L52

Transaction: https://blockstream.info/tx/c061c23190ed3370ad5206769651eaf6fac6d87d85b5db34e30a74e0c4a6da3e

const hash = hex.decode('c061c23190ed3370ad5206769651eaf6fac6d87d85b5db34e30a74e0c4a6da3e').reverse();
// 3edaa6c4e0740ae334dbb5857dd8c6faf6ea5196760652ad7033ed9031c261c0

When hash is passed as bytes in reverse order of original txid:

import * as btc from 'micro-btc-signer';
import { hex } from '@scure/base';

const tx = new btc.Transaction();

tx.addInput({
  hash: hex.decode('c061c23190ed3370ad5206769651eaf6fac6d87d85b5db34e30a74e0c4a6da3e').reverse(),
  index: 0,
});

console.log(hex.encode(tx.unsignedTx));
// 0200000001c061c23190ed3370ad5206769651eaf6fac6d87d85b5db34e30a74e0c4a6da3e0000000000ffffffff0000000000

It produces transaction with reversed bytes one more time.

Expected transaction hex is:

// 02000000013edaa6c4e0740ae334dbb5857dd8c6faf6ea5196760652ad7033ed9031c261c00000000000ffffffff0000000000

Some libraries treats string parameter as txid and converts it on the fly but Buffer/butes parameter keeps as is.

When string is passed as hash:

tx.addInput({
  hash: 'c061c23190ed3370ad5206769651eaf6fac6d87d85b5db34e30a74e0c4a6da3e',
  index: 0,
});

console.log(hex.encode(tx.unsignedTx));
// 0200000001c061c23190ed3370ad5206769651eaf6fac6d87d85b5db34e30a74e0c4a6da3e0000000000ffffffff0000000000

It produces the same wrong order of bytes as it is in original txid.

paulmillr commented 1 year ago

Fixed. It was a naming confusion. Made it clear