Search in sources :

Example 1 with NodeAddress

use of io.bitsquare.p2p.NodeAddress in project bitsquare by bitsquare.

the class PeerManagerTest method test2SeedNodes.

@Test
public void test2SeedNodes() throws InterruptedException {
    LocalhostNetworkNode.setSimulateTorDelayTorNode(0);
    LocalhostNetworkNode.setSimulateTorDelayHiddenService(0);
    seedNodes = new HashSet<>();
    NodeAddress nodeAddress1 = new NodeAddress("localhost:8001");
    seedNodes.add(nodeAddress1);
    NodeAddress nodeAddress2 = new NodeAddress("localhost:8002");
    seedNodes.add(nodeAddress2);
    latch = new CountDownLatch(6);
    seedNode1 = new DummySeedNode("test_dummy_dir");
    seedNode1.createAndStartP2PService(nodeAddress1, MAX_CONNECTIONS, useLocalhost, 2, true, seedNodes, new P2PServiceListener() {

        @Override
        public void onRequestingDataCompleted() {
            latch.countDown();
        }

        @Override
        public void onNoSeedNodeAvailable() {
        }

        @Override
        public void onTorNodeReady() {
        }

        @Override
        public void onNoPeersAvailable() {
        }

        @Override
        public void onBootstrapComplete() {
            latch.countDown();
        }

        @Override
        public void onHiddenServicePublished() {
            latch.countDown();
        }

        @Override
        public void onSetupFailed(Throwable throwable) {
        }
    });
    P2PService p2PService1 = seedNode1.getSeedNodeP2PService();
    Thread.sleep(500);
    seedNode2 = new DummySeedNode("test_dummy_dir");
    seedNode2.createAndStartP2PService(nodeAddress2, MAX_CONNECTIONS, useLocalhost, 2, true, seedNodes, new P2PServiceListener() {

        @Override
        public void onRequestingDataCompleted() {
            latch.countDown();
        }

        @Override
        public void onNoSeedNodeAvailable() {
        }

        @Override
        public void onTorNodeReady() {
        }

        @Override
        public void onNoPeersAvailable() {
        }

        @Override
        public void onBootstrapComplete() {
            latch.countDown();
        }

        @Override
        public void onHiddenServicePublished() {
            latch.countDown();
        }

        @Override
        public void onSetupFailed(Throwable throwable) {
        }
    });
    P2PService p2PService2 = seedNode2.getSeedNodeP2PService();
    latch.await();
// Assert.assertEquals(1, p2PService1.getPeerManager().getAuthenticatedAndReportedPeers().size());
// Assert.assertEquals(1, p2PService2.getPeerManager().getAuthenticatedAndReportedPeers().size());
}
Also used : P2PServiceListener(io.bitsquare.p2p.P2PServiceListener) DummySeedNode(io.bitsquare.p2p.DummySeedNode) NodeAddress(io.bitsquare.p2p.NodeAddress) CountDownLatch(java.util.concurrent.CountDownLatch) P2PService(io.bitsquare.p2p.P2PService) Test(org.junit.Test)

Example 2 with NodeAddress

use of io.bitsquare.p2p.NodeAddress in project bitsquare by bitsquare.

the class PeerManagerTest method testSingleSeedNode.

// @Test
public void testSingleSeedNode() throws InterruptedException {
    LocalhostNetworkNode.setSimulateTorDelayTorNode(0);
    LocalhostNetworkNode.setSimulateTorDelayHiddenService(0);
    seedNodes = new HashSet<>();
    NodeAddress nodeAddress = new NodeAddress("localhost:8001");
    seedNodes.add(nodeAddress);
    seedNode1 = new DummySeedNode("test_dummy_dir");
    latch = new CountDownLatch(2);
    seedNode1.createAndStartP2PService(nodeAddress, MAX_CONNECTIONS, useLocalhost, 2, true, seedNodes, new P2PServiceListener() {

        @Override
        public void onRequestingDataCompleted() {
            latch.countDown();
        }

        @Override
        public void onTorNodeReady() {
        }

        @Override
        public void onNoSeedNodeAvailable() {
        }

        @Override
        public void onNoPeersAvailable() {
        }

        @Override
        public void onBootstrapComplete() {
        }

        @Override
        public void onHiddenServicePublished() {
            latch.countDown();
        }

        @Override
        public void onSetupFailed(Throwable throwable) {
        }
    });
    P2PService p2PService1 = seedNode1.getSeedNodeP2PService();
    latch.await();
    Thread.sleep(500);
//Assert.assertEquals(0, p2PService1.getPeerManager().getAuthenticatedAndReportedPeers().size());
}
Also used : P2PServiceListener(io.bitsquare.p2p.P2PServiceListener) DummySeedNode(io.bitsquare.p2p.DummySeedNode) NodeAddress(io.bitsquare.p2p.NodeAddress) CountDownLatch(java.util.concurrent.CountDownLatch) P2PService(io.bitsquare.p2p.P2PService)

Example 3 with NodeAddress

use of io.bitsquare.p2p.NodeAddress 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)

Example 4 with NodeAddress

use of io.bitsquare.p2p.NodeAddress in project bitsquare by bitsquare.

the class ClosedTradesView method initialize.

@Override
public void initialize() {
    tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    tableView.setPlaceholder(new Label("No closed trades available"));
    setTradeIdColumnCellFactory();
    setDirectionColumnCellFactory();
    setAmountColumnCellFactory();
    setPriceColumnCellFactory();
    setVolumeColumnCellFactory();
    setDateColumnCellFactory();
    setMarketColumnCellFactory();
    setStateColumnCellFactory();
    setAvatarColumnCellFactory();
    tradeIdColumn.setComparator((o1, o2) -> o1.getTradable().getId().compareTo(o2.getTradable().getId()));
    dateColumn.setComparator((o1, o2) -> o1.getTradable().getDate().compareTo(o2.getTradable().getDate()));
    directionColumn.setComparator((o1, o2) -> o1.getTradable().getOffer().getDirection().compareTo(o2.getTradable().getOffer().getDirection()));
    marketColumn.setComparator((o1, o2) -> model.getMarketLabel(o1).compareTo(model.getMarketLabel(o2)));
    priceColumn.setComparator((o1, o2) -> {
        final Tradable tradable1 = o1.getTradable();
        final Tradable tradable2 = o2.getTradable();
        Fiat price1 = null;
        Fiat price2 = null;
        if (tradable1 != null)
            price1 = tradable1 instanceof Trade ? ((Trade) tradable1).getTradePrice() : tradable1.getOffer().getPrice();
        if (tradable2 != null)
            price2 = tradable2 instanceof Trade ? ((Trade) tradable2).getTradePrice() : tradable2.getOffer().getPrice();
        return price1 != null && price2 != null ? price1.compareTo(price2) : 0;
    });
    volumeColumn.setComparator((o1, o2) -> {
        if (o1.getTradable() instanceof Trade && o2.getTradable() instanceof Trade) {
            Fiat tradeVolume1 = ((Trade) o1.getTradable()).getTradeVolume();
            Fiat tradeVolume2 = ((Trade) o2.getTradable()).getTradeVolume();
            return tradeVolume1 != null && tradeVolume2 != null ? tradeVolume1.compareTo(tradeVolume2) : 0;
        } else
            return 0;
    });
    amountColumn.setComparator((o1, o2) -> {
        if (o1.getTradable() instanceof Trade && o2.getTradable() instanceof Trade) {
            Coin amount1 = ((Trade) o1.getTradable()).getTradeAmount();
            Coin amount2 = ((Trade) o2.getTradable()).getTradeAmount();
            return amount1 != null && amount2 != null ? amount1.compareTo(amount2) : 0;
        } else
            return 0;
    });
    avatarColumn.setComparator((o1, o2) -> {
        if (o1.getTradable() instanceof Trade && o2.getTradable() instanceof Trade) {
            NodeAddress tradingPeerNodeAddress1 = ((Trade) o1.getTradable()).getTradingPeerNodeAddress();
            NodeAddress tradingPeerNodeAddress2 = ((Trade) o2.getTradable()).getTradingPeerNodeAddress();
            String address1 = tradingPeerNodeAddress1 != null ? tradingPeerNodeAddress1.hostName : "";
            String address2 = tradingPeerNodeAddress2 != null ? tradingPeerNodeAddress2.hostName : "";
            return address1 != null && address2 != null ? address1.compareTo(address2) : 0;
        } else
            return 0;
    });
    stateColumn.setComparator((o1, o2) -> model.getState(o1).compareTo(model.getState(o2)));
    dateColumn.setSortType(TableColumn.SortType.DESCENDING);
    tableView.getSortOrder().add(dateColumn);
    exportButton.setText("Export to csv");
}
Also used : Trade(io.bitsquare.trade.Trade) Coin(org.bitcoinj.core.Coin) Tradable(io.bitsquare.trade.Tradable) Fiat(org.bitcoinj.utils.Fiat) NodeAddress(io.bitsquare.p2p.NodeAddress)

Example 5 with NodeAddress

use of io.bitsquare.p2p.NodeAddress in project bitsquare by bitsquare.

the class OpenOfferManager method handleOfferAvailabilityRequest.

///////////////////////////////////////////////////////////////////////////////////////////
// Offer Availability
///////////////////////////////////////////////////////////////////////////////////////////
private void handleOfferAvailabilityRequest(OfferAvailabilityRequest message, NodeAddress sender) {
    log.trace("handleNewMessage: message = " + message.getClass().getSimpleName() + " from " + sender);
    if (!stopped) {
        try {
            nonEmptyStringOf(message.offerId);
            checkNotNull(message.getPubKeyRing());
        } catch (Throwable t) {
            log.warn("Invalid message " + message.toString());
            return;
        }
        Optional<OpenOffer> openOfferOptional = findOpenOffer(message.offerId);
        AvailabilityResult availabilityResult;
        if (openOfferOptional.isPresent()) {
            if (openOfferOptional.get().getState() == OpenOffer.State.AVAILABLE) {
                final Offer offer = openOfferOptional.get().getOffer();
                if (!preferences.getIgnoreTradersList().stream().filter(i -> i.equals(offer.getOffererNodeAddress().getHostNameWithoutPostFix())).findAny().isPresent()) {
                    availabilityResult = AvailabilityResult.AVAILABLE;
                    List<NodeAddress> acceptedArbitrators = user.getAcceptedArbitratorAddresses();
                    if (acceptedArbitrators != null && !acceptedArbitrators.isEmpty()) {
                        // We need to be backward compatible. takersTradePrice was not used before 0.4.9.
                        if (message.takersTradePrice > 0) {
                            // losses and therefore an outdated market price.
                            try {
                                offer.checkTradePriceTolerance(message.takersTradePrice);
                            } catch (TradePriceOutOfToleranceException e) {
                                log.warn("Trade price check failed because takers price is outside out tolerance.");
                                availabilityResult = AvailabilityResult.PRICE_OUT_OF_TOLERANCE;
                            } catch (MarketPriceNotAvailableException e) {
                                log.warn(e.getMessage());
                                availabilityResult = AvailabilityResult.MARKET_PRICE_NOT_AVAILABLE;
                            } catch (Throwable e) {
                                log.warn("Trade price check failed. " + e.getMessage());
                                availabilityResult = AvailabilityResult.UNKNOWN_FAILURE;
                            }
                        }
                    } else {
                        log.warn("acceptedArbitrators is null or empty: acceptedArbitrators=" + acceptedArbitrators);
                        availabilityResult = AvailabilityResult.NO_ARBITRATORS;
                    }
                } else {
                    availabilityResult = AvailabilityResult.USER_IGNORED;
                }
            } else {
                availabilityResult = AvailabilityResult.OFFER_TAKEN;
            }
        } else {
            log.warn("handleOfferAvailabilityRequest: openOffer not found. That should never happen.");
            availabilityResult = AvailabilityResult.OFFER_TAKEN;
        }
        try {
            p2PService.sendEncryptedDirectMessage(sender, message.getPubKeyRing(), new OfferAvailabilityResponse(message.offerId, availabilityResult), new SendDirectMessageListener() {

                @Override
                public void onArrived() {
                    log.trace("OfferAvailabilityResponse successfully arrived at peer");
                }

                @Override
                public void onFault() {
                    log.debug("Sending OfferAvailabilityResponse failed.");
                }
            });
        } catch (Throwable t) {
            t.printStackTrace();
            log.debug("Exception at handleRequestIsOfferAvailableMessage " + t.getMessage());
        }
    } else {
        log.debug("We have stopped already. We ignore that handleOfferAvailabilityRequest call.");
    }
}
Also used : OfferAvailabilityResponse(io.bitsquare.trade.protocol.availability.messages.OfferAvailabilityResponse) PriceFeedService(io.bitsquare.btc.pricefeed.PriceFeedService) P2PService(io.bitsquare.p2p.P2PService) TradableList(io.bitsquare.trade.TradableList) ErrorMessageHandler(io.bitsquare.common.handlers.ErrorMessageHandler) Coin(org.bitcoinj.core.Coin) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) Timer(io.bitsquare.common.Timer) AvailabilityResult(io.bitsquare.trade.protocol.availability.AvailabilityResult) TransactionResultHandler(io.bitsquare.trade.handlers.TransactionResultHandler) PlaceOfferModel(io.bitsquare.trade.protocol.placeoffer.PlaceOfferModel) ArrayList(java.util.ArrayList) DevFlags(io.bitsquare.app.DevFlags) User(io.bitsquare.user.User) WalletService(io.bitsquare.btc.WalletService) PeerManager(io.bitsquare.p2p.peers.PeerManager) KeyRing(io.bitsquare.common.crypto.KeyRing) TradeWalletService(io.bitsquare.btc.TradeWalletService) ResultHandler(io.bitsquare.common.handlers.ResultHandler) Named(javax.inject.Named) AddressEntry(io.bitsquare.btc.AddressEntry) Nullable(javax.annotation.Nullable) Log(io.bitsquare.app.Log) Logger(org.slf4j.Logger) Validator.nonEmptyStringOf(io.bitsquare.util.Validator.nonEmptyStringOf) UserThread(io.bitsquare.common.UserThread) OfferAvailabilityRequest(io.bitsquare.trade.protocol.availability.messages.OfferAvailabilityRequest) Message(io.bitsquare.p2p.Message) NodeAddress(io.bitsquare.p2p.NodeAddress) BootstrapListener(io.bitsquare.p2p.BootstrapListener) ClosedTradableManager(io.bitsquare.trade.closed.ClosedTradableManager) SendDirectMessageListener(io.bitsquare.p2p.messaging.SendDirectMessageListener) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) MarketPriceNotAvailableException(io.bitsquare.trade.exceptions.MarketPriceNotAvailableException) Preferences(io.bitsquare.user.Preferences) DecryptedDirectMessageListener(io.bitsquare.p2p.messaging.DecryptedDirectMessageListener) List(java.util.List) com.google.inject.internal.util.$Preconditions.checkNotNull(com.google.inject.internal.util.$Preconditions.checkNotNull) TradePriceOutOfToleranceException(io.bitsquare.trade.exceptions.TradePriceOutOfToleranceException) PlaceOfferProtocol(io.bitsquare.trade.protocol.placeoffer.PlaceOfferProtocol) Optional(java.util.Optional) Storage(io.bitsquare.storage.Storage) DecryptedMsgWithPubKey(io.bitsquare.crypto.DecryptedMsgWithPubKey) ObservableList(javafx.collections.ObservableList) AvailabilityResult(io.bitsquare.trade.protocol.availability.AvailabilityResult) TradePriceOutOfToleranceException(io.bitsquare.trade.exceptions.TradePriceOutOfToleranceException) OfferAvailabilityResponse(io.bitsquare.trade.protocol.availability.messages.OfferAvailabilityResponse) SendDirectMessageListener(io.bitsquare.p2p.messaging.SendDirectMessageListener) MarketPriceNotAvailableException(io.bitsquare.trade.exceptions.MarketPriceNotAvailableException) NodeAddress(io.bitsquare.p2p.NodeAddress)

Aggregations

NodeAddress (io.bitsquare.p2p.NodeAddress)34 WalletService (io.bitsquare.btc.WalletService)5 Contract (io.bitsquare.trade.Contract)5 Logger (org.slf4j.Logger)5 LoggerFactory (org.slf4j.LoggerFactory)5 Log (io.bitsquare.app.Log)4 AddressEntry (io.bitsquare.btc.AddressEntry)4 Timer (io.bitsquare.common.Timer)4 UserThread (io.bitsquare.common.UserThread)4 PubKeyRing (io.bitsquare.common.crypto.PubKeyRing)4 P2PService (io.bitsquare.p2p.P2PService)4 SendMailboxMessageListener (io.bitsquare.p2p.messaging.SendMailboxMessageListener)4 TimeUnit (java.util.concurrent.TimeUnit)4 DummySeedNode (io.bitsquare.p2p.DummySeedNode)3 P2PServiceListener (io.bitsquare.p2p.P2PServiceListener)3 Connection (io.bitsquare.p2p.network.Connection)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 Collectors (java.util.stream.Collectors)3 FutureCallback (com.google.common.util.concurrent.FutureCallback)2 Futures (com.google.common.util.concurrent.Futures)2