Skip to content

Instantly share code, notes, and snippets.

@dlarchikov
Created June 10, 2020 07:11
Show Gist options
  • Save dlarchikov/fe463c260d527f8d505a9379ad3505b2 to your computer and use it in GitHub Desktop.
Save dlarchikov/fe463c260d527f8d505a9379ad3505b2 to your computer and use it in GitHub Desktop.
import coinSelect from 'coinselect'
import { address as Address, Network, networks, payments, Psbt, Transaction, ECPair } from 'bitcoinjs-lib'
const sigwitInputs = [
{
tx_hash: '2e1bc58c73574bd57a3155b1118cf942b43dc8dd9fe7786f6c8110b59c298f5d',
block_height: 632654,
tx_input_n: -1,
tx_output_n: 0,
value: 98320,
ref_balance: 98320,
spent: false,
confirmations: 134,
confirmed: '2020-06-01T21:41:00Z',
double_spend: false,
script: '76a91468cc0558fb58119c005bf89f320a243bc580d19988ac',
},
]
const utxos = sigwitInputs.map(i => {
return {
txId: i.tx_hash,
vout: i.tx_output_n,
value: i.value,
scriptPubKey: i.script,
// redeemScript: i.redeemScript,
// nonWitnessUtxo: Buffer.from(i.hash, 'hex'),
witnessUtxo: {
script: Buffer.from(i.script, 'hex'),
value: i.value,
},
}
})
const utxosSum = utxos.reduce((sum, i) => sum + i.value, 0)
const targets = [
{
address: '3Qg2QXYAtjrKJj7fE5j9tGfRsLSVUoSGs8',
value: 95440,
},
]
let { inputs, outputs, fee } = coinSelect(utxos, targets, 15)
console.log({ fee, utxosSum, max: utxosSum - fee })
outputs = outputs.map(i => {
if (!i.address) {
i.address = '1AZ7ga5K2taigmTHrHFngb5UDj5Ej4jUgL'
}
return i
})
const keyPair = ECPair.fromWIF('KxzypGRWQA6CqAAwCh6R4YpPE2DHaRbLwTiaPz1RnMLZRj3mdX76', networks.bitcoin)
const a = payments.p2wpkh({ pubkey: keyPair.publicKey, network: networks.bitcoin })
const b = payments.p2sh({ redeem: a, network: networks.bitcoin })
const redeemScript = b.redeem.output.toString('hex')
console.log(b.address.toString())
console.log({ utxosSum, inputs, outputs, fee, utxos, redeemScript })
const psbt = new Psbt({ network: networks.bitcoin })
inputs.forEach(input =>
psbt.addInput({
hash: input.txId,
index: input.vout,
redeemScript: Buffer.from(redeemScript, 'hex'),
witnessUtxo: input.witnessUtxo,
})
)
outputs.forEach(output => {
psbt.addOutput({
address: output.address,
value: output.value,
})
})
// for (let i = 0; i < psbt.inputCount; i++) {
// psbt.signInput(i, keyPair)
// }
psbt.signAllInputs(keyPair)
psbt.finalizeAllInputs()
console.log(psbt.extractTransaction().toHex())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment