UNPKG

@vbyte/btc-dev

Version:

Batteries-included toolset for plebian bitcoin development

72 lines (71 loc) 2.51 kB
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 { decode_tx } from './decode.js'; 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 transcode_tx(txdata, use_segwit = true) { const decoded = decode_tx(txdata); return encode_tx(decoded, use_segwit); } export function get_txid(txdata) { let buffer; if (txdata instanceof Uint8Array) { buffer = transcode_tx(txdata, false); } else if (typeof txdata === 'object') { assert_tx_template(txdata); buffer = encode_tx(txdata, false); } else if (typeof txdata === 'string') { Assert.is_hex(txdata); buffer = transcode_tx(txdata, false); } else { throw new TypeError('invalid txdata type: ' + typeof txdata); } return hash256(buffer).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) }; }