-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsignBTC.js
More file actions
68 lines (59 loc) · 2.34 KB
/
signBTC.js
File metadata and controls
68 lines (59 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const bitcoin = require ('bitcoinjs-lib');
const fetch = require('node-fetch');
const { Keychain } = require('../lib'); // require('keychain.js') if you run it outside of keychain.js repository
const API_URL = 'https://test-insight.bitpay.com/api';
const fetchUnspents = (address) =>
fetch(`${API_URL}/addr/${address}/utxo`).then( data => data.json() );
const broadcastTx = (txRaw) =>
fetch(`${API_URL}/tx/send`, {method: 'post',
body: JSON.stringify({rawtx: txRaw}),
headers: { 'Content-Type': 'application/json' }}
)
.then(response => {
if(response.ok) {
return response.json();
}
throw response.statusText;
});
const addressFromPublicKey = (publicKey) => {
const pubkey = Buffer.from(`03${publicKey.substr(0, 64)}`, 'hex');
const keyPair = bitcoin.ECPair.fromPublicKeyBuffer(pubkey, bitcoin.networks.testnet);
return keyPair.getAddress();
};
async function main() {
const keychain = new Keychain();
const publicKey = await keychain.selectKey();
const tx = {
from: addressFromPublicKey(publicKey),
to: 'mqkrYyihgXVUZisi452KQ4tpTsaE8Tk8uj',
amount: 20000,
feeValue: 226
};
const txb = new bitcoin.TransactionBuilder(bitcoin.networks.testnet);
const unspents = await fetchUnspents(tx.from);
const totalUnspent = unspents.reduce((summ, { satoshis }) => summ + satoshis, 0);
const changeAmount = totalUnspent - tx.amount - tx.feeValue;
unspents.forEach(({ txid, vout }) => txb.addInput(txid, vout, 0xfffffffe));
txb.addOutput(tx.to, tx.amount);
if (changeAmount > 546) {
txb.addOutput(tx.from, changeAmount);
}
const txRaw = txb.buildIncomplete();
// add input scripts to unsigned transaction https://github.com/bitcoinjs/bitcoinjs-lib/issues/1011#issuecomment-368394185
unspents.forEach(({ scriptPubKey }, index) => txRaw.ins[index].script = Buffer.from(scriptPubKey, 'hex'));
const rawHex = await keychain.signTrx(
txRaw.toHex(),
publicKey,
'bitcoin'
);
console.log('rawHex: ', rawHex);
// uncomment to broadcast the transaction
// try {
// const broadcastResult = await broadcastTx(rawHex);
// console.log('broadcastResult: ', broadcastResult);
// console.log('broadcastResult: ', `https://test-insight.bitpay.com/tx/${broadcastResult.txid}`);
// } catch (error) {
// console.log('Cannot broadcast a transaction: ', error);
// }
}
main();