Search in sources :

Example 46 with Coin

use of org.bitcoinj.core.Coin 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());
    }
}
Also used : Coin(org.bitcoinj.core.Coin) AddressFormatException(org.bitcoinj.core.AddressFormatException) AddressEntryException(io.bitsquare.btc.AddressEntryException) AddressEntry(io.bitsquare.btc.AddressEntry) Popup(io.bitsquare.gui.main.overlays.popups.Popup) BSFormatter(io.bitsquare.gui.util.BSFormatter) WalletService(io.bitsquare.btc.WalletService)

Example 47 with Coin

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

the class BuyerStep5View method doWithdrawal.

private void doWithdrawal(Coin receiverAmount) {
    String toAddress = withdrawAddressTextField.getText();
    ResultHandler resultHandler = this::handleTradeCompleted;
    FaultHandler faultHandler = (errorMessage, throwable) -> {
        useSavingsWalletButton.setDisable(false);
        withdrawToExternalWalletButton.setDisable(false);
        if (throwable != null && throwable.getMessage() != null)
            new Popup().error(errorMessage + "\n\n" + throwable.getMessage()).show();
        else
            new Popup().error(errorMessage).show();
    };
    if (model.dataModel.walletService.getWallet().isEncrypted()) {
        UserThread.runAfter(() -> model.dataModel.walletPasswordWindow.onAesKey(aesKey -> doWithdrawRequest(toAddress, receiverAmount, aesKey, resultHandler, faultHandler)).show(), 300, TimeUnit.MILLISECONDS);
    } else
        doWithdrawRequest(toAddress, receiverAmount, null, resultHandler, faultHandler);
}
Also used : TradeStepView(io.bitsquare.gui.main.portfolio.pendingtrades.steps.TradeStepView) Button(javafx.scene.control.Button) Popup(io.bitsquare.gui.main.overlays.popups.Popup) MainView(io.bitsquare.gui.main.MainView) Coin(org.bitcoinj.core.Coin) Restrictions(io.bitsquare.btc.Restrictions) Tuple2(io.bitsquare.common.util.Tuple2) FundsView(io.bitsquare.gui.main.funds.FundsView) DevFlags(io.bitsquare.app.DevFlags) PendingTradesViewModel(io.bitsquare.gui.main.portfolio.pendingtrades.PendingTradesViewModel) Insets(javafx.geometry.Insets) WalletService(io.bitsquare.btc.WalletService) Layout(io.bitsquare.gui.util.Layout) ResultHandler(io.bitsquare.common.handlers.ResultHandler) KeyParameter(org.spongycastle.crypto.params.KeyParameter) AddressEntry(io.bitsquare.btc.AddressEntry) GridPane(javafx.scene.layout.GridPane) Log(io.bitsquare.app.Log) BSFormatter(io.bitsquare.gui.util.BSFormatter) HBox(javafx.scene.layout.HBox) AddressFormatException(org.bitcoinj.core.AddressFormatException) InputTextField(io.bitsquare.gui.components.InputTextField) TextField(javafx.scene.control.TextField) Label(javafx.scene.control.Label) UserThread(io.bitsquare.common.UserThread) TimeUnit(java.util.concurrent.TimeUnit) AddressEntryException(io.bitsquare.btc.AddressEntryException) FormBuilder(io.bitsquare.gui.util.FormBuilder) Notification(io.bitsquare.gui.main.overlays.notifications.Notification) FaultHandler(io.bitsquare.common.handlers.FaultHandler) ChangeListener(javafx.beans.value.ChangeListener) TransactionsView(io.bitsquare.gui.main.funds.transactions.TransactionsView) Popup(io.bitsquare.gui.main.overlays.popups.Popup) ResultHandler(io.bitsquare.common.handlers.ResultHandler) FaultHandler(io.bitsquare.common.handlers.FaultHandler)

Example 48 with Coin

use of org.bitcoinj.core.Coin in project bitcoin-wallet by bitcoin-wallet.

the class MaintenanceDialogFragment method onCreateDialog.

@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
    final View view = LayoutInflater.from(activity).inflate(R.layout.maintenance_dialog, null);
    Coin value = Coin.ZERO;
    Coin fee = Coin.ZERO;
    for (final Transaction tx : determineMaintenanceTransactions()) {
        value = value.add(tx.getValueSentFromMe(wallet));
        fee = fee.add(tx.getFee());
    }
    final TextView messageView = (TextView) view.findViewById(R.id.maintenance_dialog_message);
    final MonetaryFormat format = application.getConfiguration().getFormat();
    messageView.setText(getString(R.string.maintenance_dialog_message, format.format(value), format.format(fee)));
    passwordGroup = view.findViewById(R.id.maintenance_dialog_password_group);
    passwordView = (EditText) view.findViewById(R.id.maintenance_dialog_password);
    passwordView.setText(null);
    badPasswordView = view.findViewById(R.id.maintenance_dialog_bad_password);
    final DialogBuilder builder = new DialogBuilder(activity);
    builder.setTitle(R.string.maintenance_dialog_title);
    builder.setView(view);
    // dummies, just to make buttons show
    builder.setPositiveButton(R.string.maintenance_dialog_button_move, null);
    builder.setNegativeButton(R.string.button_dismiss, null);
    builder.setCancelable(false);
    final AlertDialog dialog = builder.create();
    dialog.setCanceledOnTouchOutside(false);
    dialog.setOnShowListener(new OnShowListener() {

        @Override
        public void onShow(final DialogInterface d) {
            positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
            negativeButton = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
            positiveButton.setTypeface(Typeface.DEFAULT_BOLD);
            positiveButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(final View v) {
                    log.info("user decided to do maintenance");
                    handleGo();
                }
            });
            negativeButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(final View v) {
                    log.info("user decided to dismiss");
                    dismissAllowingStateLoss();
                }
            });
            passwordView.addTextChangedListener(textWatcher);
            MaintenanceDialogFragment.this.dialog = dialog;
            updateView();
        }
    });
    log.info("showing maintenance dialog");
    return dialog;
}
Also used : AlertDialog(android.app.AlertDialog) Coin(org.bitcoinj.core.Coin) MonetaryFormat(org.bitcoinj.utils.MonetaryFormat) Transaction(org.bitcoinj.core.Transaction) DialogInterface(android.content.DialogInterface) OnClickListener(android.view.View.OnClickListener) TextView(android.widget.TextView) DialogBuilder(de.schildbach.wallet.ui.DialogBuilder) View(android.view.View) TextView(android.widget.TextView) OnShowListener(android.content.DialogInterface.OnShowListener)

Example 49 with Coin

use of org.bitcoinj.core.Coin in project bitcoin-wallet by bitcoin-wallet.

the class RequestWalletBalanceTask method requestWalletBalance.

public void requestWalletBalance(final AssetManager assets, final Address address) {
    backgroundHandler.post(new Runnable() {

        @Override
        public void run() {
            org.bitcoinj.core.Context.propagate(Constants.CONTEXT);
            try {
                final List<ElectrumServer> servers = loadElectrumServers(assets.open(Constants.Files.ELECTRUM_SERVERS_FILENAME));
                final ElectrumServer server = servers.get(new Random().nextInt(servers.size()));
                log.info("trying to request wallet balance from {}: {}", server.socketAddress, address);
                final Socket socket;
                if (server.type == ElectrumServer.Type.TLS) {
                    final SocketFactory sf = sslTrustAllCertificates();
                    socket = sf.createSocket(server.socketAddress.getHostName(), server.socketAddress.getPort());
                    final SSLSession sslSession = ((SSLSocket) socket).getSession();
                    final Certificate certificate = sslSession.getPeerCertificates()[0];
                    final String certificateFingerprint = sslCertificateFingerprint(certificate);
                    if (server.certificateFingerprint == null) {
                        // signed by CA
                        if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(server.socketAddress.getHostName(), sslSession))
                            throw new SSLHandshakeException("Expected " + server.socketAddress.getHostName() + ", got " + sslSession.getPeerPrincipal());
                    } else {
                        // self-signed
                        if (!certificateFingerprint.equals(server.certificateFingerprint))
                            throw new SSLHandshakeException("Expected " + server.certificateFingerprint + ", got " + certificateFingerprint);
                    }
                } else if (server.type == ElectrumServer.Type.TCP) {
                    socket = new Socket();
                    socket.connect(server.socketAddress, 5000);
                } else {
                    throw new IllegalStateException("Cannot handle: " + server.type);
                }
                final BufferedSink sink = Okio.buffer(Okio.sink(socket));
                sink.timeout().timeout(5000, TimeUnit.MILLISECONDS);
                final BufferedSource source = Okio.buffer(Okio.source(socket));
                source.timeout().timeout(5000, TimeUnit.MILLISECONDS);
                final Moshi moshi = new Moshi.Builder().build();
                final JsonAdapter<JsonRpcRequest> requestAdapter = moshi.adapter(JsonRpcRequest.class);
                final JsonRpcRequest request = new JsonRpcRequest("blockchain.address.listunspent", new String[] { address.toBase58() });
                requestAdapter.toJson(sink, request);
                sink.writeUtf8("\n").flush();
                final JsonAdapter<JsonRpcResponse> responseAdapter = moshi.adapter(JsonRpcResponse.class);
                final JsonRpcResponse response = responseAdapter.fromJson(source);
                if (response.id == request.id) {
                    if (response.result == null)
                        throw new JsonDataException("empty response");
                    final Set<UTXO> utxos = new HashSet<>();
                    for (final JsonRpcResponse.Utxo responseUtxo : response.result) {
                        final Sha256Hash utxoHash = Sha256Hash.wrap(responseUtxo.tx_hash);
                        final int utxoIndex = responseUtxo.tx_pos;
                        final Coin utxoValue = Coin.valueOf(responseUtxo.value);
                        final Script script = ScriptBuilder.createOutputScript(address);
                        final UTXO utxo = new UTXO(utxoHash, utxoIndex, utxoValue, responseUtxo.height, false, script);
                        utxos.add(utxo);
                    }
                    log.info("fetched {} unspent outputs from {}", response.result.length, server.socketAddress);
                    onResult(utxos);
                } else {
                    log.info("id mismatch response:{} vs request:{}", response.id, request.id);
                    onFail(R.string.error_parse, server.socketAddress.toString());
                }
            } catch (final JsonDataException x) {
                log.info("problem parsing json", x);
                onFail(R.string.error_parse, x.getMessage());
            } catch (final IOException x) {
                log.info("problem querying unspent outputs", x);
                onFail(R.string.error_io, x.getMessage());
            }
        }
    });
}
Also used : Moshi(com.squareup.moshi.Moshi) HashSet(java.util.HashSet) Set(java.util.Set) ScriptBuilder(org.bitcoinj.script.ScriptBuilder) Sha256Hash(org.bitcoinj.core.Sha256Hash) BufferedSink(okio.BufferedSink) JsonAdapter(com.squareup.moshi.JsonAdapter) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) Coin(org.bitcoinj.core.Coin) Random(java.util.Random) LinkedList(java.util.LinkedList) List(java.util.List) BufferedSource(okio.BufferedSource) Script(org.bitcoinj.script.Script) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) SocketFactory(javax.net.SocketFactory) SSLSession(javax.net.ssl.SSLSession) IOException(java.io.IOException) UTXO(org.bitcoinj.core.UTXO) JsonDataException(com.squareup.moshi.JsonDataException) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 50 with Coin

use of org.bitcoinj.core.Coin in project bitcoin-wallet by bitcoin-wallet.

the class SendCoinsFragment method handleEmpty.

private void handleEmpty() {
    final Coin available = wallet.getBalance(BalanceType.AVAILABLE);
    amountCalculatorLink.setBtcAmount(available);
    updateView();
    handler.post(dryrunRunnable);
}
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