use of io.bitsquare.btc.WalletService in project bitsquare by bitsquare.
the class OffererCreatesAndSignsDepositTxAsSeller method run.
@Override
protected void run() {
try {
runInterceptHook();
checkNotNull(trade.getTradeAmount(), "trade.getTradeAmount() must not be null");
Offer offer = trade.getOffer();
Coin sellerInputAmount = FeePolicy.getSecurityDeposit(offer).add(FeePolicy.getFixedTxFeeForTrades(offer)).add(trade.getTradeAmount());
Coin msOutputAmount = sellerInputAmount.add(FeePolicy.getSecurityDeposit(offer));
log.debug("\n\n------------------------------------------------------------\n" + "Contract as json\n" + trade.getContractAsJson() + "\n------------------------------------------------------------\n");
byte[] contractHash = Hash.getHash(trade.getContractAsJson());
trade.setContractHash(contractHash);
WalletService walletService = processModel.getWalletService();
String id = processModel.getOffer().getId();
AddressEntry offererAddressEntry = walletService.getOrCreateAddressEntry(id, AddressEntry.Context.RESERVED_FOR_TRADE);
AddressEntry sellerMultiSigAddressEntry = walletService.getOrCreateAddressEntry(id, AddressEntry.Context.MULTI_SIG);
sellerMultiSigAddressEntry.setCoinLockedInMultiSig(sellerInputAmount.subtract(FeePolicy.getFixedTxFeeForTrades(offer)));
Address changeAddress = walletService.getOrCreateAddressEntry(AddressEntry.Context.AVAILABLE).getAddress();
PreparedDepositTxAndOffererInputs result = processModel.getTradeWalletService().offererCreatesAndSignsDepositTx(false, contractHash, sellerInputAmount, msOutputAmount, processModel.tradingPeer.getRawTransactionInputs(), processModel.tradingPeer.getChangeOutputValue(), processModel.tradingPeer.getChangeOutputAddress(), offererAddressEntry.getAddress(), changeAddress, processModel.tradingPeer.getMultiSigPubKey(), sellerMultiSigAddressEntry.getPubKey(), trade.getArbitratorPubKey());
processModel.setPreparedDepositTx(result.depositTransaction);
processModel.setRawTransactionInputs(result.rawOffererInputs);
complete();
} catch (Throwable t) {
failed(t);
}
}
use of io.bitsquare.btc.WalletService in project bitsquare by bitsquare.
the class SendPayDepositRequest method run.
@Override
protected void run() {
try {
runInterceptHook();
checkNotNull(trade.getTradeAmount(), "TradeAmount must not be null");
checkNotNull(trade.getTakeOfferFeeTxId(), "TakeOfferFeeTxId must not be null");
WalletService walletService = processModel.getWalletService();
AddressEntry takerMultiSigPubKeyAddressEntry = walletService.getOrCreateAddressEntry(processModel.getOffer().getId(), AddressEntry.Context.MULTI_SIG);
AddressEntry takerPayoutAddressEntry = walletService.getOrCreateAddressEntry(processModel.getOffer().getId(), AddressEntry.Context.TRADE_PAYOUT);
byte[] takerMultiSigPubKey = takerMultiSigPubKeyAddressEntry.getPubKey();
String takerPayoutAddressString = takerPayoutAddressEntry.getAddressString();
PayDepositRequest payDepositRequest = new PayDepositRequest(processModel.getMyNodeAddress(), processModel.getId(), trade.getTradeAmount().value, trade.getTradePrice().value, processModel.getRawTransactionInputs(), processModel.getChangeOutputValue(), processModel.getChangeOutputAddress(), takerMultiSigPubKey, takerPayoutAddressString, processModel.getPubKeyRing(), processModel.getPaymentAccountContractData(trade), processModel.getAccountId(), trade.getTakeOfferFeeTxId(), new ArrayList<>(processModel.getUser().getAcceptedArbitratorAddresses()), trade.getArbitratorNodeAddress());
processModel.getP2PService().sendEncryptedMailboxMessage(trade.getTradingPeerNodeAddress(), processModel.tradingPeer.getPubKeyRing(), payDepositRequest, new SendMailboxMessageListener() {
@Override
public void onArrived() {
log.trace("Message arrived at peer.");
complete();
}
@Override
public void onStoredInMailbox() {
log.trace("Message stored in mailbox.");
complete();
}
@Override
public void onFault(String errorMessage) {
appendToErrorMessage("PayDepositRequest sending failed");
failed();
}
});
} catch (Throwable t) {
failed(t);
}
}
use of io.bitsquare.btc.WalletService in project bitsquare by bitsquare.
the class TakerCreatesDepositTxInputsAsSeller method run.
@Override
protected void run() {
try {
runInterceptHook();
if (trade.getTradeAmount() != null) {
Offer offer = trade.getOffer();
Coin takerInputAmount = FeePolicy.getSecurityDeposit(offer).add(FeePolicy.getFixedTxFeeForTrades(offer)).add(trade.getTradeAmount());
WalletService walletService = processModel.getWalletService();
AddressEntry takersAddressEntry = walletService.getOrCreateAddressEntry(processModel.getOffer().getId(), AddressEntry.Context.RESERVED_FOR_TRADE);
Address changeAddress = walletService.getOrCreateAddressEntry(AddressEntry.Context.AVAILABLE).getAddress();
InputsAndChangeOutput result = processModel.getTradeWalletService().takerCreatesDepositsTxInputs(takerInputAmount, takersAddressEntry.getAddress(), changeAddress);
processModel.setRawTransactionInputs(result.rawTransactionInputs);
processModel.setChangeOutputValue(result.changeOutputValue);
processModel.setChangeOutputAddress(result.changeOutputAddress);
complete();
} else {
failed("trade.getTradeAmount() = null");
}
} catch (Throwable t) {
failed(t);
}
}
use of io.bitsquare.btc.WalletService in project bitsquare by bitsquare.
the class MainViewModel method onAllServicesInitialized.
private void onAllServicesInitialized() {
Log.traceCall();
clock.start();
// disputeManager
disputeManager.onAllServicesInitialized();
disputeManager.getDisputesAsObservableList().addListener((ListChangeListener<Dispute>) change -> {
change.next();
onDisputesChangeListener(change.getAddedSubList(), change.getRemoved());
});
onDisputesChangeListener(disputeManager.getDisputesAsObservableList(), null);
// tradeManager
tradeManager.onAllServicesInitialized();
tradeManager.getTrades().addListener((ListChangeListener<Trade>) c -> updateBalance());
tradeManager.getTrades().addListener((ListChangeListener<Trade>) change -> onTradesChanged());
onTradesChanged();
// We handle the trade period here as we display a global popup if we reached dispute time
tradesAndUIReady = EasyBind.combine(isSplashScreenRemoved, tradeManager.pendingTradesInitializedProperty(), (a, b) -> a && b);
tradesAndUIReady.subscribe((observable, oldValue, newValue) -> {
if (newValue)
applyTradePeriodState();
});
// walletService
walletService.addBalanceListener(new BalanceListener() {
@Override
public void onBalanceChanged(Coin balance, Transaction tx) {
updateBalance();
}
});
openOfferManager.getOpenOffers().addListener((ListChangeListener<OpenOffer>) c -> updateBalance());
tradeManager.getTrades().addListener((ListChangeListener<Trade>) c -> updateBalance());
openOfferManager.onAllServicesInitialized();
arbitratorManager.onAllServicesInitialized();
alertManager.alertMessageProperty().addListener((observable, oldValue, newValue) -> displayAlertIfPresent(newValue));
privateNotificationManager.privateNotificationProperty().addListener((observable, oldValue, newValue) -> displayPrivateNotification(newValue));
displayAlertIfPresent(alertManager.alertMessageProperty().get());
p2PService.onAllServicesInitialized();
setupBtcNumPeersWatcher();
setupP2PNumPeersWatcher();
updateBalance();
if (DevFlags.DEV_MODE) {
preferences.setShowOwnOffersInOfferBook(true);
if (user.getPaymentAccounts().isEmpty())
setupDevDummyPaymentAccounts();
}
setupMarketPriceFeed();
swapPendingOfferFundingEntries();
fillPriceFeedComboBoxItems();
showAppScreen.set(true);
// We want to test if the client is compiled with the correct crypto provider (BountyCastle)
// and if the unlimited Strength for cryptographic keys is set.
// If users compile themselves they might miss that step and then would get an exception in the trade.
// To avoid that we add here at startup a sample encryption and signing to see if it don't causes an exception.
// See: https://github.com/bitsquare/bitsquare/blob/master/doc/build.md#7-enable-unlimited-strength-for-cryptographic-keys
Thread checkCryptoThread = new Thread() {
@Override
public void run() {
try {
Thread.currentThread().setName("checkCryptoThread");
log.trace("Run crypto test");
// just use any simple dummy msg
io.bitsquare.p2p.peers.keepalive.messages.Ping payload = new Ping(1, 1);
SealedAndSigned sealedAndSigned = Encryption.encryptHybridWithSignature(payload, keyRing.getSignatureKeyPair(), keyRing.getPubKeyRing().getEncryptionPubKey());
DecryptedDataTuple tuple = Encryption.decryptHybridWithSignature(sealedAndSigned, keyRing.getEncryptionKeyPair().getPrivate());
if (tuple.payload instanceof Ping && ((Ping) tuple.payload).nonce == payload.nonce && ((Ping) tuple.payload).lastRoundTripTime == payload.lastRoundTripTime)
log.debug("Crypto test succeeded");
else
throw new CryptoException("Payload not correct after decryption");
} catch (CryptoException e) {
e.printStackTrace();
String msg = "Seems that you use a self compiled binary and have not following the build " + "instructions in https://github.com/bitsquare/bitsquare/blob/master/doc/build.md#7-enable-unlimited-strength-for-cryptographic-keys.\n\n" + "If that is not the case and you use the official Bitsquare binary, " + "please file a bug report to the Github page.\n" + "Error=" + e.getMessage();
log.error(msg);
UserThread.execute(() -> new Popup<>().warning(msg).actionButtonText("Shut down").onAction(BitsquareApp.shutDownHandler::run).closeButtonText("Report bug at Github issues").onClose(() -> GUIUtil.openWebPage("https://github.com/bitsquare/bitsquare/issues")).show());
}
}
};
checkCryptoThread.start();
if (Security.getProvider("BC") == null) {
new Popup<>().warning("There is a problem with the crypto libraries. BountyCastle is not available.").actionButtonText("Shut down").onAction(BitsquareApp.shutDownHandler::run).closeButtonText("Report bug at Github issues").onClose(() -> GUIUtil.openWebPage("https://github.com/bitsquare/bitsquare/issues")).show();
}
String remindPasswordAndBackupKey = "remindPasswordAndBackup";
user.getPaymentAccountsAsObservable().addListener((SetChangeListener<PaymentAccount>) change -> {
if (!walletService.getWallet().isEncrypted() && preferences.showAgain(remindPasswordAndBackupKey) && change.wasAdded()) {
new Popup<>().headLine("Important security recommendation").information("We would like to remind you to consider using password protection for your wallet if you have not already enabled that.\n\n" + "It is also highly recommended to write down the wallet seed words. Those seed words are like a master password for recovering your Bitcoin wallet.\n" + "At the \"Wallet Seed\" section you find more information.\n\n" + "Additionally you can backup the complete application data folder at the \"Backup\" section.\n" + "Please note, that this backup is not encrypted!").dontShowAgainId(remindPasswordAndBackupKey, preferences).show();
}
});
checkIfOpenOffersMatchTradeProtocolVersion();
}
use of io.bitsquare.btc.WalletService in project bitsquare by bitsquare.
the class BuyerStep5View method reviewWithdrawal.
private void reviewWithdrawal() {
Coin senderAmount = trade.getPayoutAmount();
WalletService walletService = model.dataModel.walletService;
AddressEntry fromAddressesEntry = walletService.getOrCreateAddressEntry(trade.getId(), AddressEntry.Context.TRADE_PAYOUT);
String fromAddresses = fromAddressesEntry.getAddressString();
String toAddresses = withdrawAddressTextField.getText();
// TODO at some error situation it can be tha the funds are already paid out and we get stuck here
// need handling to remove the trade (planned for next release)
Coin balance = walletService.getBalanceForAddress(fromAddressesEntry.getAddress());
try {
Coin requiredFee = walletService.getRequiredFee(fromAddresses, toAddresses, senderAmount, AddressEntry.Context.TRADE_PAYOUT);
Coin receiverAmount = senderAmount.subtract(requiredFee);
if (balance.isZero()) {
new Popup().warning("Your funds have already been withdrawn.\nPlease check the transaction history.").show();
model.dataModel.tradeManager.addTradeToClosedTrades(trade);
} else {
if (toAddresses.isEmpty()) {
validateWithdrawAddress();
} else if (Restrictions.isAboveFixedTxFeeForTradesAndDust(senderAmount)) {
if (DevFlags.DEV_MODE) {
doWithdrawal(receiverAmount);
} else {
BSFormatter formatter = model.formatter;
String key = "reviewWithdrawalAtTradeComplete";
if (!DevFlags.DEV_MODE && preferences.showAgain(key)) {
new Popup().headLine("Confirm withdrawal request").confirmation("Sending: " + formatter.formatCoinWithCode(senderAmount) + "\n" + "From address: " + fromAddresses + "\n" + "To receiving address: " + toAddresses + ".\n" + "Required transaction fee is: " + formatter.formatCoinWithCode(requiredFee) + "\n\n" + "The recipient will receive: " + formatter.formatCoinWithCode(receiverAmount) + "\n\n" + "Are you sure you want to proceed with the withdrawal?").closeButtonText("Cancel").onClose(() -> {
useSavingsWalletButton.setDisable(false);
withdrawToExternalWalletButton.setDisable(false);
}).actionButtonText("Yes").onAction(() -> doWithdrawal(receiverAmount)).dontShowAgainId(key, preferences).show();
} else {
doWithdrawal(receiverAmount);
}
}
} else {
new Popup().warning("The amount to transfer is lower than the transaction fee and the min. possible tx value (dust).").show();
}
}
} catch (AddressFormatException e) {
validateWithdrawAddress();
} catch (AddressEntryException e) {
log.error(e.getMessage());
}
}
Aggregations