Search in sources :

Example 1 with Ping

use of io.bitsquare.p2p.peers.keepalive.messages.Ping 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 2 with Ping

use of io.bitsquare.p2p.peers.keepalive.messages.Ping in project bitsquare by bitsquare.

the class MainViewModel method onAllServicesInitialized.

private void onAllServicesInitialized() {
    Log.traceCall();
    clock.start();
    // disputeManager
    disputeManager.onAllServicesInitialized();
    disputeManager.getDisputesAsObservableList().addListener((ListChangeListener<Dispute>) change -> {
        change.next();
        onDisputesChangeListener(change.getAddedSubList(), change.getRemoved());
    });
    onDisputesChangeListener(disputeManager.getDisputesAsObservableList(), null);
    // tradeManager
    tradeManager.onAllServicesInitialized();
    tradeManager.getTrades().addListener((ListChangeListener<Trade>) c -> updateBalance());
    tradeManager.getTrades().addListener((ListChangeListener<Trade>) change -> onTradesChanged());
    onTradesChanged();
    // We handle the trade period here as we display a global popup if we reached dispute time
    tradesAndUIReady = EasyBind.combine(isSplashScreenRemoved, tradeManager.pendingTradesInitializedProperty(), (a, b) -> a && b);
    tradesAndUIReady.subscribe((observable, oldValue, newValue) -> {
        if (newValue)
            applyTradePeriodState();
    });
    // walletService
    walletService.addBalanceListener(new BalanceListener() {

        @Override
        public void onBalanceChanged(Coin balance, Transaction tx) {
            updateBalance();
        }
    });
    openOfferManager.getOpenOffers().addListener((ListChangeListener<OpenOffer>) c -> updateBalance());
    tradeManager.getTrades().addListener((ListChangeListener<Trade>) c -> updateBalance());
    openOfferManager.onAllServicesInitialized();
    arbitratorManager.onAllServicesInitialized();
    alertManager.alertMessageProperty().addListener((observable, oldValue, newValue) -> displayAlertIfPresent(newValue));
    privateNotificationManager.privateNotificationProperty().addListener((observable, oldValue, newValue) -> displayPrivateNotification(newValue));
    displayAlertIfPresent(alertManager.alertMessageProperty().get());
    p2PService.onAllServicesInitialized();
    setupBtcNumPeersWatcher();
    setupP2PNumPeersWatcher();
    updateBalance();
    if (DevFlags.DEV_MODE) {
        preferences.setShowOwnOffersInOfferBook(true);
        if (user.getPaymentAccounts().isEmpty())
            setupDevDummyPaymentAccounts();
    }
    setupMarketPriceFeed();
    swapPendingOfferFundingEntries();
    fillPriceFeedComboBoxItems();
    showAppScreen.set(true);
    // We want to test if the client is compiled with the correct crypto provider (BountyCastle) 
    // and if the unlimited Strength for cryptographic keys is set.
    // If users compile themselves they might miss that step and then would get an exception in the trade.
    // To avoid that we add here at startup a sample encryption and signing to see if it don't causes an exception.
    // See: https://github.com/bitsquare/bitsquare/blob/master/doc/build.md#7-enable-unlimited-strength-for-cryptographic-keys
    Thread checkCryptoThread = new Thread() {

        @Override
        public void run() {
            try {
                Thread.currentThread().setName("checkCryptoThread");
                log.trace("Run crypto test");
                // just use any simple dummy msg
                io.bitsquare.p2p.peers.keepalive.messages.Ping payload = new Ping(1, 1);
                SealedAndSigned sealedAndSigned = Encryption.encryptHybridWithSignature(payload, keyRing.getSignatureKeyPair(), keyRing.getPubKeyRing().getEncryptionPubKey());
                DecryptedDataTuple tuple = Encryption.decryptHybridWithSignature(sealedAndSigned, keyRing.getEncryptionKeyPair().getPrivate());
                if (tuple.payload instanceof Ping && ((Ping) tuple.payload).nonce == payload.nonce && ((Ping) tuple.payload).lastRoundTripTime == payload.lastRoundTripTime)
                    log.debug("Crypto test succeeded");
                else
                    throw new CryptoException("Payload not correct after decryption");
            } catch (CryptoException e) {
                e.printStackTrace();
                String msg = "Seems that you use a self compiled binary and have not following the build " + "instructions in https://github.com/bitsquare/bitsquare/blob/master/doc/build.md#7-enable-unlimited-strength-for-cryptographic-keys.\n\n" + "If that is not the case and you use the official Bitsquare binary, " + "please file a bug report to the Github page.\n" + "Error=" + e.getMessage();
                log.error(msg);
                UserThread.execute(() -> new Popup<>().warning(msg).actionButtonText("Shut down").onAction(BitsquareApp.shutDownHandler::run).closeButtonText("Report bug at Github issues").onClose(() -> GUIUtil.openWebPage("https://github.com/bitsquare/bitsquare/issues")).show());
            }
        }
    };
    checkCryptoThread.start();
    if (Security.getProvider("BC") == null) {
        new Popup<>().warning("There is a problem with the crypto libraries. BountyCastle is not available.").actionButtonText("Shut down").onAction(BitsquareApp.shutDownHandler::run).closeButtonText("Report bug at Github issues").onClose(() -> GUIUtil.openWebPage("https://github.com/bitsquare/bitsquare/issues")).show();
    }
    String remindPasswordAndBackupKey = "remindPasswordAndBackup";
    user.getPaymentAccountsAsObservable().addListener((SetChangeListener<PaymentAccount>) change -> {
        if (!walletService.getWallet().isEncrypted() && preferences.showAgain(remindPasswordAndBackupKey) && change.wasAdded()) {
            new Popup<>().headLine("Important security recommendation").information("We would like to remind you to consider using password protection for your wallet if you have not already enabled that.\n\n" + "It is also highly recommended to write down the wallet seed words. Those seed words are like a master password for recovering your Bitcoin wallet.\n" + "At the \"Wallet Seed\" section you find more information.\n\n" + "Additionally you can backup the complete application data folder at the \"Backup\" section.\n" + "Please note, that this backup is not encrypted!").dontShowAgainId(remindPasswordAndBackupKey, preferences).show();
        }
    });
    checkIfOpenOffersMatchTradeProtocolVersion();
}
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) BalanceListener(io.bitsquare.btc.listeners.BalanceListener) PaymentAccount(io.bitsquare.payment.PaymentAccount) OpenOffer(io.bitsquare.trade.offer.OpenOffer) UserThread(io.bitsquare.common.UserThread) BitsquareApp(io.bitsquare.app.BitsquareApp) Trade(io.bitsquare.trade.Trade) Coin(org.bitcoinj.core.Coin) Transaction(org.bitcoinj.core.Transaction) Ping(io.bitsquare.p2p.peers.keepalive.messages.Ping) Popup(io.bitsquare.gui.main.overlays.popups.Popup) Dispute(io.bitsquare.arbitration.Dispute) Ping(io.bitsquare.p2p.peers.keepalive.messages.Ping)

Example 3 with Ping

use of io.bitsquare.p2p.peers.keepalive.messages.Ping in project bitsquare by bitsquare.

the class KeepAliveManager method onMessage.

///////////////////////////////////////////////////////////////////////////////////////////
// MessageListener implementation
///////////////////////////////////////////////////////////////////////////////////////////
@Override
public void onMessage(Message message, Connection connection) {
    if (message instanceof Ping) {
        Log.traceCall(message.toString() + "\n\tconnection=" + connection);
        if (!stopped) {
            Ping ping = (Ping) message;
            // We get from peer last measured rrt
            connection.getStatistic().setRoundTripTime(ping.lastRoundTripTime);
            Pong pong = new Pong(ping.nonce);
            SettableFuture<Connection> future = networkNode.sendMessage(connection, pong);
            Futures.addCallback(future, new FutureCallback<Connection>() {

                @Override
                public void onSuccess(Connection connection) {
                    log.trace("Pong sent successfully");
                }

                @Override
                public void onFailure(@NotNull Throwable throwable) {
                    if (!stopped) {
                        String errorMessage = "Sending pong to " + connection + " failed. That is expected if the peer is offline. pong=" + pong + "." + "Exception: " + throwable.getMessage();
                        log.debug(errorMessage);
                        peerManager.handleConnectionFault(connection);
                    } else {
                        log.warn("We have stopped already. We ignore that  networkNode.sendMessage.onFailure call.");
                    }
                }
            });
        } else {
            log.warn("We have stopped already. We ignore that onMessage call.");
        }
    }
}
Also used : Ping(io.bitsquare.p2p.peers.keepalive.messages.Ping) Pong(io.bitsquare.p2p.peers.keepalive.messages.Pong)

Aggregations

Ping (io.bitsquare.p2p.peers.keepalive.messages.Ping)3 Inject (com.google.inject.Inject)1 Alert (io.bitsquare.alert.Alert)1 AlertManager (io.bitsquare.alert.AlertManager)1 PrivateNotification (io.bitsquare.alert.PrivateNotification)1 PrivateNotificationManager (io.bitsquare.alert.PrivateNotificationManager)1 BitsquareApp (io.bitsquare.app.BitsquareApp)1 DevFlags (io.bitsquare.app.DevFlags)1 Log (io.bitsquare.app.Log)1 Version (io.bitsquare.app.Version)1 ArbitratorManager (io.bitsquare.arbitration.ArbitratorManager)1 Dispute (io.bitsquare.arbitration.Dispute)1 DisputeManager (io.bitsquare.arbitration.DisputeManager)1 AddressEntry (io.bitsquare.btc.AddressEntry)1 TradeWalletService (io.bitsquare.btc.TradeWalletService)1 WalletService (io.bitsquare.btc.WalletService)1 BalanceListener (io.bitsquare.btc.listeners.BalanceListener)1 MarketPrice (io.bitsquare.btc.pricefeed.MarketPrice)1 PriceFeedService (io.bitsquare.btc.pricefeed.PriceFeedService)1 Clock (io.bitsquare.common.Clock)1