Search in sources :

Example 1 with Connection

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

the class PeerExchangeHandler method sendGetPeersRequest.

private void sendGetPeersRequest(NodeAddress nodeAddress) {
    Log.traceCall("nodeAddress=" + nodeAddress + " / this=" + this);
    if (!stopped) {
        if (networkNode.getNodeAddress() != null) {
            GetPeersRequest getPeersRequest = new GetPeersRequest(networkNode.getNodeAddress(), nonce, peerManager.getConnectedNonSeedNodeReportedPeers(nodeAddress));
            if (timeoutTimer == null) {
                timeoutTimer = UserThread.runAfter(() -> {
                    // setup before sending to avoid race conditions
                    if (!stopped) {
                        String errorMessage = "A timeout occurred at sending getPeersRequest:" + getPeersRequest + " for nodeAddress:" + nodeAddress;
                        log.debug(errorMessage + " / PeerExchangeHandler=" + PeerExchangeHandler.this);
                        log.debug("timeoutTimer called on " + this);
                        handleFault(errorMessage, CloseConnectionReason.SEND_MSG_TIMEOUT, nodeAddress);
                    } else {
                        log.trace("We have stopped that handler already. We ignore that timeoutTimer.run call.");
                    }
                }, TIME_OUT_SEC, TimeUnit.SECONDS);
            }
            SettableFuture<Connection> future = networkNode.sendMessage(nodeAddress, getPeersRequest);
            Futures.addCallback(future, new FutureCallback<Connection>() {

                @Override
                public void onSuccess(Connection connection) {
                    if (!stopped) {
                        //TODO
                        /*if (!connection.getPeersNodeAddressOptional().isPresent()) {
                                connection.setPeersNodeAddress(nodeAddress);
                                log.warn("sendGetPeersRequest: !connection.getPeersNodeAddressOptional().isPresent()");
                            }*/
                        PeerExchangeHandler.this.connection = connection;
                        connection.addMessageListener(PeerExchangeHandler.this);
                        log.trace("Send " + getPeersRequest + " to " + nodeAddress + " succeeded.");
                    } else {
                        log.trace("We have stopped that handler already. We ignore that sendGetPeersRequest.onSuccess call.");
                    }
                }

                @Override
                public void onFailure(@NotNull Throwable throwable) {
                    if (!stopped) {
                        String errorMessage = "Sending getPeersRequest to " + nodeAddress + " failed. That is expected if the peer is offline.\n\tgetPeersRequest=" + getPeersRequest + ".\n\tException=" + throwable.getMessage();
                        log.debug(errorMessage);
                        handleFault(errorMessage, CloseConnectionReason.SEND_MSG_FAILURE, nodeAddress);
                    } else {
                        log.trace("We have stopped that handler already. We ignore that sendGetPeersRequest.onFailure call.");
                    }
                }
            });
        } else {
            log.debug("My node address is still null at sendGetPeersRequest. We ignore that call.");
        }
    } else {
        log.trace("We have stopped that handler already. We ignore that sendGetPeersRequest call.");
    }
}
Also used : Connection(io.bitsquare.p2p.network.Connection) GetPeersRequest(io.bitsquare.p2p.peers.peerexchange.messages.GetPeersRequest)

Example 2 with Connection

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

the class TakeOfferViewModel method createListeners.

private void createListeners() {
    amountListener = (ov, oldValue, newValue) -> {
        if (isBtcInputValid(newValue).isValid) {
            setAmountToModel();
            calculateVolume();
            dataModel.calculateTotalToPay();
        }
        updateButtonDisableState();
    };
    amountAsCoinListener = (ov, oldValue, newValue) -> amount.set(formatter.formatCoin(newValue));
    isWalletFundedListener = (ov, oldValue, newValue) -> {
        updateButtonDisableState();
    };
    tradeStateListener = (ov, oldValue, newValue) -> applyTradeState(newValue);
    tradeErrorListener = (ov, oldValue, newValue) -> applyTradeErrorMessage(newValue);
    offerStateListener = (ov, oldValue, newValue) -> applyOfferState(newValue);
    connectionListener = new ConnectionListener() {

        @Override
        public void onDisconnect(CloseConnectionReason closeConnectionReason, Connection connection) {
            if (connection.getPeersNodeAddressOptional().isPresent() && connection.getPeersNodeAddressOptional().get().equals(offer.getOffererNodeAddress())) {
                offerWarning.set("You lost connection to the offerer.\n" + "He might have gone offline or has closed the connection to you because of too " + "many open connections.\n\n" + "If you can still see his offer in the offerbook you can try to take the offer again.");
                updateSpinnerInfo();
            }
        }

        @Override
        public void onConnection(Connection connection) {
        }

        @Override
        public void onError(Throwable throwable) {
        }
    };
}
Also used : Connection(io.bitsquare.p2p.network.Connection) CloseConnectionReason(io.bitsquare.p2p.network.CloseConnectionReason) ConnectionListener(io.bitsquare.p2p.network.ConnectionListener)

Example 3 with Connection

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

the class RequestDataHandler method requestData.

///////////////////////////////////////////////////////////////////////////////////////////
// API
///////////////////////////////////////////////////////////////////////////////////////////
public void requestData(NodeAddress nodeAddress, boolean isPreliminaryDataRequest) {
    Log.traceCall("nodeAddress=" + nodeAddress);
    peersNodeAddress = nodeAddress;
    if (!stopped) {
        GetDataRequest getDataRequest;
        // We collect the keys of the PersistedStoragePayload items so we exclude them in our request.
        // PersistedStoragePayload items don't get removed, so we don't have an issue with the case that
        // an object gets removed in between PreliminaryGetDataRequest and the GetUpdatedDataRequest and we would 
        // miss that event if we do not load the full set or use some delta handling.
        Set<byte[]> excludedKeys = dataStorage.getMap().entrySet().stream().filter(e -> e.getValue().getStoragePayload() instanceof PersistedStoragePayload).map(e -> e.getKey().bytes).collect(Collectors.toSet());
        if (isPreliminaryDataRequest)
            getDataRequest = new PreliminaryGetDataRequest(nonce, excludedKeys);
        else
            getDataRequest = new GetUpdatedDataRequest(networkNode.getNodeAddress(), nonce, excludedKeys);
        if (timeoutTimer == null) {
            timeoutTimer = UserThread.runAfter(() -> {
                // setup before sending to avoid race conditions
                if (!stopped) {
                    String errorMessage = "A timeout occurred at sending getDataRequest:" + getDataRequest + " on nodeAddress:" + nodeAddress;
                    log.debug(errorMessage + " / RequestDataHandler=" + RequestDataHandler.this);
                    handleFault(errorMessage, nodeAddress, CloseConnectionReason.SEND_MSG_TIMEOUT);
                } else {
                    log.trace("We have stopped already. We ignore that timeoutTimer.run call. " + "Might be caused by an previous networkNode.sendMessage.onFailure.");
                }
            }, TIME_OUT_SEC);
        }
        log.debug("We send a {} to peer {}. ", getDataRequest.getClass().getSimpleName(), nodeAddress);
        networkNode.addMessageListener(this);
        SettableFuture<Connection> future = networkNode.sendMessage(nodeAddress, getDataRequest);
        Futures.addCallback(future, new FutureCallback<Connection>() {

            @Override
            public void onSuccess(Connection connection) {
                if (!stopped) {
                    RequestDataHandler.this.connection = connection;
                    log.trace("Send " + getDataRequest + " to " + nodeAddress + " succeeded.");
                } else {
                    log.trace("We have stopped already. We ignore that networkNode.sendMessage.onSuccess call." + "Might be caused by an previous timeout.");
                }
            }

            @Override
            public void onFailure(@NotNull Throwable throwable) {
                if (!stopped) {
                    String errorMessage = "Sending getDataRequest to " + nodeAddress + " failed. That is expected if the peer is offline.\n\t" + "getDataRequest=" + getDataRequest + "." + "\n\tException=" + throwable.getMessage();
                    log.debug(errorMessage);
                    handleFault(errorMessage, nodeAddress, CloseConnectionReason.SEND_MSG_FAILURE);
                } else {
                    log.trace("We have stopped already. We ignore that networkNode.sendMessage.onFailure call. " + "Might be caused by an previous timeout.");
                }
            }
        });
    } else {
        log.warn("We have stopped already. We ignore that requestData call.");
    }
}
Also used : java.util(java.util) ProtectedStorageEntry(io.bitsquare.p2p.storage.storageentry.ProtectedStorageEntry) LoggerFactory(org.slf4j.LoggerFactory) Connection(io.bitsquare.p2p.network.Connection) Timer(io.bitsquare.common.Timer) SettableFuture(com.google.common.util.concurrent.SettableFuture) GetDataRequest(io.bitsquare.p2p.peers.getdata.messages.GetDataRequest) PreliminaryGetDataRequest(io.bitsquare.p2p.peers.getdata.messages.PreliminaryGetDataRequest) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) PersistedStoragePayload(io.bitsquare.p2p.storage.payload.PersistedStoragePayload) PeerManager(io.bitsquare.p2p.peers.PeerManager) Log(io.bitsquare.app.Log) P2PDataStorage(io.bitsquare.p2p.storage.P2PDataStorage) GetUpdatedDataRequest(io.bitsquare.p2p.peers.getdata.messages.GetUpdatedDataRequest) Logger(org.slf4j.Logger) GetDataResponse(io.bitsquare.p2p.peers.getdata.messages.GetDataResponse) UserThread(io.bitsquare.common.UserThread) Message(io.bitsquare.p2p.Message) NodeAddress(io.bitsquare.p2p.NodeAddress) StoragePayload(io.bitsquare.p2p.storage.payload.StoragePayload) Collectors(java.util.stream.Collectors) FutureCallback(com.google.common.util.concurrent.FutureCallback) TimeUnit(java.util.concurrent.TimeUnit) Nullable(org.jetbrains.annotations.Nullable) Futures(com.google.common.util.concurrent.Futures) LazyProcessedStoragePayload(io.bitsquare.p2p.storage.payload.LazyProcessedStoragePayload) MessageListener(io.bitsquare.p2p.network.MessageListener) CloseConnectionReason(io.bitsquare.p2p.network.CloseConnectionReason) NotNull(org.jetbrains.annotations.NotNull) NetworkNode(io.bitsquare.p2p.network.NetworkNode) PreliminaryGetDataRequest(io.bitsquare.p2p.peers.getdata.messages.PreliminaryGetDataRequest) PersistedStoragePayload(io.bitsquare.p2p.storage.payload.PersistedStoragePayload) Connection(io.bitsquare.p2p.network.Connection) GetDataRequest(io.bitsquare.p2p.peers.getdata.messages.GetDataRequest) PreliminaryGetDataRequest(io.bitsquare.p2p.peers.getdata.messages.PreliminaryGetDataRequest) GetUpdatedDataRequest(io.bitsquare.p2p.peers.getdata.messages.GetUpdatedDataRequest)

Example 4 with Connection

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

the class KeepAliveHandler method sendPing.

private void sendPing(Connection connection) {
    Log.traceCall("connection=" + connection + " / this=" + this);
    if (!stopped) {
        Ping ping = new Ping(nonce, connection.getStatistic().roundTripTimeProperty().get());
        sendTs = System.currentTimeMillis();
        SettableFuture<Connection> future = networkNode.sendMessage(connection, ping);
        Futures.addCallback(future, new FutureCallback<Connection>() {

            @Override
            public void onSuccess(Connection connection) {
                if (!stopped) {
                    log.trace("Send " + ping + " to " + connection + " succeeded.");
                    KeepAliveHandler.this.connection = connection;
                    connection.addMessageListener(KeepAliveHandler.this);
                } 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 ping to " + connection + " failed. That is expected if the peer is offline.\n\tping=" + ping + ".\n\tException=" + throwable.getMessage();
                    log.debug(errorMessage);
                    cleanup();
                    //peerManager.shutDownConnection(connection, CloseConnectionReason.SEND_MSG_FAILURE);
                    peerManager.handleConnectionFault(connection);
                    listener.onFault(errorMessage);
                } else {
                    log.trace("We have stopped already. We ignore that networkNode.sendMessage.onFailure call.");
                }
            }
        });
    } else {
        log.trace("We have stopped already. We ignore that sendPing call.");
    }
}
Also used : Ping(io.bitsquare.p2p.peers.keepalive.messages.Ping) Connection(io.bitsquare.p2p.network.Connection)

Example 5 with Connection

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

the class BroadcastHandler method sendToPeer.

private void sendToPeer(Connection connection, BroadcastMessage message) {
    String errorMessage = "Message not broadcasted because we have stopped the handler already.\n\t" + "message = " + Utilities.toTruncatedString(message);
    if (!stopped) {
        if (!connection.isStopped()) {
            if (!connection.isCapabilityRequired(message) || connection.isCapabilitySupported(message)) {
                NodeAddress nodeAddress = connection.getPeersNodeAddressOptional().get();
                log.trace("Broadcast message to " + nodeAddress + ".");
                SettableFuture<Connection> future = networkNode.sendMessage(connection, message);
                Futures.addCallback(future, new FutureCallback<Connection>() {

                    @Override
                    public void onSuccess(Connection connection) {
                        numOfCompletedBroadcasts++;
                        if (!stopped) {
                            log.trace("Broadcast to " + nodeAddress + " succeeded.");
                            if (listener != null)
                                listener.onBroadcasted(message, numOfCompletedBroadcasts);
                            if (listener != null && numOfCompletedBroadcasts == 1)
                                listener.onBroadcastedToFirstPeer(message);
                            if (numOfCompletedBroadcasts + numOfFailedBroadcasts == numOfPeers) {
                                if (listener != null)
                                    listener.onBroadcastCompleted(message, numOfCompletedBroadcasts, numOfFailedBroadcasts);
                                cleanup();
                                resultHandler.onCompleted(BroadcastHandler.this);
                            }
                        } else {
                            // TODO investigate why that is called very often at seed nodes
                            onFault("stopped at onSuccess: " + errorMessage, false);
                        }
                    }

                    @Override
                    public void onFailure(@NotNull Throwable throwable) {
                        numOfFailedBroadcasts++;
                        if (!stopped) {
                            log.debug("Broadcast to " + nodeAddress + " failed.\n\t" + "ErrorMessage=" + throwable.getMessage());
                            if (numOfCompletedBroadcasts + numOfFailedBroadcasts == numOfPeers)
                                onFault("stopped at onFailure: " + errorMessage);
                        } else {
                            onFault("stopped at onFailure: " + errorMessage);
                        }
                    }
                });
            }
        } else {
            onFault("Connection stopped already", false);
        }
    } else {
        onFault("stopped at sendToPeer: " + errorMessage, false);
    }
}
Also used : Connection(io.bitsquare.p2p.network.Connection) NodeAddress(io.bitsquare.p2p.NodeAddress)

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