UNPKG

@bitcoinerlab/coinselect

Version:

A TypeScript library for Bitcoin transaction management, based on Bitcoin Descriptors for defining inputs and outputs. It facilitates optimal UTXO selection and transaction size calculation.

63 lines (62 loc) 2.02 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isSegwitTx = exports.isSegwit = exports.guessOutput = void 0; const bitcoinjs_lib_1 = require("bitcoinjs-lib"); function guessOutput(output) { function guessSH(output) { try { bitcoinjs_lib_1.payments.p2sh({ output }); return true; } catch (err) { return false; } } function guessWPKH(output) { try { bitcoinjs_lib_1.payments.p2wpkh({ output }); return true; } catch (err) { return false; } } function guessPKH(output) { try { bitcoinjs_lib_1.payments.p2pkh({ output }); return true; } catch (err) { return false; } } const isPKH = guessPKH(output.getScriptPubKey()); const isWPKH = guessWPKH(output.getScriptPubKey()); const isSH = guessSH(output.getScriptPubKey()); if ([isPKH, isWPKH, isSH].filter(Boolean).length > 1) throw new Error('Cannot have multiple output types.'); return { isPKH, isWPKH, isSH }; } exports.guessOutput = guessOutput; /** * It assumes that an addr(SH_ADDRESS) is always a add(SH_WPKH) address */ function isSegwit(output) { let isSegwit = output.isSegwit(); const expansion = output.expand().expandedExpression; const { isPKH, isWPKH, isSH } = guessOutput(output); //expansion is not generated for addr() descriptors: if (!expansion && isPKH) isSegwit = false; if (!expansion && isWPKH) isSegwit = true; if (!expansion && isSH) isSegwit = true; //Assume PSH-P2WPKH if (isSegwit === undefined) throw new Error('Cannot guess whether the Output is Segwit or not'); //we will assume that any addr(SH_TYPE_ADDRESS) is in fact SH_WPKH. return isSegwit; } exports.isSegwit = isSegwit; const isSegwitTx = (inputs) => inputs.some(input => isSegwit(input)); exports.isSegwitTx = isSegwitTx;