Search in sources :

Example 36 with Coin

use of org.bitcoinj.core.Coin in project bitsquare by bitsquare.

the class MainViewModel method updateReservedBalance.

private void updateReservedBalance() {
    Coin sum = Coin.valueOf(openOfferManager.getOpenOffers().stream().map(openOffer -> {
        Address address = walletService.getOrCreateAddressEntry(openOffer.getId(), AddressEntry.Context.RESERVED_FOR_TRADE).getAddress();
        return walletService.getBalanceForAddress(address);
    }).mapToLong(Coin::getValue).sum());
    reservedBalance.set(formatter.formatCoinWithCode(sum));
}
Also used : Clock(io.bitsquare.common.Clock) OpenOffer(io.bitsquare.trade.offer.OpenOffer) PriceFeedService(io.bitsquare.btc.pricefeed.PriceFeedService) Popup(io.bitsquare.gui.main.overlays.popups.Popup) Transaction(org.bitcoinj.core.Transaction) MarketPrice(io.bitsquare.btc.pricefeed.MarketPrice) Coin(org.bitcoinj.core.Coin) Inject(com.google.inject.Inject) ViewModel(io.bitsquare.gui.common.model.ViewModel) LoggerFactory(org.slf4j.LoggerFactory) TradeCurrency(io.bitsquare.locale.TradeCurrency) Security(java.security.Security) TimeoutException(java.util.concurrent.TimeoutException) DisputeManager(io.bitsquare.arbitration.DisputeManager) BalanceWithConfirmationTextField(io.bitsquare.gui.components.BalanceWithConfirmationTextField) Trade(io.bitsquare.trade.Trade) GUIUtil(io.bitsquare.gui.util.GUIUtil) DevFlags(io.bitsquare.app.DevFlags) PaymentAccount(io.bitsquare.payment.PaymentAccount) NotificationCenter(io.bitsquare.gui.main.overlays.notifications.NotificationCenter) ListChangeListener(javafx.collections.ListChangeListener) Navigation(io.bitsquare.gui.Navigation) TradeWalletService(io.bitsquare.btc.TradeWalletService) BlockStoreException(org.bitcoinj.store.BlockStoreException) MonadicBinding(org.fxmisc.easybind.monadic.MonadicBinding) AddressEntry(io.bitsquare.btc.AddressEntry) WalletPasswordWindow(io.bitsquare.gui.main.overlays.windows.WalletPasswordWindow) FilterManager(io.bitsquare.filter.FilterManager) Subscription(org.fxmisc.easybind.Subscription) Collectors(java.util.stream.Collectors) PrivateNotificationManager(io.bitsquare.alert.PrivateNotificationManager) ConnectionListener(io.bitsquare.p2p.network.ConnectionListener) Preferences(io.bitsquare.user.Preferences) CryptoCurrencyAccount(io.bitsquare.payment.CryptoCurrencyAccount) Dispute(io.bitsquare.arbitration.Dispute) BalanceTextField(io.bitsquare.gui.components.BalanceTextField) Address(org.bitcoinj.core.Address) Ping(io.bitsquare.p2p.peers.keepalive.messages.Ping) ObservableList(javafx.collections.ObservableList) CurrencyUtil(io.bitsquare.locale.CurrencyUtil) io.bitsquare.common.crypto(io.bitsquare.common.crypto) PrivateNotification(io.bitsquare.alert.PrivateNotification) Version(io.bitsquare.app.Version) P2PServiceListener(io.bitsquare.p2p.P2PServiceListener) java.util(java.util) P2PService(io.bitsquare.p2p.P2PService) SetChangeListener(javafx.collections.SetChangeListener) FXCollections(javafx.collections.FXCollections) BitsquareApp(io.bitsquare.app.BitsquareApp) AddBitcoinNodesWindow(io.bitsquare.gui.main.overlays.windows.AddBitcoinNodesWindow) Connection(io.bitsquare.p2p.network.Connection) Timer(io.bitsquare.common.Timer) BalanceListener(io.bitsquare.btc.listeners.BalanceListener) OKPayAccount(io.bitsquare.payment.OKPayAccount) TradeManager(io.bitsquare.trade.TradeManager) User(io.bitsquare.user.User) WalletService(io.bitsquare.btc.WalletService) TacWindow(io.bitsquare.gui.main.overlays.windows.TacWindow) Alert(io.bitsquare.alert.Alert) DisplayAlertMessageWindow(io.bitsquare.gui.main.overlays.windows.DisplayAlertMessageWindow) Nullable(javax.annotation.Nullable) Log(io.bitsquare.app.Log) BSFormatter(io.bitsquare.gui.util.BSFormatter) javafx.beans.property(javafx.beans.property) Logger(org.slf4j.Logger) UserThread(io.bitsquare.common.UserThread) TxIdTextField(io.bitsquare.gui.components.TxIdTextField) Wallet(org.bitcoinj.core.Wallet) TimeUnit(java.util.concurrent.TimeUnit) EasyBind(org.fxmisc.easybind.EasyBind) OpenOfferManager(io.bitsquare.trade.offer.OpenOfferManager) ArbitratorManager(io.bitsquare.arbitration.ArbitratorManager) CloseConnectionReason(io.bitsquare.p2p.network.CloseConnectionReason) ChangeListener(javafx.beans.value.ChangeListener) AlertManager(io.bitsquare.alert.AlertManager) Coin(org.bitcoinj.core.Coin) Address(org.bitcoinj.core.Address)

Example 37 with Coin

use of org.bitcoinj.core.Coin 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();
}
Also used : Clock(io.bitsquare.common.Clock) OpenOffer(io.bitsquare.trade.offer.OpenOffer) PriceFeedService(io.bitsquare.btc.pricefeed.PriceFeedService) Popup(io.bitsquare.gui.main.overlays.popups.Popup) Transaction(org.bitcoinj.core.Transaction) MarketPrice(io.bitsquare.btc.pricefeed.MarketPrice) Coin(org.bitcoinj.core.Coin) Inject(com.google.inject.Inject) ViewModel(io.bitsquare.gui.common.model.ViewModel) LoggerFactory(org.slf4j.LoggerFactory) TradeCurrency(io.bitsquare.locale.TradeCurrency) Security(java.security.Security) TimeoutException(java.util.concurrent.TimeoutException) DisputeManager(io.bitsquare.arbitration.DisputeManager) BalanceWithConfirmationTextField(io.bitsquare.gui.components.BalanceWithConfirmationTextField) Trade(io.bitsquare.trade.Trade) GUIUtil(io.bitsquare.gui.util.GUIUtil) DevFlags(io.bitsquare.app.DevFlags) PaymentAccount(io.bitsquare.payment.PaymentAccount) NotificationCenter(io.bitsquare.gui.main.overlays.notifications.NotificationCenter) ListChangeListener(javafx.collections.ListChangeListener) Navigation(io.bitsquare.gui.Navigation) TradeWalletService(io.bitsquare.btc.TradeWalletService) BlockStoreException(org.bitcoinj.store.BlockStoreException) MonadicBinding(org.fxmisc.easybind.monadic.MonadicBinding) AddressEntry(io.bitsquare.btc.AddressEntry) WalletPasswordWindow(io.bitsquare.gui.main.overlays.windows.WalletPasswordWindow) FilterManager(io.bitsquare.filter.FilterManager) Subscription(org.fxmisc.easybind.Subscription) Collectors(java.util.stream.Collectors) PrivateNotificationManager(io.bitsquare.alert.PrivateNotificationManager) ConnectionListener(io.bitsquare.p2p.network.ConnectionListener) Preferences(io.bitsquare.user.Preferences) CryptoCurrencyAccount(io.bitsquare.payment.CryptoCurrencyAccount) Dispute(io.bitsquare.arbitration.Dispute) BalanceTextField(io.bitsquare.gui.components.BalanceTextField) Address(org.bitcoinj.core.Address) Ping(io.bitsquare.p2p.peers.keepalive.messages.Ping) ObservableList(javafx.collections.ObservableList) CurrencyUtil(io.bitsquare.locale.CurrencyUtil) io.bitsquare.common.crypto(io.bitsquare.common.crypto) PrivateNotification(io.bitsquare.alert.PrivateNotification) Version(io.bitsquare.app.Version) P2PServiceListener(io.bitsquare.p2p.P2PServiceListener) java.util(java.util) P2PService(io.bitsquare.p2p.P2PService) SetChangeListener(javafx.collections.SetChangeListener) FXCollections(javafx.collections.FXCollections) BitsquareApp(io.bitsquare.app.BitsquareApp) AddBitcoinNodesWindow(io.bitsquare.gui.main.overlays.windows.AddBitcoinNodesWindow) Connection(io.bitsquare.p2p.network.Connection) Timer(io.bitsquare.common.Timer) BalanceListener(io.bitsquare.btc.listeners.BalanceListener) OKPayAccount(io.bitsquare.payment.OKPayAccount) TradeManager(io.bitsquare.trade.TradeManager) User(io.bitsquare.user.User) WalletService(io.bitsquare.btc.WalletService) TacWindow(io.bitsquare.gui.main.overlays.windows.TacWindow) Alert(io.bitsquare.alert.Alert) DisplayAlertMessageWindow(io.bitsquare.gui.main.overlays.windows.DisplayAlertMessageWindow) Nullable(javax.annotation.Nullable) Log(io.bitsquare.app.Log) BSFormatter(io.bitsquare.gui.util.BSFormatter) javafx.beans.property(javafx.beans.property) Logger(org.slf4j.Logger) UserThread(io.bitsquare.common.UserThread) TxIdTextField(io.bitsquare.gui.components.TxIdTextField) Wallet(org.bitcoinj.core.Wallet) TimeUnit(java.util.concurrent.TimeUnit) EasyBind(org.fxmisc.easybind.EasyBind) OpenOfferManager(io.bitsquare.trade.offer.OpenOfferManager) ArbitratorManager(io.bitsquare.arbitration.ArbitratorManager) CloseConnectionReason(io.bitsquare.p2p.network.CloseConnectionReason) ChangeListener(javafx.beans.value.ChangeListener) AlertManager(io.bitsquare.alert.AlertManager) BalanceListener(io.bitsquare.btc.listeners.BalanceListener) PaymentAccount(io.bitsquare.payment.PaymentAccount) OpenOffer(io.bitsquare.trade.offer.OpenOffer) UserThread(io.bitsquare.common.UserThread) BitsquareApp(io.bitsquare.app.BitsquareApp) Trade(io.bitsquare.trade.Trade) Coin(org.bitcoinj.core.Coin) Transaction(org.bitcoinj.core.Transaction) Ping(io.bitsquare.p2p.peers.keepalive.messages.Ping) Popup(io.bitsquare.gui.main.overlays.popups.Popup) Dispute(io.bitsquare.arbitration.Dispute) Ping(io.bitsquare.p2p.peers.keepalive.messages.Ping)

Example 38 with Coin

use of org.bitcoinj.core.Coin in project bitsquare by bitsquare.

the class SpreadViewModel method update.

private void update(ObservableList<OfferBookListItem> offerBookListItems) {
    Map<String, List<Offer>> offersByCurrencyMap = new HashMap<>();
    for (OfferBookListItem offerBookListItem : offerBookListItems) {
        Offer offer = offerBookListItem.getOffer();
        String currencyCode = offer.getCurrencyCode();
        if (!offersByCurrencyMap.containsKey(currencyCode))
            offersByCurrencyMap.put(currencyCode, new ArrayList<>());
        offersByCurrencyMap.get(currencyCode).add(offer);
    }
    spreadItems.clear();
    for (String currencyCode : offersByCurrencyMap.keySet()) {
        List<Offer> offers = offersByCurrencyMap.get(currencyCode);
        List<Offer> buyOffers = offers.stream().filter(e -> e.getDirection().equals(Offer.Direction.BUY)).sorted((o1, o2) -> {
            long a = o1.getPrice() != null ? o1.getPrice().value : 0;
            long b = o2.getPrice() != null ? o2.getPrice().value : 0;
            if (a != b)
                return a < b ? 1 : -1;
            return 0;
        }).collect(Collectors.toList());
        List<Offer> sellOffers = offers.stream().filter(e -> e.getDirection().equals(Offer.Direction.SELL)).sorted((o1, o2) -> {
            long a = o1.getPrice() != null ? o1.getPrice().value : 0;
            long b = o2.getPrice() != null ? o2.getPrice().value : 0;
            if (a != b)
                return a > b ? 1 : -1;
            return 0;
        }).collect(Collectors.toList());
        Fiat spread = null;
        String percentage = "";
        Fiat bestSellOfferPrice = sellOffers.isEmpty() ? null : sellOffers.get(0).getPrice();
        Fiat bestBuyOfferPrice = buyOffers.isEmpty() ? null : buyOffers.get(0).getPrice();
        if (bestBuyOfferPrice != null && bestSellOfferPrice != null) {
            MarketPrice marketPrice = priceFeedService.getMarketPrice(currencyCode);
            // happens again
            try {
                spread = bestSellOfferPrice.subtract(bestBuyOfferPrice);
                if (spread != null && marketPrice != null) {
                    double marketPriceAsDouble = marketPrice.getPrice(PriceFeedService.Type.LAST);
                    if (CurrencyUtil.isFiatCurrency(currencyCode)) {
                        double result = ((double) spread.value / 10000D) / marketPriceAsDouble;
                        percentage = " (" + formatter.formatPercentagePrice(result) + ")";
                    } else {
                        final double spreadAsDouble = spread.value != 0 ? 10000D / spread.value : 0;
                        double result = marketPriceAsDouble / spreadAsDouble;
                        percentage = " (" + formatter.formatPercentagePrice(result) + ")";
                    }
                }
            } catch (Throwable t) {
                try {
                    String msg = "An error occurred at the spread calculation.\n" + "Error msg: " + t.toString() + "\n" + "Details of offer data: \n" + "bestSellOfferPrice: " + bestSellOfferPrice.value + "\n" + "bestBuyOfferPrice: " + bestBuyOfferPrice.value + "\n" + "sellOffer getCurrencyCode: " + sellOffers.get(0).getCurrencyCode() + "\n" + "buyOffer getCurrencyCode: " + buyOffers.get(0).getCurrencyCode() + "\n\n" + "Please copy and paste this data and send it to the developers so they can investigate the issue.";
                    new Popup().error(msg).show();
                    log.error(t.toString());
                    t.printStackTrace();
                } catch (Throwable t2) {
                    log.error(t2.toString());
                    t2.printStackTrace();
                }
            }
        }
        Coin totalAmount = Coin.valueOf(offers.stream().mapToLong(offer -> offer.getAmount().getValue()).sum());
        spreadItems.add(new SpreadItem(currencyCode, buyOffers.size(), sellOffers.size(), offers.size(), spread, percentage, totalAmount));
    }
}
Also used : PriceFeedService(io.bitsquare.btc.pricefeed.PriceFeedService) Popup(io.bitsquare.gui.main.overlays.popups.Popup) MarketPrice(io.bitsquare.btc.pricefeed.MarketPrice) ActivatableViewModel(io.bitsquare.gui.common.model.ActivatableViewModel) Coin(org.bitcoinj.core.Coin) Inject(com.google.inject.Inject) FXCollections(javafx.collections.FXCollections) Fiat(org.bitcoinj.utils.Fiat) HashMap(java.util.HashMap) OfferBookListItem(io.bitsquare.gui.main.offer.offerbook.OfferBookListItem) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) Offer(io.bitsquare.trade.offer.Offer) List(java.util.List) OfferBook(io.bitsquare.gui.main.offer.offerbook.OfferBook) ListChangeListener(javafx.collections.ListChangeListener) Map(java.util.Map) ObservableList(javafx.collections.ObservableList) CurrencyUtil(io.bitsquare.locale.CurrencyUtil) BSFormatter(io.bitsquare.gui.util.BSFormatter) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Coin(org.bitcoinj.core.Coin) OfferBookListItem(io.bitsquare.gui.main.offer.offerbook.OfferBookListItem) MarketPrice(io.bitsquare.btc.pricefeed.MarketPrice) Offer(io.bitsquare.trade.offer.Offer) Fiat(org.bitcoinj.utils.Fiat) Popup(io.bitsquare.gui.main.overlays.popups.Popup) ArrayList(java.util.ArrayList) List(java.util.List) ObservableList(javafx.collections.ObservableList)

Example 39 with Coin

use of org.bitcoinj.core.Coin in project bitsquare by bitsquare.

the class DepositView method initialize.

@Override
public void initialize() {
    // trigger creation of at least 1 savings address
    walletService.getOrCreateAddressEntry(AddressEntry.Context.AVAILABLE);
    tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    tableView.setPlaceholder(new Label("No deposit addresses have been generated yet"));
    tableViewSelectionListener = (observableValue, oldValue, newValue) -> {
        if (newValue != null)
            fillForm(newValue.getAddressString());
    };
    setSelectColumnCellFactory();
    setAddressColumnCellFactory();
    setBalanceColumnCellFactory();
    setUsageColumnCellFactory();
    setConfidenceColumnCellFactory();
    addressColumn.setComparator((o1, o2) -> o1.getAddressString().compareTo(o2.getAddressString()));
    balanceColumn.setComparator((o1, o2) -> o1.getBalanceAsCoin().compareTo(o2.getBalanceAsCoin()));
    confidenceColumn.setComparator((o1, o2) -> Double.valueOf(o1.getTxConfidenceIndicator().getProgress()).compareTo(o2.getTxConfidenceIndicator().getProgress()));
    usageColumn.setComparator((a, b) -> (a.getNumTxOutputs() < b.getNumTxOutputs()) ? -1 : ((a.getNumTxOutputs() == b.getNumTxOutputs()) ? 0 : 1));
    tableView.getSortOrder().add(usageColumn);
    tableView.setItems(sortedList);
    titledGroupBg = addTitledGroupBg(gridPane, gridRow, 3, "Fund your wallet");
    qrCodeLabel = addLabel(gridPane, gridRow, "", 0);
    //GridPane.setMargin(qrCodeLabel, new Insets(Layout.FIRST_ROW_DISTANCE - 9, 0, 0, 5));
    qrCodeImageView = new ImageView();
    qrCodeImageView.setStyle("-fx-cursor: hand;");
    Tooltip.install(qrCodeImageView, new Tooltip("Open large QR-Code window"));
    qrCodeImageView.setOnMouseClicked(e -> GUIUtil.showFeeInfoBeforeExecute(() -> UserThread.runAfter(() -> new QRCodeWindow(getBitcoinURI()).show(), 200, TimeUnit.MILLISECONDS)));
    GridPane.setRowIndex(qrCodeImageView, gridRow);
    GridPane.setColumnIndex(qrCodeImageView, 1);
    GridPane.setMargin(qrCodeImageView, new Insets(Layout.FIRST_ROW_DISTANCE, 0, 0, 0));
    gridPane.getChildren().add(qrCodeImageView);
    Tuple2<Label, AddressTextField> addressTuple = addLabelAddressTextField(gridPane, ++gridRow, "Address:");
    addressLabel = addressTuple.first;
    //GridPane.setValignment(addressLabel, VPos.TOP);
    //GridPane.setMargin(addressLabel, new Insets(3, 0, 0, 0));
    addressTextField = addressTuple.second;
    addressTextField.setPaymentLabel(paymentLabelString);
    Tuple2<Label, InputTextField> amountTuple = addLabelInputTextField(gridPane, ++gridRow, "Amount in BTC (optional):");
    amountLabel = amountTuple.first;
    amountTextField = amountTuple.second;
    if (DevFlags.DEV_MODE)
        amountTextField.setText("10");
    titledGroupBg.setVisible(false);
    titledGroupBg.setManaged(false);
    qrCodeLabel.setVisible(false);
    qrCodeLabel.setManaged(false);
    qrCodeImageView.setVisible(false);
    qrCodeImageView.setManaged(false);
    addressLabel.setVisible(false);
    addressLabel.setManaged(false);
    addressTextField.setVisible(false);
    addressTextField.setManaged(false);
    amountLabel.setVisible(false);
    amountTextField.setManaged(false);
    generateNewAddressButton = addButton(gridPane, ++gridRow, "Generate new address", -20);
    GridPane.setColumnIndex(generateNewAddressButton, 0);
    GridPane.setHalignment(generateNewAddressButton, HPos.LEFT);
    generateNewAddressButton.setOnAction(event -> {
        boolean hasUnUsedAddress = observableList.stream().filter(e -> e.getNumTxOutputs() == 0).findAny().isPresent();
        if (hasUnUsedAddress) {
            new Popup().warning("Please select an unused address from the table above rather than generating a new one.").show();
        } else {
            AddressEntry newSavingsAddressEntry = walletService.getOrCreateUnusedAddressEntry(AddressEntry.Context.AVAILABLE);
            updateList();
            observableList.stream().filter(depositListItem -> depositListItem.getAddressString().equals(newSavingsAddressEntry.getAddressString())).findAny().ifPresent(depositListItem -> tableView.getSelectionModel().select(depositListItem));
        }
    });
    balanceListener = new BalanceListener() {

        @Override
        public void onBalanceChanged(Coin balance, Transaction tx) {
            updateList();
        }
    };
}
Also used : Insets(javafx.geometry.Insets) BalanceListener(io.bitsquare.btc.listeners.BalanceListener) AddressEntry(io.bitsquare.btc.AddressEntry) AddressTextField(io.bitsquare.gui.components.AddressTextField) InputTextField(io.bitsquare.gui.components.InputTextField) QRCodeWindow(io.bitsquare.gui.main.overlays.windows.QRCodeWindow) Coin(org.bitcoinj.core.Coin) Transaction(org.bitcoinj.core.Transaction) Popup(io.bitsquare.gui.main.overlays.popups.Popup) ImageView(javafx.scene.image.ImageView)

Example 40 with Coin

use of org.bitcoinj.core.Coin in project bitsquare by bitsquare.

the class CreateOfferDataModel method calculateTotalToPay.

void calculateTotalToPay() {
    if (direction != null && amount.get() != null) {
        Coin feeAndSecDeposit = offerFeeAsCoin.add(networkFeeAsCoin).add(securityDepositAsCoin);
        Coin feeAndSecDepositAndAmount = feeAndSecDeposit.add(amount.get());
        Coin required = direction == Offer.Direction.BUY ? feeAndSecDeposit : feeAndSecDepositAndAmount;
        totalToPayAsCoin.set(required);
        log.debug("totalToPayAsCoin " + totalToPayAsCoin.get().toFriendlyString());
        updateBalance();
    }
}
Also used : Coin(org.bitcoinj.core.Coin)

Aggregations

Coin (org.bitcoinj.core.Coin)64 Transaction (org.bitcoinj.core.Transaction)16 AddressEntry (io.bitsquare.btc.AddressEntry)13 WalletService (io.bitsquare.btc.WalletService)13 Address (org.bitcoinj.core.Address)10 Popup (io.bitsquare.gui.main.overlays.popups.Popup)8 Inject (com.google.inject.Inject)7 Nullable (javax.annotation.Nullable)7 BalanceListener (io.bitsquare.btc.listeners.BalanceListener)6 Collectors (java.util.stream.Collectors)6 FXCollections (javafx.collections.FXCollections)6 ListChangeListener (javafx.collections.ListChangeListener)6 ObservableList (javafx.collections.ObservableList)6 BSFormatter (io.bitsquare.gui.util.BSFormatter)5 Offer (io.bitsquare.trade.offer.Offer)5 AddressEntry (io.bisq.core.btc.AddressEntry)4 Trade (io.bisq.core.trade.Trade)4 UserThread (io.bitsquare.common.UserThread)4 PaymentAccountUtil.isPaymentAccountValidForOffer (io.bisq.core.payment.PaymentAccountUtil.isPaymentAccountValidForOffer)3 DevFlags (io.bitsquare.app.DevFlags)3