Search in sources :

Example 6 with Connection

use of io.bitsquare.p2p.network.Connection in project bitsquare by bitsquare.

the class MainViewModel method initP2PNetwork.

///////////////////////////////////////////////////////////////////////////////////////////
// Initialisation
///////////////////////////////////////////////////////////////////////////////////////////
private BooleanProperty initP2PNetwork() {
    Log.traceCall();
    StringProperty bootstrapState = new SimpleStringProperty();
    StringProperty bootstrapWarning = new SimpleStringProperty();
    BooleanProperty hiddenServicePublished = new SimpleBooleanProperty();
    BooleanProperty initialP2PNetworkDataReceived = new SimpleBooleanProperty();
    p2PNetworkInfoBinding = EasyBind.combine(bootstrapState, bootstrapWarning, p2PService.getNumConnectedPeers(), hiddenServicePublished, initialP2PNetworkDataReceived, (state, warning, numPeers, hiddenService, dataReceived) -> {
        String result = "";
        int peers = (int) numPeers;
        if (warning != null && peers == 0) {
            result = warning;
        } else {
            if (dataReceived && hiddenService)
                result = "P2P network peers: " + numPeers;
            else if (peers == 0)
                result = state;
            else
                result = state + " / P2P network peers: " + numPeers;
        }
        return result;
    });
    p2PNetworkInfoBinding.subscribe((observable, oldValue, newValue) -> {
        p2PNetworkInfo.set(newValue);
    });
    bootstrapState.set("Connecting to Tor network...");
    p2PService.getNetworkNode().addConnectionListener(new ConnectionListener() {

        @Override
        public void onConnection(Connection connection) {
        }

        @Override
        public void onDisconnect(CloseConnectionReason closeConnectionReason, Connection connection) {
            // Other disconnects might be caused by peers running an older version
            if (connection.getPeerType() == Connection.PeerType.SEED_NODE && closeConnectionReason == CloseConnectionReason.RULE_VIOLATION) {
                log.warn("RULE_VIOLATION onDisconnect closeConnectionReason=" + closeConnectionReason);
                log.warn("RULE_VIOLATION onDisconnect connection=" + connection);
            //TODO
            /* new Popup()
                            .warning("You got disconnected from a seed node.\n\n" +
                                    "Reason for getting disconnected: " + connection.getRuleViolation().name() + "\n\n" +
                                    "It might be that your installed version is not compatible with " +
                                    "the network.\n\n" +
                                    "Please check if you run the latest software version.\n" +
                                    "You can download the latest version of Bitsquare at:\n" +
                                    "https://github.com/bitsquare/bitsquare/releases")
                            .show();*/
            }
        }

        @Override
        public void onError(Throwable throwable) {
        }
    });
    final BooleanProperty p2pNetworkInitialized = new SimpleBooleanProperty();
    p2PService.start(new P2PServiceListener() {

        @Override
        public void onTorNodeReady() {
            bootstrapState.set("Tor node created");
            p2PNetworkIconId.set("image-connection-tor");
            if (preferences.getUseTorForBitcoinJ())
                initWalletService();
        }

        @Override
        public void onHiddenServicePublished() {
            hiddenServicePublished.set(true);
            bootstrapState.set("Hidden Service published");
        }

        @Override
        public void onRequestingDataCompleted() {
            initialP2PNetworkDataReceived.set(true);
            bootstrapState.set("Initial data received");
            splashP2PNetworkAnimationVisible.set(false);
            p2pNetworkInitialized.set(true);
        }

        @Override
        public void onNoSeedNodeAvailable() {
            if (p2PService.getNumConnectedPeers().get() == 0)
                bootstrapWarning.set("No seed nodes available");
            else
                bootstrapWarning.set(null);
            splashP2PNetworkAnimationVisible.set(false);
            p2pNetworkInitialized.set(true);
        }

        @Override
        public void onNoPeersAvailable() {
            if (p2PService.getNumConnectedPeers().get() == 0) {
                p2pNetworkWarnMsg.set("There are no seed nodes or persisted peers available for requesting data.\n" + "Please check your internet connection or try to restart the application.");
                bootstrapWarning.set("No seed nodes and peers available");
                p2pNetworkLabelId.set("splash-error-state-msg");
            } else {
                bootstrapWarning.set(null);
                p2pNetworkLabelId.set("footer-pane");
            }
            splashP2PNetworkAnimationVisible.set(false);
            p2pNetworkInitialized.set(true);
        }

        @Override
        public void onBootstrapComplete() {
            splashP2PNetworkAnimationVisible.set(false);
            bootstrapComplete.set(true);
        }

        @Override
        public void onSetupFailed(Throwable throwable) {
            p2pNetworkWarnMsg.set("Connecting to the P2P network failed (reported error: " + throwable.getMessage() + ").\n" + "Please check your internet connection or try to restart the application.");
            splashP2PNetworkAnimationVisible.set(false);
            bootstrapWarning.set("Bootstrapping to P2P network failed");
            p2pNetworkLabelId.set("splash-error-state-msg");
        }
    });
    return p2pNetworkInitialized;
}
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) Connection(io.bitsquare.p2p.network.Connection) P2PServiceListener(io.bitsquare.p2p.P2PServiceListener) CloseConnectionReason(io.bitsquare.p2p.network.CloseConnectionReason) ConnectionListener(io.bitsquare.p2p.network.ConnectionListener)

Example 7 with Connection

use of io.bitsquare.p2p.network.Connection in project bitsquare by bitsquare.

the class MainViewModel method initWalletService.

private void initWalletService() {
    Log.traceCall();
    ObjectProperty<Throwable> walletServiceException = new SimpleObjectProperty<>();
    btcInfoBinding = EasyBind.combine(walletService.downloadPercentageProperty(), walletService.numPeersProperty(), walletServiceException, (downloadPercentage, numPeers, exception) -> {
        String result = "";
        if (exception == null) {
            double percentage = (double) downloadPercentage;
            int peers = (int) numPeers;
            String numPeersString = "Bitcoin network peers: " + peers;
            btcSyncProgress.set(percentage);
            if (percentage == 1) {
                result = numPeersString + " / synchronized with " + btcNetworkAsString;
                btcSplashSyncIconId.set("image-connection-synced");
            } else if (percentage > 0.0) {
                result = numPeersString + " / synchronizing with " + btcNetworkAsString + ": " + formatter.formatToPercentWithSymbol(percentage);
            } else {
                result = numPeersString + " / connecting to " + btcNetworkAsString;
            }
        } else {
            result = "Bitcoin network peers: " + numBtcPeers + " / connecting to " + btcNetworkAsString + " failed";
            if (exception instanceof TimeoutException) {
                walletServiceErrorMsg.set("Connecting to the bitcoin network failed because of a timeout.");
            } else if (exception.getCause() instanceof BlockStoreException) {
                log.error(exception.getMessage());
                // Ugly, but no other way to cover that specific case
                if (exception.getMessage().equals("Store file is already locked by another process"))
                    new Popup().warning("Bitsquare is already running. You cannot run two instances of Bitsquare.").closeButtonText("Shut down").onClose(BitsquareApp.shutDownHandler::run).show();
                else
                    new Popup().error("Cannot open wallet because of an exception:\n" + exception.getMessage()).show();
            } else if (exception.getMessage() != null) {
                walletServiceErrorMsg.set("Connection to the bitcoin network failed because of an error:" + exception.getMessage());
            } else {
                walletServiceErrorMsg.set("Connection to the bitcoin network failed because of an error:" + exception.toString());
            }
        }
        return result;
    });
    btcInfoBinding.subscribe((observable, oldValue, newValue) -> {
        btcInfo.set(newValue);
    });
    walletService.initialize(null, () -> {
        numBtcPeers = walletService.numPeersProperty().get();
        if (walletService.getWallet().isEncrypted()) {
            if (p2pNetWorkReady.get())
                splashP2PNetworkAnimationVisible.set(false);
            walletPasswordWindow.onAesKey(aesKey -> {
                walletService.setAesKey(aesKey);
                tradeWalletService.setAesKey(aesKey);
                walletInitialized.set(true);
            }).hideCloseButton().show();
        } else {
            walletInitialized.set(true);
        }
    }, walletServiceException::set);
}
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) BlockStoreException(org.bitcoinj.store.BlockStoreException) Popup(io.bitsquare.gui.main.overlays.popups.Popup) TimeoutException(java.util.concurrent.TimeoutException)

Example 8 with Connection

use of io.bitsquare.p2p.network.Connection in project bitsquare by bitsquare.

the class BroadcastHandler method broadcast.

///////////////////////////////////////////////////////////////////////////////////////////
// API
///////////////////////////////////////////////////////////////////////////////////////////
public void broadcast(BroadcastMessage message, @Nullable NodeAddress sender, ResultHandler resultHandler, @Nullable Listener listener, boolean isDataOwner) {
    this.message = message;
    this.resultHandler = resultHandler;
    this.listener = listener;
    Log.traceCall("Sender=" + sender + "\n\t" + "Message=" + Utilities.toTruncatedString(message));
    Set<Connection> connectedPeersSet = networkNode.getConfirmedConnections().stream().filter(connection -> !connection.getPeersNodeAddressOptional().get().equals(sender)).collect(Collectors.toSet());
    if (!connectedPeersSet.isEmpty()) {
        numOfCompletedBroadcasts = 0;
        List<Connection> connectedPeersList = new ArrayList<>(connectedPeersSet);
        Collections.shuffle(connectedPeersList);
        numOfPeers = connectedPeersList.size();
        int delay = 50;
        if (!isDataOwner) {
            // for not data owner (relay nodes) we send to max. 7 nodes and use a longer delay
            numOfPeers = Math.min(7, connectedPeersList.size());
            delay = 100;
        }
        long timeoutDelay = TIMEOUT_PER_PEER_SEC * numOfPeers;
        timeoutTimer = UserThread.runAfter(() -> {
            // setup before sending to avoid race conditions
            String errorMessage = "Timeout: Broadcast did not complete after " + timeoutDelay + " sec.";
            log.debug(errorMessage + "\n\t" + "numOfPeers=" + numOfPeers + "\n\t" + "numOfCompletedBroadcasts=" + numOfCompletedBroadcasts + "\n\t" + "numOfCompletedBroadcasts=" + numOfCompletedBroadcasts + "\n\t" + "numOfFailedBroadcasts=" + numOfFailedBroadcasts);
            onFault(errorMessage, false);
        }, timeoutDelay);
        log.debug("Broadcast message to {} peers out of {} total connected peers.", numOfPeers, connectedPeersSet.size());
        for (int i = 0; i < numOfPeers; i++) {
            if (stopped)
                // do not continue sending after a timeout or a cancellation
                break;
            final long minDelay = (i + 1) * delay;
            final long maxDelay = (i + 2) * delay;
            final Connection connection = connectedPeersList.get(i);
            UserThread.runAfterRandomDelay(() -> sendToPeer(connection, message), minDelay, maxDelay, TimeUnit.MILLISECONDS);
        }
    } else {
        onFault("Message not broadcasted because we have no available peers yet.\n\t" + "message = " + Utilities.toTruncatedString(message), false);
    }
}
Also used : java.util(java.util) Utilities(io.bitsquare.common.util.Utilities) Logger(org.slf4j.Logger) UserThread(io.bitsquare.common.UserThread) LoggerFactory(org.slf4j.LoggerFactory) NodeAddress(io.bitsquare.p2p.NodeAddress) Connection(io.bitsquare.p2p.network.Connection) Timer(io.bitsquare.common.Timer) SettableFuture(com.google.common.util.concurrent.SettableFuture) Collectors(java.util.stream.Collectors) FutureCallback(com.google.common.util.concurrent.FutureCallback) BroadcastMessage(io.bitsquare.p2p.storage.messages.BroadcastMessage) TimeUnit(java.util.concurrent.TimeUnit) Nullable(org.jetbrains.annotations.Nullable) Futures(com.google.common.util.concurrent.Futures) NotNull(org.jetbrains.annotations.NotNull) NetworkNode(io.bitsquare.p2p.network.NetworkNode) Log(io.bitsquare.app.Log) Connection(io.bitsquare.p2p.network.Connection)

Example 9 with Connection

use of io.bitsquare.p2p.network.Connection in project bitsquare by bitsquare.

the class GetDataRequestHandler method handle.

///////////////////////////////////////////////////////////////////////////////////////////
// API
///////////////////////////////////////////////////////////////////////////////////////////
public void handle(GetDataRequest getDataRequest, final Connection connection) {
    Log.traceCall(getDataRequest + "\n\tconnection=" + connection);
    final HashSet<ProtectedStorageEntry> filteredDataSet = new HashSet<>();
    final Set<Integer> lookupSet = new HashSet<>();
    Set<P2PDataStorage.ByteArray> excludedItems = getDataRequest.getExcludedKeys() != null ? getDataRequest.getExcludedKeys().stream().map(P2PDataStorage.ByteArray::new).collect(Collectors.toSet()) : new HashSet<>();
    for (ProtectedStorageEntry protectedStorageEntry : dataStorage.getFilteredValues(excludedItems)) {
        final StoragePayload storagePayload = protectedStorageEntry.getStoragePayload();
        boolean doAdd = false;
        if (storagePayload instanceof CapabilityRequiringPayload) {
            final List<Integer> requiredCapabilities = ((CapabilityRequiringPayload) storagePayload).getRequiredCapabilities();
            final List<Integer> supportedCapabilities = connection.getSupportedCapabilities();
            if (supportedCapabilities != null) {
                for (int messageCapability : requiredCapabilities) {
                    for (int connectionCapability : supportedCapabilities) {
                        if (messageCapability == connectionCapability) {
                            doAdd = true;
                            break;
                        }
                    }
                }
                if (!doAdd)
                    log.debug("We do not send the message to the peer because he does not support the required capability for that message type.\n" + "Required capabilities is: " + requiredCapabilities.toString() + "\n" + "Supported capabilities is: " + supportedCapabilities.toString() + "\n" + "storagePayload is: " + Utilities.toTruncatedString(storagePayload));
            } else {
                log.debug("We do not send the message to the peer because he uses an old version which does not support capabilities.\n" + "Required capabilities is: " + requiredCapabilities.toString() + "\n" + "storagePayload is: " + Utilities.toTruncatedString(storagePayload));
            }
        } else {
            doAdd = true;
        }
        if (doAdd) {
            // We have TradeStatistic data of both traders but we only send 1 item, 
            // so we use lookupSet as for a fast lookup. Using filteredDataSet would require a loop as it stores 
            // protectedStorageEntry not storagePayload. protectedStorageEntry is different for both traders but storagePayload not, 
            // as we ignore the pubKey and data there in the hashCode method.
            boolean notContained = lookupSet.add(storagePayload.hashCode());
            if (notContained)
                filteredDataSet.add(protectedStorageEntry);
        }
    }
    GetDataResponse getDataResponse = new GetDataResponse(filteredDataSet, getDataRequest.getNonce(), getDataRequest instanceof GetUpdatedDataRequest);
    if (timeoutTimer == null) {
        timeoutTimer = UserThread.runAfter(() -> {
            // setup before sending to avoid race conditions
            String errorMessage = "A timeout occurred for getDataResponse:" + getDataResponse + " on connection:" + connection;
            handleFault(errorMessage, CloseConnectionReason.SEND_MSG_TIMEOUT, connection);
        }, TIME_OUT_SEC, TimeUnit.SECONDS);
    }
    SettableFuture<Connection> future = networkNode.sendMessage(connection, getDataResponse);
    Futures.addCallback(future, new FutureCallback<Connection>() {

        @Override
        public void onSuccess(Connection connection) {
            if (!stopped) {
                log.trace("Send DataResponse to {} succeeded. getDataResponse={}", connection.getPeersNodeAddressOptional(), getDataResponse);
                cleanup();
                listener.onComplete();
            } else {
                log.trace("We have stopped already. We ignore that networkNode.sendMessage.onSuccess call.");
            }
        }

        @Override
        public void onFailure(@NotNull Throwable throwable) {
            if (!stopped) {
                String errorMessage = "Sending getDataRequest to " + connection + " failed. That is expected if the peer is offline. getDataResponse=" + getDataResponse + "." + "Exception: " + throwable.getMessage();
                handleFault(errorMessage, CloseConnectionReason.SEND_MSG_FAILURE, connection);
            } else {
                log.trace("We have stopped already. We ignore that networkNode.sendMessage.onFailure call.");
            }
        }
    });
}
Also used : Connection(io.bitsquare.p2p.network.Connection) CapabilityRequiringPayload(io.bitsquare.p2p.storage.payload.CapabilityRequiringPayload) GetDataResponse(io.bitsquare.p2p.peers.getdata.messages.GetDataResponse) GetUpdatedDataRequest(io.bitsquare.p2p.peers.getdata.messages.GetUpdatedDataRequest) StoragePayload(io.bitsquare.p2p.storage.payload.StoragePayload) HashSet(java.util.HashSet) ProtectedStorageEntry(io.bitsquare.p2p.storage.storageentry.ProtectedStorageEntry)

Example 10 with Connection

use of io.bitsquare.p2p.network.Connection in project bitsquare by bitsquare.

the class GetPeersRequestHandler method handle.

///////////////////////////////////////////////////////////////////////////////////////////
// API
///////////////////////////////////////////////////////////////////////////////////////////
public void handle(GetPeersRequest getPeersRequest, final Connection connection) {
    Log.traceCall("getPeersRequest=" + getPeersRequest + "\n\tconnection=" + connection + "\n\tthis=" + this);
    checkArgument(connection.getPeersNodeAddressOptional().isPresent(), "The peers address must have been already set at the moment");
    GetPeersResponse getPeersResponse = new GetPeersResponse(getPeersRequest.nonce, peerManager.getConnectedNonSeedNodeReportedPeers(connection.getPeersNodeAddressOptional().get()));
    checkArgument(timeoutTimer == null, "onGetPeersRequest must not be called twice.");
    timeoutTimer = UserThread.runAfter(() -> {
        // setup before sending to avoid race conditions
        if (!stopped) {
            String errorMessage = "A timeout occurred at sending getPeersResponse:" + getPeersResponse + " on connection:" + connection;
            log.debug(errorMessage + " / PeerExchangeHandshake=" + GetPeersRequestHandler.this);
            log.debug("timeoutTimer called. this=" + this);
            handleFault(errorMessage, CloseConnectionReason.SEND_MSG_TIMEOUT, connection);
        } else {
            log.trace("We have stopped already. We ignore that timeoutTimer.run call.");
        }
    }, TIME_OUT_SEC, TimeUnit.SECONDS);
    SettableFuture<Connection> future = networkNode.sendMessage(connection, getPeersResponse);
    Futures.addCallback(future, new FutureCallback<Connection>() {

        @Override
        public void onSuccess(Connection connection) {
            if (!stopped) {
                log.trace("GetPeersResponse sent successfully");
                cleanup();
                listener.onComplete();
            } else {
                log.trace("We have stopped already. We ignore that networkNode.sendMessage.onSuccess call.");
            }
        }

        @Override
        public void onFailure(@NotNull Throwable throwable) {
            if (!stopped) {
                String errorMessage = "Sending getPeersResponse to " + connection + " failed. That is expected if the peer is offline. getPeersResponse=" + getPeersResponse + "." + "Exception: " + throwable.getMessage();
                log.debug(errorMessage);
                handleFault(errorMessage, CloseConnectionReason.SEND_MSG_FAILURE, connection);
            } else {
                log.trace("We have stopped already. We ignore that networkNode.sendMessage.onFailure call.");
            }
        }
    });
    peerManager.addToReportedPeers(getPeersRequest.reportedPeers, connection);
}
Also used : GetPeersResponse(io.bitsquare.p2p.peers.peerexchange.messages.GetPeersResponse) Connection(io.bitsquare.p2p.network.Connection)

Aggregations

Connection (io.bitsquare.p2p.network.Connection)10 Log (io.bitsquare.app.Log)4 Timer (io.bitsquare.common.Timer)4 UserThread (io.bitsquare.common.UserThread)4 java.util (java.util)4 TimeUnit (java.util.concurrent.TimeUnit)4 Collectors (java.util.stream.Collectors)4 Logger (org.slf4j.Logger)4 LoggerFactory (org.slf4j.LoggerFactory)4 Inject (com.google.inject.Inject)2 Alert (io.bitsquare.alert.Alert)2 AlertManager (io.bitsquare.alert.AlertManager)2 PrivateNotification (io.bitsquare.alert.PrivateNotification)2 PrivateNotificationManager (io.bitsquare.alert.PrivateNotificationManager)2 BitsquareApp (io.bitsquare.app.BitsquareApp)2 DevFlags (io.bitsquare.app.DevFlags)2 Version (io.bitsquare.app.Version)2 ArbitratorManager (io.bitsquare.arbitration.ArbitratorManager)2 Dispute (io.bitsquare.arbitration.Dispute)2 DisputeManager (io.bitsquare.arbitration.DisputeManager)2