资源介绍
bitcoinj项目富含完整demo
此项目使用maven构建,不会使用maven的同学,查看项目pom.xml文件,并在http://mvnrepository.com/下载相应的依赖jar包.
demo:bitcoinj签名交易
/**
* @param unSpentBTCList 未花费utxo集合
* @param from 发送者地址
* @param to 接收者地址
* @param privateKey 私钥
* @param value 发送金额.单位:聪
* @param fee 旷工费.单位:聪
* @return 签名之后未广播的原生交易字符串
* @throws Exception
*/
public static String signBTCTransactionData(List unSpentBTCList, String from, String to, String privateKey, long value, long fee) throws Exception {
NetworkParameters networkParameters = null;
// networkParameters = MainNetParams.get();
//测试网络
networkParameters = TestNet3Params.get();
Transaction transaction = new Transaction(networkParameters);
DumpedPrivateKey dumpedPrivateKey = DumpedPrivateKey.fromBase58(networkParameters, privateKey);
ECKey ecKey = dumpedPrivateKey.getKey();
long totalMoney = 0;
List utxos = new ArrayList();
//遍历未花费列表,组装合适的item
for (UnSpentBTC us : unSpentBTCList) {
if (totalMoney >= (value + fee))
break;
UTXO utxo = new UTXO(Sha256Hash.wrap(us.getTxid()), us.getVout(), Coin.valueOf(us.getSatoshis()),
us.getHeight(), false, new Script(Hex.decode(us.getScriptPubKey())));
utxos.add(utxo);
totalMoney += us.getSatoshis();
}
transaction.addOutput(Coin.valueOf(value), Address.fromBase58(networkParameters, to));
// transaction.
//消费列表总金额 - 已经转账的金额 - 手续费 就等于需要返回给自己的金额了
long balance = totalMoney - value - fee;
//输出-转给自己
if (balance > 0) {
transaction.addOutput(Coin.valueOf(balance), Address.fromBase58(networkParameters, from));
}
//输入未消费列表项
for (UTXO utxo : utxos) {
TransactionOutPoint outPoint = new TransactionOutPoint(networkParameters, utxo.getIndex(), utxo.getHash());
transaction.addSignedInput(outPoint, utxo.getScript(), ecKey, Transaction.SigHash.ALL, true);
}
return Hex.toHexString(transaction.bitcoinSerialize());
}