Search in sources :

Example 6 with Address

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

the class AltCoinAddressValidator method validate.

@Override
public ValidationResult validate(String input) {
    ValidationResult validationResult = super.validate(input);
    if (!validationResult.isValid || currencyCode == null) {
        return validationResult;
    } else {
        // Validation: 
        // 1: With a regex checking the correct structure of an address 
        // 2: If the address contains a checksum, verify the checksum
        ValidationResult wrongChecksum = new ValidationResult(false, "Address validation failed because checksum was not correct.");
        ValidationResult regexTestFailed = new ValidationResult(false, "Address validation failed because it does not match the structure of a " + currencyCode + " address.");
        switch(currencyCode) {
            case "ETH":
                // https://github.com/ethereum/web3.js/blob/master/lib/utils/utils.js#L403
                if (!input.matches("^(0x)?[0-9a-fA-F]{40}$"))
                    return regexTestFailed;
                else
                    return new ValidationResult(true);
            // Example for BTC, though for BTC we use the BitcoinJ library address check
            case "BTC":
                // taken form: https://stackoverflow.com/questions/21683680/regex-to-match-bitcoin-addresses
                if (input.matches("^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$")) {
                    if (verifyChecksum(input))
                        try {
                            new Address(MainNetParams.get(), input);
                            return new ValidationResult(true);
                        } catch (AddressFormatException e) {
                            return new ValidationResult(false, getErrorMessage(e));
                        }
                    else
                        return wrongChecksum;
                } else {
                    return regexTestFailed;
                }
            case "PIVX":
                if (input.matches("^[D][a-km-zA-HJ-NP-Z1-9]{25,34}$")) {
                    if (verifyChecksum(input)) {
                        try {
                            new Address(PivxParams.get(), input);
                            return new ValidationResult(true);
                        } catch (AddressFormatException e) {
                            return new ValidationResult(false, getErrorMessage(e));
                        }
                    } else {
                        return wrongChecksum;
                    }
                } else {
                    return regexTestFailed;
                }
            case "IOP":
                if (input.matches("^[p][a-km-zA-HJ-NP-Z1-9]{25,34}$")) {
                    if (verifyChecksum(input)) {
                        try {
                            new Address(IOPParams.get(), input);
                            return new ValidationResult(true);
                        } catch (AddressFormatException e) {
                            return new ValidationResult(false, getErrorMessage(e));
                        }
                    } else {
                        return wrongChecksum;
                    }
                } else {
                    return regexTestFailed;
                }
            case "888":
                if (input.matches("^[83][a-km-zA-HJ-NP-Z1-9]{25,34}$")) {
                    if (OctocoinAddressValidator.ValidateAddress(input)) {
                        try {
                            new Address(OctocoinParams.get(), input);
                            return new ValidationResult(true);
                        } catch (AddressFormatException e) {
                            return new ValidationResult(false, getErrorMessage(e));
                        }
                    } else {
                        return wrongChecksum;
                    }
                } else {
                    return regexTestFailed;
                }
            case "ZEC":
                // We only support t addresses (transparent transactions)
                if (input.startsWith("t"))
                    return validationResult;
                else
                    return new ValidationResult(false, "ZEC address need to start with t. Addresses starting with z are not supported.");
            /*case "XTO":
                    if (input.matches("^[T2][a-km-zA-HJ-NP-Z1-9]{25,34}$")) {
                        if (verifyChecksum(input))
                            try {
                                new Address(MainNetParams.get(), input);
                                return new ValidationResult(true);
                            } catch (AddressFormatException e) {
                                return new ValidationResult(false, getErrorMessage(e));
                            }
                        else
                            return wrongChecksum;
                    } else {
                        return regexTestFailed;
                    }*/
            case "GBYTE":
                return ByteballAddressValidator.validate(input);
            case "NXT":
                if (!input.startsWith("NXT-") || !input.equals(input.toUpperCase())) {
                    return regexTestFailed;
                }
                try {
                    long accountId = NxtReedSolomon.decode(input.substring(4));
                    return new ValidationResult(accountId != 0);
                } catch (NxtReedSolomon.DecodeException e) {
                    return wrongChecksum;
                }
            default:
                log.debug("Validation for AltCoinAddress not implemented yet. currencyCode:" + currencyCode);
                return validationResult;
        }
    }
}
Also used : AddressFormatException(org.bitcoinj.core.AddressFormatException) NxtReedSolomon(io.bitsquare.gui.util.validation.altcoins.NxtReedSolomon) Address(org.bitcoinj.core.Address)

Example 7 with Address

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

the class SweepWalletFragment method requestWalletBalance.

private void requestWalletBalance() {
    ProgressDialogFragment.showProgress(fragmentManager, getString(R.string.sweep_wallet_fragment_request_wallet_balance_progress));
    final RequestWalletBalanceTask.ResultCallback callback = new RequestWalletBalanceTask.ResultCallback() {

        @Override
        public void onResult(final Set<UTXO> utxos) {
            ProgressDialogFragment.dismissProgress(fragmentManager);
            // Filter UTXOs we've already spent and sort the rest.
            final Set<Transaction> walletTxns = application.getWallet().getTransactions(false);
            final Set<UTXO> sortedUtxos = new TreeSet<>(UTXO_COMPARATOR);
            for (final UTXO utxo : utxos) if (!utxoSpentBy(walletTxns, utxo))
                sortedUtxos.add(utxo);
            // Fake transaction funding the wallet to sweep.
            final Map<Sha256Hash, Transaction> fakeTxns = new HashMap<>();
            for (final UTXO utxo : sortedUtxos) {
                Transaction fakeTx = fakeTxns.get(utxo.getHash());
                if (fakeTx == null) {
                    fakeTx = new FakeTransaction(Constants.NETWORK_PARAMETERS, utxo.getHash());
                    fakeTx.getConfidence().setConfidenceType(ConfidenceType.BUILDING);
                    fakeTxns.put(fakeTx.getHash(), fakeTx);
                }
                final TransactionOutput fakeOutput = new TransactionOutput(Constants.NETWORK_PARAMETERS, fakeTx, utxo.getValue(), utxo.getScript().getProgram());
                // Fill with output dummies as needed.
                while (fakeTx.getOutputs().size() < utxo.getIndex()) fakeTx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, fakeTx, Coin.NEGATIVE_SATOSHI, new byte[] {}));
                // Add the actual output we will spend later.
                fakeTx.addOutput(fakeOutput);
            }
            walletToSweep.clearTransactions(0);
            for (final Transaction tx : fakeTxns.values()) walletToSweep.addWalletTransaction(new WalletTransaction(WalletTransaction.Pool.UNSPENT, tx));
            log.info("built wallet to sweep:\n{}", walletToSweep.toString(false, true, false, null));
            updateView();
        }

        private boolean utxoSpentBy(final Set<Transaction> transactions, final UTXO utxo) {
            for (final Transaction tx : transactions) {
                for (final TransactionInput input : tx.getInputs()) {
                    final TransactionOutPoint outpoint = input.getOutpoint();
                    if (outpoint.getHash().equals(utxo.getHash()) && outpoint.getIndex() == utxo.getIndex())
                        return true;
                }
            }
            return false;
        }

        @Override
        public void onFail(final int messageResId, final Object... messageArgs) {
            ProgressDialogFragment.dismissProgress(fragmentManager);
            final DialogBuilder dialog = DialogBuilder.warn(activity, R.string.sweep_wallet_fragment_request_wallet_balance_failed_title);
            dialog.setMessage(getString(messageResId, messageArgs));
            dialog.setPositiveButton(R.string.button_retry, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    requestWalletBalance();
                }
            });
            dialog.setNegativeButton(R.string.button_dismiss, null);
            dialog.show();
        }
    };
    final Address address = walletToSweep.getImportedKeys().iterator().next().toAddress(Constants.NETWORK_PARAMETERS);
    new RequestWalletBalanceTask(backgroundHandler, callback).requestWalletBalance(activity.getAssets(), address);
}
Also used : Set(java.util.Set) TreeSet(java.util.TreeSet) TransactionOutput(org.bitcoinj.core.TransactionOutput) Address(org.bitcoinj.core.Address) HashMap(java.util.HashMap) DialogInterface(android.content.DialogInterface) Sha256Hash(org.bitcoinj.core.Sha256Hash) TransactionInput(org.bitcoinj.core.TransactionInput) TransactionOutPoint(org.bitcoinj.core.TransactionOutPoint) UTXO(org.bitcoinj.core.UTXO) Transaction(org.bitcoinj.core.Transaction) WalletTransaction(org.bitcoinj.wallet.WalletTransaction) TreeSet(java.util.TreeSet) WalletTransaction(org.bitcoinj.wallet.WalletTransaction) DialogBuilder(de.schildbach.wallet.ui.DialogBuilder) TransactionOutPoint(org.bitcoinj.core.TransactionOutPoint)

Example 8 with Address

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

the class PaymentIntent method fromBitcoinUri.

public static PaymentIntent fromBitcoinUri(final BitcoinURI bitcoinUri) {
    final Address address = bitcoinUri.getAddress();
    final Output[] outputs = address != null ? buildSimplePayTo(bitcoinUri.getAmount(), address) : null;
    final String bluetoothMac = (String) bitcoinUri.getParameterByName(Bluetooth.MAC_URI_PARAM);
    final String paymentRequestHashStr = (String) bitcoinUri.getParameterByName("h");
    final byte[] paymentRequestHash = paymentRequestHashStr != null ? base64UrlDecode(paymentRequestHashStr) : null;
    return new PaymentIntent(PaymentIntent.Standard.BIP21, null, null, outputs, bitcoinUri.getLabel(), bluetoothMac != null ? "bt:" + bluetoothMac : null, null, bitcoinUri.getPaymentRequestUrl(), paymentRequestHash);
}
Also used : Address(org.bitcoinj.core.Address)

Example 9 with Address

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

the class BlockchainService method notifyCoinsReceived.

private void notifyCoinsReceived(@Nullable final Address address, final Coin amount, final Sha256Hash transactionHash) {
    notificationCount++;
    notificationAccumulatedAmount = notificationAccumulatedAmount.add(amount);
    if (address != null && !notificationAddresses.contains(address))
        notificationAddresses.add(address);
    final MonetaryFormat btcFormat = config.getFormat();
    final String packageFlavor = application.applicationPackageFlavor();
    final String msgSuffix = packageFlavor != null ? " [" + packageFlavor + "]" : "";
    // summary notification
    final NotificationCompat.Builder summaryNotification = new NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL_ID_RECEIVED);
    summaryNotification.setGroup(Constants.NOTIFICATION_GROUP_KEY_RECEIVED);
    summaryNotification.setGroupSummary(true);
    summaryNotification.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
    summaryNotification.setWhen(System.currentTimeMillis());
    summaryNotification.setSmallIcon(R.drawable.stat_notify_received_24dp);
    summaryNotification.setContentTitle(getString(R.string.notification_coins_received_msg, btcFormat.format(notificationAccumulatedAmount)) + msgSuffix);
    if (!notificationAddresses.isEmpty()) {
        final StringBuilder text = new StringBuilder();
        for (final Address notificationAddress : notificationAddresses) {
            if (text.length() > 0)
                text.append(", ");
            final String addressStr = notificationAddress.toBase58();
            final String label = AddressBookProvider.resolveLabel(getApplicationContext(), addressStr);
            text.append(label != null ? label : addressStr);
        }
        summaryNotification.setContentText(text);
    }
    summaryNotification.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, WalletActivity.class), 0));
    nm.notify(Constants.NOTIFICATION_ID_COINS_RECEIVED, summaryNotification.build());
    // child notification
    final NotificationCompat.Builder childNotification = new NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL_ID_RECEIVED);
    childNotification.setGroup(Constants.NOTIFICATION_GROUP_KEY_RECEIVED);
    childNotification.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
    childNotification.setWhen(System.currentTimeMillis());
    childNotification.setSmallIcon(R.drawable.stat_notify_received_24dp);
    final String msg = getString(R.string.notification_coins_received_msg, btcFormat.format(amount)) + msgSuffix;
    childNotification.setTicker(msg);
    childNotification.setContentTitle(msg);
    if (address != null) {
        final String addressStr = address.toBase58();
        final String addressLabel = AddressBookProvider.resolveLabel(getApplicationContext(), addressStr);
        if (addressLabel != null)
            childNotification.setContentText(addressLabel);
        else
            childNotification.setContentText(addressStr);
    }
    childNotification.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, WalletActivity.class), 0));
    childNotification.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.coins_received));
    nm.notify(transactionHash.toString(), Constants.NOTIFICATION_ID_COINS_RECEIVED, childNotification.build());
}
Also used : MonetaryFormat(org.bitcoinj.utils.MonetaryFormat) InetSocketAddress(java.net.InetSocketAddress) Address(org.bitcoinj.core.Address) NotificationCompat(android.support.v4.app.NotificationCompat) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent)

Example 10 with Address

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

the class SendingAddressesFragment method handlePasteClipboard.

private void handlePasteClipboard() {
    final Address address = getAddressFromPrimaryClip();
    if (address == null) {
        final DialogBuilder dialog = new DialogBuilder(activity);
        dialog.setTitle(R.string.address_book_options_paste_from_clipboard_title);
        dialog.setMessage(R.string.address_book_options_paste_from_clipboard_invalid);
        dialog.singleDismissButton(null);
        dialog.show();
    } else if (!wallet.isPubKeyHashMine(address.getHash160())) {
        EditAddressBookEntryFragment.edit(getFragmentManager(), address);
    } else {
        final DialogBuilder dialog = new DialogBuilder(activity);
        dialog.setTitle(R.string.address_book_options_paste_from_clipboard_title);
        dialog.setMessage(R.string.address_book_options_paste_from_clipboard_own_address);
        dialog.singleDismissButton(null);
        dialog.show();
    }
}
Also used : Address(org.bitcoinj.core.Address)

Aggregations

Address (org.bitcoinj.core.Address)26 WalletService (io.bitsquare.btc.WalletService)8 Coin (org.bitcoinj.core.Coin)8 Transaction (org.bitcoinj.core.Transaction)8 AddressEntry (io.bitsquare.btc.AddressEntry)7 TextView (android.widget.TextView)5 View (android.view.View)3 Offer (io.bitsquare.trade.offer.Offer)3 DialogInterface (android.content.DialogInterface)2 Intent (android.content.Intent)2 Uri (android.net.Uri)2 Bundle (android.os.Bundle)2 Inject (com.google.inject.Inject)2 Arbitrator (io.bitsquare.arbitration.Arbitrator)2 PreparedDepositTxAndOffererInputs (io.bitsquare.btc.data.PreparedDepositTxAndOffererInputs)2 BalanceListener (io.bitsquare.btc.listeners.BalanceListener)2 UserThread (io.bitsquare.common.UserThread)2 NodeAddress (io.bitsquare.p2p.NodeAddress)2 Trade (io.bitsquare.trade.Trade)2 InetSocketAddress (java.net.InetSocketAddress)2