离线交易生成 hex交易值、手动广播出去即可。
广播交易
// 1、私钥
ECKey privKey = ECKey.fromPrivate(Utils.HEX.decode(unspentBean.getPrivKey()));
// 2、计算金额
long amount = (long) (unspentBean.getAmout() * LongMath.pow(10, netParams.getUnitExponent()));// 输入金额
long fee = (long) (unspentBean.getFeeD() * LongMath.pow(10, netParams.getUnitExponent())); // 旷工费
long inputSum = 0L; // 总输入金额
long needed = amount + fee; // 最终转账金额:输入金额+旷工费
long change; // 找零 总输入-总消费
// 3、符合的utxo列表
List<UnspentBean.UtxoBean> utxoList = unspentBean.getUtxos();
for (UnspentBean.UtxoBean utxo : utxoList) {
inputSum += utxo.getValue();
if (inputSum >= needed) {
break;
}
}
// 4、计算找零
change = inputSum - needed;
// 5、构建交易
Transaction tx = new Transaction(netParams);
tx.addOutput(Coin.valueOf(amount), Address.fromBase58(netParams, unspentBean.getToA())); // 转出
tx.addOutput(Coin.valueOf(change), Address.fromBase58(netParams, unspentBean.getFromA()));// 找零
// 6、签名输出脚本
for (UnspentBean.UtxoBean utxosBean : utxoList) {
UTXO sUtxo = new UTXO(Sha256Hash.wrap(utxosBean.getTx_hash()),
utxosBean.getTx_pos(),
Coin.valueOf(utxosBean.getValue()),
utxosBean.getHeight(),
false,
new Script(Utils.HEX.decode(utxosBean.getScriptPubKey())));
TransactionOutPoint outPoint = new TransactionOutPoint(netParams, sUtxo.getIndex(), sUtxo.getHash());
tx.addSignedInput(outPoint, sUtxo.getScript(), privKey, Transaction.SigHash.ALL, true);
}
// 7、构建交易签名
tx.getConfidence().setSource(TransactionConfidence.Source.SELF);
tx.setPurpose(Transaction.Purpose.USER_PAYMENT);
String transCode = Utils.HEX.encode(tx.bitcoinSerialize());
Logger.e("交易签名:"+transCode);