Improve tx and withdrawal screens, make multiple address selection possible at withdrawal

This commit is contained in:
Manfred Karrer 2016-02-03 15:43:55 +01:00
parent 85b2cb1d44
commit c70df863d6
31 changed files with 930 additions and 354 deletions

View file

@ -25,6 +25,7 @@ import io.bitsquare.trade.Contract;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.bitcoinj.core.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -73,6 +74,7 @@ public class Dispute implements Serializable {
private boolean isClosed;
private DisputeResult disputeResult;
private Transaction disputePayoutTx;
transient private Storage<DisputeList<Dispute>> storage;
transient private ObservableList<DisputeDirectMessage> disputeDirectMessagesAsObservableList = FXCollections.observableArrayList(disputeDirectMessages);
@ -166,6 +168,11 @@ public class Dispute implements Serializable {
storage.queueUpForSave();
}
public void setDisputePayoutTx(Transaction disputePayoutTx) {
this.disputePayoutTx = disputePayoutTx;
}
///////////////////////////////////////////////////////////////////////////////////////////
// Getters
///////////////////////////////////////////////////////////////////////////////////////////
@ -266,6 +273,9 @@ public class Dispute implements Serializable {
return new Date(tradeDate);
}
public Transaction getDisputePayoutTx() {
return disputePayoutTx;
}
@Override
public boolean equals(Object o) {

View file

@ -510,6 +510,7 @@ public class DisputeManager {
// after successful publish we send peer the tx
dispute.setDisputePayoutTx(transaction);
sendPeerPublishedPayoutTxMessage(transaction, dispute, contract);
}
@ -546,7 +547,8 @@ public class DisputeManager {
// losing trader or in case of 50/50 the seller gets the tx sent from the winner or buyer
private void onDisputedPayoutTxMessage(PeerPublishedPayoutTxMessage peerPublishedPayoutTxMessage) {
tradeWalletService.addTransactionToWallet(peerPublishedPayoutTxMessage.transaction);
Transaction transaction = tradeWalletService.addTransactionToWallet(peerPublishedPayoutTxMessage.transaction);
findOwnDispute(peerPublishedPayoutTxMessage.tradeId).ifPresent(dispute -> dispute.setDisputePayoutTx(transaction));
}

View file

@ -24,11 +24,9 @@ import org.bitcoinj.wallet.CoinSelector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.*;
import static com.google.common.base.Preconditions.checkNotNull;
@ -39,7 +37,10 @@ import static com.google.common.base.Preconditions.checkNotNull;
class AddressBasedCoinSelector implements CoinSelector {
private static final Logger log = LoggerFactory.getLogger(AddressBasedCoinSelector.class);
private final NetworkParameters params;
private final AddressEntry addressEntry;
@Nullable
private Set<AddressEntry> addressEntries;
@Nullable
private AddressEntry addressEntry;
///////////////////////////////////////////////////////////////////////////////////////////
// Constructor
@ -50,6 +51,11 @@ class AddressBasedCoinSelector implements CoinSelector {
this.addressEntry = addressEntry;
}
public AddressBasedCoinSelector(NetworkParameters params, Set<AddressEntry> addressEntries) {
this.params = params;
this.addressEntries = addressEntries;
}
@VisibleForTesting
static void sortOutputs(ArrayList<TransactionOutput> outputs) {
Collections.sort(outputs, (a, b) -> {
@ -94,15 +100,26 @@ class AddressBasedCoinSelector implements CoinSelector {
if (transactionOutput.getScriptPubKey().isSentToAddress() || transactionOutput.getScriptPubKey().isPayToScriptHash
()) {
Address addressOutput = transactionOutput.getScriptPubKey().getToAddress(params);
log.trace("matchesRequiredAddress?");
log.trace("matchesRequiredAddress(es)?");
log.trace(addressOutput.toString());
log.trace(addressEntry.getAddress().toString());
if (addressEntry != null && addressEntry.getAddress() != null) {
log.trace(addressEntry.getAddress().toString());
if (addressOutput.equals(addressEntry.getAddress()))
return true;
else {
log.trace("No match found at matchesRequiredAddress addressOutput / addressEntry " + addressOutput.toString
() + " / " + addressEntry.getAddress().toString());
}
} else if (addressEntries != null) {
log.trace(addressEntries.toString());
for (AddressEntry entry : addressEntries) {
if (addressOutput.equals(entry.getAddress()))
return true;
}
if (addressOutput.equals(addressEntry.getAddress())) {
return true;
log.trace("No match found at matchesRequiredAddress addressOutput / addressEntries " + addressOutput.toString
() + " / " + addressEntries.toString());
}
log.trace("No match found at matchesRequiredAddress addressOutput / addressEntry " + addressOutput.toString
() + " / " + addressEntry.getAddress().toString());
}
return false;
}

View file

@ -56,6 +56,8 @@ import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* WalletService handles all non trade specific wallet and bitcoin related services.
* It startup the wallet app kit and initialized the wallet.
@ -325,7 +327,9 @@ public class WalletService {
}
public AddressEntry getAddressEntryByOfferId(String offerId) {
Optional<AddressEntry> addressEntry = getAddressEntryList().stream().filter(e -> offerId.equals(e.getOfferId())).findFirst();
Optional<AddressEntry> addressEntry = getAddressEntryList().stream()
.filter(e -> offerId.equals(e.getOfferId()))
.findAny();
if (addressEntry.isPresent())
return addressEntry.get();
else
@ -333,7 +337,9 @@ public class WalletService {
}
private Optional<AddressEntry> getAddressEntryByAddress(String address) {
return getAddressEntryList().stream().filter(e -> address.equals(e.getAddressString())).findFirst();
return getAddressEntryList().stream()
.filter(e -> e.getAddressString() != null && e.getAddressString().equals(address))
.findAny();
}
@ -450,7 +456,8 @@ public class WalletService {
public Coin getRequiredFee(String fromAddress,
String toAddress,
Coin amount,
KeyParameter aesKey) throws AddressFormatException, IllegalArgumentException, InsufficientMoneyException {
@Nullable KeyParameter aesKey) throws AddressFormatException, IllegalArgumentException,
InsufficientMoneyException {
Coin fee;
try {
wallet.completeTx(getSendRequest(fromAddress, toAddress, amount, aesKey));
@ -463,10 +470,28 @@ public class WalletService {
return fee;
}
public Coin getRequiredFeeForMultipleAddresses(Set<String> fromAddresses,
String toAddress,
Coin amount,
@Nullable KeyParameter aesKey) throws AddressFormatException,
IllegalArgumentException, InsufficientMoneyException {
Coin fee;
try {
wallet.completeTx(getSendRequestForMultipleAddresses(fromAddresses, toAddress, amount, null, aesKey));
fee = Coin.ZERO;
} catch (InsufficientMoneyException e) {
log.info("The amount to be transferred is not enough to pay the transaction fees of {}. " +
"We subtract that fee from the receivers amount to make the transaction possible.");
fee = e.missing;
}
return fee;
}
public Wallet.SendRequest getSendRequest(String fromAddress,
String toAddress,
Coin amount,
@Nullable KeyParameter aesKey) throws AddressFormatException, IllegalArgumentException, InsufficientMoneyException {
@Nullable KeyParameter aesKey) throws AddressFormatException,
IllegalArgumentException, InsufficientMoneyException {
Transaction tx = new Transaction(params);
Preconditions.checkArgument(Restrictions.isAboveDust(amount),
"You cannot send an amount which are smaller than 546 satoshis.");
@ -485,11 +510,53 @@ public class WalletService {
return sendRequest;
}
public Wallet.SendRequest getSendRequestForMultipleAddresses(Set<String> fromAddresses,
String toAddress,
Coin amount,
@Nullable String changeAddress,
@Nullable KeyParameter aesKey) throws
AddressFormatException, IllegalArgumentException, InsufficientMoneyException {
Transaction tx = new Transaction(params);
Preconditions.checkArgument(Restrictions.isAboveDust(amount),
"You cannot send an amount which are smaller than 546 satoshis.");
tx.addOutput(amount, new Address(params, toAddress));
Wallet.SendRequest sendRequest = Wallet.SendRequest.forTx(tx);
sendRequest.aesKey = aesKey;
sendRequest.shuffleOutputs = false;
Set<AddressEntry> addressEntries = fromAddresses.stream()
.map(e -> getAddressEntryByAddress(e))
.filter(e -> e.isPresent())
.map(e -> e.get()).collect(Collectors.toSet());
if (addressEntries.isEmpty())
throw new IllegalArgumentException("No withdrawFromAddresses not found in our wallets.\n\t" +
"fromAddresses=" + fromAddresses);
sendRequest.coinSelector = new AddressBasedCoinSelector(params, addressEntries);
Optional<AddressEntry> addressEntryOptional = Optional.empty();
AddressEntry changeAddressAddressEntry = null;
if (changeAddress != null)
addressEntryOptional = getAddressEntryByAddress(changeAddress);
if (addressEntryOptional.isPresent()) {
changeAddressAddressEntry = addressEntryOptional.get();
} else {
ArrayList<AddressEntry> list = new ArrayList<>(addressEntries);
if (!list.isEmpty())
changeAddressAddressEntry = list.get(0);
}
checkNotNull(changeAddressAddressEntry, "change address must not be null");
sendRequest.changeAddress = changeAddressAddressEntry.getAddress();
sendRequest.feePerKb = FeePolicy.getFeePerKb();
return sendRequest;
}
public String sendFunds(String fromAddress,
String toAddress,
Coin amount,
KeyParameter aesKey,
FutureCallback<Transaction> callback) throws AddressFormatException, IllegalArgumentException, InsufficientMoneyException {
@Nullable KeyParameter aesKey,
FutureCallback<Transaction> callback) throws AddressFormatException,
IllegalArgumentException, InsufficientMoneyException {
Coin fee = getRequiredFee(fromAddress, toAddress, amount, aesKey);
Wallet.SendResult sendResult = wallet.sendCoins(getSendRequest(fromAddress, toAddress, amount.subtract(fee), aesKey));
Futures.addCallback(sendResult.broadcastComplete, callback);
@ -498,6 +565,22 @@ public class WalletService {
return sendResult.tx.getHashAsString();
}
public String sendFundsForMultipleAddresses(Set<String> fromAddresses,
String toAddress,
Coin amount,
@Nullable String changeAddress,
@Nullable KeyParameter aesKey,
FutureCallback<Transaction> callback) throws AddressFormatException,
IllegalArgumentException, InsufficientMoneyException {
Coin fee = getRequiredFeeForMultipleAddresses(fromAddresses, toAddress, amount, aesKey);
Wallet.SendResult sendResult = wallet.sendCoins(getSendRequestForMultipleAddresses(fromAddresses, toAddress,
amount.subtract(fee), changeAddress, aesKey));
Futures.addCallback(sendResult.broadcastComplete, callback);
printTxWithInputs("sendFunds", sendResult.tx);
return sendResult.tx.getHashAsString();
}
public void emptyWallet(String toAddress, KeyParameter aesKey, ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler)
throws InsufficientMoneyException, AddressFormatException {
Wallet.SendRequest sendRequest = Wallet.SendRequest.emptyWallet(new Address(params, toAddress));

View file

@ -21,6 +21,7 @@ import com.google.common.base.Throwables;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import io.bitsquare.app.Log;
import io.bitsquare.app.Version;
import io.bitsquare.arbitration.ArbitratorManager;
import io.bitsquare.btc.FeePolicy;
@ -125,12 +126,6 @@ abstract public class Trade implements Tradable, Model, Serializable {
TRADE_PERIOD_OVER
}
// Mutable
private Coin tradeAmount;
private NodeAddress tradingPeerNodeAddress;
transient private ObjectProperty<Coin> tradeAmountProperty;
transient private ObjectProperty<Fiat> tradeVolumeProperty;
///////////////////////////////////////////////////////////////////////////////////////////
// Fields
@ -152,7 +147,8 @@ abstract public class Trade implements Tradable, Model, Serializable {
// Mutable
private DecryptedMsgWithPubKey decryptedMsgWithPubKey;
private Date takeOfferDate = new Date(0); // in some error cases the date is not set and cause null pointers, so we set a default
private Coin tradeAmount;
private NodeAddress tradingPeerNodeAddress;
protected State state;
private DisputeState disputeState = DisputeState.NONE;
private TradePeriodState tradePeriodState = TradePeriodState.NORMAL;
@ -172,6 +168,10 @@ abstract public class Trade implements Tradable, Model, Serializable {
private boolean tradePeriodOverWarningDisplayed;
private String errorMessage;
transient private StringProperty errorMessageProperty;
transient private ObjectProperty<Coin> tradeAmountProperty;
transient private ObjectProperty<Fiat> tradeVolumeProperty;
@Nullable
private Transaction takeOfferFeeTx;
///////////////////////////////////////////////////////////////////////////////////////////
@ -306,6 +306,7 @@ abstract public class Trade implements Tradable, Model, Serializable {
}
public void setDisputeState(DisputeState disputeState) {
Log.traceCall("disputeState=" + disputeState + "\n\ttrade=" + this);
this.disputeState = disputeState;
disputeStateProperty.set(disputeState);
persist();
@ -561,6 +562,13 @@ abstract public class Trade implements Tradable, Model, Serializable {
return contractHash;
}
public void setTakeOfferFeeTx(Transaction takeOfferFeeTx) {
this.takeOfferFeeTx = takeOfferFeeTx;
}
public Transaction getTakeOfferFeeTx() {
return takeOfferFeeTx;
}
///////////////////////////////////////////////////////////////////////////////////////////
// Private
@ -620,11 +628,10 @@ abstract public class Trade implements Tradable, Model, Serializable {
"\n\tdisputeState=" + disputeState +
"\n\ttradePeriodState=" + tradePeriodState +
"\n\tdepositTx=" + depositTx +
"\n\ttakeOfferFeeTx.getHashAsString()=" + (takeOfferFeeTx != null ? takeOfferFeeTx.getHashAsString() : "") +
"\n\tcontract=" + contract +
/* "\n\tcontractAsJson='" + contractAsJson + '\'' +*/
/* "\n\tcontractHash=" + Arrays.toString(contractHash) +*/
"\n\ttakerContractSignature.hashCode()='" + takerContractSignature.hashCode() + '\'' +
"\n\toffererContractSignature.hashCode()='" + offererContractSignature.hashCode() + '\'' +
"\n\ttakerContractSignature.hashCode()='" + (takerContractSignature != null ? takerContractSignature.hashCode() : "") + '\'' +
"\n\toffererContractSignature.hashCode()='" + (offererContractSignature != null ? offererContractSignature.hashCode() : "") + '\'' +
"\n\tpayoutTx=" + payoutTx +
"\n\tlockTimeAsBlockHeight=" + lockTimeAsBlockHeight +
"\n\topenDisputeTimeAsBlockHeight=" + openDisputeTimeAsBlockHeight +

View file

@ -36,7 +36,6 @@ import io.bitsquare.trade.offer.Offer;
import io.bitsquare.trade.offer.OpenOfferManager;
import io.bitsquare.trade.protocol.trade.messages.TradeMessage;
import io.bitsquare.user.User;
import org.bitcoinj.core.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -68,7 +67,6 @@ public class ProcessModel implements Model, Serializable {
transient private TradeMessage tradeMessage;
private String takeOfferFeeTxId;
private byte[] payoutTxSignature;
private Transaction takeOfferFeeTx;
private List<NodeAddress> takerAcceptedArbitratorNodeAddresses;
@ -168,15 +166,6 @@ public class ProcessModel implements Model, Serializable {
return tradeMessage;
}
@Nullable
public Transaction getTakeOfferFeeTx() {
return takeOfferFeeTx;
}
public void setTakeOfferFeeTx(Transaction takeOfferFeeTx) {
this.takeOfferFeeTx = takeOfferFeeTx;
}
public PaymentAccountContractData getPaymentAccountContractData(Trade trade) {
if (trade instanceof OffererTrade)
return user.getPaymentAccount(offer.getOffererPaymentAccountId()).getContractData();

View file

@ -37,7 +37,7 @@ public class BroadcastTakeOfferFeeTx extends TradeTask {
protected void run() {
try {
runInterceptHook();
processModel.getTradeWalletService().broadcastTx(processModel.getTakeOfferFeeTx(),
processModel.getTradeWalletService().broadcastTx(trade.getTakeOfferFeeTx(),
new FutureCallback<Transaction>() {
@Override
public void onSuccess(Transaction transaction) {

View file

@ -50,7 +50,7 @@ public class CreateTakeOfferFeeTx extends TradeTask {
FeePolicy.getTakeOfferFee(),
selectedArbitrator.getBtcAddress());
processModel.setTakeOfferFeeTx(createTakeOfferFeeTx);
trade.setTakeOfferFeeTx(createTakeOfferFeeTx);
// TODO check if needed as we have stored tx already at setTakeOfferFeeTx
processModel.setTakeOfferFeeTxId(createTakeOfferFeeTx.getHashAsString());

View file

@ -25,6 +25,8 @@ import io.bitsquare.trade.protocol.trade.tasks.TradeTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.checkNotNull;
public class SendPayDepositRequest extends TradeTask {
private static final Logger log = LoggerFactory.getLogger(SendPayDepositRequest.class);
@ -36,7 +38,8 @@ public class SendPayDepositRequest extends TradeTask {
protected void run() {
try {
runInterceptHook();
if (processModel.getTakeOfferFeeTx() != null) {
if (trade.getTakeOfferFeeTx() != null) {
checkNotNull(trade.getTradeAmount());
PayDepositRequest payDepositRequest = new PayDepositRequest(
processModel.getMyAddress(),
processModel.getId(),
@ -49,7 +52,7 @@ public class SendPayDepositRequest extends TradeTask {
processModel.getPubKeyRing(),
processModel.getPaymentAccountContractData(trade),
processModel.getAccountId(),
processModel.getTakeOfferFeeTx().getHashAsString(),
trade.getTakeOfferFeeTx().getHashAsString(),
processModel.getUser().getAcceptedArbitratorAddresses(),
trade.getArbitratorNodeAddress()
);
@ -79,7 +82,7 @@ public class SendPayDepositRequest extends TradeTask {
}
);
} else {
log.error("processModel.getTakeOfferFeeTx() = " + processModel.getTakeOfferFeeTx());
log.error("trade.getTakeOfferFeeTx() = " + trade.getTakeOfferFeeTx());
failed("TakeOfferFeeTx is null");
}
} catch (Throwable t) {

View file

@ -42,7 +42,7 @@ public class VerifyAndSignContract extends TradeTask {
try {
runInterceptHook();
if (processModel.getTakeOfferFeeTx() != null) {
if (trade.getTakeOfferFeeTx() != null) {
TradingPeer offerer = processModel.tradingPeer;
PaymentAccountContractData offererPaymentAccountContractData = offerer.getPaymentAccountContractData();
PaymentAccountContractData takerPaymentAccountContractData = processModel.getPaymentAccountContractData(trade);
@ -57,7 +57,7 @@ public class VerifyAndSignContract extends TradeTask {
Contract contract = new Contract(
processModel.getOffer(),
trade.getTradeAmount(),
processModel.getTakeOfferFeeTx().getHashAsString(),
trade.getTakeOfferFeeTx().getHashAsString(),
buyerNodeAddress,
sellerNodeAddress,
trade.getArbitratorNodeAddress(),