Search in sources :

Example 21 with NodeAddress

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

the class DisputeManager method sendPeerOpenedDisputeMessage.

// arbitrator sends that to trading peer when he received openDispute request
private void sendPeerOpenedDisputeMessage(Dispute disputeFromOpener) {
    Contract contractFromOpener = disputeFromOpener.getContract();
    PubKeyRing pubKeyRing = disputeFromOpener.isDisputeOpenerIsBuyer() ? contractFromOpener.getSellerPubKeyRing() : contractFromOpener.getBuyerPubKeyRing();
    Dispute dispute = new Dispute(disputeStorage, disputeFromOpener.getTradeId(), pubKeyRing.hashCode(), !disputeFromOpener.isDisputeOpenerIsBuyer(), !disputeFromOpener.isDisputeOpenerIsOfferer(), pubKeyRing, disputeFromOpener.getTradeDate(), contractFromOpener, disputeFromOpener.getContractHash(), disputeFromOpener.getDepositTxSerialized(), disputeFromOpener.getPayoutTxSerialized(), disputeFromOpener.getDepositTxId(), disputeFromOpener.getPayoutTxId(), disputeFromOpener.getContractAsJson(), disputeFromOpener.getOffererContractSignature(), disputeFromOpener.getTakerContractSignature(), disputeFromOpener.getArbitratorPubKeyRing(), disputeFromOpener.isSupportTicket());
    final Optional<Dispute> storedDisputeOptional = findDispute(dispute.getTradeId(), dispute.getTraderId());
    if (!storedDisputeOptional.isPresent()) {
        DisputeCommunicationMessage disputeCommunicationMessage = new DisputeCommunicationMessage(dispute.getTradeId(), keyRing.getPubKeyRing().hashCode(), true, "System message: " + (dispute.isSupportTicket() ? "Your trading peer has requested support due technical problems. Please wait for further instructions." : "Your trading peer has requested a dispute.\n\n" + disputeInfo), p2PService.getAddress());
        disputeCommunicationMessage.setIsSystemMessage(true);
        dispute.addDisputeMessage(disputeCommunicationMessage);
        disputes.add(dispute);
        disputesObservableList.add(dispute);
        // we mirrored dispute already!
        Contract contract = dispute.getContract();
        PubKeyRing peersPubKeyRing = dispute.isDisputeOpenerIsBuyer() ? contract.getBuyerPubKeyRing() : contract.getSellerPubKeyRing();
        NodeAddress peerNodeAddress = dispute.isDisputeOpenerIsBuyer() ? contract.getBuyerNodeAddress() : contract.getSellerNodeAddress();
        log.trace("sendPeerOpenedDisputeMessage to peerAddress " + peerNodeAddress);
        p2PService.sendEncryptedMailboxMessage(peerNodeAddress, peersPubKeyRing, new PeerOpenedDisputeMessage(dispute, p2PService.getAddress()), new SendMailboxMessageListener() {

            @Override
            public void onArrived() {
                disputeCommunicationMessage.setArrived(true);
            }

            @Override
            public void onStoredInMailbox() {
                disputeCommunicationMessage.setStoredInMailbox(true);
            }

            @Override
            public void onFault(String errorMessage) {
                log.error("sendEncryptedMessage failed");
            }
        });
    } else {
        log.warn("We got a dispute already open for that trade and trading peer.\n" + "TradeId = " + dispute.getTradeId());
    }
}
Also used : PubKeyRing(io.bitsquare.common.crypto.PubKeyRing) NodeAddress(io.bitsquare.p2p.NodeAddress) SendMailboxMessageListener(io.bitsquare.p2p.messaging.SendMailboxMessageListener) Contract(io.bitsquare.trade.Contract)

Example 22 with NodeAddress

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

the class SellerAsOffererProtocol method doApplyMailboxMessage.

///////////////////////////////////////////////////////////////////////////////////////////
// Mailbox
///////////////////////////////////////////////////////////////////////////////////////////
@Override
public void doApplyMailboxMessage(Message message, Trade trade) {
    this.trade = trade;
    NodeAddress peerNodeAddress = ((MailboxMessage) message).getSenderNodeAddress();
    if (message instanceof PayoutTxFinalizedMessage) {
        handle((PayoutTxFinalizedMessage) message, peerNodeAddress);
    } else {
        if (message instanceof FiatTransferStartedMessage) {
            handle((FiatTransferStartedMessage) message, peerNodeAddress);
        } else if (message instanceof DepositTxPublishedMessage) {
            handle((DepositTxPublishedMessage) message, peerNodeAddress);
        }
    }
}
Also used : NodeAddress(io.bitsquare.p2p.NodeAddress) MailboxMessage(io.bitsquare.p2p.messaging.MailboxMessage)

Example 23 with NodeAddress

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

the class TraderDisputeView method initialize.

@Override
public void initialize() {
    Label label = new Label("Filter list:");
    HBox.setMargin(label, new Insets(5, 0, 0, 0));
    filterTextField = new InputTextField();
    filterTextField.setText("open");
    filterTextFieldListener = (observable, oldValue, newValue) -> applyFilteredListPredicate(filterTextField.getText());
    filterBox = new HBox();
    filterBox.setSpacing(5);
    filterBox.getChildren().addAll(label, filterTextField);
    VBox.setVgrow(filterBox, Priority.NEVER);
    filterBox.setVisible(false);
    filterBox.setManaged(false);
    tableView = new TableView<>();
    VBox.setVgrow(tableView, Priority.SOMETIMES);
    tableView.setMinHeight(150);
    root.getChildren().addAll(filterBox, tableView);
    tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    Label placeholder = new Label("There are no open tickets");
    placeholder.setWrapText(true);
    tableView.setPlaceholder(placeholder);
    tableView.getSelectionModel().clearSelection();
    tableView.getColumns().add(getSelectColumn());
    TableColumn<Dispute, Dispute> contractColumn = getContractColumn();
    tableView.getColumns().add(contractColumn);
    TableColumn<Dispute, Dispute> dateColumn = getDateColumn();
    tableView.getColumns().add(dateColumn);
    TableColumn<Dispute, Dispute> tradeIdColumn = getTradeIdColumn();
    tableView.getColumns().add(tradeIdColumn);
    TableColumn<Dispute, Dispute> buyerOnionAddressColumn = getBuyerOnionAddressColumn();
    tableView.getColumns().add(buyerOnionAddressColumn);
    TableColumn<Dispute, Dispute> sellerOnionAddressColumn = getSellerOnionAddressColumn();
    tableView.getColumns().add(sellerOnionAddressColumn);
    TableColumn<Dispute, Dispute> marketColumn = getMarketColumn();
    tableView.getColumns().add(marketColumn);
    TableColumn<Dispute, Dispute> roleColumn = getRoleColumn();
    tableView.getColumns().add(roleColumn);
    TableColumn<Dispute, Dispute> stateColumn = getStateColumn();
    tableView.getColumns().add(stateColumn);
    tradeIdColumn.setComparator((o1, o2) -> o1.getTradeId().compareTo(o2.getTradeId()));
    dateColumn.setComparator((o1, o2) -> o1.getOpeningDate().compareTo(o2.getOpeningDate()));
    buyerOnionAddressColumn.setComparator((o1, o2) -> getBuyerOnionAddressColumnLabel(o1).compareTo(getBuyerOnionAddressColumnLabel(o2)));
    sellerOnionAddressColumn.setComparator((o1, o2) -> getSellerOnionAddressColumnLabel(o1).compareTo(getSellerOnionAddressColumnLabel(o2)));
    marketColumn.setComparator((o1, o2) -> formatter.getCurrencyPair(o1.getContract().offer.getCurrencyCode()).compareTo(o2.getContract().offer.getCurrencyCode()));
    dateColumn.setSortType(TableColumn.SortType.DESCENDING);
    tableView.getSortOrder().add(dateColumn);
    /*inputTextAreaListener = (observable, oldValue, newValue) ->
                sendButton.setDisable(newValue.length() == 0
                        && tempAttachments.size() == 0 &&
                        selectedDispute.disputeResultProperty().get() == null);*/
    selectedDisputeClosedPropertyListener = (observable, oldValue, newValue) -> {
        messagesInputBox.setVisible(!newValue);
        messagesInputBox.setManaged(!newValue);
        AnchorPane.setBottomAnchor(messageListView, newValue ? 0d : 120d);
    };
    disputeDirectMessageListListener = c -> scrollToBottom();
    keyEventEventHandler = event -> {
        if (new KeyCodeCombination(KeyCode.L, KeyCombination.ALT_DOWN).match(event)) {
            Map<String, List<Dispute>> map = new HashMap<>();
            disputeManager.getDisputesAsObservableList().stream().forEach(dispute -> {
                String tradeId = dispute.getTradeId();
                List<Dispute> list;
                if (!map.containsKey(tradeId))
                    map.put(tradeId, new ArrayList<>());
                list = map.get(tradeId);
                list.add(dispute);
            });
            List<List<Dispute>> disputeGroups = new ArrayList<>();
            map.entrySet().stream().forEach(entry -> {
                disputeGroups.add(entry.getValue());
            });
            disputeGroups.sort((o1, o2) -> !o1.isEmpty() && !o2.isEmpty() ? o1.get(0).getOpeningDate().compareTo(o2.get(0).getOpeningDate()) : 0);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("Summary of all disputes (No. of disputes: " + disputeGroups.size() + ")\n\n");
            disputeGroups.stream().forEach(disputeGroup -> {
                Dispute dispute0 = disputeGroup.get(0);
                stringBuilder.append("##########################################################################################/\n").append("## Trade ID: ").append(dispute0.getTradeId()).append("\n").append("## Date: ").append(formatter.formatDateTime(dispute0.getOpeningDate())).append("\n").append("## Is support ticket: ").append(dispute0.isSupportTicket()).append("\n");
                if (dispute0.disputeResultProperty().get() != null && dispute0.disputeResultProperty().get().getReason() != null) {
                    stringBuilder.append("## Reason: ").append(dispute0.disputeResultProperty().get().getReason()).append("\n");
                }
                stringBuilder.append("##########################################################################################/\n").append("\n");
                disputeGroup.stream().forEach(dispute -> {
                    stringBuilder.append("*******************************************************************************************\n").append("** Trader's ID: ").append(dispute.getTraderId()).append("\n*******************************************************************************************\n").append("\n");
                    dispute.getDisputeCommunicationMessagesAsObservableList().stream().forEach(m -> {
                        String role = m.isSenderIsTrader() ? ">> Trader's msg: " : "<< Arbitrator's msg: ";
                        stringBuilder.append(role).append(m.getMessage()).append("\n");
                    });
                    stringBuilder.append("\n");
                });
                stringBuilder.append("\n");
            });
            String message = stringBuilder.toString();
            new Popup().headLine("All disputes (" + disputeGroups.size() + ")").information(message).width(1000).actionButtonText("Copy").onAction(() -> Utilities.copyToClipboard(message)).show();
        } else if (new KeyCodeCombination(KeyCode.U, KeyCombination.ALT_DOWN).match(event)) {
            if (selectedDispute != null) {
                if (selectedDisputeClosedPropertyListener != null)
                    selectedDispute.isClosedProperty().removeListener(selectedDisputeClosedPropertyListener);
                selectedDispute.setIsClosed(false);
            }
        } else if (new KeyCodeCombination(KeyCode.R, KeyCombination.ALT_DOWN).match(event)) {
            if (selectedDispute != null) {
                PubKeyRing pubKeyRing = selectedDispute.getTraderPubKeyRing();
                NodeAddress nodeAddress;
                if (pubKeyRing.equals(selectedDispute.getContract().getBuyerPubKeyRing()))
                    nodeAddress = selectedDispute.getContract().getBuyerNodeAddress();
                else
                    nodeAddress = selectedDispute.getContract().getSellerNodeAddress();
                new SendPrivateNotificationWindow(pubKeyRing, nodeAddress).onAddAlertMessage(privateNotificationManager::sendPrivateNotificationMessageIfKeyIsValid).show();
            }
        }
    };
}
Also used : Insets(javafx.geometry.Insets) InputTextField(io.bitsquare.gui.components.InputTextField) KeyCodeCombination(javafx.scene.input.KeyCodeCombination) SendPrivateNotificationWindow(io.bitsquare.gui.main.overlays.windows.SendPrivateNotificationWindow) Popup(io.bitsquare.gui.main.overlays.popups.Popup) PubKeyRing(io.bitsquare.common.crypto.PubKeyRing) Dispute(io.bitsquare.arbitration.Dispute) SortedList(javafx.collections.transformation.SortedList) FilteredList(javafx.collections.transformation.FilteredList) ObservableList(javafx.collections.ObservableList) NodeAddress(io.bitsquare.p2p.NodeAddress)

Example 24 with NodeAddress

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

the class TorNetworkNode method start.

///////////////////////////////////////////////////////////////////////////////////////////
// API
///////////////////////////////////////////////////////////////////////////////////////////
@Override
public void start(@Nullable SetupListener setupListener) {
    if (setupListener != null)
        addSetupListener(setupListener);
    createExecutorService();
    // Create the tor node (takes about 6 sec.)
    createTorNode(torDir, torNode -> {
        Log.traceCall("torNode created");
        TorNetworkNode.this.torNetworkNode = torNode;
        setupListeners.stream().forEach(SetupListener::onTorNodeReady);
        createHiddenService(torNode, Utils.findFreeSystemPort(), servicePort, hiddenServiceDescriptor -> {
            Log.traceCall("hiddenService created");
            TorNetworkNode.this.hiddenServiceDescriptor = hiddenServiceDescriptor;
            nodeAddressProperty.set(new NodeAddress(hiddenServiceDescriptor.getFullAddress()));
            startServer(hiddenServiceDescriptor.getServerSocket());
            setupListeners.stream().forEach(SetupListener::onHiddenServicePublished);
        });
    });
}
Also used : NodeAddress(io.bitsquare.p2p.NodeAddress)

Example 25 with NodeAddress

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

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