private void addInputsToTransaction(Address sourceAddress, Transaction tx, @NonNull BalanceResponse.Unspents[] unspents, Long amount) {
long gatheredAmount = 0L;
long requiredAmount = amount + TX_FEE;
for (BalanceResponse.Unspents unspent : unspents) {
gatheredAmount += unspent.getAmount();
TransactionOutPoint outPoint = new TransactionOutPoint(networkParams, unspent.getvOut(), Sha256Hash.wrap(unspent.getTxId()));
TransactionInput transactionInput = new TransactionInput(networkParams, tx, hexStringToByteArray(unspent.getScriptPubKey()),
outPoint, Coin.valueOf(unspent.getAmount());
tx.addInput(transactionInput);
if (gatheredAmount >= requiredAmount) {
break;
}
}
if (gatheredAmount > requiredAmount) {
//return change to sender, in real life it should use different address
tx.addOutput(Coin.valueOf((gatheredAmount - requiredAmount)), sourceAddress);
}
}
private void signInputsOfTransaction(Address sourceAddress, @NonNull Transaction tx, ECKey key) {
for (int i = 0; i < tx.getInputs().size(); i++) {
Script scriptPubKey = ScriptBuilder.createOutputScript(sourceAddress);
Sha256Hash hash = tx.hashForSignature(i, scriptPubKey, Transaction.SigHash.ALL, true);
ECKey.ECDSASignature ecdsaSignature = key.sign(hash);
TransactionSignature txSignature = new TransactionSignature(ecdsaSignature, Transaction.SigHash.ALL, true);
if (scriptPubKeyScriptPattern.isSentToRawPubKeyisP2PK(scriptPubKey)) {
tx.getInput(i).setScriptSig(ScriptBuilder.createInputScript(txSignature));
} else {
if (!scriptPubKeyScriptPattern.isSentToAddressisP2PKH(scriptPubKey)) {
throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Unable to sign this scriptPubKeyscrptPubKey: " + scriptPubKey);
}
tx.getInput(i).setScriptSig(ScriptBuilder.createInputScript(txSignature, key));
}
}
}