index.html 中引入 <script src="static/bitcoinjs-3.3.2.js"></script>
离线签名代码是参照 的这位博主 https://blog.youkuaiyun.com/jiang_xinxing/article/details/85162829
function usdtSign(privateKey, utxo, feeValue, usdtValue, fromAddress, toAddress) {
let bitcoin = bitcoinjs.bitcoin;
var txb = new bitcoin.TransactionBuilder();
const testnet = bitcoin.networks.bitcoin;
var set = bitcoin.ECPair.fromWIF(privateKey,testnet);
// const fundValue = 546;//如果需要每笔交易附带btc转账数量,可以设置这个参数
var feeValue = parseInt(feeValue * 1e8);//交易费用,可自行设置调节
var usdtAmount = parseInt(usdtValue * 1e8).toString(16);//usdt转账数量
var totalUnspent = 0;
for(var i = 0; i < utxo.length; i++) {
totalUnspent = totalUnspent + utxo[i].value;//计算未花费的btc总数量
}
// const changeValue = totalUnspent - fundValue - (feeValue);
// if(totalUnspent < feeValue+fundValue) {
const changeValue = totalUnspent - (feeValue);
if(totalUnspent < feeValue) {
_this.$layer.open({
content: "BTC 数量不足",
skin: 'msg',
time: 3
});
_this.$layer.close(_this.ajaxLoading)
return false;
}
for(var i = 0; i < utxo.length; i++) {
txb.addInput(utxo[i].tx_hash_big_endian, utxo[i].tx_output_n, 0xfffffffe);
}
const usdtInfo = [
"6f6d6e69",
"0000",
"00000000001f",
addPreZero(usdtAmount)
].join('');
const data = Buffer.from(usdtInfo, "hex");
const omniOutput = bitcoin.script.compile([
bitcoin.opcodes.OP_RETURN,
data
]);
// txb.addOutput(toAddress, fundValue);
txb.addOutput(omniOutput, 0);
txb.addOutput(fromAddress, changeValue);
for(var i = 0; i < utxo.length; i++) {
txb.sign(i, set);
}
return txb.buildIncomplete().toHex();
};
function addPreZero(num){
var t = (num+'').length,
s = '';
for(var i=0; i<16-t; i++){
s += '0';
}
return s+num;
}
BTC UTXO通过这个第三方接口获取
$.get('https://blockchain.info/unspent?active='+this.account).then(res => {
var utxo = res.unspent_outputs//未花费过的交易输出
var privateKey = this.privateKey;//私钥
var usdtValue = this.money;//转账usdt数量
var feeValue = this.freeBTC;//btc手续费
var fromAddress = this.account;//转账地址
var toAddress = this.address;//收款地址
var sign = usdtSign(privateKey, utxo, feeValue, usdtValue, fromAddress, toAddress);
if(sign) {
//广播交易
$.get('https://api.omniexplorer.info/v1/transaction/pushtx/' + sign).then(response => {
console.log(response)
})
}
}).catch(err => {
console.log(err)
})