|
|
@ -25,31 +25,62 @@ let BtcUtil = { |
|
|
|
} |
|
|
|
return balance; |
|
|
|
}, |
|
|
|
btcToSatoshi:function(btcAmount){ |
|
|
|
return Math.ceil(btcAmount * 1e8); |
|
|
|
}, |
|
|
|
sendTransaction:async function(fromAddress, toAddress, value, privateKey){ |
|
|
|
const utxo = await fetch(systemConfiguration.constant.btcUtxo+fromAddress); |
|
|
|
const utxoData=await utxo.json(); |
|
|
|
const txs=utxoData.data.txs; |
|
|
|
let txsList=[]; |
|
|
|
let remainingValue=value; |
|
|
|
let balanceSatoshis=0; |
|
|
|
|
|
|
|
for(let i=0;i<txs.length;i++){ |
|
|
|
txsList.push(txs[i]); |
|
|
|
balanceSatoshis=Number(balanceSatoshis)+Number(txs[i].value); |
|
|
|
if(txs[i].value>remainingValue){ |
|
|
|
break; |
|
|
|
} |
|
|
|
remainingValue=remainingValue-txs[i].value; |
|
|
|
} |
|
|
|
if(balanceSatoshis<=value){ |
|
|
|
throw new Error("Insufficient balance"); |
|
|
|
} |
|
|
|
console.log(balanceSatoshis,value) |
|
|
|
const feeSatoshis=this.btcToSatoshi(0.0001); |
|
|
|
|
|
|
|
let bob = new bitcoin.ECPair.fromWIF(privateKey); |
|
|
|
balanceSatoshis=this.btcToSatoshi(balanceSatoshis); |
|
|
|
value=this.btcToSatoshi(value); |
|
|
|
let change = balanceSatoshis - feeSatoshis - value; |
|
|
|
|
|
|
|
const txb = new bitcoin.TransactionBuilder(systemConfiguration.constant.btcNetwork); |
|
|
|
let bob = new bitcoin.ECPair.fromWIF(privateKey,systemConfiguration.constant.btcNetwork); |
|
|
|
let txb = new bitcoin.TransactionBuilder(systemConfiguration.constant.btcNetwork); |
|
|
|
for(let i=0;i<txsList.length;i++){ |
|
|
|
|
|
|
|
txb.addInput(txsList[i].txid, txsList[i].output_no); |
|
|
|
|
|
|
|
} |
|
|
|
console.log(change) |
|
|
|
txb.addOutput(fromAddress, change); |
|
|
|
console.log(txsList[0].txid,txsList[0].output_no) |
|
|
|
txb.addOutput(toAddress, value); |
|
|
|
|
|
|
|
txb.setVersion(1); |
|
|
|
// 在这个交易中, bob在第0个位置,上图所示
|
|
|
|
txb.addInput("5799a647d6b89a9f73122d75faee6f5a0210bd3cb22c48a70d35eac33ce5d426", 0); |
|
|
|
txb.addOutput(toAddress, 2000000); |
|
|
|
console.log(txb,1111111111) |
|
|
|
for(let i=0;i<txsList.length;i++){ |
|
|
|
txb.sign(i, bob); |
|
|
|
} |
|
|
|
// 签名交易,0代表索引,输入排序,这里只有一个输入,所以是第0位。
|
|
|
|
txb.sign(0, bob); |
|
|
|
|
|
|
|
|
|
|
|
// 序列化成一串字符
|
|
|
|
const tx = txb.build().toHex(); |
|
|
|
console.log(tx); |
|
|
|
const result = await fetch('https://api.blockcypher.com/v1/btc/test3/txs/push',{ |
|
|
|
const result = await fetch(systemConfiguration.constant.btcSendTransaction,{ |
|
|
|
method:'post', |
|
|
|
headers:{'Content-Type':'application/json'}, |
|
|
|
body:JSON.stringify({tx}) |
|
|
|
}); |
|
|
|
|
|
|
|
// 打印结果
|
|
|
|
console.log(result); |
|
|
|
return tx; |
|
|
|
} |
|
|
|
} |
|
|
|
export default BtcUtil |