@vbyte/btc-dev
Version:
Batteries-included toolset for plebian bitcoin development
56 lines (55 loc) • 2 kB
JavaScript
import { Buff } from '@vbyte/buff';
import { Test } from '@vbyte/micro-lib';
import { Assert } from '@vbyte/micro-lib/assert';
import { hash256 } from '@vbyte/micro-lib/hash';
import { encode_tx } from './encode.js';
import { parse_tx } from './parse.js';
import { assert_tx_template } from './validate.js';
import { DEFAULT } from '../../const.js';
export function get_txid(txdata) {
if (typeof txdata === 'object') {
assert_tx_template(txdata);
txdata = encode_tx(txdata, false);
}
return hash256(txdata).reverse().hex;
}
export function get_txhash(txdata) {
if (typeof txdata === 'object') {
assert_tx_template(txdata);
txdata = encode_tx(txdata, true);
}
return hash256(txdata).reverse().hex;
}
export function get_tx_value(txdata) {
const tx = parse_tx(txdata);
assert_tx_template(tx);
const vin = tx.vin.reduce((acc, txin) => acc + (txin.prevout?.value ?? 0n), 0n);
const vout = tx.vout.reduce((acc, txout) => acc + txout.value, 0n);
const fees = (vin > vout) ? (vin - vout) : 0n;
return { fees, vin, vout };
}
export function get_prevouts(txdata) {
assert_tx_template(txdata);
const prevouts = txdata.vin.map(e => e.prevout);
Assert.ok(prevouts.every(e => e !== null), 'prevouts missing from tx');
return prevouts;
}
export function normalize_sequence(sequence) {
if (!Test.exists(sequence))
return DEFAULT.SEQUENCE;
if (Test.is_hex(sequence))
return Buff.hex(sequence, 4).reverse().num;
if (Test.is_uint(sequence))
return sequence;
throw new Error('invalid sequence value: ' + String(sequence));
}
export function normalize_value(value) {
if (Test.is_uint(value))
return BigInt(value);
if (typeof value === 'bigint')
return value;
throw new TypeError('invalid output value: ' + String(value));
}
export function normalize_prevout(prevout) {
return { script_pk: prevout.script_pk, value: normalize_value(prevout.value) };
}