shrub/psbt_sign.js

48 lines
1.4 KiB
JavaScript
Raw Normal View History

2020-12-17 22:31:45 +03:00
/*
Usage:
2021-01-10 12:16:05 +03:00
var p = require("./psbt_sign.js")
2020-12-17 22:31:45 +03:00
const psbt = PSBT_STRING_BASE64
const mnemonics = MNEMONICS_STRING
2021-01-10 12:16:05 +03:00
const [psbt, mnemonics] = []
2020-12-17 22:31:45 +03:00
p.run(mnemonics, psbt)
*/
const bitcoin = require('bitcoinjs-lib');
const ecpair = bitcoin.ECPair;
const crypto = bitcoin.crypto;
const bscript = bitcoin.script;
const bip39 = require('bip39');
const NETWORK = bitcoin.networks.bitcoin;
const LOCK_TIME = 0;
const SIGHASH_ALL = 1;
const isSegwitTx = (rawTx) => {
return rawTx.substring(8, 12) === '0001';
};
2020-12-18 12:11:48 +03:00
// const PATHS = ["m/84'/0'/0'/0/0", "m/84'/0'/0'/1/0"];
2020-12-17 22:31:45 +03:00
const run = async(mnemonics, psbtStr) => {
const psbt = bitcoin.Psbt.fromBase64(psbtStr);
2020-12-18 12:11:48 +03:00
const is = psbt.data.inputs;
2020-12-17 22:31:45 +03:00
const seed = await bip39.mnemonicToSeed(mnemonics);
const node = bitcoin.bip32.fromSeed(seed, NETWORK);
2020-12-18 12:11:48 +03:00
for(let i=0; i<is.length; i++) {
const der = is[i].bip32Derivation[0];
const walletDer = node.derivePath(der.path);
2020-12-17 22:31:45 +03:00
2020-12-18 12:11:48 +03:00
if(0 === Buffer.compare(der.pubkey, walletDer.publicKey)) {
console.log(`Signing ${der.path}`);
psbt.signInput(i, bitcoin.ECPair.fromPrivateKey(walletDer.privateKey));
}
const validate = await psbt.validateSignaturesOfAllInputs();
await psbt.finalizeAllInputs();
const hex = psbt.extractTransaction().toHex();
console.log({ validate, hex});
}
2020-12-17 22:31:45 +03:00
return;
};
exports.run = run;