Search in sources :

Example 66 with Address

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

the class BlockchainService method observeLiveDatasThatAreDependentOnWalletAndBlockchain.

private void observeLiveDatasThatAreDependentOnWalletAndBlockchain() {
    final NewTransactionLiveData newTransaction = new NewTransactionLiveData(wallet.getValue());
    newTransaction.observe(this, tx -> {
        final Wallet wallet = BlockchainService.this.wallet.getValue();
        postDelayedStopSelf(5 * DateUtils.MINUTE_IN_MILLIS);
        final Coin amount = tx.getValue(wallet);
        if (amount.isPositive()) {
            final Address address = WalletUtils.getWalletAddressOfReceived(tx, wallet);
            final ConfidenceType confidenceType = tx.getConfidence().getConfidenceType();
            final boolean replaying = blockChain.getBestChainHeight() < config.getBestChainHeightEver();
            final boolean isReplayedTx = confidenceType == ConfidenceType.BUILDING && replaying;
            if (!isReplayedTx)
                notifyCoinsReceived(address, amount, tx.getTxId());
        }
    });
    impediments = new ImpedimentsLiveData(application);
    impediments.observe(this, new Observer<Set<Impediment>>() {

        @Override
        public void onChanged(final Set<Impediment> impediments) {
            if (impediments.isEmpty() && peerGroup == null && Constants.ENABLE_BLOCKCHAIN_SYNC)
                startup();
            else if (!impediments.isEmpty() && peerGroup != null)
                shutdown();
            broadcastBlockchainState();
        }

        private void startup() {
            final Wallet wallet = BlockchainService.this.wallet.getValue();
            // consistency check
            final int walletLastBlockSeenHeight = wallet.getLastBlockSeenHeight();
            final int bestChainHeight = blockChain.getBestChainHeight();
            if (walletLastBlockSeenHeight != -1 && walletLastBlockSeenHeight != bestChainHeight) {
                final String message = "wallet/blockchain out of sync: " + walletLastBlockSeenHeight + "/" + bestChainHeight;
                log.error(message);
                CrashReporter.saveBackgroundTrace(new RuntimeException(message), application.packageInfo());
            }
            final Configuration.SyncMode syncMode = config.getSyncMode();
            peerGroup = new PeerGroup(Constants.NETWORK_PARAMETERS, blockChain);
            log.info("creating {}, sync mode: {}", peerGroup, syncMode);
            // recursive implementation causes StackOverflowError
            peerGroup.setDownloadTxDependencies(0);
            peerGroup.addWallet(wallet);
            peerGroup.setBloomFilteringEnabled(syncMode == Configuration.SyncMode.CONNECTION_FILTER);
            peerGroup.setUserAgent(Constants.USER_AGENT, application.packageInfo().versionName);
            peerGroup.addConnectedEventListener(peerConnectivityListener);
            peerGroup.addDisconnectedEventListener(peerConnectivityListener);
            final int maxConnectedPeers = application.maxConnectedPeers();
            final Set<HostAndPort> trustedPeers = config.getTrustedPeers();
            final boolean trustedPeerOnly = config.isTrustedPeersOnly();
            peerGroup.setMaxConnections(trustedPeerOnly ? 0 : maxConnectedPeers);
            peerGroup.setConnectTimeoutMillis(Constants.PEER_TIMEOUT_MS);
            peerGroup.setPeerDiscoveryTimeoutMillis(Constants.PEER_DISCOVERY_TIMEOUT_MS);
            peerGroup.setStallThreshold(20, Block.HEADER_SIZE * 10);
            final ResolveDnsTask resolveDnsTask = new ResolveDnsTask(backgroundHandler) {

                @Override
                protected void onSuccess(final HostAndPort hostAndPort, final InetSocketAddress socketAddress) {
                    log.info("trusted peer '{}' resolved to {}", hostAndPort, socketAddress.getAddress().getHostAddress());
                    if (socketAddress != null) {
                        peerGroup.addAddress(new PeerAddress(Constants.NETWORK_PARAMETERS, socketAddress), 10);
                        if (peerGroup.getMaxConnections() > maxConnectedPeers)
                            peerGroup.setMaxConnections(maxConnectedPeers);
                    }
                }

                @Override
                protected void onUnknownHost(final HostAndPort hostAndPort) {
                    log.info("trusted peer '{}' unknown host", hostAndPort);
                }
            };
            for (final HostAndPort trustedPeer : trustedPeers) resolveDnsTask.resolve(trustedPeer);
            if (trustedPeerOnly) {
                log.info("trusted peers only – not adding any random nodes from the P2P network");
            } else {
                log.info("adding random peers from the P2P network");
                if (syncMode == Configuration.SyncMode.CONNECTION_FILTER)
                    peerGroup.setRequiredServices(VersionMessage.NODE_BLOOM | VersionMessage.NODE_WITNESS);
                else
                    peerGroup.setRequiredServices(VersionMessage.NODE_WITNESS);
            }
            // start peergroup
            log.info("starting {} asynchronously", peerGroup);
            peerGroup.startAsync();
            peerGroup.startBlockChainDownload(blockchainDownloadListener);
            postDelayedStopSelf(DateUtils.MINUTE_IN_MILLIS / 2);
        }

        private void shutdown() {
            final Wallet wallet = BlockchainService.this.wallet.getValue();
            peerGroup.removeDisconnectedEventListener(peerConnectivityListener);
            peerGroup.removeConnectedEventListener(peerConnectivityListener);
            peerGroup.removeWallet(wallet);
            log.info("stopping {} asynchronously", peerGroup);
            peerGroup.stopAsync();
            peerGroup = null;
        }
    });
}
Also used : EnumSet(java.util.EnumSet) Set(java.util.Set) InetSocketAddress(java.net.InetSocketAddress) Address(org.bitcoinj.core.Address) PeerAddress(org.bitcoinj.core.PeerAddress) Wallet(org.bitcoinj.wallet.Wallet) InetSocketAddress(java.net.InetSocketAddress) PeerGroup(org.bitcoinj.core.PeerGroup) ResolveDnsTask(de.schildbach.wallet.ui.preference.ResolveDnsTask) Impediment(de.schildbach.wallet.service.BlockchainState.Impediment) Coin(org.bitcoinj.core.Coin) ConfidenceType(org.bitcoinj.core.TransactionConfidence.ConfidenceType) HostAndPort(com.google.common.net.HostAndPort) PeerAddress(org.bitcoinj.core.PeerAddress)

Example 67 with Address

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

the class RequestCoinsViewModel method maybeGeneratePaymentRequest.

private void maybeGeneratePaymentRequest() {
    final Address address = freshReceiveAddress.getValue();
    if (address != null) {
        final String bluetoothMac = this.bluetoothMac.getValue();
        final String paymentUrl = bluetoothMac != null ? "bt:" + bluetoothMac : null;
        paymentRequest.setValue(PaymentProtocol.createPaymentRequest(Constants.NETWORK_PARAMETERS, amount.getValue(), address, ownName.getValue(), paymentUrl, null).build().toByteArray());
    }
}
Also used : Address(org.bitcoinj.core.Address)

Example 68 with Address

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

the class EditAddressBookEntryFragment method onCreateDialog.

@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
    final Bundle args = getArguments();
    final Address address = Address.fromString(Constants.NETWORK_PARAMETERS, args.getString(KEY_ADDRESS));
    final String suggestedAddressLabel = args.getString(KEY_SUGGESTED_ADDRESS_LABEL);
    final LayoutInflater inflater = LayoutInflater.from(activity);
    final String label = addressBookDao.resolveLabel(address.toString());
    final boolean isAdd = label == null;
    final boolean isOwn = wallet.isAddressMine(address);
    final int titleResId;
    if (isOwn)
        titleResId = isAdd ? R.string.edit_address_book_entry_dialog_title_add_receive : R.string.edit_address_book_entry_dialog_title_edit_receive;
    else
        titleResId = isAdd ? R.string.edit_address_book_entry_dialog_title_add : R.string.edit_address_book_entry_dialog_title_edit;
    final View view = inflater.inflate(R.layout.edit_address_book_entry_dialog, null);
    final TextView viewAddress = view.findViewById(R.id.edit_address_book_entry_address);
    viewAddress.setText(WalletUtils.formatAddress(address, Constants.ADDRESS_FORMAT_GROUP_SIZE, Constants.ADDRESS_FORMAT_LINE_SIZE));
    final TextView viewLabel = view.findViewById(R.id.edit_address_book_entry_label);
    viewLabel.setText(label != null ? label : suggestedAddressLabel);
    final DialogBuilder dialog = DialogBuilder.custom(activity, titleResId, view);
    final DialogInterface.OnClickListener onClickListener = (d, which) -> {
        if (which == DialogInterface.BUTTON_POSITIVE) {
            final String newLabel = viewLabel.getText().toString().trim();
            if (!newLabel.isEmpty()) {
                addressBookDao.insertOrUpdate(new AddressBookEntry(address.toString(), newLabel));
                maybeSelectAddress(address);
            } else if (!isAdd) {
                addressBookDao.delete(address.toString());
            }
        } else if (which == DialogInterface.BUTTON_NEUTRAL) {
            addressBookDao.delete(address.toString());
        }
        dismiss();
    };
    dialog.setPositiveButton(isAdd ? R.string.button_add : R.string.edit_address_book_entry_dialog_button_edit, onClickListener);
    if (!isAdd)
        dialog.setNeutralButton(R.string.button_delete, onClickListener);
    dialog.setNegativeButton(R.string.button_cancel, (d, which) -> dismissAllowingStateLoss());
    return dialog.create();
}
Also used : Context(android.content.Context) WalletUtils(de.schildbach.wallet.util.WalletUtils) FragmentManager(androidx.fragment.app.FragmentManager) AddressBookEntry(de.schildbach.wallet.addressbook.AddressBookEntry) Bundle(android.os.Bundle) Logger(org.slf4j.Logger) ViewModelProvider(androidx.lifecycle.ViewModelProvider) LayoutInflater(android.view.LayoutInflater) Wallet(org.bitcoinj.wallet.Wallet) LoggerFactory(org.slf4j.LoggerFactory) Dialog(android.app.Dialog) AddressBookDao(de.schildbach.wallet.addressbook.AddressBookDao) TextView(android.widget.TextView) Nullable(androidx.annotation.Nullable) Handler(android.os.Handler) View(android.view.View) R(de.schildbach.wallet.R) Address(org.bitcoinj.core.Address) WalletApplication(de.schildbach.wallet.WalletApplication) Constants(de.schildbach.wallet.Constants) DialogInterface(android.content.DialogInterface) DialogFragment(androidx.fragment.app.DialogFragment) AddressBookDatabase(de.schildbach.wallet.addressbook.AddressBookDatabase) Address(org.bitcoinj.core.Address) DialogInterface(android.content.DialogInterface) Bundle(android.os.Bundle) AddressBookEntry(de.schildbach.wallet.addressbook.AddressBookEntry) TextView(android.widget.TextView) View(android.view.View) LayoutInflater(android.view.LayoutInflater) TextView(android.widget.TextView)

Example 69 with Address

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

the class AddressBookActivity method onCreate.

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final FragmentManager fragmentManager = getSupportFragmentManager();
    setContentView(R.layout.address_book_content);
    final ViewPager2 pager = findViewById(R.id.address_book_pager);
    final ViewPagerTabs pagerTabs = findViewById(R.id.address_book_pager_tabs);
    pagerTabs.addTabLabels(TAB_LABELS);
    final boolean twoPanes = getResources().getBoolean(R.bool.address_book_two_panes);
    walletActivityViewModel = new ViewModelProvider(this).get(AbstractWalletActivityViewModel.class);
    walletActivityViewModel.wallet.observe(this, wallet -> invalidateOptionsMenu());
    viewModel = new ViewModelProvider(this).get(AddressBookViewModel.class);
    viewModel.pageTo.observe(this, new Event.Observer<Integer>() {

        @Override
        protected void onEvent(final Integer position) {
            if (!twoPanes)
                pager.setCurrentItem(position, true);
        }
    });
    viewModel.showEditAddressBookEntryDialog.observe(this, new Event.Observer<Address>() {

        @Override
        protected void onEvent(final Address address) {
            EditAddressBookEntryFragment.edit(fragmentManager, address);
        }
    });
    viewModel.showScanOwnAddressDialog.observe(this, new Event.Observer<Void>() {

        @Override
        protected void onEvent(final Void v) {
            final DialogBuilder dialog = DialogBuilder.dialog(AddressBookActivity.this, R.string.address_book_options_scan_title, R.string.address_book_options_scan_own_address);
            dialog.singleDismissButton(null);
            dialog.show();
        }
    });
    viewModel.showScanInvalidDialog.observe(this, new Event.Observer<Void>() {

        @Override
        protected void onEvent(final Void v) {
            final DialogBuilder dialog = DialogBuilder.dialog(AddressBookActivity.this, R.string.address_book_options_scan_title, R.string.address_book_options_scan_invalid);
            dialog.singleDismissButton(null);
            dialog.show();
        }
    });
    if (twoPanes) {
        final RecyclerView recyclerView = (RecyclerView) pager.getChildAt(0);
        recyclerView.setClipToPadding(false);
        recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            final int width = recyclerView.getWidth();
            recyclerView.setPadding(0, 0, width / 2, 0);
            pager.setCurrentItem(0);
        });
        pager.setUserInputEnabled(false);
        pagerTabs.setMode(ViewPagerTabs.Mode.STATIC);
    } else {
        pager.setPageTransformer(new ZoomOutPageTransformer());
        pager.registerOnPageChangeCallback(pagerTabs.getPageChangeCallback());
        pagerTabs.setMode(ViewPagerTabs.Mode.DYNAMIC);
    }
    pager.setOffscreenPageLimit(1);
    pager.setAdapter(new AddressBookActivity.PagerAdapter());
}
Also used : ViewPagerTabs(de.schildbach.wallet.util.ViewPagerTabs) Address(org.bitcoinj.core.Address) FragmentManager(androidx.fragment.app.FragmentManager) ViewPager2(androidx.viewpager2.widget.ViewPager2) RecyclerView(androidx.recyclerview.widget.RecyclerView) ViewModelProvider(androidx.lifecycle.ViewModelProvider) ZoomOutPageTransformer(de.schildbach.wallet.util.ZoomOutPageTransformer)

Example 70 with Address

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

the class PaymentIntent method getAddress.

public Address getAddress() {
    if (outputs == null || outputs.length != 1)
        throw new IllegalStateException();
    final Script script = outputs[0].script;
    final Address address = WalletUtils.getToAddress(script);
    if (address == null)
        throw new IllegalStateException();
    return address;
}
Also used : Script(org.bitcoinj.script.Script) Address(org.bitcoinj.core.Address)

Aggregations

Address (org.bitcoinj.core.Address)78 Transaction (org.bitcoinj.core.Transaction)32 Coin (org.bitcoinj.core.Coin)28 TransactionOutput (org.bitcoinj.core.TransactionOutput)15 TransactionInput (org.bitcoinj.core.TransactionInput)13 ArrayList (java.util.ArrayList)12 AddressEntry (bisq.core.btc.AddressEntry)11 Wallet (org.bitcoinj.wallet.Wallet)11 BtcWalletService (bisq.core.btc.wallet.BtcWalletService)10 AddressFormatException (org.bitcoinj.core.AddressFormatException)10 TransactionConfidence (org.bitcoinj.core.TransactionConfidence)10 IOException (java.io.IOException)9 SendRequest (org.bitcoinj.wallet.SendRequest)9 WalletService (io.bitsquare.btc.WalletService)8 List (java.util.List)8 Collectors (java.util.stream.Collectors)8 Nullable (javax.annotation.Nullable)8 TransactionOutPoint (org.bitcoinj.core.TransactionOutPoint)8 Script (org.bitcoinj.script.Script)8 Intent (android.content.Intent)7