Rename Address to NodeAddress

This commit is contained in:
Manfred Karrer 2016-01-21 12:32:15 +01:00
parent cb685d3b5c
commit c180491430
112 changed files with 866 additions and 866 deletions

View file

@ -19,7 +19,7 @@ package io.bitsquare.arbitration;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.common.crypto.PubKeyRing; import io.bitsquare.common.crypto.PubKeyRing;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.storage.data.PubKeyProtectedExpirablePayload; import io.bitsquare.p2p.storage.data.PubKeyProtectedExpirablePayload;
import java.security.PublicKey; import java.security.PublicKey;
@ -36,14 +36,14 @@ public final class Arbitrator implements PubKeyProtectedExpirablePayload {
// Persisted fields // Persisted fields
private final byte[] btcPubKey; private final byte[] btcPubKey;
private final PubKeyRing pubKeyRing; private final PubKeyRing pubKeyRing;
private final Address arbitratorAddress; private final NodeAddress arbitratorNodeAddress;
private final List<String> languageCodes; private final List<String> languageCodes;
private final String btcAddress; private final String btcAddress;
private final long registrationDate; private final long registrationDate;
private final String registrationSignature; private final String registrationSignature;
private final byte[] registrationPubKey; private final byte[] registrationPubKey;
public Arbitrator(Address arbitratorAddress, public Arbitrator(NodeAddress arbitratorNodeAddress,
byte[] btcPubKey, byte[] btcPubKey,
String btcAddress, String btcAddress,
PubKeyRing pubKeyRing, PubKeyRing pubKeyRing,
@ -51,7 +51,7 @@ public final class Arbitrator implements PubKeyProtectedExpirablePayload {
Date registrationDate, Date registrationDate,
byte[] registrationPubKey, byte[] registrationPubKey,
String registrationSignature) { String registrationSignature) {
this.arbitratorAddress = arbitratorAddress; this.arbitratorNodeAddress = arbitratorNodeAddress;
this.btcPubKey = btcPubKey; this.btcPubKey = btcPubKey;
this.btcAddress = btcAddress; this.btcAddress = btcAddress;
this.pubKeyRing = pubKeyRing; this.pubKeyRing = pubKeyRing;
@ -84,8 +84,8 @@ public final class Arbitrator implements PubKeyProtectedExpirablePayload {
return pubKeyRing; return pubKeyRing;
} }
public Address getArbitratorAddress() { public NodeAddress getArbitratorNodeAddress() {
return arbitratorAddress; return arbitratorNodeAddress;
} }
public Date getRegistrationDate() { public Date getRegistrationDate() {
@ -118,7 +118,7 @@ public final class Arbitrator implements PubKeyProtectedExpirablePayload {
if (registrationDate != that.registrationDate) return false; if (registrationDate != that.registrationDate) return false;
if (!Arrays.equals(btcPubKey, that.btcPubKey)) return false; if (!Arrays.equals(btcPubKey, that.btcPubKey)) return false;
if (pubKeyRing != null ? !pubKeyRing.equals(that.pubKeyRing) : that.pubKeyRing != null) return false; if (pubKeyRing != null ? !pubKeyRing.equals(that.pubKeyRing) : that.pubKeyRing != null) return false;
if (arbitratorAddress != null ? !arbitratorAddress.equals(that.arbitratorAddress) : that.arbitratorAddress != null) if (arbitratorNodeAddress != null ? !arbitratorNodeAddress.equals(that.arbitratorNodeAddress) : that.arbitratorNodeAddress != null)
return false; return false;
if (languageCodes != null ? !languageCodes.equals(that.languageCodes) : that.languageCodes != null) if (languageCodes != null ? !languageCodes.equals(that.languageCodes) : that.languageCodes != null)
return false; return false;
@ -133,7 +133,7 @@ public final class Arbitrator implements PubKeyProtectedExpirablePayload {
public int hashCode() { public int hashCode() {
int result = btcPubKey != null ? Arrays.hashCode(btcPubKey) : 0; int result = btcPubKey != null ? Arrays.hashCode(btcPubKey) : 0;
result = 31 * result + (pubKeyRing != null ? pubKeyRing.hashCode() : 0); result = 31 * result + (pubKeyRing != null ? pubKeyRing.hashCode() : 0);
result = 31 * result + (arbitratorAddress != null ? arbitratorAddress.hashCode() : 0); result = 31 * result + (arbitratorNodeAddress != null ? arbitratorNodeAddress.hashCode() : 0);
result = 31 * result + (languageCodes != null ? languageCodes.hashCode() : 0); result = 31 * result + (languageCodes != null ? languageCodes.hashCode() : 0);
result = 31 * result + (btcAddress != null ? btcAddress.hashCode() : 0); result = 31 * result + (btcAddress != null ? btcAddress.hashCode() : 0);
result = 31 * result + (int) (registrationDate ^ (registrationDate >>> 32)); result = 31 * result + (int) (registrationDate ^ (registrationDate >>> 32));
@ -145,7 +145,7 @@ public final class Arbitrator implements PubKeyProtectedExpirablePayload {
@Override @Override
public String toString() { public String toString() {
return "Arbitrator{" + return "Arbitrator{" +
"arbitratorAddress=" + arbitratorAddress + "arbitratorAddress=" + arbitratorNodeAddress +
", languageCodes=" + languageCodes + ", languageCodes=" + languageCodes +
", btcAddress='" + btcAddress + '\'' + ", btcAddress='" + btcAddress + '\'' +
", registrationDate=" + registrationDate + ", registrationDate=" + registrationDate +

View file

@ -26,8 +26,8 @@ import io.bitsquare.common.crypto.KeyRing;
import io.bitsquare.common.handlers.ErrorMessageHandler; import io.bitsquare.common.handlers.ErrorMessageHandler;
import io.bitsquare.common.handlers.ResultHandler; import io.bitsquare.common.handlers.ResultHandler;
import io.bitsquare.common.util.Utilities; import io.bitsquare.common.util.Utilities;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.FirstPeerAuthenticatedListener; import io.bitsquare.p2p.FirstPeerAuthenticatedListener;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.P2PService; import io.bitsquare.p2p.P2PService;
import io.bitsquare.p2p.storage.HashMapChangedListener; import io.bitsquare.p2p.storage.HashMapChangedListener;
import io.bitsquare.p2p.storage.data.ProtectedData; import io.bitsquare.p2p.storage.data.ProtectedData;
@ -60,7 +60,7 @@ public class ArbitratorManager {
private final KeyRing keyRing; private final KeyRing keyRing;
private final ArbitratorService arbitratorService; private final ArbitratorService arbitratorService;
private final User user; private final User user;
private final ObservableMap<Address, Arbitrator> arbitratorsObservableMap = FXCollections.observableHashMap(); private final ObservableMap<NodeAddress, Arbitrator> arbitratorsObservableMap = FXCollections.observableHashMap();
// Keys for invited arbitrators in bootstrapping phase (before registration is open to anyone and security payment is implemented) // Keys for invited arbitrators in bootstrapping phase (before registration is open to anyone and security payment is implemented)
// For testing purpose here is a private key so anyone can setup an arbitrator for now. // For testing purpose here is a private key so anyone can setup an arbitrator for now.
@ -157,13 +157,13 @@ public class ArbitratorManager {
} }
public void applyArbitrators() { public void applyArbitrators() {
Map<Address, Arbitrator> map = arbitratorService.getArbitrators(); Map<NodeAddress, Arbitrator> map = arbitratorService.getArbitrators();
log.trace("Arbitrators . size=" + (map.values() != null ? map.values().size() : "0")); log.trace("Arbitrators . size=" + (map.values() != null ? map.values().size() : "0"));
arbitratorsObservableMap.clear(); arbitratorsObservableMap.clear();
Map<Address, Arbitrator> filtered = map.values().stream() Map<NodeAddress, Arbitrator> filtered = map.values().stream()
.filter(e -> isPublicKeyInList(Utils.HEX.encode(e.getRegistrationPubKey())) .filter(e -> isPublicKeyInList(Utils.HEX.encode(e.getRegistrationPubKey()))
&& verifySignature(e.getPubKeyRing().getSignaturePubKey(), e.getRegistrationPubKey(), e.getRegistrationSignature())) && verifySignature(e.getPubKeyRing().getSignaturePubKey(), e.getRegistrationPubKey(), e.getRegistrationSignature()))
.collect(Collectors.toMap(Arbitrator::getArbitratorAddress, Function.identity())); .collect(Collectors.toMap(Arbitrator::getArbitratorNodeAddress, Function.identity()));
arbitratorsObservableMap.putAll(filtered); arbitratorsObservableMap.putAll(filtered);
// we need to remove accepted arbitrators which are not available anymore // we need to remove accepted arbitrators which are not available anymore
@ -184,7 +184,7 @@ public class ArbitratorManager {
public void addArbitrator(Arbitrator arbitrator, ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler) { public void addArbitrator(Arbitrator arbitrator, ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler) {
user.setRegisteredArbitrator(arbitrator); user.setRegisteredArbitrator(arbitrator);
arbitratorsObservableMap.put(arbitrator.getArbitratorAddress(), arbitrator); arbitratorsObservableMap.put(arbitrator.getArbitratorNodeAddress(), arbitrator);
arbitratorService.addArbitrator(arbitrator, arbitratorService.addArbitrator(arbitrator,
() -> { () -> {
log.debug("Arbitrator successfully saved in P2P network"); log.debug("Arbitrator successfully saved in P2P network");
@ -200,7 +200,7 @@ public class ArbitratorManager {
Arbitrator registeredArbitrator = user.getRegisteredArbitrator(); Arbitrator registeredArbitrator = user.getRegisteredArbitrator();
if (registeredArbitrator != null) { if (registeredArbitrator != null) {
user.setRegisteredArbitrator(null); user.setRegisteredArbitrator(null);
arbitratorsObservableMap.remove(registeredArbitrator.getArbitratorAddress()); arbitratorsObservableMap.remove(registeredArbitrator.getArbitratorNodeAddress());
arbitratorService.removeArbitrator(registeredArbitrator, arbitratorService.removeArbitrator(registeredArbitrator,
() -> { () -> {
log.debug("Arbitrator successfully removed from P2P network"); log.debug("Arbitrator successfully removed from P2P network");
@ -210,7 +210,7 @@ public class ArbitratorManager {
} }
} }
public ObservableMap<Address, Arbitrator> getArbitratorsObservableMap() { public ObservableMap<NodeAddress, Arbitrator> getArbitratorsObservableMap() {
return arbitratorsObservableMap; return arbitratorsObservableMap;
} }

View file

@ -19,7 +19,7 @@ package io.bitsquare.arbitration;
import io.bitsquare.common.handlers.ErrorMessageHandler; import io.bitsquare.common.handlers.ErrorMessageHandler;
import io.bitsquare.common.handlers.ResultHandler; import io.bitsquare.common.handlers.ResultHandler;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.P2PService; import io.bitsquare.p2p.P2PService;
import io.bitsquare.p2p.storage.HashMapChangedListener; import io.bitsquare.p2p.storage.HashMapChangedListener;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -82,17 +82,17 @@ public class ArbitratorService {
return p2PService; return p2PService;
} }
public Map<Address, Arbitrator> getArbitrators() { public Map<NodeAddress, Arbitrator> getArbitrators() {
Set<Arbitrator> arbitratorSet = p2PService.getDataMap().values().stream() Set<Arbitrator> arbitratorSet = p2PService.getDataMap().values().stream()
.filter(e -> e.expirablePayload instanceof Arbitrator) .filter(e -> e.expirablePayload instanceof Arbitrator)
.map(e -> (Arbitrator) e.expirablePayload) .map(e -> (Arbitrator) e.expirablePayload)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
Map<Address, Arbitrator> map = new HashMap<>(); Map<NodeAddress, Arbitrator> map = new HashMap<>();
for (Arbitrator arbitrator : arbitratorSet) { for (Arbitrator arbitrator : arbitratorSet) {
Address arbitratorAddress = arbitrator.getArbitratorAddress(); NodeAddress arbitratorNodeAddress = arbitrator.getArbitratorNodeAddress();
if (!map.containsKey(arbitratorAddress)) if (!map.containsKey(arbitratorNodeAddress))
map.put(arbitratorAddress, arbitrator); map.put(arbitratorNodeAddress, arbitrator);
else else
log.warn("arbitratorAddress already exist in arbitrator map. Seems an arbitrator object is already registered with the same address."); log.warn("arbitratorAddress already exist in arbitrator map. Seems an arbitrator object is already registered with the same address.");
} }

View file

@ -26,9 +26,9 @@ import io.bitsquare.btc.exceptions.TransactionVerificationException;
import io.bitsquare.btc.exceptions.WalletException; import io.bitsquare.btc.exceptions.WalletException;
import io.bitsquare.common.crypto.KeyRing; import io.bitsquare.common.crypto.KeyRing;
import io.bitsquare.common.crypto.PubKeyRing; import io.bitsquare.common.crypto.PubKeyRing;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.FirstPeerAuthenticatedListener; import io.bitsquare.p2p.FirstPeerAuthenticatedListener;
import io.bitsquare.p2p.Message; import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.P2PService; import io.bitsquare.p2p.P2PService;
import io.bitsquare.p2p.messaging.DecryptedMsgWithPubKey; import io.bitsquare.p2p.messaging.DecryptedMsgWithPubKey;
import io.bitsquare.p2p.messaging.SendMailboxMessageListener; import io.bitsquare.p2p.messaging.SendMailboxMessageListener;
@ -181,7 +181,7 @@ public class DisputeManager {
disputes.add(dispute); disputes.add(dispute);
disputesObservableList.add(dispute); disputesObservableList.add(dispute);
p2PService.sendEncryptedMailboxMessage(dispute.getContract().arbitratorAddress, p2PService.sendEncryptedMailboxMessage(dispute.getContract().arbitratorNodeAddress,
dispute.getArbitratorPubKeyRing(), dispute.getArbitratorPubKeyRing(),
new OpenNewDisputeMessage(dispute, p2PService.getAddress()), new OpenNewDisputeMessage(dispute, p2PService.getAddress()),
new SendMailboxMessageListener() { new SendMailboxMessageListener() {
@ -246,9 +246,9 @@ public class DisputeManager {
// we mirrored dispute already! // we mirrored dispute already!
Contract contract = dispute.getContract(); Contract contract = dispute.getContract();
PubKeyRing peersPubKeyRing = dispute.isDisputeOpenerIsBuyer() ? contract.getBuyerPubKeyRing() : contract.getSellerPubKeyRing(); PubKeyRing peersPubKeyRing = dispute.isDisputeOpenerIsBuyer() ? contract.getBuyerPubKeyRing() : contract.getSellerPubKeyRing();
Address peerAddress = dispute.isDisputeOpenerIsBuyer() ? contract.getBuyerAddress() : contract.getSellerAddress(); NodeAddress peerNodeAddress = dispute.isDisputeOpenerIsBuyer() ? contract.getBuyerNodeAddress() : contract.getSellerNodeAddress();
log.trace("sendPeerOpenedDisputeMessage to peerAddress " + peerAddress); log.trace("sendPeerOpenedDisputeMessage to peerAddress " + peerNodeAddress);
p2PService.sendEncryptedMailboxMessage(peerAddress, p2PService.sendEncryptedMailboxMessage(peerNodeAddress,
peersPubKeyRing, peersPubKeyRing,
new PeerOpenedDisputeMessage(dispute, p2PService.getAddress()), new PeerOpenedDisputeMessage(dispute, p2PService.getAddress()),
new SendMailboxMessageListener() { new SendMailboxMessageListener() {
@ -279,26 +279,26 @@ public class DisputeManager {
p2PService.getAddress()); p2PService.getAddress());
disputeMailMessage.addAllAttachments(attachments); disputeMailMessage.addAllAttachments(attachments);
PubKeyRing receiverPubKeyRing = null; PubKeyRing receiverPubKeyRing = null;
Address peerAddress = null; NodeAddress peerNodeAddress = null;
if (isTrader(dispute)) { if (isTrader(dispute)) {
dispute.addDisputeMessage(disputeMailMessage); dispute.addDisputeMessage(disputeMailMessage);
receiverPubKeyRing = dispute.getArbitratorPubKeyRing(); receiverPubKeyRing = dispute.getArbitratorPubKeyRing();
peerAddress = dispute.getContract().arbitratorAddress; peerNodeAddress = dispute.getContract().arbitratorNodeAddress;
} else if (isArbitrator(dispute)) { } else if (isArbitrator(dispute)) {
if (!disputeMailMessage.isSystemMessage()) if (!disputeMailMessage.isSystemMessage())
dispute.addDisputeMessage(disputeMailMessage); dispute.addDisputeMessage(disputeMailMessage);
receiverPubKeyRing = dispute.getTraderPubKeyRing(); receiverPubKeyRing = dispute.getTraderPubKeyRing();
Contract contract = dispute.getContract(); Contract contract = dispute.getContract();
if (contract.getBuyerPubKeyRing().equals(receiverPubKeyRing)) if (contract.getBuyerPubKeyRing().equals(receiverPubKeyRing))
peerAddress = contract.getBuyerAddress(); peerNodeAddress = contract.getBuyerNodeAddress();
else else
peerAddress = contract.getSellerAddress(); peerNodeAddress = contract.getSellerNodeAddress();
} else { } else {
log.error("That must not happen. Trader cannot communicate to other trader."); log.error("That must not happen. Trader cannot communicate to other trader.");
} }
if (receiverPubKeyRing != null) { if (receiverPubKeyRing != null) {
log.trace("sendDisputeMailMessage to peerAddress " + peerAddress); log.trace("sendDisputeMailMessage to peerAddress " + peerNodeAddress);
p2PService.sendEncryptedMailboxMessage(peerAddress, p2PService.sendEncryptedMailboxMessage(peerNodeAddress,
receiverPubKeyRing, receiverPubKeyRing,
disputeMailMessage, disputeMailMessage,
new SendMailboxMessageListener() { new SendMailboxMessageListener() {
@ -333,13 +333,13 @@ public class DisputeManager {
dispute.addDisputeMessage(disputeMailMessage); dispute.addDisputeMessage(disputeMailMessage);
disputeResult.setResultMailMessage(disputeMailMessage); disputeResult.setResultMailMessage(disputeMailMessage);
Address peerAddress; NodeAddress peerNodeAddress;
Contract contract = dispute.getContract(); Contract contract = dispute.getContract();
if (contract.getBuyerPubKeyRing().equals(dispute.getTraderPubKeyRing())) if (contract.getBuyerPubKeyRing().equals(dispute.getTraderPubKeyRing()))
peerAddress = contract.getBuyerAddress(); peerNodeAddress = contract.getBuyerNodeAddress();
else else
peerAddress = contract.getSellerAddress(); peerNodeAddress = contract.getSellerNodeAddress();
p2PService.sendEncryptedMailboxMessage(peerAddress, p2PService.sendEncryptedMailboxMessage(peerNodeAddress,
dispute.getTraderPubKeyRing(), dispute.getTraderPubKeyRing(),
new DisputeResultMessage(disputeResult, p2PService.getAddress()), new DisputeResultMessage(disputeResult, p2PService.getAddress()),
new SendMailboxMessageListener() { new SendMailboxMessageListener() {
@ -364,9 +364,9 @@ public class DisputeManager {
// winner (or buyer in case of 50/50) sends tx to other peer // winner (or buyer in case of 50/50) sends tx to other peer
private void sendPeerPublishedPayoutTxMessage(Transaction transaction, Dispute dispute, Contract contract) { private void sendPeerPublishedPayoutTxMessage(Transaction transaction, Dispute dispute, Contract contract) {
PubKeyRing peersPubKeyRing = dispute.isDisputeOpenerIsBuyer() ? contract.getSellerPubKeyRing() : contract.getBuyerPubKeyRing(); PubKeyRing peersPubKeyRing = dispute.isDisputeOpenerIsBuyer() ? contract.getSellerPubKeyRing() : contract.getBuyerPubKeyRing();
Address peerAddress = dispute.isDisputeOpenerIsBuyer() ? contract.getSellerAddress() : contract.getBuyerAddress(); NodeAddress peerNodeAddress = dispute.isDisputeOpenerIsBuyer() ? contract.getSellerNodeAddress() : contract.getBuyerNodeAddress();
log.trace("sendPeerPublishedPayoutTxMessage to peerAddress " + peerAddress); log.trace("sendPeerPublishedPayoutTxMessage to peerAddress " + peerNodeAddress);
p2PService.sendEncryptedMailboxMessage(peerAddress, p2PService.sendEncryptedMailboxMessage(peerNodeAddress,
peersPubKeyRing, peersPubKeyRing,
new PeerPublishedPayoutTxMessage(transaction.bitcoinSerialize(), dispute.getTradeId(), p2PService.getAddress()), new PeerPublishedPayoutTxMessage(transaction.bitcoinSerialize(), dispute.getTradeId(), p2PService.getAddress()),
new SendMailboxMessageListener() { new SendMailboxMessageListener() {

View file

@ -18,7 +18,7 @@
package io.bitsquare.arbitration.messages; package io.bitsquare.arbitration.messages;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import javafx.beans.property.BooleanProperty; import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleBooleanProperty;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -47,17 +47,17 @@ public final class DisputeMailMessage extends DisputeMessage {
private boolean arrived; private boolean arrived;
private boolean storedInMailbox; private boolean storedInMailbox;
private boolean isSystemMessage; private boolean isSystemMessage;
private final Address myAddress; private final NodeAddress myNodeAddress;
transient private BooleanProperty arrivedProperty = new SimpleBooleanProperty(); transient private BooleanProperty arrivedProperty = new SimpleBooleanProperty();
transient private BooleanProperty storedInMailboxProperty = new SimpleBooleanProperty(); transient private BooleanProperty storedInMailboxProperty = new SimpleBooleanProperty();
public DisputeMailMessage(String tradeId, int traderId, boolean senderIsTrader, String message, Address myAddress) { public DisputeMailMessage(String tradeId, int traderId, boolean senderIsTrader, String message, NodeAddress myNodeAddress) {
this.tradeId = tradeId; this.tradeId = tradeId;
this.traderId = traderId; this.traderId = traderId;
this.senderIsTrader = senderIsTrader; this.senderIsTrader = senderIsTrader;
this.message = message; this.message = message;
this.myAddress = myAddress; this.myNodeAddress = myNodeAddress;
date = new Date().getTime(); date = new Date().getTime();
} }
@ -72,8 +72,8 @@ public final class DisputeMailMessage extends DisputeMessage {
} }
@Override @Override
public Address getSenderAddress() { public NodeAddress getSenderNodeAddress() {
return myAddress; return myNodeAddress;
} }
public void addAttachment(Attachment attachment) { public void addAttachment(Attachment attachment) {
@ -150,7 +150,7 @@ public final class DisputeMailMessage extends DisputeMessage {
if (tradeId != null ? !tradeId.equals(that.tradeId) : that.tradeId != null) return false; if (tradeId != null ? !tradeId.equals(that.tradeId) : that.tradeId != null) return false;
if (message != null ? !message.equals(that.message) : that.message != null) return false; if (message != null ? !message.equals(that.message) : that.message != null) return false;
if (attachments != null ? !attachments.equals(that.attachments) : that.attachments != null) return false; if (attachments != null ? !attachments.equals(that.attachments) : that.attachments != null) return false;
return !(myAddress != null ? !myAddress.equals(that.myAddress) : that.myAddress != null); return !(myNodeAddress != null ? !myNodeAddress.equals(that.myNodeAddress) : that.myNodeAddress != null);
} }
@ -165,7 +165,7 @@ public final class DisputeMailMessage extends DisputeMessage {
result = 31 * result + (arrived ? 1 : 0); result = 31 * result + (arrived ? 1 : 0);
result = 31 * result + (storedInMailbox ? 1 : 0); result = 31 * result + (storedInMailbox ? 1 : 0);
result = 31 * result + (isSystemMessage ? 1 : 0); result = 31 * result + (isSystemMessage ? 1 : 0);
result = 31 * result + (myAddress != null ? myAddress.hashCode() : 0); result = 31 * result + (myNodeAddress != null ? myNodeAddress.hashCode() : 0);
return result; return result;
} }

View file

@ -19,18 +19,18 @@ package io.bitsquare.arbitration.messages;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.arbitration.DisputeResult; import io.bitsquare.arbitration.DisputeResult;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
public final class DisputeResultMessage extends DisputeMessage { public final class DisputeResultMessage extends DisputeMessage {
// That object is sent over the wire, so we need to take care of version compatibility. // That object is sent over the wire, so we need to take care of version compatibility.
private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION; private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION;
public final DisputeResult disputeResult; public final DisputeResult disputeResult;
private final Address myAddress; private final NodeAddress myNodeAddress;
public DisputeResultMessage(DisputeResult disputeResult, Address myAddress) { public DisputeResultMessage(DisputeResult disputeResult, NodeAddress myNodeAddress) {
this.disputeResult = disputeResult; this.disputeResult = disputeResult;
this.myAddress = myAddress; this.myNodeAddress = myNodeAddress;
} }
@Override @Override
@ -42,19 +42,19 @@ public final class DisputeResultMessage extends DisputeMessage {
if (disputeResult != null ? !disputeResult.equals(that.disputeResult) : that.disputeResult != null) if (disputeResult != null ? !disputeResult.equals(that.disputeResult) : that.disputeResult != null)
return false; return false;
return !(myAddress != null ? !myAddress.equals(that.myAddress) : that.myAddress != null); return !(myNodeAddress != null ? !myNodeAddress.equals(that.myNodeAddress) : that.myNodeAddress != null);
} }
@Override @Override
public int hashCode() { public int hashCode() {
int result = disputeResult != null ? disputeResult.hashCode() : 0; int result = disputeResult != null ? disputeResult.hashCode() : 0;
result = 31 * result + (myAddress != null ? myAddress.hashCode() : 0); result = 31 * result + (myNodeAddress != null ? myNodeAddress.hashCode() : 0);
return result; return result;
} }
@Override @Override
public Address getSenderAddress() { public NodeAddress getSenderNodeAddress() {
return myAddress; return myNodeAddress;
} }
} }

View file

@ -19,18 +19,18 @@ package io.bitsquare.arbitration.messages;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.arbitration.Dispute; import io.bitsquare.arbitration.Dispute;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
public final class OpenNewDisputeMessage extends DisputeMessage { public final class OpenNewDisputeMessage extends DisputeMessage {
// That object is sent over the wire, so we need to take care of version compatibility. // That object is sent over the wire, so we need to take care of version compatibility.
private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION; private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION;
public final Dispute dispute; public final Dispute dispute;
private final Address myAddress; private final NodeAddress myNodeAddress;
public OpenNewDisputeMessage(Dispute dispute, Address myAddress) { public OpenNewDisputeMessage(Dispute dispute, NodeAddress myNodeAddress) {
this.dispute = dispute; this.dispute = dispute;
this.myAddress = myAddress; this.myNodeAddress = myNodeAddress;
} }
@Override @Override
@ -41,19 +41,19 @@ public final class OpenNewDisputeMessage extends DisputeMessage {
OpenNewDisputeMessage that = (OpenNewDisputeMessage) o; OpenNewDisputeMessage that = (OpenNewDisputeMessage) o;
if (dispute != null ? !dispute.equals(that.dispute) : that.dispute != null) return false; if (dispute != null ? !dispute.equals(that.dispute) : that.dispute != null) return false;
return !(myAddress != null ? !myAddress.equals(that.myAddress) : that.myAddress != null); return !(myNodeAddress != null ? !myNodeAddress.equals(that.myNodeAddress) : that.myNodeAddress != null);
} }
@Override @Override
public int hashCode() { public int hashCode() {
int result = dispute != null ? dispute.hashCode() : 0; int result = dispute != null ? dispute.hashCode() : 0;
result = 31 * result + (myAddress != null ? myAddress.hashCode() : 0); result = 31 * result + (myNodeAddress != null ? myNodeAddress.hashCode() : 0);
return result; return result;
} }
@Override @Override
public Address getSenderAddress() { public NodeAddress getSenderNodeAddress() {
return myAddress; return myNodeAddress;
} }
} }

View file

@ -19,17 +19,17 @@ package io.bitsquare.arbitration.messages;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.arbitration.Dispute; import io.bitsquare.arbitration.Dispute;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
public final class PeerOpenedDisputeMessage extends DisputeMessage { public final class PeerOpenedDisputeMessage extends DisputeMessage {
// That object is sent over the wire, so we need to take care of version compatibility. // That object is sent over the wire, so we need to take care of version compatibility.
private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION; private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION;
public final Dispute dispute; public final Dispute dispute;
private final Address myAddress; private final NodeAddress myNodeAddress;
public PeerOpenedDisputeMessage(Dispute dispute, Address myAddress) { public PeerOpenedDisputeMessage(Dispute dispute, NodeAddress myNodeAddress) {
this.dispute = dispute; this.dispute = dispute;
this.myAddress = myAddress; this.myNodeAddress = myNodeAddress;
} }
@Override @Override
@ -40,19 +40,19 @@ public final class PeerOpenedDisputeMessage extends DisputeMessage {
PeerOpenedDisputeMessage that = (PeerOpenedDisputeMessage) o; PeerOpenedDisputeMessage that = (PeerOpenedDisputeMessage) o;
if (dispute != null ? !dispute.equals(that.dispute) : that.dispute != null) return false; if (dispute != null ? !dispute.equals(that.dispute) : that.dispute != null) return false;
return !(myAddress != null ? !myAddress.equals(that.myAddress) : that.myAddress != null); return !(myNodeAddress != null ? !myNodeAddress.equals(that.myNodeAddress) : that.myNodeAddress != null);
} }
@Override @Override
public int hashCode() { public int hashCode() {
int result = dispute != null ? dispute.hashCode() : 0; int result = dispute != null ? dispute.hashCode() : 0;
result = 31 * result + (myAddress != null ? myAddress.hashCode() : 0); result = 31 * result + (myNodeAddress != null ? myNodeAddress.hashCode() : 0);
return result; return result;
} }
@Override @Override
public Address getSenderAddress() { public NodeAddress getSenderNodeAddress() {
return myAddress; return myNodeAddress;
} }
} }

View file

@ -18,7 +18,7 @@
package io.bitsquare.arbitration.messages; package io.bitsquare.arbitration.messages;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import java.util.Arrays; import java.util.Arrays;
@ -28,12 +28,12 @@ public final class PeerPublishedPayoutTxMessage extends DisputeMessage {
public final byte[] transaction; public final byte[] transaction;
public final String tradeId; public final String tradeId;
private final Address myAddress; private final NodeAddress myNodeAddress;
public PeerPublishedPayoutTxMessage(byte[] transaction, String tradeId, Address myAddress) { public PeerPublishedPayoutTxMessage(byte[] transaction, String tradeId, NodeAddress myNodeAddress) {
this.transaction = transaction; this.transaction = transaction;
this.tradeId = tradeId; this.tradeId = tradeId;
this.myAddress = myAddress; this.myNodeAddress = myNodeAddress;
} }
@Override @Override
@ -45,7 +45,7 @@ public final class PeerPublishedPayoutTxMessage extends DisputeMessage {
if (!Arrays.equals(transaction, that.transaction)) return false; if (!Arrays.equals(transaction, that.transaction)) return false;
if (tradeId != null ? !tradeId.equals(that.tradeId) : that.tradeId != null) return false; if (tradeId != null ? !tradeId.equals(that.tradeId) : that.tradeId != null) return false;
return !(myAddress != null ? !myAddress.equals(that.myAddress) : that.myAddress != null); return !(myNodeAddress != null ? !myNodeAddress.equals(that.myNodeAddress) : that.myNodeAddress != null);
} }
@ -53,13 +53,13 @@ public final class PeerPublishedPayoutTxMessage extends DisputeMessage {
public int hashCode() { public int hashCode() {
int result = transaction != null ? Arrays.hashCode(transaction) : 0; int result = transaction != null ? Arrays.hashCode(transaction) : 0;
result = 31 * result + (tradeId != null ? tradeId.hashCode() : 0); result = 31 * result + (tradeId != null ? tradeId.hashCode() : 0);
result = 31 * result + (myAddress != null ? myAddress.hashCode() : 0); result = 31 * result + (myNodeAddress != null ? myNodeAddress.hashCode() : 0);
return result; return result;
} }
@Override @Override
public Address getSenderAddress() { public NodeAddress getSenderNodeAddress() {
return myAddress; return myNodeAddress;
} }
} }

View file

@ -19,7 +19,7 @@ package io.bitsquare.trade;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.btc.FeePolicy; import io.bitsquare.btc.FeePolicy;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.storage.Storage; import io.bitsquare.storage.Storage;
import io.bitsquare.trade.offer.Offer; import io.bitsquare.trade.offer.Offer;
import io.bitsquare.trade.protocol.trade.BuyerAsOffererProtocol; import io.bitsquare.trade.protocol.trade.BuyerAsOffererProtocol;
@ -71,7 +71,7 @@ public class BuyerAsOffererTrade extends BuyerTrade implements OffererTrade, Ser
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Override @Override
public void handleTakeOfferRequest(TradeMessage message, Address taker) { public void handleTakeOfferRequest(TradeMessage message, NodeAddress taker) {
((OffererProtocol) tradeProtocol).handleTakeOfferRequest(message, taker); ((OffererProtocol) tradeProtocol).handleTakeOfferRequest(message, taker);
} }

View file

@ -19,7 +19,7 @@ package io.bitsquare.trade;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.btc.FeePolicy; import io.bitsquare.btc.FeePolicy;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.storage.Storage; import io.bitsquare.storage.Storage;
import io.bitsquare.trade.offer.Offer; import io.bitsquare.trade.offer.Offer;
import io.bitsquare.trade.protocol.trade.BuyerAsTakerProtocol; import io.bitsquare.trade.protocol.trade.BuyerAsTakerProtocol;
@ -46,8 +46,8 @@ public class BuyerAsTakerTrade extends BuyerTrade implements TakerTrade, Seriali
// Constructor, initialization // Constructor, initialization
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public BuyerAsTakerTrade(Offer offer, Coin tradeAmount, Address tradingPeerAddress, Storage<? extends TradableList> storage) { public BuyerAsTakerTrade(Offer offer, Coin tradeAmount, NodeAddress tradingPeerNodeAddress, Storage<? extends TradableList> storage) {
super(offer, tradeAmount, tradingPeerAddress, storage); super(offer, tradeAmount, tradingPeerNodeAddress, storage);
} }
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {

View file

@ -18,7 +18,7 @@
package io.bitsquare.trade; package io.bitsquare.trade;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.storage.Storage; import io.bitsquare.storage.Storage;
import io.bitsquare.trade.offer.Offer; import io.bitsquare.trade.offer.Offer;
import io.bitsquare.trade.protocol.trade.BuyerProtocol; import io.bitsquare.trade.protocol.trade.BuyerProtocol;
@ -36,8 +36,8 @@ public abstract class BuyerTrade extends Trade implements Serializable {
private static final Logger log = LoggerFactory.getLogger(BuyerAsOffererTrade.class); private static final Logger log = LoggerFactory.getLogger(BuyerAsOffererTrade.class);
BuyerTrade(Offer offer, Coin tradeAmount, Address tradingPeerAddress, Storage<? extends TradableList> storage) { BuyerTrade(Offer offer, Coin tradeAmount, NodeAddress tradingPeerNodeAddress, Storage<? extends TradableList> storage) {
super(offer, tradeAmount, tradingPeerAddress, storage); super(offer, tradeAmount, tradingPeerNodeAddress, storage);
} }
BuyerTrade(Offer offer, Storage<? extends TradableList> storage) { BuyerTrade(Offer offer, Storage<? extends TradableList> storage) {

View file

@ -20,7 +20,7 @@ package io.bitsquare.trade;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.common.crypto.PubKeyRing; import io.bitsquare.common.crypto.PubKeyRing;
import io.bitsquare.common.util.JsonExclude; import io.bitsquare.common.util.JsonExclude;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.payment.PaymentAccountContractData; import io.bitsquare.payment.PaymentAccountContractData;
import io.bitsquare.trade.offer.Offer; import io.bitsquare.trade.offer.Offer;
import org.bitcoinj.core.Coin; import org.bitcoinj.core.Coin;
@ -41,7 +41,7 @@ public class Contract implements Serializable {
public final Offer offer; public final Offer offer;
private final long tradeAmount; private final long tradeAmount;
public final String takeOfferFeeTxID; public final String takeOfferFeeTxID;
public final Address arbitratorAddress; public final NodeAddress arbitratorNodeAddress;
private final boolean isBuyerOffererAndSellerTaker; private final boolean isBuyerOffererAndSellerTaker;
private final String offererAccountId; private final String offererAccountId;
private final String takerAccountId; private final String takerAccountId;
@ -51,8 +51,8 @@ public class Contract implements Serializable {
private final PubKeyRing offererPubKeyRing; private final PubKeyRing offererPubKeyRing;
@JsonExclude @JsonExclude
private final PubKeyRing takerPubKeyRing; private final PubKeyRing takerPubKeyRing;
private final Address buyerAddress; private final NodeAddress buyerNodeAddress;
private final Address sellerAddress; private final NodeAddress sellerNodeAddress;
private final String offererPayoutAddressString; private final String offererPayoutAddressString;
@ -65,9 +65,9 @@ public class Contract implements Serializable {
public Contract(Offer offer, public Contract(Offer offer,
Coin tradeAmount, Coin tradeAmount,
String takeOfferFeeTxID, String takeOfferFeeTxID,
Address buyerAddress, NodeAddress buyerNodeAddress,
Address sellerAddress, NodeAddress sellerNodeAddress,
Address arbitratorAddress, NodeAddress arbitratorNodeAddress,
boolean isBuyerOffererAndSellerTaker, boolean isBuyerOffererAndSellerTaker,
String offererAccountId, String offererAccountId,
String takerAccountId, String takerAccountId,
@ -80,11 +80,11 @@ public class Contract implements Serializable {
byte[] offererBtcPubKey, byte[] offererBtcPubKey,
byte[] takerBtcPubKey) { byte[] takerBtcPubKey) {
this.offer = offer; this.offer = offer;
this.buyerAddress = buyerAddress; this.buyerNodeAddress = buyerNodeAddress;
this.sellerAddress = sellerAddress; this.sellerNodeAddress = sellerNodeAddress;
this.tradeAmount = tradeAmount.value; this.tradeAmount = tradeAmount.value;
this.takeOfferFeeTxID = takeOfferFeeTxID; this.takeOfferFeeTxID = takeOfferFeeTxID;
this.arbitratorAddress = arbitratorAddress; this.arbitratorNodeAddress = arbitratorNodeAddress;
this.isBuyerOffererAndSellerTaker = isBuyerOffererAndSellerTaker; this.isBuyerOffererAndSellerTaker = isBuyerOffererAndSellerTaker;
this.offererAccountId = offererAccountId; this.offererAccountId = offererAccountId;
this.takerAccountId = takerAccountId; this.takerAccountId = takerAccountId;
@ -150,13 +150,13 @@ public class Contract implements Serializable {
return Coin.valueOf(tradeAmount); return Coin.valueOf(tradeAmount);
} }
public Address getBuyerAddress() { public NodeAddress getBuyerNodeAddress() {
return buyerAddress; return buyerNodeAddress;
} }
public Address getSellerAddress() { public NodeAddress getSellerNodeAddress() {
return sellerAddress; return sellerNodeAddress;
} }
@Override @Override
@ -165,7 +165,7 @@ public class Contract implements Serializable {
"offer=" + offer + "offer=" + offer +
", tradeAmount=" + tradeAmount + ", tradeAmount=" + tradeAmount +
", takeOfferFeeTxID='" + takeOfferFeeTxID + '\'' + ", takeOfferFeeTxID='" + takeOfferFeeTxID + '\'' +
", arbitratorAddress=" + arbitratorAddress + ", arbitratorAddress=" + arbitratorNodeAddress +
", isBuyerOffererAndSellerTaker=" + isBuyerOffererAndSellerTaker + ", isBuyerOffererAndSellerTaker=" + isBuyerOffererAndSellerTaker +
", offererAccountId='" + offererAccountId + '\'' + ", offererAccountId='" + offererAccountId + '\'' +
", takerAccountId='" + takerAccountId + '\'' + ", takerAccountId='" + takerAccountId + '\'' +
@ -173,8 +173,8 @@ public class Contract implements Serializable {
", takerPaymentAccountContractData=" + takerPaymentAccountContractData + ", takerPaymentAccountContractData=" + takerPaymentAccountContractData +
", offererPubKeyRing=" + offererPubKeyRing + ", offererPubKeyRing=" + offererPubKeyRing +
", takerPubKeyRing=" + takerPubKeyRing + ", takerPubKeyRing=" + takerPubKeyRing +
", buyerAddress=" + buyerAddress + ", buyerAddress=" + buyerNodeAddress +
", sellerAddress=" + sellerAddress + ", sellerAddress=" + sellerNodeAddress +
", offererPayoutAddressString='" + offererPayoutAddressString + '\'' + ", offererPayoutAddressString='" + offererPayoutAddressString + '\'' +
", takerPayoutAddressString='" + takerPayoutAddressString + '\'' + ", takerPayoutAddressString='" + takerPayoutAddressString + '\'' +
", offererBtcPubKey=" + Arrays.toString(offererBtcPubKey) + ", offererBtcPubKey=" + Arrays.toString(offererBtcPubKey) +
@ -194,7 +194,7 @@ public class Contract implements Serializable {
if (offer != null ? !offer.equals(contract.offer) : contract.offer != null) return false; if (offer != null ? !offer.equals(contract.offer) : contract.offer != null) return false;
if (takeOfferFeeTxID != null ? !takeOfferFeeTxID.equals(contract.takeOfferFeeTxID) : contract.takeOfferFeeTxID != null) if (takeOfferFeeTxID != null ? !takeOfferFeeTxID.equals(contract.takeOfferFeeTxID) : contract.takeOfferFeeTxID != null)
return false; return false;
if (arbitratorAddress != null ? !arbitratorAddress.equals(contract.arbitratorAddress) : contract.arbitratorAddress != null) if (arbitratorNodeAddress != null ? !arbitratorNodeAddress.equals(contract.arbitratorNodeAddress) : contract.arbitratorNodeAddress != null)
return false; return false;
if (offererAccountId != null ? !offererAccountId.equals(contract.offererAccountId) : contract.offererAccountId != null) if (offererAccountId != null ? !offererAccountId.equals(contract.offererAccountId) : contract.offererAccountId != null)
return false; return false;
@ -208,9 +208,9 @@ public class Contract implements Serializable {
return false; return false;
if (takerPubKeyRing != null ? !takerPubKeyRing.equals(contract.takerPubKeyRing) : contract.takerPubKeyRing != null) if (takerPubKeyRing != null ? !takerPubKeyRing.equals(contract.takerPubKeyRing) : contract.takerPubKeyRing != null)
return false; return false;
if (buyerAddress != null ? !buyerAddress.equals(contract.buyerAddress) : contract.buyerAddress != null) if (buyerNodeAddress != null ? !buyerNodeAddress.equals(contract.buyerNodeAddress) : contract.buyerNodeAddress != null)
return false; return false;
if (sellerAddress != null ? !sellerAddress.equals(contract.sellerAddress) : contract.sellerAddress != null) if (sellerNodeAddress != null ? !sellerNodeAddress.equals(contract.sellerNodeAddress) : contract.sellerNodeAddress != null)
return false; return false;
if (offererPayoutAddressString != null ? !offererPayoutAddressString.equals(contract.offererPayoutAddressString) : contract.offererPayoutAddressString != null) if (offererPayoutAddressString != null ? !offererPayoutAddressString.equals(contract.offererPayoutAddressString) : contract.offererPayoutAddressString != null)
return false; return false;
@ -226,7 +226,7 @@ public class Contract implements Serializable {
int result = offer != null ? offer.hashCode() : 0; int result = offer != null ? offer.hashCode() : 0;
result = 31 * result + (int) (tradeAmount ^ (tradeAmount >>> 32)); result = 31 * result + (int) (tradeAmount ^ (tradeAmount >>> 32));
result = 31 * result + (takeOfferFeeTxID != null ? takeOfferFeeTxID.hashCode() : 0); result = 31 * result + (takeOfferFeeTxID != null ? takeOfferFeeTxID.hashCode() : 0);
result = 31 * result + (arbitratorAddress != null ? arbitratorAddress.hashCode() : 0); result = 31 * result + (arbitratorNodeAddress != null ? arbitratorNodeAddress.hashCode() : 0);
result = 31 * result + (isBuyerOffererAndSellerTaker ? 1 : 0); result = 31 * result + (isBuyerOffererAndSellerTaker ? 1 : 0);
result = 31 * result + (offererAccountId != null ? offererAccountId.hashCode() : 0); result = 31 * result + (offererAccountId != null ? offererAccountId.hashCode() : 0);
result = 31 * result + (takerAccountId != null ? takerAccountId.hashCode() : 0); result = 31 * result + (takerAccountId != null ? takerAccountId.hashCode() : 0);
@ -234,8 +234,8 @@ public class Contract implements Serializable {
result = 31 * result + (takerPaymentAccountContractData != null ? takerPaymentAccountContractData.hashCode() : 0); result = 31 * result + (takerPaymentAccountContractData != null ? takerPaymentAccountContractData.hashCode() : 0);
result = 31 * result + (offererPubKeyRing != null ? offererPubKeyRing.hashCode() : 0); result = 31 * result + (offererPubKeyRing != null ? offererPubKeyRing.hashCode() : 0);
result = 31 * result + (takerPubKeyRing != null ? takerPubKeyRing.hashCode() : 0); result = 31 * result + (takerPubKeyRing != null ? takerPubKeyRing.hashCode() : 0);
result = 31 * result + (buyerAddress != null ? buyerAddress.hashCode() : 0); result = 31 * result + (buyerNodeAddress != null ? buyerNodeAddress.hashCode() : 0);
result = 31 * result + (sellerAddress != null ? sellerAddress.hashCode() : 0); result = 31 * result + (sellerNodeAddress != null ? sellerNodeAddress.hashCode() : 0);
result = 31 * result + (offererPayoutAddressString != null ? offererPayoutAddressString.hashCode() : 0); result = 31 * result + (offererPayoutAddressString != null ? offererPayoutAddressString.hashCode() : 0);
result = 31 * result + (takerPayoutAddressString != null ? takerPayoutAddressString.hashCode() : 0); result = 31 * result + (takerPayoutAddressString != null ? takerPayoutAddressString.hashCode() : 0);
result = 31 * result + (offererBtcPubKey != null ? Arrays.hashCode(offererBtcPubKey) : 0); result = 31 * result + (offererBtcPubKey != null ? Arrays.hashCode(offererBtcPubKey) : 0);

View file

@ -18,9 +18,9 @@
package io.bitsquare.trade; package io.bitsquare.trade;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.trade.protocol.trade.messages.TradeMessage; import io.bitsquare.trade.protocol.trade.messages.TradeMessage;
public interface OffererTrade { public interface OffererTrade {
void handleTakeOfferRequest(TradeMessage message, Address peerAddress); void handleTakeOfferRequest(TradeMessage message, NodeAddress peerNodeAddress);
} }

View file

@ -18,7 +18,7 @@
package io.bitsquare.trade; package io.bitsquare.trade;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.storage.Storage; import io.bitsquare.storage.Storage;
import io.bitsquare.trade.offer.Offer; import io.bitsquare.trade.offer.Offer;
import io.bitsquare.trade.protocol.trade.OffererProtocol; import io.bitsquare.trade.protocol.trade.OffererProtocol;
@ -67,7 +67,7 @@ public class SellerAsOffererTrade extends SellerTrade implements OffererTrade, S
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Override @Override
public void handleTakeOfferRequest(TradeMessage message, Address taker) { public void handleTakeOfferRequest(TradeMessage message, NodeAddress taker) {
((OffererProtocol) tradeProtocol).handleTakeOfferRequest(message, taker); ((OffererProtocol) tradeProtocol).handleTakeOfferRequest(message, taker);
} }
} }

View file

@ -18,7 +18,7 @@
package io.bitsquare.trade; package io.bitsquare.trade;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.storage.Storage; import io.bitsquare.storage.Storage;
import io.bitsquare.trade.offer.Offer; import io.bitsquare.trade.offer.Offer;
import io.bitsquare.trade.protocol.trade.SellerAsTakerProtocol; import io.bitsquare.trade.protocol.trade.SellerAsTakerProtocol;
@ -43,8 +43,8 @@ public class SellerAsTakerTrade extends SellerTrade implements TakerTrade, Seria
// Constructor, initialization // Constructor, initialization
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public SellerAsTakerTrade(Offer offer, Coin tradeAmount, Address tradingPeerAddress, Storage<? extends TradableList> storage) { public SellerAsTakerTrade(Offer offer, Coin tradeAmount, NodeAddress tradingPeerNodeAddress, Storage<? extends TradableList> storage) {
super(offer, tradeAmount, tradingPeerAddress, storage); super(offer, tradeAmount, tradingPeerNodeAddress, storage);
} }
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {

View file

@ -18,7 +18,7 @@
package io.bitsquare.trade; package io.bitsquare.trade;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.storage.Storage; import io.bitsquare.storage.Storage;
import io.bitsquare.trade.offer.Offer; import io.bitsquare.trade.offer.Offer;
import io.bitsquare.trade.protocol.trade.SellerProtocol; import io.bitsquare.trade.protocol.trade.SellerProtocol;
@ -36,8 +36,8 @@ public abstract class SellerTrade extends Trade implements Serializable {
private static final Logger log = LoggerFactory.getLogger(BuyerAsTakerTrade.class); private static final Logger log = LoggerFactory.getLogger(BuyerAsTakerTrade.class);
public SellerTrade(Offer offer, Coin tradeAmount, Address tradingPeerAddress, Storage<? extends TradableList> storage) { public SellerTrade(Offer offer, Coin tradeAmount, NodeAddress tradingPeerNodeAddress, Storage<? extends TradableList> storage) {
super(offer, tradeAmount, tradingPeerAddress, storage); super(offer, tradeAmount, tradingPeerNodeAddress, storage);
} }
public SellerTrade(Offer offer, Storage<? extends TradableList> storage) { public SellerTrade(Offer offer, Storage<? extends TradableList> storage) {

View file

@ -28,7 +28,7 @@ import io.bitsquare.btc.TradeWalletService;
import io.bitsquare.btc.WalletService; import io.bitsquare.btc.WalletService;
import io.bitsquare.common.crypto.KeyRing; import io.bitsquare.common.crypto.KeyRing;
import io.bitsquare.common.taskrunner.Model; import io.bitsquare.common.taskrunner.Model;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.P2PService; import io.bitsquare.p2p.P2PService;
import io.bitsquare.p2p.messaging.DecryptedMsgWithPubKey; import io.bitsquare.p2p.messaging.DecryptedMsgWithPubKey;
import io.bitsquare.storage.Storage; import io.bitsquare.storage.Storage;
@ -127,7 +127,7 @@ abstract public class Trade implements Tradable, Model, Serializable {
// Mutable // Mutable
private Coin tradeAmount; private Coin tradeAmount;
private Address tradingPeerAddress; private NodeAddress tradingPeerNodeAddress;
transient private ObjectProperty<Coin> tradeAmountProperty; transient private ObjectProperty<Coin> tradeAmountProperty;
transient private ObjectProperty<Fiat> tradeVolumeProperty; transient private ObjectProperty<Fiat> tradeVolumeProperty;
@ -166,7 +166,7 @@ abstract public class Trade implements Tradable, Model, Serializable {
private long lockTimeAsBlockHeight; private long lockTimeAsBlockHeight;
private int openDisputeTimeAsBlockHeight; private int openDisputeTimeAsBlockHeight;
private int checkPaymentTimeAsBlockHeight; private int checkPaymentTimeAsBlockHeight;
private Address arbitratorAddress; private NodeAddress arbitratorNodeAddress;
private String takerPaymentAccountId; private String takerPaymentAccountId;
private boolean halfTradePeriodReachedWarningDisplayed; private boolean halfTradePeriodReachedWarningDisplayed;
private boolean tradePeriodOverWarningDisplayed; private boolean tradePeriodOverWarningDisplayed;
@ -192,12 +192,12 @@ abstract public class Trade implements Tradable, Model, Serializable {
} }
// taker // taker
protected Trade(Offer offer, Coin tradeAmount, Address tradingPeerAddress, protected Trade(Offer offer, Coin tradeAmount, NodeAddress tradingPeerNodeAddress,
Storage<? extends TradableList> storage) { Storage<? extends TradableList> storage) {
this(offer, storage); this(offer, storage);
this.tradeAmount = tradeAmount; this.tradeAmount = tradeAmount;
this.tradingPeerAddress = tradingPeerAddress; this.tradingPeerNodeAddress = tradingPeerNodeAddress;
tradeAmountProperty.set(tradeAmount); tradeAmountProperty.set(tradeAmount);
tradeVolumeProperty.set(getTradeVolume()); tradeVolumeProperty.set(getTradeVolume());
} }
@ -417,16 +417,16 @@ abstract public class Trade implements Tradable, Model, Serializable {
this.takeOfferDate = takeOfferDate; this.takeOfferDate = takeOfferDate;
} }
public void setTradingPeerAddress(Address tradingPeerAddress) { public void setTradingPeerNodeAddress(NodeAddress tradingPeerNodeAddress) {
if (tradingPeerAddress == null) if (tradingPeerNodeAddress == null)
log.error("tradingPeerAddress=null"); log.error("tradingPeerAddress=null");
else else
this.tradingPeerAddress = tradingPeerAddress; this.tradingPeerNodeAddress = tradingPeerNodeAddress;
} }
@Nullable @Nullable
public Address getTradingPeerAddress() { public NodeAddress getTradingPeerNodeAddress() {
return tradingPeerAddress; return tradingPeerNodeAddress;
} }
public void setTradeAmount(Coin tradeAmount) { public void setTradeAmount(Coin tradeAmount) {
@ -519,12 +519,12 @@ abstract public class Trade implements Tradable, Model, Serializable {
return errorMessageProperty; return errorMessageProperty;
} }
public Address getArbitratorAddress() { public NodeAddress getArbitratorNodeAddress() {
return arbitratorAddress; return arbitratorNodeAddress;
} }
public void setArbitratorAddress(Address arbitratorAddress) { public void setArbitratorNodeAddress(NodeAddress arbitratorNodeAddress) {
this.arbitratorAddress = arbitratorAddress; this.arbitratorNodeAddress = arbitratorNodeAddress;
} }
public String getTakerPaymentAccountId() { public String getTakerPaymentAccountId() {
@ -610,7 +610,7 @@ abstract public class Trade implements Tradable, Model, Serializable {
public String toString() { public String toString() {
return "Trade{" + return "Trade{" +
"tradeAmount=" + tradeAmount + "tradeAmount=" + tradeAmount +
", tradingPeer=" + tradingPeerAddress + ", tradingPeer=" + tradingPeerNodeAddress +
", tradeAmountProperty=" + tradeAmountProperty + ", tradeAmountProperty=" + tradeAmountProperty +
", tradeVolumeProperty=" + tradeVolumeProperty + ", tradeVolumeProperty=" + tradeVolumeProperty +
", processStateProperty=" + processStateProperty + ", processStateProperty=" + processStateProperty +

View file

@ -26,9 +26,9 @@ import io.bitsquare.common.UserThread;
import io.bitsquare.common.crypto.KeyRing; import io.bitsquare.common.crypto.KeyRing;
import io.bitsquare.common.handlers.FaultHandler; import io.bitsquare.common.handlers.FaultHandler;
import io.bitsquare.common.handlers.ResultHandler; import io.bitsquare.common.handlers.ResultHandler;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.FirstPeerAuthenticatedListener; import io.bitsquare.p2p.FirstPeerAuthenticatedListener;
import io.bitsquare.p2p.Message; import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.P2PService; import io.bitsquare.p2p.P2PService;
import io.bitsquare.p2p.messaging.DecryptedMailListener; import io.bitsquare.p2p.messaging.DecryptedMailListener;
import io.bitsquare.p2p.messaging.DecryptedMailboxListener; import io.bitsquare.p2p.messaging.DecryptedMailboxListener;
@ -114,27 +114,27 @@ public class TradeManager {
p2PService.addDecryptedMailListener(new DecryptedMailListener() { p2PService.addDecryptedMailListener(new DecryptedMailListener() {
@Override @Override
public void onMailMessage(DecryptedMsgWithPubKey decryptedMsgWithPubKey, Address peerAddress) { public void onMailMessage(DecryptedMsgWithPubKey decryptedMsgWithPubKey, NodeAddress peerNodeAddress) {
Message message = decryptedMsgWithPubKey.message; Message message = decryptedMsgWithPubKey.message;
// Handler for incoming initial messages from taker // Handler for incoming initial messages from taker
if (message instanceof PayDepositRequest) { if (message instanceof PayDepositRequest) {
log.trace("Received PayDepositRequest: " + message); log.trace("Received PayDepositRequest: " + message);
handleInitialTakeOfferRequest((PayDepositRequest) message, peerAddress); handleInitialTakeOfferRequest((PayDepositRequest) message, peerNodeAddress);
} }
} }
}); });
p2PService.addDecryptedMailboxListener(new DecryptedMailboxListener() { p2PService.addDecryptedMailboxListener(new DecryptedMailboxListener() {
@Override @Override
public void onMailboxMessageAdded(DecryptedMsgWithPubKey decryptedMsgWithPubKey, Address senderAddress) { public void onMailboxMessageAdded(DecryptedMsgWithPubKey decryptedMsgWithPubKey, NodeAddress senderNodeAddress) {
log.trace("onMailboxMessageAdded decryptedMessageWithPubKey: " + decryptedMsgWithPubKey); log.trace("onMailboxMessageAdded decryptedMessageWithPubKey: " + decryptedMsgWithPubKey);
log.trace("onMailboxMessageAdded senderAddress: " + senderAddress); log.trace("onMailboxMessageAdded senderAddress: " + senderNodeAddress);
Message message = decryptedMsgWithPubKey.message; Message message = decryptedMsgWithPubKey.message;
if (message instanceof PayDepositRequest) { if (message instanceof PayDepositRequest) {
PayDepositRequest payDepositRequest = (PayDepositRequest) message; PayDepositRequest payDepositRequest = (PayDepositRequest) message;
log.trace("Received payDepositRequest: " + payDepositRequest); log.trace("Received payDepositRequest: " + payDepositRequest);
if (payDepositRequest.getSenderAddress().equals(senderAddress)) if (payDepositRequest.getSenderNodeAddress().equals(senderNodeAddress))
handleInitialTakeOfferRequest(payDepositRequest, senderAddress); handleInitialTakeOfferRequest(payDepositRequest, senderNodeAddress);
else else
log.warn("Peer address not matching for payDepositRequest"); log.warn("Peer address not matching for payDepositRequest");
} else if (message instanceof TradeMessage) { } else if (message instanceof TradeMessage) {
@ -192,8 +192,8 @@ public class TradeManager {
//failedTrades.stream().filter(Trade::isTakerFeePaid).forEach(this::addTradeToFailedTrades); //failedTrades.stream().filter(Trade::isTakerFeePaid).forEach(this::addTradeToFailedTrades);
} }
private void handleInitialTakeOfferRequest(TradeMessage message, Address peerAddress) { private void handleInitialTakeOfferRequest(TradeMessage message, NodeAddress peerNodeAddress) {
log.trace("handleNewMessage: message = " + message.getClass().getSimpleName() + " from " + peerAddress); log.trace("handleNewMessage: message = " + message.getClass().getSimpleName() + " from " + peerNodeAddress);
try { try {
nonEmptyStringOf(message.tradeId); nonEmptyStringOf(message.tradeId);
} catch (Throwable t) { } catch (Throwable t) {
@ -215,7 +215,7 @@ public class TradeManager {
trade.setStorage(tradableListStorage); trade.setStorage(tradableListStorage);
initTrade(trade); initTrade(trade);
trades.add(trade); trades.add(trade);
((OffererTrade) trade).handleTakeOfferRequest(message, peerAddress); ((OffererTrade) trade).handleTakeOfferRequest(message, peerNodeAddress);
} else { } else {
// TODO respond // TODO respond
//(RequestDepositTxInputsMessage)message. //(RequestDepositTxInputsMessage)message.
@ -278,9 +278,9 @@ public class TradeManager {
TradeResultHandler tradeResultHandler) { TradeResultHandler tradeResultHandler) {
Trade trade; Trade trade;
if (offer.getDirection() == Offer.Direction.BUY) if (offer.getDirection() == Offer.Direction.BUY)
trade = new SellerAsTakerTrade(offer, amount, model.getPeerAddress(), tradableListStorage); trade = new SellerAsTakerTrade(offer, amount, model.getPeerNodeAddress(), tradableListStorage);
else else
trade = new BuyerAsTakerTrade(offer, amount, model.getPeerAddress(), tradableListStorage); trade = new BuyerAsTakerTrade(offer, amount, model.getPeerNodeAddress(), tradableListStorage);
trade.setTakeOfferDate(new Date()); trade.setTakeOfferDate(new Date());
trade.setTakerPaymentAccountId(paymentAccountId); trade.setTakerPaymentAccountId(paymentAccountId);

View file

@ -24,7 +24,7 @@ import io.bitsquare.common.crypto.PubKeyRing;
import io.bitsquare.common.handlers.ResultHandler; import io.bitsquare.common.handlers.ResultHandler;
import io.bitsquare.common.util.JsonExclude; import io.bitsquare.common.util.JsonExclude;
import io.bitsquare.locale.Country; import io.bitsquare.locale.Country;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.storage.data.PubKeyProtectedExpirablePayload; import io.bitsquare.p2p.storage.data.PubKeyProtectedExpirablePayload;
import io.bitsquare.payment.PaymentMethod; import io.bitsquare.payment.PaymentMethod;
import io.bitsquare.trade.protocol.availability.OfferAvailabilityModel; import io.bitsquare.trade.protocol.availability.OfferAvailabilityModel;
@ -79,7 +79,7 @@ public final class Offer implements PubKeyProtectedExpirablePayload {
private final long fiatPrice; private final long fiatPrice;
private final long amount; private final long amount;
private final long minAmount; private final long minAmount;
private final Address offererAddress; private final NodeAddress offererNodeAddress;
@JsonExclude @JsonExclude
private final PubKeyRing pubKeyRing; private final PubKeyRing pubKeyRing;
private final String paymentMethodName; private final String paymentMethodName;
@ -89,7 +89,7 @@ public final class Offer implements PubKeyProtectedExpirablePayload {
@Nullable @Nullable
private final List<String> acceptedCountryCodes; private final List<String> acceptedCountryCodes;
private final List<Address> arbitratorAddresses; private final List<NodeAddress> arbitratorNodeAddresses;
// Mutable property. Has to be set before offer is save in P2P network as it changes the objects hash! // Mutable property. Has to be set before offer is save in P2P network as it changes the objects hash!
private String offerFeePaymentTxID; private String offerFeePaymentTxID;
@ -111,7 +111,7 @@ public final class Offer implements PubKeyProtectedExpirablePayload {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public Offer(String id, public Offer(String id,
Address offererAddress, NodeAddress offererNodeAddress,
PubKeyRing pubKeyRing, PubKeyRing pubKeyRing,
Direction direction, Direction direction,
long fiatPrice, long fiatPrice,
@ -121,10 +121,10 @@ public final class Offer implements PubKeyProtectedExpirablePayload {
String currencyCode, String currencyCode,
@Nullable Country paymentMethodCountry, @Nullable Country paymentMethodCountry,
String offererPaymentAccountId, String offererPaymentAccountId,
List<Address> arbitratorAddresses, List<NodeAddress> arbitratorNodeAddresses,
@Nullable List<String> acceptedCountryCodes) { @Nullable List<String> acceptedCountryCodes) {
this.id = id; this.id = id;
this.offererAddress = offererAddress; this.offererNodeAddress = offererNodeAddress;
this.pubKeyRing = pubKeyRing; this.pubKeyRing = pubKeyRing;
this.direction = direction; this.direction = direction;
this.fiatPrice = fiatPrice; this.fiatPrice = fiatPrice;
@ -134,7 +134,7 @@ public final class Offer implements PubKeyProtectedExpirablePayload {
this.currencyCode = currencyCode; this.currencyCode = currencyCode;
this.paymentMethodCountryCode = paymentMethodCountry != null ? paymentMethodCountry.code : null; this.paymentMethodCountryCode = paymentMethodCountry != null ? paymentMethodCountry.code : null;
this.offererPaymentAccountId = offererPaymentAccountId; this.offererPaymentAccountId = offererPaymentAccountId;
this.arbitratorAddresses = arbitratorAddresses; this.arbitratorNodeAddresses = arbitratorNodeAddresses;
this.acceptedCountryCodes = acceptedCountryCodes; this.acceptedCountryCodes = acceptedCountryCodes;
date = new Date().getTime(); date = new Date().getTime();
@ -155,7 +155,7 @@ public final class Offer implements PubKeyProtectedExpirablePayload {
public void validate() { public void validate() {
checkNotNull(getAmount(), "Amount is null"); checkNotNull(getAmount(), "Amount is null");
checkNotNull(getArbitratorAddresses(), "Arbitrator is null"); checkNotNull(getArbitratorNodeAddresses(), "Arbitrator is null");
checkNotNull(getDate(), "CreationDate is null"); checkNotNull(getDate(), "CreationDate is null");
checkNotNull(getCurrencyCode(), "Currency is null"); checkNotNull(getCurrencyCode(), "Currency is null");
checkNotNull(getDirection(), "Direction is null"); checkNotNull(getDirection(), "Direction is null");
@ -266,8 +266,8 @@ public final class Offer implements PubKeyProtectedExpirablePayload {
return id.substring(0, 8); return id.substring(0, 8);
} }
public Address getOffererAddress() { public NodeAddress getOffererNodeAddress() {
return offererAddress; return offererNodeAddress;
} }
public PubKeyRing getPubKeyRing() { public PubKeyRing getPubKeyRing() {
@ -316,8 +316,8 @@ public final class Offer implements PubKeyProtectedExpirablePayload {
return offerFeePaymentTxID; return offerFeePaymentTxID;
} }
public List<Address> getArbitratorAddresses() { public List<NodeAddress> getArbitratorNodeAddresses() {
return arbitratorAddresses; return arbitratorNodeAddresses;
} }
public Date getDate() { public Date getDate() {
@ -354,7 +354,7 @@ public final class Offer implements PubKeyProtectedExpirablePayload {
if (id != null ? !id.equals(offer.id) : offer.id != null) return false; if (id != null ? !id.equals(offer.id) : offer.id != null) return false;
if (direction != offer.direction) return false; if (direction != offer.direction) return false;
if (currencyCode != null ? !currencyCode.equals(offer.currencyCode) : offer.currencyCode != null) return false; if (currencyCode != null ? !currencyCode.equals(offer.currencyCode) : offer.currencyCode != null) return false;
if (offererAddress != null ? !offererAddress.equals(offer.offererAddress) : offer.offererAddress != null) if (offererNodeAddress != null ? !offererNodeAddress.equals(offer.offererNodeAddress) : offer.offererNodeAddress != null)
return false; return false;
if (pubKeyRing != null ? !pubKeyRing.equals(offer.pubKeyRing) : offer.pubKeyRing != null) return false; if (pubKeyRing != null ? !pubKeyRing.equals(offer.pubKeyRing) : offer.pubKeyRing != null) return false;
if (paymentMethodName != null ? !paymentMethodName.equals(offer.paymentMethodName) : offer.paymentMethodName != null) if (paymentMethodName != null ? !paymentMethodName.equals(offer.paymentMethodName) : offer.paymentMethodName != null)
@ -365,7 +365,7 @@ public final class Offer implements PubKeyProtectedExpirablePayload {
return false; return false;
if (acceptedCountryCodes != null ? !acceptedCountryCodes.equals(offer.acceptedCountryCodes) : offer.acceptedCountryCodes != null) if (acceptedCountryCodes != null ? !acceptedCountryCodes.equals(offer.acceptedCountryCodes) : offer.acceptedCountryCodes != null)
return false; return false;
if (arbitratorAddresses != null ? !arbitratorAddresses.equals(offer.arbitratorAddresses) : offer.arbitratorAddresses != null) if (arbitratorNodeAddresses != null ? !arbitratorNodeAddresses.equals(offer.arbitratorNodeAddresses) : offer.arbitratorNodeAddresses != null)
return false; return false;
return !(offerFeePaymentTxID != null ? !offerFeePaymentTxID.equals(offer.offerFeePaymentTxID) : offer.offerFeePaymentTxID != null); return !(offerFeePaymentTxID != null ? !offerFeePaymentTxID.equals(offer.offerFeePaymentTxID) : offer.offerFeePaymentTxID != null);
@ -380,13 +380,13 @@ public final class Offer implements PubKeyProtectedExpirablePayload {
result = 31 * result + (int) (fiatPrice ^ (fiatPrice >>> 32)); result = 31 * result + (int) (fiatPrice ^ (fiatPrice >>> 32));
result = 31 * result + (int) (amount ^ (amount >>> 32)); result = 31 * result + (int) (amount ^ (amount >>> 32));
result = 31 * result + (int) (minAmount ^ (minAmount >>> 32)); result = 31 * result + (int) (minAmount ^ (minAmount >>> 32));
result = 31 * result + (offererAddress != null ? offererAddress.hashCode() : 0); result = 31 * result + (offererNodeAddress != null ? offererNodeAddress.hashCode() : 0);
result = 31 * result + (pubKeyRing != null ? pubKeyRing.hashCode() : 0); result = 31 * result + (pubKeyRing != null ? pubKeyRing.hashCode() : 0);
result = 31 * result + (paymentMethodName != null ? paymentMethodName.hashCode() : 0); result = 31 * result + (paymentMethodName != null ? paymentMethodName.hashCode() : 0);
result = 31 * result + (paymentMethodCountryCode != null ? paymentMethodCountryCode.hashCode() : 0); result = 31 * result + (paymentMethodCountryCode != null ? paymentMethodCountryCode.hashCode() : 0);
result = 31 * result + (offererPaymentAccountId != null ? offererPaymentAccountId.hashCode() : 0); result = 31 * result + (offererPaymentAccountId != null ? offererPaymentAccountId.hashCode() : 0);
result = 31 * result + (acceptedCountryCodes != null ? acceptedCountryCodes.hashCode() : 0); result = 31 * result + (acceptedCountryCodes != null ? acceptedCountryCodes.hashCode() : 0);
result = 31 * result + (arbitratorAddresses != null ? arbitratorAddresses.hashCode() : 0); result = 31 * result + (arbitratorNodeAddresses != null ? arbitratorNodeAddresses.hashCode() : 0);
result = 31 * result + (offerFeePaymentTxID != null ? offerFeePaymentTxID.hashCode() : 0); result = 31 * result + (offerFeePaymentTxID != null ? offerFeePaymentTxID.hashCode() : 0);
return result; return result;
} }
@ -401,13 +401,13 @@ public final class Offer implements PubKeyProtectedExpirablePayload {
", fiatPrice=" + fiatPrice + ", fiatPrice=" + fiatPrice +
", amount=" + amount + ", amount=" + amount +
", minAmount=" + minAmount + ", minAmount=" + minAmount +
", offererAddress=" + offererAddress + ", offererAddress=" + offererNodeAddress +
", pubKeyRing=" + pubKeyRing + ", pubKeyRing=" + pubKeyRing +
", paymentMethodName='" + paymentMethodName + '\'' + ", paymentMethodName='" + paymentMethodName + '\'' +
", paymentMethodCountryCode='" + paymentMethodCountryCode + '\'' + ", paymentMethodCountryCode='" + paymentMethodCountryCode + '\'' +
", offererPaymentAccountId='" + offererPaymentAccountId + '\'' + ", offererPaymentAccountId='" + offererPaymentAccountId + '\'' +
", acceptedCountryCodes=" + acceptedCountryCodes + ", acceptedCountryCodes=" + acceptedCountryCodes +
", arbitratorAddresses=" + arbitratorAddresses + ", arbitratorAddresses=" + arbitratorNodeAddresses +
", offerFeePaymentTxID='" + offerFeePaymentTxID + '\'' + ", offerFeePaymentTxID='" + offerFeePaymentTxID + '\'' +
", state=" + state + ", state=" + state +
", stateProperty=" + stateProperty + ", stateProperty=" + stateProperty +

View file

@ -24,9 +24,9 @@ import io.bitsquare.common.UserThread;
import io.bitsquare.common.crypto.KeyRing; import io.bitsquare.common.crypto.KeyRing;
import io.bitsquare.common.handlers.ErrorMessageHandler; import io.bitsquare.common.handlers.ErrorMessageHandler;
import io.bitsquare.common.handlers.ResultHandler; import io.bitsquare.common.handlers.ResultHandler;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.FirstPeerAuthenticatedListener; import io.bitsquare.p2p.FirstPeerAuthenticatedListener;
import io.bitsquare.p2p.Message; import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.P2PService; import io.bitsquare.p2p.P2PService;
import io.bitsquare.p2p.messaging.SendMailMessageListener; import io.bitsquare.p2p.messaging.SendMailMessageListener;
import io.bitsquare.storage.Storage; import io.bitsquare.storage.Storage;
@ -287,7 +287,7 @@ public class OpenOfferManager {
// Offer Availability // Offer Availability
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
private void handleOfferAvailabilityRequest(OfferAvailabilityRequest message, Address sender) { private void handleOfferAvailabilityRequest(OfferAvailabilityRequest message, NodeAddress sender) {
log.trace("handleNewMessage: message = " + message.getClass().getSimpleName() + " from " + sender); log.trace("handleNewMessage: message = " + message.getClass().getSimpleName() + " from " + sender);
try { try {
nonEmptyStringOf(message.offerId); nonEmptyStringOf(message.offerId);

View file

@ -19,7 +19,7 @@ package io.bitsquare.trade.protocol.availability;
import io.bitsquare.common.crypto.PubKeyRing; import io.bitsquare.common.crypto.PubKeyRing;
import io.bitsquare.common.taskrunner.Model; import io.bitsquare.common.taskrunner.Model;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.P2PService; import io.bitsquare.p2p.P2PService;
import io.bitsquare.trade.offer.Offer; import io.bitsquare.trade.offer.Offer;
import io.bitsquare.trade.protocol.availability.messages.OfferMessage; import io.bitsquare.trade.protocol.availability.messages.OfferMessage;
@ -33,7 +33,7 @@ public class OfferAvailabilityModel implements Model {
public final PubKeyRing pubKeyRing; public final PubKeyRing pubKeyRing;
public final P2PService p2PService; public final P2PService p2PService;
private Address peerAddress; private NodeAddress peerNodeAddress;
private OfferMessage message; private OfferMessage message;
public OfferAvailabilityModel(Offer offer, public OfferAvailabilityModel(Offer offer,
@ -44,12 +44,12 @@ public class OfferAvailabilityModel implements Model {
this.p2PService = p2PService; this.p2PService = p2PService;
} }
public Address getPeerAddress() { public NodeAddress getPeerNodeAddress() {
return peerAddress; return peerNodeAddress;
} }
public void setPeerAddress(Address peerAddress) { public void setPeerNodeAddress(NodeAddress peerNodeAddress) {
this.peerAddress = peerAddress; this.peerNodeAddress = peerNodeAddress;
} }
public void setMessage(OfferMessage message) { public void setMessage(OfferMessage message) {

View file

@ -85,7 +85,7 @@ public class OfferAvailabilityProtocol {
model.offer.setState(Offer.State.UNDEFINED); model.offer.setState(Offer.State.UNDEFINED);
model.p2PService.addDecryptedMailListener(decryptedMailListener); model.p2PService.addDecryptedMailListener(decryptedMailListener);
model.setPeerAddress(model.offer.getOffererAddress()); model.setPeerNodeAddress(model.offer.getOffererNodeAddress());
taskRunner = new TaskRunner<>(model, taskRunner = new TaskRunner<>(model,
() -> { () -> {

View file

@ -38,7 +38,7 @@ public class SendOfferAvailabilityRequest extends Task<OfferAvailabilityModel> {
try { try {
runInterceptHook(); runInterceptHook();
model.p2PService.sendEncryptedMailMessage(model.getPeerAddress(), model.p2PService.sendEncryptedMailMessage(model.getPeerNodeAddress(),
model.offer.getPubKeyRing(), model.offer.getPubKeyRing(),
new OfferAvailabilityRequest(model.offer.getId(), model.getPubKeyRing()), new OfferAvailabilityRequest(model.offer.getId(), model.getPubKeyRing()),
new SendMailMessageListener() { new SendMailMessageListener() {

View file

@ -21,7 +21,7 @@ import io.bitsquare.arbitration.Arbitrator;
import io.bitsquare.btc.FeePolicy; import io.bitsquare.btc.FeePolicy;
import io.bitsquare.common.taskrunner.Task; import io.bitsquare.common.taskrunner.Task;
import io.bitsquare.common.taskrunner.TaskRunner; import io.bitsquare.common.taskrunner.TaskRunner;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.trade.protocol.placeoffer.PlaceOfferModel; import io.bitsquare.trade.protocol.placeoffer.PlaceOfferModel;
import io.bitsquare.trade.protocol.trade.ArbitrationSelectionRule; import io.bitsquare.trade.protocol.trade.ArbitrationSelectionRule;
import org.bitcoinj.core.Transaction; import org.bitcoinj.core.Transaction;
@ -40,9 +40,9 @@ public class CreateOfferFeeTx extends Task<PlaceOfferModel> {
try { try {
runInterceptHook(); runInterceptHook();
Address selectedArbitratorAddress = ArbitrationSelectionRule.select(model.user.getAcceptedArbitratorAddresses(), model.offer); NodeAddress selectedArbitratorNodeAddress = ArbitrationSelectionRule.select(model.user.getAcceptedArbitratorAddresses(), model.offer);
log.debug("selectedArbitratorAddress " + selectedArbitratorAddress); log.debug("selectedArbitratorAddress " + selectedArbitratorNodeAddress);
Arbitrator selectedArbitrator = model.user.getAcceptedArbitratorByAddress(selectedArbitratorAddress); Arbitrator selectedArbitrator = model.user.getAcceptedArbitratorByAddress(selectedArbitratorNodeAddress);
Transaction transaction = model.tradeWalletService.createTradingFeeTx( Transaction transaction = model.tradeWalletService.createTradingFeeTx(
model.walletService.getAddressEntryByOfferId(model.offer.getId()), model.walletService.getAddressEntryByOfferId(model.offer.getId()),
FeePolicy.getCreateOfferFee(), FeePolicy.getCreateOfferFee(),

View file

@ -17,7 +17,7 @@
package io.bitsquare.trade.protocol.trade; package io.bitsquare.trade.protocol.trade;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.trade.offer.Offer; import io.bitsquare.trade.offer.Offer;
import org.bitcoinj.core.Sha256Hash; import org.bitcoinj.core.Sha256Hash;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -32,15 +32,15 @@ import static com.google.common.base.Preconditions.checkArgument;
public class ArbitrationSelectionRule { public class ArbitrationSelectionRule {
private static final Logger log = LoggerFactory.getLogger(ArbitrationSelectionRule.class); private static final Logger log = LoggerFactory.getLogger(ArbitrationSelectionRule.class);
public static Address select(List<Address> acceptedArbitratorAddresses, Offer offer) { public static NodeAddress select(List<NodeAddress> acceptedArbitratorNodeAddresses, Offer offer) {
List<Address> candidates = new ArrayList<>(); List<NodeAddress> candidates = new ArrayList<>();
for (Address offerArbitratorAddress : offer.getArbitratorAddresses()) { for (NodeAddress offerArbitratorNodeAddress : offer.getArbitratorNodeAddresses()) {
candidates.addAll(acceptedArbitratorAddresses.stream().filter(offerArbitratorAddress::equals).collect(Collectors.toList())); candidates.addAll(acceptedArbitratorNodeAddresses.stream().filter(offerArbitratorNodeAddress::equals).collect(Collectors.toList()));
} }
checkArgument(candidates.size() > 0, "candidates.size() <= 0"); checkArgument(candidates.size() > 0, "candidates.size() <= 0");
int index = Math.abs(Sha256Hash.hash(offer.getId().getBytes()).hashCode()) % candidates.size(); int index = Math.abs(Sha256Hash.hash(offer.getId().getBytes()).hashCode()) % candidates.size();
Address selectedArbitrator = candidates.get(index); NodeAddress selectedArbitrator = candidates.get(index);
log.debug("selectedArbitrator " + selectedArbitrator); log.debug("selectedArbitrator " + selectedArbitrator);
return selectedArbitrator; return selectedArbitrator;
} }

View file

@ -17,8 +17,8 @@
package io.bitsquare.trade.protocol.trade; package io.bitsquare.trade.protocol.trade;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message; import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.messaging.MailboxMessage; import io.bitsquare.p2p.messaging.MailboxMessage;
import io.bitsquare.trade.BuyerAsOffererTrade; import io.bitsquare.trade.BuyerAsOffererTrade;
import io.bitsquare.trade.Trade; import io.bitsquare.trade.Trade;
@ -79,11 +79,11 @@ public class BuyerAsOffererProtocol extends TradeProtocol implements BuyerProtoc
if (message instanceof MailboxMessage) { if (message instanceof MailboxMessage) {
MailboxMessage mailboxMessage = (MailboxMessage) message; MailboxMessage mailboxMessage = (MailboxMessage) message;
Address peerAddress = mailboxMessage.getSenderAddress(); NodeAddress peerNodeAddress = mailboxMessage.getSenderNodeAddress();
if (message instanceof FinalizePayoutTxRequest) { if (message instanceof FinalizePayoutTxRequest) {
handle((FinalizePayoutTxRequest) message, peerAddress); handle((FinalizePayoutTxRequest) message, peerNodeAddress);
} else if (message instanceof DepositTxPublishedMessage) { } else if (message instanceof DepositTxPublishedMessage) {
handle((DepositTxPublishedMessage) message, peerAddress); handle((DepositTxPublishedMessage) message, peerNodeAddress);
} }
} }
} }
@ -94,11 +94,11 @@ public class BuyerAsOffererProtocol extends TradeProtocol implements BuyerProtoc
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Override @Override
public void handleTakeOfferRequest(TradeMessage message, Address peerAddress) { public void handleTakeOfferRequest(TradeMessage message, NodeAddress peerNodeAddress) {
checkTradeId(processModel.getId(), message); checkTradeId(processModel.getId(), message);
checkArgument(message instanceof PayDepositRequest); checkArgument(message instanceof PayDepositRequest);
processModel.setTradeMessage(message); processModel.setTradeMessage(message);
processModel.setTempTradingPeerAddress(peerAddress); processModel.setTempTradingPeerNodeAddress(peerNodeAddress);
TradeTaskRunner taskRunner = new TradeTaskRunner(buyerAsOffererTrade, TradeTaskRunner taskRunner = new TradeTaskRunner(buyerAsOffererTrade,
() -> handleTaskRunnerSuccess("handleTakeOfferRequest"), () -> handleTaskRunnerSuccess("handleTakeOfferRequest"),
@ -123,10 +123,10 @@ public class BuyerAsOffererProtocol extends TradeProtocol implements BuyerProtoc
// Incoming message handling // Incoming message handling
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
private void handle(DepositTxPublishedMessage tradeMessage, Address peerAddress) { private void handle(DepositTxPublishedMessage tradeMessage, NodeAddress peerNodeAddress) {
stopTimeout(); stopTimeout();
processModel.setTradeMessage(tradeMessage); processModel.setTradeMessage(tradeMessage);
processModel.setTempTradingPeerAddress(peerAddress); processModel.setTempTradingPeerNodeAddress(peerNodeAddress);
TradeTaskRunner taskRunner = new TradeTaskRunner(buyerAsOffererTrade, TradeTaskRunner taskRunner = new TradeTaskRunner(buyerAsOffererTrade,
() -> handleTaskRunnerSuccess("handle DepositTxPublishedMessage"), () -> handleTaskRunnerSuccess("handle DepositTxPublishedMessage"),
@ -163,10 +163,10 @@ public class BuyerAsOffererProtocol extends TradeProtocol implements BuyerProtoc
// Incoming message handling // Incoming message handling
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
private void handle(FinalizePayoutTxRequest tradeMessage, Address peerAddress) { private void handle(FinalizePayoutTxRequest tradeMessage, NodeAddress peerNodeAddress) {
log.debug("handle RequestFinalizePayoutTxMessage called"); log.debug("handle RequestFinalizePayoutTxMessage called");
processModel.setTradeMessage(tradeMessage); processModel.setTradeMessage(tradeMessage);
processModel.setTempTradingPeerAddress(peerAddress); processModel.setTempTradingPeerNodeAddress(peerNodeAddress);
TradeTaskRunner taskRunner = new TradeTaskRunner(buyerAsOffererTrade, TradeTaskRunner taskRunner = new TradeTaskRunner(buyerAsOffererTrade,
() -> { () -> {
@ -191,11 +191,11 @@ public class BuyerAsOffererProtocol extends TradeProtocol implements BuyerProtoc
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Override @Override
protected void doHandleDecryptedMessage(TradeMessage tradeMessage, Address peerAddress) { protected void doHandleDecryptedMessage(TradeMessage tradeMessage, NodeAddress peerNodeAddress) {
if (tradeMessage instanceof DepositTxPublishedMessage) { if (tradeMessage instanceof DepositTxPublishedMessage) {
handle((DepositTxPublishedMessage) tradeMessage, peerAddress); handle((DepositTxPublishedMessage) tradeMessage, peerNodeAddress);
} else if (tradeMessage instanceof FinalizePayoutTxRequest) { } else if (tradeMessage instanceof FinalizePayoutTxRequest) {
handle((FinalizePayoutTxRequest) tradeMessage, peerAddress); handle((FinalizePayoutTxRequest) tradeMessage, peerNodeAddress);
} else { } else {
log.error("Incoming decrypted tradeMessage not supported. " + tradeMessage); log.error("Incoming decrypted tradeMessage not supported. " + tradeMessage);
} }

View file

@ -18,8 +18,8 @@
package io.bitsquare.trade.protocol.trade; package io.bitsquare.trade.protocol.trade;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message; import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.messaging.MailboxMessage; import io.bitsquare.p2p.messaging.MailboxMessage;
import io.bitsquare.trade.BuyerAsTakerTrade; import io.bitsquare.trade.BuyerAsTakerTrade;
import io.bitsquare.trade.Trade; import io.bitsquare.trade.Trade;
@ -75,7 +75,7 @@ public class BuyerAsTakerProtocol extends TradeProtocol implements BuyerProtocol
this.trade = trade; this.trade = trade;
if (message instanceof FinalizePayoutTxRequest) if (message instanceof FinalizePayoutTxRequest)
handle((FinalizePayoutTxRequest) message, ((MailboxMessage) message).getSenderAddress()); handle((FinalizePayoutTxRequest) message, ((MailboxMessage) message).getSenderNodeAddress());
} }
@ -106,10 +106,10 @@ public class BuyerAsTakerProtocol extends TradeProtocol implements BuyerProtocol
// Incoming message handling // Incoming message handling
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
private void handle(PublishDepositTxRequest tradeMessage, Address sender) { private void handle(PublishDepositTxRequest tradeMessage, NodeAddress sender) {
stopTimeout(); stopTimeout();
processModel.setTradeMessage(tradeMessage); processModel.setTradeMessage(tradeMessage);
processModel.setTempTradingPeerAddress(sender); processModel.setTempTradingPeerNodeAddress(sender);
TradeTaskRunner taskRunner = new TradeTaskRunner(buyerAsTakerTrade, TradeTaskRunner taskRunner = new TradeTaskRunner(buyerAsTakerTrade,
() -> handleTaskRunnerSuccess("PublishDepositTxRequest"), () -> handleTaskRunnerSuccess("PublishDepositTxRequest"),
@ -149,9 +149,9 @@ public class BuyerAsTakerProtocol extends TradeProtocol implements BuyerProtocol
// Incoming message handling // Incoming message handling
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
private void handle(FinalizePayoutTxRequest tradeMessage, Address sender) { private void handle(FinalizePayoutTxRequest tradeMessage, NodeAddress sender) {
processModel.setTradeMessage(tradeMessage); processModel.setTradeMessage(tradeMessage);
processModel.setTempTradingPeerAddress(sender); processModel.setTempTradingPeerNodeAddress(sender);
TradeTaskRunner taskRunner = new TradeTaskRunner(buyerAsTakerTrade, TradeTaskRunner taskRunner = new TradeTaskRunner(buyerAsTakerTrade,
() -> { () -> {
@ -175,7 +175,7 @@ public class BuyerAsTakerProtocol extends TradeProtocol implements BuyerProtocol
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Override @Override
protected void doHandleDecryptedMessage(TradeMessage tradeMessage, Address sender) { protected void doHandleDecryptedMessage(TradeMessage tradeMessage, NodeAddress sender) {
if (tradeMessage instanceof PublishDepositTxRequest) { if (tradeMessage instanceof PublishDepositTxRequest) {
handle((PublishDepositTxRequest) tradeMessage, sender); handle((PublishDepositTxRequest) tradeMessage, sender);
} else if (tradeMessage instanceof FinalizePayoutTxRequest) { } else if (tradeMessage instanceof FinalizePayoutTxRequest) {

View file

@ -18,9 +18,9 @@
package io.bitsquare.trade.protocol.trade; package io.bitsquare.trade.protocol.trade;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.trade.protocol.trade.messages.TradeMessage; import io.bitsquare.trade.protocol.trade.messages.TradeMessage;
public interface OffererProtocol { public interface OffererProtocol {
void handleTakeOfferRequest(TradeMessage message, Address taker); void handleTakeOfferRequest(TradeMessage message, NodeAddress taker);
} }

View file

@ -26,7 +26,7 @@ import io.bitsquare.btc.data.RawInput;
import io.bitsquare.common.crypto.KeyRing; import io.bitsquare.common.crypto.KeyRing;
import io.bitsquare.common.crypto.PubKeyRing; import io.bitsquare.common.crypto.PubKeyRing;
import io.bitsquare.common.taskrunner.Model; import io.bitsquare.common.taskrunner.Model;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.P2PService; import io.bitsquare.p2p.P2PService;
import io.bitsquare.payment.PaymentAccountContractData; import io.bitsquare.payment.PaymentAccountContractData;
import io.bitsquare.trade.OffererTrade; import io.bitsquare.trade.OffererTrade;
@ -70,11 +70,11 @@ public class ProcessModel implements Model, Serializable {
private byte[] payoutTxSignature; private byte[] payoutTxSignature;
private Transaction takeOfferFeeTx; private Transaction takeOfferFeeTx;
private List<Address> takerAcceptedArbitratorAddresses; private List<NodeAddress> takerAcceptedArbitratorNodeAddresses;
// that is used to store temp. the peers address when we get an incoming message before the message is verified. // that is used to store temp. the peers address when we get an incoming message before the message is verified.
// After successful verified we copy that over to the trade.tradingPeerAddress // After successful verified we copy that over to the trade.tradingPeerAddress
private Address tempTradingPeerAddress; private NodeAddress tempTradingPeerNodeAddress;
private byte[] preparedDepositTx; private byte[] preparedDepositTx;
private List<RawInput> rawInputs; private List<RawInput> rawInputs;
private long changeOutputValue; private long changeOutputValue;
@ -135,8 +135,8 @@ public class ProcessModel implements Model, Serializable {
return tradeWalletService; return tradeWalletService;
} }
public byte[] getArbitratorPubKey(Address arbitratorAddress) { public byte[] getArbitratorPubKey(NodeAddress arbitratorNodeAddress) {
return user.getAcceptedArbitratorByAddress(arbitratorAddress).getBtcPubKey(); return user.getAcceptedArbitratorByAddress(arbitratorNodeAddress).getBtcPubKey();
} }
public Offer getOffer() { public Offer getOffer() {
@ -151,7 +151,7 @@ public class ProcessModel implements Model, Serializable {
return user; return user;
} }
public Address getMyAddress() { public NodeAddress getMyAddress() {
return p2PService.getAddress(); return p2PService.getAddress();
} }
@ -234,20 +234,20 @@ public class ProcessModel implements Model, Serializable {
return keyRing; return keyRing;
} }
public void setTakerAcceptedArbitratorAddresses(List<Address> takerAcceptedArbitratorAddresses) { public void setTakerAcceptedArbitratorNodeAddresses(List<NodeAddress> takerAcceptedArbitratorNodeAddresses) {
this.takerAcceptedArbitratorAddresses = takerAcceptedArbitratorAddresses; this.takerAcceptedArbitratorNodeAddresses = takerAcceptedArbitratorNodeAddresses;
} }
public List<Address> getTakerAcceptedArbitratorAddresses() { public List<NodeAddress> getTakerAcceptedArbitratorNodeAddresses() {
return takerAcceptedArbitratorAddresses; return takerAcceptedArbitratorNodeAddresses;
} }
public void setTempTradingPeerAddress(Address tempTradingPeerAddress) { public void setTempTradingPeerNodeAddress(NodeAddress tempTradingPeerNodeAddress) {
this.tempTradingPeerAddress = tempTradingPeerAddress; this.tempTradingPeerNodeAddress = tempTradingPeerNodeAddress;
} }
public Address getTempTradingPeerAddress() { public NodeAddress getTempTradingPeerNodeAddress() {
return tempTradingPeerAddress; return tempTradingPeerNodeAddress;
} }
public ArbitratorManager getArbitratorManager() { public ArbitratorManager getArbitratorManager() {

View file

@ -18,8 +18,8 @@
package io.bitsquare.trade.protocol.trade; package io.bitsquare.trade.protocol.trade;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message; import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.messaging.MailboxMessage; import io.bitsquare.p2p.messaging.MailboxMessage;
import io.bitsquare.trade.SellerAsOffererTrade; import io.bitsquare.trade.SellerAsOffererTrade;
import io.bitsquare.trade.Trade; import io.bitsquare.trade.Trade;
@ -75,14 +75,14 @@ public class SellerAsOffererProtocol extends TradeProtocol implements SellerProt
public void doApplyMailboxMessage(Message message, Trade trade) { public void doApplyMailboxMessage(Message message, Trade trade) {
this.trade = trade; this.trade = trade;
Address peerAddress = ((MailboxMessage) message).getSenderAddress(); NodeAddress peerNodeAddress = ((MailboxMessage) message).getSenderNodeAddress();
if (message instanceof PayoutTxFinalizedMessage) { if (message instanceof PayoutTxFinalizedMessage) {
handle((PayoutTxFinalizedMessage) message, peerAddress); handle((PayoutTxFinalizedMessage) message, peerNodeAddress);
} else { } else {
if (message instanceof FiatTransferStartedMessage) { if (message instanceof FiatTransferStartedMessage) {
handle((FiatTransferStartedMessage) message, peerAddress); handle((FiatTransferStartedMessage) message, peerNodeAddress);
} else if (message instanceof DepositTxPublishedMessage) { } else if (message instanceof DepositTxPublishedMessage) {
handle((DepositTxPublishedMessage) message, peerAddress); handle((DepositTxPublishedMessage) message, peerNodeAddress);
} }
} }
} }
@ -93,11 +93,11 @@ public class SellerAsOffererProtocol extends TradeProtocol implements SellerProt
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Override @Override
public void handleTakeOfferRequest(TradeMessage message, Address sender) { public void handleTakeOfferRequest(TradeMessage message, NodeAddress sender) {
checkTradeId(processModel.getId(), message); checkTradeId(processModel.getId(), message);
checkArgument(message instanceof PayDepositRequest); checkArgument(message instanceof PayDepositRequest);
processModel.setTradeMessage(message); processModel.setTradeMessage(message);
processModel.setTempTradingPeerAddress(sender); processModel.setTempTradingPeerNodeAddress(sender);
TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsOffererTrade, TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsOffererTrade,
() -> handleTaskRunnerSuccess("handleTakeOfferRequest"), () -> handleTaskRunnerSuccess("handleTakeOfferRequest"),
@ -123,10 +123,10 @@ public class SellerAsOffererProtocol extends TradeProtocol implements SellerProt
// Incoming message handling // Incoming message handling
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
private void handle(DepositTxPublishedMessage tradeMessage, Address sender) { private void handle(DepositTxPublishedMessage tradeMessage, NodeAddress sender) {
stopTimeout(); stopTimeout();
processModel.setTradeMessage(tradeMessage); processModel.setTradeMessage(tradeMessage);
processModel.setTempTradingPeerAddress(sender); processModel.setTempTradingPeerNodeAddress(sender);
TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsOffererTrade, TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsOffererTrade,
() -> handleTaskRunnerSuccess("DepositTxPublishedMessage"), () -> handleTaskRunnerSuccess("DepositTxPublishedMessage"),
@ -144,9 +144,9 @@ public class SellerAsOffererProtocol extends TradeProtocol implements SellerProt
// After peer has started Fiat tx // After peer has started Fiat tx
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
private void handle(FiatTransferStartedMessage tradeMessage, Address sender) { private void handle(FiatTransferStartedMessage tradeMessage, NodeAddress sender) {
processModel.setTradeMessage(tradeMessage); processModel.setTradeMessage(tradeMessage);
processModel.setTempTradingPeerAddress(sender); processModel.setTempTradingPeerNodeAddress(sender);
TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsOffererTrade, TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsOffererTrade,
() -> handleTaskRunnerSuccess("FiatTransferStartedMessage"), () -> handleTaskRunnerSuccess("FiatTransferStartedMessage"),
@ -178,9 +178,9 @@ public class SellerAsOffererProtocol extends TradeProtocol implements SellerProt
taskRunner.run(); taskRunner.run();
} }
private void handle(PayoutTxFinalizedMessage tradeMessage, Address sender) { private void handle(PayoutTxFinalizedMessage tradeMessage, NodeAddress sender) {
processModel.setTradeMessage(tradeMessage); processModel.setTradeMessage(tradeMessage);
processModel.setTempTradingPeerAddress(sender); processModel.setTempTradingPeerNodeAddress(sender);
TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsOffererTrade, TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsOffererTrade,
() -> { () -> {
@ -202,7 +202,7 @@ public class SellerAsOffererProtocol extends TradeProtocol implements SellerProt
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Override @Override
protected void doHandleDecryptedMessage(TradeMessage tradeMessage, Address sender) { protected void doHandleDecryptedMessage(TradeMessage tradeMessage, NodeAddress sender) {
if (tradeMessage instanceof DepositTxPublishedMessage) { if (tradeMessage instanceof DepositTxPublishedMessage) {
handle((DepositTxPublishedMessage) tradeMessage, sender); handle((DepositTxPublishedMessage) tradeMessage, sender);
} else if (tradeMessage instanceof FiatTransferStartedMessage) { } else if (tradeMessage instanceof FiatTransferStartedMessage) {

View file

@ -18,8 +18,8 @@
package io.bitsquare.trade.protocol.trade; package io.bitsquare.trade.protocol.trade;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message; import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.messaging.MailboxMessage; import io.bitsquare.p2p.messaging.MailboxMessage;
import io.bitsquare.trade.SellerAsTakerTrade; import io.bitsquare.trade.SellerAsTakerTrade;
import io.bitsquare.trade.Trade; import io.bitsquare.trade.Trade;
@ -77,11 +77,11 @@ public class SellerAsTakerProtocol extends TradeProtocol implements SellerProtoc
this.trade = trade; this.trade = trade;
if (message instanceof MailboxMessage) { if (message instanceof MailboxMessage) {
Address peerAddress = ((MailboxMessage) message).getSenderAddress(); NodeAddress peerNodeAddress = ((MailboxMessage) message).getSenderNodeAddress();
if (message instanceof PayoutTxFinalizedMessage) { if (message instanceof PayoutTxFinalizedMessage) {
handle((PayoutTxFinalizedMessage) message, peerAddress); handle((PayoutTxFinalizedMessage) message, peerNodeAddress);
} else if (message instanceof FiatTransferStartedMessage) { } else if (message instanceof FiatTransferStartedMessage) {
handle((FiatTransferStartedMessage) message, peerAddress); handle((FiatTransferStartedMessage) message, peerNodeAddress);
} }
} }
} }
@ -114,11 +114,11 @@ public class SellerAsTakerProtocol extends TradeProtocol implements SellerProtoc
// Incoming message handling // Incoming message handling
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
private void handle(PublishDepositTxRequest tradeMessage, Address sender) { private void handle(PublishDepositTxRequest tradeMessage, NodeAddress sender) {
log.debug("handle RequestPayDepositMessage"); log.debug("handle RequestPayDepositMessage");
stopTimeout(); stopTimeout();
processModel.setTradeMessage(tradeMessage); processModel.setTradeMessage(tradeMessage);
processModel.setTempTradingPeerAddress(sender); processModel.setTempTradingPeerNodeAddress(sender);
TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsTakerTrade, TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsTakerTrade,
() -> handleTaskRunnerSuccess("PayDepositRequest"), () -> handleTaskRunnerSuccess("PayDepositRequest"),
@ -139,9 +139,9 @@ public class SellerAsTakerProtocol extends TradeProtocol implements SellerProtoc
// After peer has started Fiat tx // After peer has started Fiat tx
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
private void handle(FiatTransferStartedMessage tradeMessage, Address sender) { private void handle(FiatTransferStartedMessage tradeMessage, NodeAddress sender) {
processModel.setTradeMessage(tradeMessage); processModel.setTradeMessage(tradeMessage);
processModel.setTempTradingPeerAddress(sender); processModel.setTempTradingPeerNodeAddress(sender);
TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsTakerTrade, TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsTakerTrade,
() -> handleTaskRunnerSuccess("FiatTransferStartedMessage"), () -> handleTaskRunnerSuccess("FiatTransferStartedMessage"),
@ -173,10 +173,10 @@ public class SellerAsTakerProtocol extends TradeProtocol implements SellerProtoc
taskRunner.run(); taskRunner.run();
} }
private void handle(PayoutTxFinalizedMessage tradeMessage, Address sender) { private void handle(PayoutTxFinalizedMessage tradeMessage, NodeAddress sender) {
stopTimeout(); stopTimeout();
processModel.setTradeMessage(tradeMessage); processModel.setTradeMessage(tradeMessage);
processModel.setTempTradingPeerAddress(sender); processModel.setTempTradingPeerNodeAddress(sender);
TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsTakerTrade, TradeTaskRunner taskRunner = new TradeTaskRunner(sellerAsTakerTrade,
() -> { () -> {
@ -199,7 +199,7 @@ public class SellerAsTakerProtocol extends TradeProtocol implements SellerProtoc
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Override @Override
protected void doHandleDecryptedMessage(TradeMessage tradeMessage, Address sender) { protected void doHandleDecryptedMessage(TradeMessage tradeMessage, NodeAddress sender) {
if (tradeMessage instanceof PublishDepositTxRequest) { if (tradeMessage instanceof PublishDepositTxRequest) {
handle((PublishDepositTxRequest) tradeMessage, sender); handle((PublishDepositTxRequest) tradeMessage, sender);
} else if (tradeMessage instanceof FiatTransferStartedMessage) { } else if (tradeMessage instanceof FiatTransferStartedMessage) {

View file

@ -19,8 +19,8 @@ package io.bitsquare.trade.protocol.trade;
import io.bitsquare.common.UserThread; import io.bitsquare.common.UserThread;
import io.bitsquare.common.crypto.PubKeyRing; import io.bitsquare.common.crypto.PubKeyRing;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message; import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.messaging.DecryptedMailListener; import io.bitsquare.p2p.messaging.DecryptedMailListener;
import io.bitsquare.p2p.messaging.DecryptedMsgWithPubKey; import io.bitsquare.p2p.messaging.DecryptedMsgWithPubKey;
import io.bitsquare.trade.OffererTrade; import io.bitsquare.trade.OffererTrade;
@ -102,7 +102,7 @@ public abstract class TradeProtocol {
protected abstract void doApplyMailboxMessage(Message message, Trade trade); protected abstract void doApplyMailboxMessage(Message message, Trade trade);
protected abstract void doHandleDecryptedMessage(TradeMessage tradeMessage, Address peerAddress); protected abstract void doHandleDecryptedMessage(TradeMessage tradeMessage, NodeAddress peerNodeAddress);
public void checkPayoutTxTimeLock(Trade trade) { public void checkPayoutTxTimeLock(Trade trade) {
this.trade = trade; this.trade = trade;

View file

@ -18,7 +18,7 @@
package io.bitsquare.trade.protocol.trade.messages; package io.bitsquare.trade.protocol.trade.messages;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.messaging.MailboxMessage; import io.bitsquare.p2p.messaging.MailboxMessage;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
@ -30,17 +30,17 @@ public final class DepositTxPublishedMessage extends TradeMessage implements Mai
private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION; private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION;
public final byte[] depositTx; public final byte[] depositTx;
private final Address senderAddress; private final NodeAddress senderNodeAddress;
public DepositTxPublishedMessage(String tradeId, byte[] depositTx, Address senderAddress) { public DepositTxPublishedMessage(String tradeId, byte[] depositTx, NodeAddress senderNodeAddress) {
super(tradeId); super(tradeId);
this.depositTx = depositTx; this.depositTx = depositTx;
this.senderAddress = senderAddress; this.senderNodeAddress = senderNodeAddress;
} }
@Override @Override
public Address getSenderAddress() { public NodeAddress getSenderNodeAddress() {
return senderAddress; return senderNodeAddress;
} }
@Override @Override
@ -52,7 +52,7 @@ public final class DepositTxPublishedMessage extends TradeMessage implements Mai
DepositTxPublishedMessage that = (DepositTxPublishedMessage) o; DepositTxPublishedMessage that = (DepositTxPublishedMessage) o;
if (!Arrays.equals(depositTx, that.depositTx)) return false; if (!Arrays.equals(depositTx, that.depositTx)) return false;
return !(senderAddress != null ? !senderAddress.equals(that.senderAddress) : that.senderAddress != null); return !(senderNodeAddress != null ? !senderNodeAddress.equals(that.senderNodeAddress) : that.senderNodeAddress != null);
} }
@ -60,7 +60,7 @@ public final class DepositTxPublishedMessage extends TradeMessage implements Mai
public int hashCode() { public int hashCode() {
int result = super.hashCode(); int result = super.hashCode();
result = 31 * result + (depositTx != null ? Arrays.hashCode(depositTx) : 0); result = 31 * result + (depositTx != null ? Arrays.hashCode(depositTx) : 0);
result = 31 * result + (senderAddress != null ? senderAddress.hashCode() : 0); result = 31 * result + (senderNodeAddress != null ? senderNodeAddress.hashCode() : 0);
return result; return result;
} }
} }

View file

@ -18,7 +18,7 @@
package io.bitsquare.trade.protocol.trade.messages; package io.bitsquare.trade.protocol.trade.messages;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.messaging.MailboxMessage; import io.bitsquare.p2p.messaging.MailboxMessage;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
@ -29,17 +29,17 @@ public final class FiatTransferStartedMessage extends TradeMessage implements Ma
private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION; private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION;
public final String buyerPayoutAddress; public final String buyerPayoutAddress;
private final Address senderAddress; private final NodeAddress senderNodeAddress;
public FiatTransferStartedMessage(String tradeId, String buyerPayoutAddress, Address senderAddress) { public FiatTransferStartedMessage(String tradeId, String buyerPayoutAddress, NodeAddress senderNodeAddress) {
super(tradeId); super(tradeId);
this.buyerPayoutAddress = buyerPayoutAddress; this.buyerPayoutAddress = buyerPayoutAddress;
this.senderAddress = senderAddress; this.senderNodeAddress = senderNodeAddress;
} }
@Override @Override
public Address getSenderAddress() { public NodeAddress getSenderNodeAddress() {
return senderAddress; return senderNodeAddress;
} }
@Override @Override
@ -52,7 +52,7 @@ public final class FiatTransferStartedMessage extends TradeMessage implements Ma
if (buyerPayoutAddress != null ? !buyerPayoutAddress.equals(that.buyerPayoutAddress) : that.buyerPayoutAddress != null) if (buyerPayoutAddress != null ? !buyerPayoutAddress.equals(that.buyerPayoutAddress) : that.buyerPayoutAddress != null)
return false; return false;
return !(senderAddress != null ? !senderAddress.equals(that.senderAddress) : that.senderAddress != null); return !(senderNodeAddress != null ? !senderNodeAddress.equals(that.senderNodeAddress) : that.senderNodeAddress != null);
} }
@ -60,7 +60,7 @@ public final class FiatTransferStartedMessage extends TradeMessage implements Ma
public int hashCode() { public int hashCode() {
int result = super.hashCode(); int result = super.hashCode();
result = 31 * result + (buyerPayoutAddress != null ? buyerPayoutAddress.hashCode() : 0); result = 31 * result + (buyerPayoutAddress != null ? buyerPayoutAddress.hashCode() : 0);
result = 31 * result + (senderAddress != null ? senderAddress.hashCode() : 0); result = 31 * result + (senderNodeAddress != null ? senderNodeAddress.hashCode() : 0);
return result; return result;
} }
} }

View file

@ -18,7 +18,7 @@
package io.bitsquare.trade.protocol.trade.messages; package io.bitsquare.trade.protocol.trade.messages;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.messaging.MailboxMessage; import io.bitsquare.p2p.messaging.MailboxMessage;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
@ -32,23 +32,23 @@ public final class FinalizePayoutTxRequest extends TradeMessage implements Mailb
public final byte[] sellerSignature; public final byte[] sellerSignature;
public final String sellerPayoutAddress; public final String sellerPayoutAddress;
public final long lockTime; public final long lockTime;
private final Address senderAddress; private final NodeAddress senderNodeAddress;
public FinalizePayoutTxRequest(String tradeId, public FinalizePayoutTxRequest(String tradeId,
byte[] sellerSignature, byte[] sellerSignature,
String sellerPayoutAddress, String sellerPayoutAddress,
long lockTime, long lockTime,
Address senderAddress) { NodeAddress senderNodeAddress) {
super(tradeId); super(tradeId);
this.sellerSignature = sellerSignature; this.sellerSignature = sellerSignature;
this.sellerPayoutAddress = sellerPayoutAddress; this.sellerPayoutAddress = sellerPayoutAddress;
this.lockTime = lockTime; this.lockTime = lockTime;
this.senderAddress = senderAddress; this.senderNodeAddress = senderNodeAddress;
} }
@Override @Override
public Address getSenderAddress() { public NodeAddress getSenderNodeAddress() {
return senderAddress; return senderNodeAddress;
} }
@Override @Override
@ -63,7 +63,7 @@ public final class FinalizePayoutTxRequest extends TradeMessage implements Mailb
if (!Arrays.equals(sellerSignature, that.sellerSignature)) return false; if (!Arrays.equals(sellerSignature, that.sellerSignature)) return false;
if (sellerPayoutAddress != null ? !sellerPayoutAddress.equals(that.sellerPayoutAddress) : that.sellerPayoutAddress != null) if (sellerPayoutAddress != null ? !sellerPayoutAddress.equals(that.sellerPayoutAddress) : that.sellerPayoutAddress != null)
return false; return false;
return !(senderAddress != null ? !senderAddress.equals(that.senderAddress) : that.senderAddress != null); return !(senderNodeAddress != null ? !senderNodeAddress.equals(that.senderNodeAddress) : that.senderNodeAddress != null);
} }
@ -73,7 +73,7 @@ public final class FinalizePayoutTxRequest extends TradeMessage implements Mailb
result = 31 * result + (sellerSignature != null ? Arrays.hashCode(sellerSignature) : 0); result = 31 * result + (sellerSignature != null ? Arrays.hashCode(sellerSignature) : 0);
result = 31 * result + (sellerPayoutAddress != null ? sellerPayoutAddress.hashCode() : 0); result = 31 * result + (sellerPayoutAddress != null ? sellerPayoutAddress.hashCode() : 0);
result = 31 * result + (int) (lockTime ^ (lockTime >>> 32)); result = 31 * result + (int) (lockTime ^ (lockTime >>> 32));
result = 31 * result + (senderAddress != null ? senderAddress.hashCode() : 0); result = 31 * result + (senderNodeAddress != null ? senderNodeAddress.hashCode() : 0);
return result; return result;
} }
} }

View file

@ -20,7 +20,7 @@ package io.bitsquare.trade.protocol.trade.messages;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.btc.data.RawInput; import io.bitsquare.btc.data.RawInput;
import io.bitsquare.common.crypto.PubKeyRing; import io.bitsquare.common.crypto.PubKeyRing;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.messaging.MailboxMessage; import io.bitsquare.p2p.messaging.MailboxMessage;
import io.bitsquare.payment.PaymentAccountContractData; import io.bitsquare.payment.PaymentAccountContractData;
@ -43,11 +43,11 @@ public final class PayDepositRequest extends TradeMessage implements MailboxMess
public final PaymentAccountContractData takerPaymentAccountContractData; public final PaymentAccountContractData takerPaymentAccountContractData;
public final String takerAccountId; public final String takerAccountId;
public final String takeOfferFeeTxId; public final String takeOfferFeeTxId;
public final List<Address> acceptedArbitratorAddresses; public final List<NodeAddress> acceptedArbitratorNodeAddresses;
public final Address arbitratorAddress; public final NodeAddress arbitratorNodeAddress;
private final Address senderAddress; private final NodeAddress senderNodeAddress;
public PayDepositRequest(Address senderAddress, public PayDepositRequest(NodeAddress senderNodeAddress,
String tradeId, String tradeId,
long tradeAmount, long tradeAmount,
List<RawInput> rawInputs, List<RawInput> rawInputs,
@ -59,10 +59,10 @@ public final class PayDepositRequest extends TradeMessage implements MailboxMess
PaymentAccountContractData takerPaymentAccountContractData, PaymentAccountContractData takerPaymentAccountContractData,
String takerAccountId, String takerAccountId,
String takeOfferFeeTxId, String takeOfferFeeTxId,
List<Address> acceptedArbitratorAddresses, List<NodeAddress> acceptedArbitratorNodeAddresses,
Address arbitratorAddress) { NodeAddress arbitratorNodeAddress) {
super(tradeId); super(tradeId);
this.senderAddress = senderAddress; this.senderNodeAddress = senderNodeAddress;
this.tradeAmount = tradeAmount; this.tradeAmount = tradeAmount;
this.rawInputs = rawInputs; this.rawInputs = rawInputs;
this.changeOutputValue = changeOutputValue; this.changeOutputValue = changeOutputValue;
@ -73,13 +73,13 @@ public final class PayDepositRequest extends TradeMessage implements MailboxMess
this.takerPaymentAccountContractData = takerPaymentAccountContractData; this.takerPaymentAccountContractData = takerPaymentAccountContractData;
this.takerAccountId = takerAccountId; this.takerAccountId = takerAccountId;
this.takeOfferFeeTxId = takeOfferFeeTxId; this.takeOfferFeeTxId = takeOfferFeeTxId;
this.acceptedArbitratorAddresses = acceptedArbitratorAddresses; this.acceptedArbitratorNodeAddresses = acceptedArbitratorNodeAddresses;
this.arbitratorAddress = arbitratorAddress; this.arbitratorNodeAddress = arbitratorNodeAddress;
} }
@Override @Override
public Address getSenderAddress() { public NodeAddress getSenderNodeAddress() {
return senderAddress; return senderNodeAddress;
} }
@Override @Override
@ -106,11 +106,11 @@ public final class PayDepositRequest extends TradeMessage implements MailboxMess
return false; return false;
if (takeOfferFeeTxId != null ? !takeOfferFeeTxId.equals(that.takeOfferFeeTxId) : that.takeOfferFeeTxId != null) if (takeOfferFeeTxId != null ? !takeOfferFeeTxId.equals(that.takeOfferFeeTxId) : that.takeOfferFeeTxId != null)
return false; return false;
if (acceptedArbitratorAddresses != null ? !acceptedArbitratorAddresses.equals(that.acceptedArbitratorAddresses) : that.acceptedArbitratorAddresses != null) if (acceptedArbitratorNodeAddresses != null ? !acceptedArbitratorNodeAddresses.equals(that.acceptedArbitratorNodeAddresses) : that.acceptedArbitratorNodeAddresses != null)
return false; return false;
if (arbitratorAddress != null ? !arbitratorAddress.equals(that.arbitratorAddress) : that.arbitratorAddress != null) if (arbitratorNodeAddress != null ? !arbitratorNodeAddress.equals(that.arbitratorNodeAddress) : that.arbitratorNodeAddress != null)
return false; return false;
return !(senderAddress != null ? !senderAddress.equals(that.senderAddress) : that.senderAddress != null); return !(senderNodeAddress != null ? !senderNodeAddress.equals(that.senderNodeAddress) : that.senderNodeAddress != null);
} }
@ -127,9 +127,9 @@ public final class PayDepositRequest extends TradeMessage implements MailboxMess
result = 31 * result + (takerPaymentAccountContractData != null ? takerPaymentAccountContractData.hashCode() : 0); result = 31 * result + (takerPaymentAccountContractData != null ? takerPaymentAccountContractData.hashCode() : 0);
result = 31 * result + (takerAccountId != null ? takerAccountId.hashCode() : 0); result = 31 * result + (takerAccountId != null ? takerAccountId.hashCode() : 0);
result = 31 * result + (takeOfferFeeTxId != null ? takeOfferFeeTxId.hashCode() : 0); result = 31 * result + (takeOfferFeeTxId != null ? takeOfferFeeTxId.hashCode() : 0);
result = 31 * result + (acceptedArbitratorAddresses != null ? acceptedArbitratorAddresses.hashCode() : 0); result = 31 * result + (acceptedArbitratorNodeAddresses != null ? acceptedArbitratorNodeAddresses.hashCode() : 0);
result = 31 * result + (arbitratorAddress != null ? arbitratorAddress.hashCode() : 0); result = 31 * result + (arbitratorNodeAddress != null ? arbitratorNodeAddress.hashCode() : 0);
result = 31 * result + (senderAddress != null ? senderAddress.hashCode() : 0); result = 31 * result + (senderNodeAddress != null ? senderNodeAddress.hashCode() : 0);
return result; return result;
} }
} }

View file

@ -18,7 +18,7 @@
package io.bitsquare.trade.protocol.trade.messages; package io.bitsquare.trade.protocol.trade.messages;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.messaging.MailboxMessage; import io.bitsquare.p2p.messaging.MailboxMessage;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
@ -30,17 +30,17 @@ public final class PayoutTxFinalizedMessage extends TradeMessage implements Mail
private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION; private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION;
public final byte[] payoutTx; public final byte[] payoutTx;
private final Address senderAddress; private final NodeAddress senderNodeAddress;
public PayoutTxFinalizedMessage(String tradeId, byte[] payoutTx, Address senderAddress) { public PayoutTxFinalizedMessage(String tradeId, byte[] payoutTx, NodeAddress senderNodeAddress) {
super(tradeId); super(tradeId);
this.payoutTx = payoutTx; this.payoutTx = payoutTx;
this.senderAddress = senderAddress; this.senderNodeAddress = senderNodeAddress;
} }
@Override @Override
public Address getSenderAddress() { public NodeAddress getSenderNodeAddress() {
return senderAddress; return senderNodeAddress;
} }
@Override @Override
@ -52,7 +52,7 @@ public final class PayoutTxFinalizedMessage extends TradeMessage implements Mail
PayoutTxFinalizedMessage that = (PayoutTxFinalizedMessage) o; PayoutTxFinalizedMessage that = (PayoutTxFinalizedMessage) o;
if (!Arrays.equals(payoutTx, that.payoutTx)) return false; if (!Arrays.equals(payoutTx, that.payoutTx)) return false;
return !(senderAddress != null ? !senderAddress.equals(that.senderAddress) : that.senderAddress != null); return !(senderNodeAddress != null ? !senderNodeAddress.equals(that.senderNodeAddress) : that.senderNodeAddress != null);
} }
@ -60,7 +60,7 @@ public final class PayoutTxFinalizedMessage extends TradeMessage implements Mail
public int hashCode() { public int hashCode() {
int result = super.hashCode(); int result = super.hashCode();
result = 31 * result + (payoutTx != null ? Arrays.hashCode(payoutTx) : 0); result = 31 * result + (payoutTx != null ? Arrays.hashCode(payoutTx) : 0);
result = 31 * result + (senderAddress != null ? senderAddress.hashCode() : 0); result = 31 * result + (senderNodeAddress != null ? senderNodeAddress.hashCode() : 0);
return result; return result;
} }
} }

View file

@ -62,7 +62,7 @@ public class CreateAndSignDepositTxAsBuyer extends TradeTask {
processModel.getAddressEntry(), processModel.getAddressEntry(),
processModel.getTradeWalletPubKey(), processModel.getTradeWalletPubKey(),
processModel.tradingPeer.getTradeWalletPubKey(), processModel.tradingPeer.getTradeWalletPubKey(),
processModel.getArbitratorPubKey(trade.getArbitratorAddress())); processModel.getArbitratorPubKey(trade.getArbitratorNodeAddress()));
processModel.setPreparedDepositTx(result.depositTransaction); processModel.setPreparedDepositTx(result.depositTransaction);
processModel.setRawInputs(result.rawOffererInputs); processModel.setRawInputs(result.rawOffererInputs);

View file

@ -50,7 +50,7 @@ public class ProcessFinalizePayoutTxRequest extends TradeTask {
trade.setState(Trade.State.FIAT_PAYMENT_RECEIPT_MSG_RECEIVED); trade.setState(Trade.State.FIAT_PAYMENT_RECEIPT_MSG_RECEIVED);
// update to the latest peer address of our peer if the message is correct // update to the latest peer address of our peer if the message is correct
trade.setTradingPeerAddress(processModel.getTempTradingPeerAddress()); trade.setTradingPeerNodeAddress(processModel.getTempTradingPeerNodeAddress());
complete(); complete();
} catch (Throwable t) { } catch (Throwable t) {

View file

@ -38,7 +38,7 @@ public class SendFiatTransferStartedMessage extends TradeTask {
runInterceptHook(); runInterceptHook();
processModel.getP2PService().sendEncryptedMailboxMessage( processModel.getP2PService().sendEncryptedMailboxMessage(
trade.getTradingPeerAddress(), trade.getTradingPeerNodeAddress(),
processModel.tradingPeer.getPubKeyRing(), processModel.tradingPeer.getPubKeyRing(),
new FiatTransferStartedMessage( new FiatTransferStartedMessage(
processModel.getId(), processModel.getId(),

View file

@ -38,7 +38,7 @@ public class SendPayoutTxFinalizedMessage extends TradeTask {
runInterceptHook(); runInterceptHook();
if (trade.getPayoutTx() != null) { if (trade.getPayoutTx() != null) {
processModel.getP2PService().sendEncryptedMailboxMessage( processModel.getP2PService().sendEncryptedMailboxMessage(
trade.getTradingPeerAddress(), trade.getTradingPeerNodeAddress(),
processModel.tradingPeer.getPubKeyRing(), processModel.tradingPeer.getPubKeyRing(),
new PayoutTxFinalizedMessage( new PayoutTxFinalizedMessage(
processModel.getId(), processModel.getId(),

View file

@ -53,7 +53,7 @@ public class SignAndFinalizePayoutTx extends TradeTask {
trade.getLockTimeAsBlockHeight(), trade.getLockTimeAsBlockHeight(),
processModel.getTradeWalletPubKey(), processModel.getTradeWalletPubKey(),
processModel.tradingPeer.getTradeWalletPubKey(), processModel.tradingPeer.getTradeWalletPubKey(),
processModel.getArbitratorPubKey(trade.getArbitratorAddress()) processModel.getArbitratorPubKey(trade.getArbitratorNodeAddress())
); );
trade.setPayoutTx(transaction); trade.setPayoutTx(transaction);

View file

@ -57,7 +57,7 @@ public class SignAndPublishDepositTxAsBuyer extends TradeTask {
processModel.tradingPeer.getRawInputs(), processModel.tradingPeer.getRawInputs(),
processModel.getTradeWalletPubKey(), processModel.getTradeWalletPubKey(),
processModel.tradingPeer.getTradeWalletPubKey(), processModel.tradingPeer.getTradeWalletPubKey(),
processModel.getArbitratorPubKey(trade.getArbitratorAddress()), processModel.getArbitratorPubKey(trade.getArbitratorNodeAddress()),
new FutureCallback<Transaction>() { new FutureCallback<Transaction>() {
@Override @Override
public void onSuccess(Transaction transaction) { public void onSuccess(Transaction transaction) {

View file

@ -20,7 +20,7 @@ package io.bitsquare.trade.protocol.trade.tasks.offerer;
import io.bitsquare.common.crypto.Sig; import io.bitsquare.common.crypto.Sig;
import io.bitsquare.common.taskrunner.TaskRunner; import io.bitsquare.common.taskrunner.TaskRunner;
import io.bitsquare.common.util.Utilities; import io.bitsquare.common.util.Utilities;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.payment.PaymentAccountContractData; import io.bitsquare.payment.PaymentAccountContractData;
import io.bitsquare.trade.BuyerAsOffererTrade; import io.bitsquare.trade.BuyerAsOffererTrade;
import io.bitsquare.trade.Contract; import io.bitsquare.trade.Contract;
@ -50,18 +50,18 @@ public class CreateAndSignContract extends TradeTask {
PaymentAccountContractData takerPaymentAccountContractData = taker.getPaymentAccountContractData(); PaymentAccountContractData takerPaymentAccountContractData = taker.getPaymentAccountContractData();
boolean isBuyerOffererAndSellerTaker = trade instanceof BuyerAsOffererTrade; boolean isBuyerOffererAndSellerTaker = trade instanceof BuyerAsOffererTrade;
Address buyerAddress = isBuyerOffererAndSellerTaker ? processModel.getMyAddress() : processModel.getTempTradingPeerAddress(); NodeAddress buyerNodeAddress = isBuyerOffererAndSellerTaker ? processModel.getMyAddress() : processModel.getTempTradingPeerNodeAddress();
Address sellerAddress = isBuyerOffererAndSellerTaker ? processModel.getTempTradingPeerAddress() : processModel.getMyAddress(); NodeAddress sellerNodeAddress = isBuyerOffererAndSellerTaker ? processModel.getTempTradingPeerNodeAddress() : processModel.getMyAddress();
log.debug("isBuyerOffererAndSellerTaker " + isBuyerOffererAndSellerTaker); log.debug("isBuyerOffererAndSellerTaker " + isBuyerOffererAndSellerTaker);
log.debug("buyerAddress " + buyerAddress); log.debug("buyerAddress " + buyerNodeAddress);
log.debug("sellerAddress " + sellerAddress); log.debug("sellerAddress " + sellerNodeAddress);
Contract contract = new Contract( Contract contract = new Contract(
processModel.getOffer(), processModel.getOffer(),
trade.getTradeAmount(), trade.getTradeAmount(),
processModel.getTakeOfferFeeTxId(), processModel.getTakeOfferFeeTxId(),
buyerAddress, buyerNodeAddress,
sellerAddress, sellerNodeAddress,
trade.getArbitratorAddress(), trade.getArbitratorNodeAddress(),
isBuyerOffererAndSellerTaker, isBuyerOffererAndSellerTaker,
processModel.getAccountId(), processModel.getAccountId(),
taker.getAccountId(), taker.getAccountId(),

View file

@ -55,7 +55,7 @@ public class ProcessDepositTxPublishedMessage extends TradeTask {
processModel.getOpenOfferManager().closeOpenOffer(trade.getOffer()); processModel.getOpenOfferManager().closeOpenOffer(trade.getOffer());
// update to the latest peer address of our peer if the message is correct // update to the latest peer address of our peer if the message is correct
trade.setTradingPeerAddress(processModel.getTempTradingPeerAddress()); trade.setTradingPeerNodeAddress(processModel.getTempTradingPeerNodeAddress());
complete(); complete();
} catch (Throwable t) { } catch (Throwable t) {

View file

@ -72,15 +72,15 @@ public class ProcessPayDepositRequest extends TradeTask {
processModel.tradingPeer.setAccountId(nonEmptyStringOf(payDepositRequest.takerAccountId)); processModel.tradingPeer.setAccountId(nonEmptyStringOf(payDepositRequest.takerAccountId));
processModel.setTakeOfferFeeTxId(nonEmptyStringOf(payDepositRequest.takeOfferFeeTxId)); processModel.setTakeOfferFeeTxId(nonEmptyStringOf(payDepositRequest.takeOfferFeeTxId));
processModel.setTakerAcceptedArbitratorAddresses(checkNotNull(payDepositRequest.acceptedArbitratorAddresses)); processModel.setTakerAcceptedArbitratorNodeAddresses(checkNotNull(payDepositRequest.acceptedArbitratorNodeAddresses));
if (payDepositRequest.acceptedArbitratorAddresses.size() < 1) if (payDepositRequest.acceptedArbitratorNodeAddresses.size() < 1)
failed("acceptedArbitratorNames size must be at least 1"); failed("acceptedArbitratorNames size must be at least 1");
trade.setArbitratorAddress(checkNotNull(payDepositRequest.arbitratorAddress)); trade.setArbitratorNodeAddress(checkNotNull(payDepositRequest.arbitratorNodeAddress));
checkArgument(payDepositRequest.tradeAmount > 0); checkArgument(payDepositRequest.tradeAmount > 0);
trade.setTradeAmount(Coin.valueOf(payDepositRequest.tradeAmount)); trade.setTradeAmount(Coin.valueOf(payDepositRequest.tradeAmount));
// update to the latest peer address of our peer if the payDepositRequest is correct // update to the latest peer address of our peer if the payDepositRequest is correct
trade.setTradingPeerAddress(processModel.getTempTradingPeerAddress()); trade.setTradingPeerNodeAddress(processModel.getTempTradingPeerNodeAddress());
complete(); complete();
} catch (Throwable t) { } catch (Throwable t) {

View file

@ -52,7 +52,7 @@ public class SendPublishDepositTxRequest extends TradeTask {
); );
processModel.getP2PService().sendEncryptedMailMessage( processModel.getP2PService().sendEncryptedMailMessage(
trade.getTradingPeerAddress(), trade.getTradingPeerNodeAddress(),
processModel.tradingPeer.getPubKeyRing(), processModel.tradingPeer.getPubKeyRing(),
tradeMessage, tradeMessage,
new SendMailMessageListener() { new SendMailMessageListener() {

View file

@ -36,7 +36,7 @@ public class VerifyArbitrationSelection extends TradeTask {
try { try {
runInterceptHook(); runInterceptHook();
if (trade.getArbitratorAddress().equals(ArbitrationSelectionRule.select(processModel.getTakerAcceptedArbitratorAddresses(), if (trade.getArbitratorNodeAddress().equals(ArbitrationSelectionRule.select(processModel.getTakerAcceptedArbitratorNodeAddresses(),
processModel.getOffer()))) processModel.getOffer())))
complete(); complete();
else else

View file

@ -62,7 +62,7 @@ public class CreateAndSignDepositTxAsSeller extends TradeTask {
processModel.getAddressEntry(), processModel.getAddressEntry(),
processModel.tradingPeer.getTradeWalletPubKey(), processModel.tradingPeer.getTradeWalletPubKey(),
processModel.getTradeWalletPubKey(), processModel.getTradeWalletPubKey(),
processModel.getArbitratorPubKey(trade.getArbitratorAddress())); processModel.getArbitratorPubKey(trade.getArbitratorNodeAddress()));
processModel.setPreparedDepositTx(result.depositTransaction); processModel.setPreparedDepositTx(result.depositTransaction);
processModel.setRawInputs(result.rawOffererInputs); processModel.setRawInputs(result.rawOffererInputs);

View file

@ -49,7 +49,7 @@ public class ProcessFiatTransferStartedMessage extends TradeTask {
trade.setState(Trade.State.FIAT_PAYMENT_STARTED_MSG_RECEIVED); trade.setState(Trade.State.FIAT_PAYMENT_STARTED_MSG_RECEIVED);
// update to the latest peer address of our peer if the message is correct // update to the latest peer address of our peer if the message is correct
trade.setTradingPeerAddress(processModel.getTempTradingPeerAddress()); trade.setTradingPeerNodeAddress(processModel.getTempTradingPeerNodeAddress());
complete(); complete();
} catch (Throwable t) { } catch (Throwable t) {

View file

@ -49,7 +49,7 @@ public class ProcessPayoutTxFinalizedMessage extends TradeTask {
trade.setState(Trade.State.PAYOUT_TX_RECEIVED); trade.setState(Trade.State.PAYOUT_TX_RECEIVED);
// update to the latest peer address of our peer if the message is correct // update to the latest peer address of our peer if the message is correct
trade.setTradingPeerAddress(processModel.getTempTradingPeerAddress()); trade.setTradingPeerNodeAddress(processModel.getTempTradingPeerNodeAddress());
complete(); complete();
} catch (Throwable t) { } catch (Throwable t) {

View file

@ -36,7 +36,7 @@ public class SendFinalizePayoutTxRequest extends TradeTask {
protected void run() { protected void run() {
try { try {
runInterceptHook(); runInterceptHook();
if (trade.getTradingPeerAddress() != null) { if (trade.getTradingPeerNodeAddress() != null) {
FinalizePayoutTxRequest message = new FinalizePayoutTxRequest( FinalizePayoutTxRequest message = new FinalizePayoutTxRequest(
processModel.getId(), processModel.getId(),
processModel.getPayoutTxSignature(), processModel.getPayoutTxSignature(),
@ -46,7 +46,7 @@ public class SendFinalizePayoutTxRequest extends TradeTask {
); );
processModel.getP2PService().sendEncryptedMailboxMessage( processModel.getP2PService().sendEncryptedMailboxMessage(
trade.getTradingPeerAddress(), trade.getTradingPeerNodeAddress(),
processModel.tradingPeer.getPubKeyRing(), processModel.tradingPeer.getPubKeyRing(),
message, message,
new SendMailboxMessageListener() { new SendMailboxMessageListener() {
@ -72,7 +72,7 @@ public class SendFinalizePayoutTxRequest extends TradeTask {
} }
); );
} else { } else {
log.error("trade.getTradingPeerAddress() = " + trade.getTradingPeerAddress()); log.error("trade.getTradingPeerAddress() = " + trade.getTradingPeerNodeAddress());
failed("A needed dependency is null"); failed("A needed dependency is null");
} }
} catch (Throwable t) { } catch (Throwable t) {

View file

@ -55,7 +55,7 @@ public class SignAndPublishDepositTxAsSeller extends TradeTask {
processModel.getRawInputs(), processModel.getRawInputs(),
processModel.tradingPeer.getTradeWalletPubKey(), processModel.tradingPeer.getTradeWalletPubKey(),
processModel.getTradeWalletPubKey(), processModel.getTradeWalletPubKey(),
processModel.getArbitratorPubKey(trade.getArbitratorAddress()), processModel.getArbitratorPubKey(trade.getArbitratorNodeAddress()),
new FutureCallback<Transaction>() { new FutureCallback<Transaction>() {
@Override @Override
public void onSuccess(Transaction transaction) { public void onSuccess(Transaction transaction) {

View file

@ -61,7 +61,7 @@ public class SignPayoutTx extends TradeTask {
lockTimeAsBlockHeight, lockTimeAsBlockHeight,
processModel.tradingPeer.getTradeWalletPubKey(), processModel.tradingPeer.getTradeWalletPubKey(),
processModel.getTradeWalletPubKey(), processModel.getTradeWalletPubKey(),
processModel.getArbitratorPubKey(trade.getArbitratorAddress())); processModel.getArbitratorPubKey(trade.getArbitratorNodeAddress()));
processModel.setPayoutTxSignature(payoutTxSignature); processModel.setPayoutTxSignature(payoutTxSignature);

View file

@ -20,7 +20,7 @@ package io.bitsquare.trade.protocol.trade.tasks.taker;
import io.bitsquare.arbitration.Arbitrator; import io.bitsquare.arbitration.Arbitrator;
import io.bitsquare.btc.FeePolicy; import io.bitsquare.btc.FeePolicy;
import io.bitsquare.common.taskrunner.TaskRunner; import io.bitsquare.common.taskrunner.TaskRunner;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.trade.Trade; import io.bitsquare.trade.Trade;
import io.bitsquare.trade.protocol.trade.ArbitrationSelectionRule; import io.bitsquare.trade.protocol.trade.ArbitrationSelectionRule;
import io.bitsquare.trade.protocol.trade.tasks.TradeTask; import io.bitsquare.trade.protocol.trade.tasks.TradeTask;
@ -42,9 +42,9 @@ public class CreateTakeOfferFeeTx extends TradeTask {
runInterceptHook(); runInterceptHook();
User user = processModel.getUser(); User user = processModel.getUser();
Address selectedArbitratorAddress = ArbitrationSelectionRule.select(user.getAcceptedArbitratorAddresses(), processModel.getOffer()); NodeAddress selectedArbitratorNodeAddress = ArbitrationSelectionRule.select(user.getAcceptedArbitratorAddresses(), processModel.getOffer());
log.debug("selectedArbitratorAddress " + selectedArbitratorAddress); log.debug("selectedArbitratorAddress " + selectedArbitratorNodeAddress);
Arbitrator selectedArbitrator = user.getAcceptedArbitratorByAddress(selectedArbitratorAddress); Arbitrator selectedArbitrator = user.getAcceptedArbitratorByAddress(selectedArbitratorNodeAddress);
Transaction createTakeOfferFeeTx = processModel.getTradeWalletService().createTradingFeeTx( Transaction createTakeOfferFeeTx = processModel.getTradeWalletService().createTradingFeeTx(
processModel.getAddressEntry(), processModel.getAddressEntry(),
FeePolicy.getTakeOfferFee(), FeePolicy.getTakeOfferFee(),

View file

@ -79,7 +79,7 @@ public class ProcessPublishDepositTxRequest extends TradeTask {
} }
// update to the latest peer address of our peer if the message is correct // update to the latest peer address of our peer if the message is correct
trade.setTradingPeerAddress(processModel.getTempTradingPeerAddress()); trade.setTradingPeerNodeAddress(processModel.getTempTradingPeerNodeAddress());
complete(); complete();
} catch (Throwable t) { } catch (Throwable t) {

View file

@ -36,7 +36,7 @@ public class SelectArbitrator extends TradeTask {
try { try {
runInterceptHook(); runInterceptHook();
trade.setArbitratorAddress(ArbitrationSelectionRule.select(processModel.getUser().getAcceptedArbitratorAddresses(), processModel.getOffer())); trade.setArbitratorNodeAddress(ArbitrationSelectionRule.select(processModel.getUser().getAcceptedArbitratorAddresses(), processModel.getOffer()));
complete(); complete();
} catch (Throwable t) { } catch (Throwable t) {

View file

@ -42,7 +42,7 @@ public class SendDepositTxPublishedMessage extends TradeTask {
processModel.getMyAddress()); processModel.getMyAddress());
processModel.getP2PService().sendEncryptedMailboxMessage( processModel.getP2PService().sendEncryptedMailboxMessage(
trade.getTradingPeerAddress(), trade.getTradingPeerNodeAddress(),
processModel.tradingPeer.getPubKeyRing(), processModel.tradingPeer.getPubKeyRing(),
tradeMessage, tradeMessage,
new SendMailboxMessageListener() { new SendMailboxMessageListener() {

View file

@ -51,11 +51,11 @@ public class SendPayDepositRequest extends TradeTask {
processModel.getAccountId(), processModel.getAccountId(),
processModel.getTakeOfferFeeTx().getHashAsString(), processModel.getTakeOfferFeeTx().getHashAsString(),
processModel.getUser().getAcceptedArbitratorAddresses(), processModel.getUser().getAcceptedArbitratorAddresses(),
trade.getArbitratorAddress() trade.getArbitratorNodeAddress()
); );
processModel.getP2PService().sendEncryptedMailboxMessage( processModel.getP2PService().sendEncryptedMailboxMessage(
trade.getTradingPeerAddress(), trade.getTradingPeerNodeAddress(),
processModel.tradingPeer.getPubKeyRing(), processModel.tradingPeer.getPubKeyRing(),
payDepositRequest, payDepositRequest,
new SendMailboxMessageListener() { new SendMailboxMessageListener() {

View file

@ -20,7 +20,7 @@ package io.bitsquare.trade.protocol.trade.tasks.taker;
import io.bitsquare.common.crypto.Sig; import io.bitsquare.common.crypto.Sig;
import io.bitsquare.common.taskrunner.TaskRunner; import io.bitsquare.common.taskrunner.TaskRunner;
import io.bitsquare.common.util.Utilities; import io.bitsquare.common.util.Utilities;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.payment.PaymentAccountContractData; import io.bitsquare.payment.PaymentAccountContractData;
import io.bitsquare.trade.Contract; import io.bitsquare.trade.Contract;
import io.bitsquare.trade.SellerAsTakerTrade; import io.bitsquare.trade.SellerAsTakerTrade;
@ -48,19 +48,19 @@ public class VerifyAndSignContract extends TradeTask {
PaymentAccountContractData takerPaymentAccountContractData = processModel.getPaymentAccountContractData(trade); PaymentAccountContractData takerPaymentAccountContractData = processModel.getPaymentAccountContractData(trade);
boolean isBuyerOffererAndSellerTaker = trade instanceof SellerAsTakerTrade; boolean isBuyerOffererAndSellerTaker = trade instanceof SellerAsTakerTrade;
Address buyerAddress = isBuyerOffererAndSellerTaker ? processModel.getTempTradingPeerAddress() : processModel.getMyAddress(); NodeAddress buyerNodeAddress = isBuyerOffererAndSellerTaker ? processModel.getTempTradingPeerNodeAddress() : processModel.getMyAddress();
Address sellerAddress = isBuyerOffererAndSellerTaker ? processModel.getMyAddress() : processModel.getTempTradingPeerAddress(); NodeAddress sellerNodeAddress = isBuyerOffererAndSellerTaker ? processModel.getMyAddress() : processModel.getTempTradingPeerNodeAddress();
log.debug("isBuyerOffererAndSellerTaker " + isBuyerOffererAndSellerTaker); log.debug("isBuyerOffererAndSellerTaker " + isBuyerOffererAndSellerTaker);
log.debug("buyerAddress " + buyerAddress); log.debug("buyerAddress " + buyerNodeAddress);
log.debug("sellerAddress " + sellerAddress); log.debug("sellerAddress " + sellerNodeAddress);
Contract contract = new Contract( Contract contract = new Contract(
processModel.getOffer(), processModel.getOffer(),
trade.getTradeAmount(), trade.getTradeAmount(),
processModel.getTakeOfferFeeTx().getHashAsString(), processModel.getTakeOfferFeeTx().getHashAsString(),
buyerAddress, buyerNodeAddress,
sellerAddress, sellerNodeAddress,
trade.getArbitratorAddress(), trade.getArbitratorNodeAddress(),
isBuyerOffererAndSellerTaker, isBuyerOffererAndSellerTaker,
offerer.getAccountId(), offerer.getAccountId(),
processModel.getAccountId(), processModel.getAccountId(),

View file

@ -23,7 +23,7 @@ import io.bitsquare.arbitration.Arbitrator;
import io.bitsquare.common.crypto.KeyRing; import io.bitsquare.common.crypto.KeyRing;
import io.bitsquare.locale.LanguageUtil; import io.bitsquare.locale.LanguageUtil;
import io.bitsquare.locale.TradeCurrency; import io.bitsquare.locale.TradeCurrency;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.payment.PaymentAccount; import io.bitsquare.payment.PaymentAccount;
import io.bitsquare.storage.Storage; import io.bitsquare.storage.Storage;
import javafx.beans.property.ObjectProperty; import javafx.beans.property.ObjectProperty;
@ -250,8 +250,8 @@ public class User implements Serializable {
return acceptedArbitrators; return acceptedArbitrators;
} }
public List<Address> getAcceptedArbitratorAddresses() { public List<NodeAddress> getAcceptedArbitratorAddresses() {
return acceptedArbitrators.stream().map(Arbitrator::getArbitratorAddress).collect(Collectors.toList()); return acceptedArbitrators.stream().map(Arbitrator::getArbitratorNodeAddress).collect(Collectors.toList());
} }
public List<String> getAcceptedLanguageLocaleCodes() { public List<String> getAcceptedLanguageLocaleCodes() {
@ -269,8 +269,8 @@ public class User implements Serializable {
return receiverAddresses; return receiverAddresses;
}*/ }*/
public Arbitrator getAcceptedArbitratorByAddress(Address address) { public Arbitrator getAcceptedArbitratorByAddress(NodeAddress nodeAddress) {
Optional<Arbitrator> arbitratorOptional = acceptedArbitrators.stream().filter(e -> e.getArbitratorAddress().equals(address)).findFirst(); Optional<Arbitrator> arbitratorOptional = acceptedArbitrators.stream().filter(e -> e.getArbitratorNodeAddress().equals(nodeAddress)).findFirst();
if (arbitratorOptional.isPresent()) if (arbitratorOptional.isPresent())
return arbitratorOptional.get(); return arbitratorOptional.get();
else else

View file

@ -27,7 +27,7 @@ import io.bitsquare.common.handlers.ErrorMessageHandler;
import io.bitsquare.common.handlers.ResultHandler; import io.bitsquare.common.handlers.ResultHandler;
import io.bitsquare.gui.common.model.ActivatableViewModel; import io.bitsquare.gui.common.model.ActivatableViewModel;
import io.bitsquare.locale.LanguageUtil; import io.bitsquare.locale.LanguageUtil;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.P2PService; import io.bitsquare.p2p.P2PService;
import io.bitsquare.user.User; import io.bitsquare.user.User;
import javafx.beans.property.*; import javafx.beans.property.*;
@ -53,7 +53,7 @@ class ArbitratorRegistrationViewModel extends ActivatableViewModel {
final ObservableList<String> languageCodes = FXCollections.observableArrayList(LanguageUtil.getDefaultLanguageLocaleAsCode()); final ObservableList<String> languageCodes = FXCollections.observableArrayList(LanguageUtil.getDefaultLanguageLocaleAsCode());
final ObservableList<String> allLanguageCodes = FXCollections.observableArrayList(LanguageUtil.getAllLanguageCodes()); final ObservableList<String> allLanguageCodes = FXCollections.observableArrayList(LanguageUtil.getAllLanguageCodes());
private boolean allDataValid; private boolean allDataValid;
private final MapChangeListener<Address, Arbitrator> arbitratorMapChangeListener; private final MapChangeListener<NodeAddress, Arbitrator> arbitratorMapChangeListener;
private ECKey registrationKey; private ECKey registrationKey;
StringProperty registrationPubKeyAsHex = new SimpleStringProperty(); StringProperty registrationPubKeyAsHex = new SimpleStringProperty();
@ -73,9 +73,9 @@ class ArbitratorRegistrationViewModel extends ActivatableViewModel {
this.walletService = walletService; this.walletService = walletService;
this.keyRing = keyRing; this.keyRing = keyRing;
arbitratorMapChangeListener = new MapChangeListener<Address, Arbitrator>() { arbitratorMapChangeListener = new MapChangeListener<NodeAddress, Arbitrator>() {
@Override @Override
public void onChanged(Change<? extends Address, ? extends Arbitrator> change) { public void onChanged(Change<? extends NodeAddress, ? extends Arbitrator> change) {
Arbitrator myRegisteredArbitrator = user.getRegisteredArbitrator(); Arbitrator myRegisteredArbitrator = user.getRegisteredArbitrator();
myArbitratorProperty.set(myRegisteredArbitrator); myArbitratorProperty.set(myRegisteredArbitrator);

View file

@ -33,7 +33,7 @@ public class ArbitratorListItem {
} }
public String getAddressString() { public String getAddressString() {
return arbitrator != null ? arbitrator.getArbitratorAddress().getFullAddress() : ""; return arbitrator != null ? arbitrator.getArbitratorNodeAddress().getFullAddress() : "";
} }
public String getLanguageCodes() { public String getLanguageCodes() {

View file

@ -24,7 +24,7 @@ import io.bitsquare.common.crypto.KeyRing;
import io.bitsquare.gui.common.model.ActivatableDataModel; import io.bitsquare.gui.common.model.ActivatableDataModel;
import io.bitsquare.gui.util.BSFormatter; import io.bitsquare.gui.util.BSFormatter;
import io.bitsquare.locale.LanguageUtil; import io.bitsquare.locale.LanguageUtil;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.user.Preferences; import io.bitsquare.user.Preferences;
import io.bitsquare.user.User; import io.bitsquare.user.User;
import javafx.collections.FXCollections; import javafx.collections.FXCollections;
@ -42,7 +42,7 @@ class ArbitratorSelectionViewModel extends ActivatableDataModel {
final ObservableList<String> languageCodes = FXCollections.observableArrayList(); final ObservableList<String> languageCodes = FXCollections.observableArrayList();
final ObservableList<ArbitratorListItem> arbitratorListItems = FXCollections.observableArrayList(); final ObservableList<ArbitratorListItem> arbitratorListItems = FXCollections.observableArrayList();
final ObservableList<String> allLanguageCodes = FXCollections.observableArrayList(LanguageUtil.getAllLanguageCodes()); final ObservableList<String> allLanguageCodes = FXCollections.observableArrayList(LanguageUtil.getAllLanguageCodes());
private final MapChangeListener<Address, Arbitrator> arbitratorMapChangeListener; private final MapChangeListener<NodeAddress, Arbitrator> arbitratorMapChangeListener;
@Inject @Inject
public ArbitratorSelectionViewModel(User user, ArbitratorManager arbitratorManager, Preferences preferences, public ArbitratorSelectionViewModel(User user, ArbitratorManager arbitratorManager, Preferences preferences,

View file

@ -26,7 +26,7 @@ import io.bitsquare.gui.common.view.*;
import io.bitsquare.gui.main.MainView; import io.bitsquare.gui.main.MainView;
import io.bitsquare.gui.main.disputes.arbitrator.ArbitratorDisputeView; import io.bitsquare.gui.main.disputes.arbitrator.ArbitratorDisputeView;
import io.bitsquare.gui.main.disputes.trader.TraderDisputeView; import io.bitsquare.gui.main.disputes.trader.TraderDisputeView;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import javafx.beans.value.ChangeListener; import javafx.beans.value.ChangeListener;
import javafx.collections.MapChangeListener; import javafx.collections.MapChangeListener;
import javafx.fxml.FXML; import javafx.fxml.FXML;
@ -50,7 +50,7 @@ public class DisputesView extends ActivatableViewAndModel<TabPane, Activatable>
private ChangeListener<Tab> tabChangeListener; private ChangeListener<Tab> tabChangeListener;
private Tab currentTab; private Tab currentTab;
private final ViewLoader viewLoader; private final ViewLoader viewLoader;
private MapChangeListener<Address, Arbitrator> arbitratorMapChangeListener; private MapChangeListener<NodeAddress, Arbitrator> arbitratorMapChangeListener;
@Inject @Inject
public DisputesView(CachingViewLoader viewLoader, Navigation navigation, ArbitratorManager arbitratorManager, KeyRing keyRing) { public DisputesView(CachingViewLoader viewLoader, Navigation navigation, ArbitratorManager arbitratorManager, KeyRing keyRing) {

View file

@ -114,7 +114,7 @@ public class ReservedListItem {
// We ignore the tx fee as it will be paid by both (once deposit, once payout) // We ignore the tx fee as it will be paid by both (once deposit, once payout)
Coin balanceInDeposit = FeePolicy.getSecurityDeposit(); Coin balanceInDeposit = FeePolicy.getSecurityDeposit();
// For the seller we add the trade amount // For the seller we add the trade amount
if (trade.getContract().getSellerAddress().equals(getAddress())) if (trade.getContract().getSellerNodeAddress().equals(getAddress()))
balanceInDeposit.add(trade.getTradeAmount()); balanceInDeposit.add(trade.getTradeAmount());
balanceLabel.setText(formatter.formatCoinWithCode(balance) + " (in MS escrow)"); balanceLabel.setText(formatter.formatCoinWithCode(balance) + " (in MS escrow)");

View file

@ -26,7 +26,7 @@ import io.bitsquare.locale.BSResources;
import io.bitsquare.locale.CountryUtil; import io.bitsquare.locale.CountryUtil;
import io.bitsquare.locale.CurrencyUtil; import io.bitsquare.locale.CurrencyUtil;
import io.bitsquare.locale.TradeCurrency; import io.bitsquare.locale.TradeCurrency;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.P2PService; import io.bitsquare.p2p.P2PService;
import io.bitsquare.payment.PaymentMethod; import io.bitsquare.payment.PaymentMethod;
import io.bitsquare.payment.SepaAccount; import io.bitsquare.payment.SepaAccount;
@ -283,9 +283,9 @@ class OfferBookViewModel extends ActivatableViewModel {
public boolean hasMatchingArbitrator(Offer offer) { public boolean hasMatchingArbitrator(Offer offer) {
for (Address offerArbitratorAddress : offer.getArbitratorAddresses()) { for (NodeAddress offerArbitratorNodeAddress : offer.getArbitratorNodeAddresses()) {
for (Address acceptedArbitratorAddress : user.getAcceptedArbitratorAddresses()) { for (NodeAddress acceptedArbitratorNodeAddress : user.getAcceptedArbitratorAddresses()) {
if (offerArbitratorAddress.equals(acceptedArbitratorAddress)) if (offerArbitratorNodeAddress.equals(acceptedArbitratorNodeAddress))
return true; return true;
} }
} }

View file

@ -269,7 +269,7 @@ public class PendingTradesDataModel extends ActivatableDataModel {
trade.getContractAsJson(), trade.getContractAsJson(),
trade.getOffererContractSignature(), trade.getOffererContractSignature(),
trade.getTakerContractSignature(), trade.getTakerContractSignature(),
user.getAcceptedArbitratorByAddress(trade.getArbitratorAddress()).getPubKeyRing(), user.getAcceptedArbitratorByAddress(trade.getArbitratorNodeAddress()).getPubKeyRing(),
isSupportTicket isSupportTicket
); );

View file

@ -26,7 +26,7 @@ import io.bitsquare.gui.common.view.ActivatableViewAndModel;
import io.bitsquare.gui.common.view.FxmlView; import io.bitsquare.gui.common.view.FxmlView;
import io.bitsquare.gui.popups.Popup; import io.bitsquare.gui.popups.Popup;
import io.bitsquare.gui.util.BSFormatter; import io.bitsquare.gui.util.BSFormatter;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.P2PService; import io.bitsquare.p2p.P2PService;
import io.bitsquare.p2p.P2PServiceListener; import io.bitsquare.p2p.P2PServiceListener;
import io.bitsquare.p2p.network.LocalhostNetworkNode; import io.bitsquare.p2p.network.LocalhostNetworkNode;
@ -72,7 +72,7 @@ public class NetworkSettingsView extends ActivatableViewAndModel<GridPane, Activ
private P2PServiceListener p2PServiceListener; private P2PServiceListener p2PServiceListener;
private ChangeListener<Number> numAuthenticatedPeersChangeListener; private ChangeListener<Number> numAuthenticatedPeersChangeListener;
private ChangeListener<List<Peer>> bitcoinPeersChangeListener; private ChangeListener<List<Peer>> bitcoinPeersChangeListener;
private Set<Address> seedNodeAddresses; private Set<NodeAddress> seedNodeNodeAddresses;
@Inject @Inject
public NetworkSettingsView(WalletService walletService, P2PService p2PService, Preferences preferences, public NetworkSettingsView(WalletService walletService, P2PService p2PService, Preferences preferences,
@ -84,7 +84,7 @@ public class NetworkSettingsView extends ActivatableViewAndModel<GridPane, Activ
BitcoinNetwork bitcoinNetwork = preferences.getBitcoinNetwork(); BitcoinNetwork bitcoinNetwork = preferences.getBitcoinNetwork();
boolean useLocalhost = p2PService.getNetworkNode() instanceof LocalhostNetworkNode; boolean useLocalhost = p2PService.getNetworkNode() instanceof LocalhostNetworkNode;
this.seedNodeAddresses = seedNodesRepository.getSeedNodeAddresses(useLocalhost, bitcoinNetwork.ordinal()); this.seedNodeNodeAddresses = seedNodesRepository.getSeedNodeAddresses(useLocalhost, bitcoinNetwork.ordinal());
} }
public void initialize() { public void initialize() {
@ -111,8 +111,8 @@ public class NetworkSettingsView extends ActivatableViewAndModel<GridPane, Activ
@Override @Override
public void activate() { public void activate() {
Address address = p2PService.getAddress(); NodeAddress nodeAddress = p2PService.getAddress();
if (address == null) { if (nodeAddress == null) {
p2PServiceListener = new P2PServiceListener() { p2PServiceListener = new P2PServiceListener() {
@Override @Override
public void onRequestingDataCompleted() { public void onRequestingDataCompleted() {
@ -145,7 +145,7 @@ public class NetworkSettingsView extends ActivatableViewAndModel<GridPane, Activ
}; };
p2PService.addP2PServiceListener(p2PServiceListener); p2PService.addP2PServiceListener(p2PServiceListener);
} else { } else {
onionAddress.setText(address.getFullAddress()); onionAddress.setText(nodeAddress.getFullAddress());
} }
bitcoinPeersChangeListener = (observable, oldValue, newValue) -> updateBitcoinPeersTextArea(); bitcoinPeersChangeListener = (observable, oldValue, newValue) -> updateBitcoinPeersTextArea();
@ -171,11 +171,11 @@ public class NetworkSettingsView extends ActivatableViewAndModel<GridPane, Activ
private void updateAuthenticatedPeersTextArea() { private void updateAuthenticatedPeersTextArea() {
authenticatedPeersTextArea.clear(); authenticatedPeersTextArea.clear();
p2PService.getAuthenticatedPeerAddresses().stream().forEach(e -> { p2PService.getAuthenticatedPeerNodeAddresses().stream().forEach(e -> {
if (authenticatedPeersTextArea.getText().length() > 0) if (authenticatedPeersTextArea.getText().length() > 0)
authenticatedPeersTextArea.appendText("\n"); authenticatedPeersTextArea.appendText("\n");
authenticatedPeersTextArea.appendText(e.getFullAddress()); authenticatedPeersTextArea.appendText(e.getFullAddress());
if (seedNodeAddresses.contains(e)) if (seedNodeNodeAddresses.contains(e))
authenticatedPeersTextArea.appendText(" (Seed node)"); authenticatedPeersTextArea.appendText(" (Seed node)");
}); });
} }

View file

@ -118,9 +118,9 @@ public class ContractPopup extends Popup {
contract.getSellerPayoutAddressString()).second.setMouseTransparent(false); contract.getSellerPayoutAddressString()).second.setMouseTransparent(false);
addLabelTextFieldWithCopyIcon(gridPane, ++rowIndex, "Contract hash:", addLabelTextFieldWithCopyIcon(gridPane, ++rowIndex, "Contract hash:",
Utils.HEX.encode(dispute.getContractHash())).second.setMouseTransparent(false); Utils.HEX.encode(dispute.getContractHash())).second.setMouseTransparent(false);
addLabelTextField(gridPane, ++rowIndex, "Buyer address:", contract.getBuyerAddress().getFullAddress()); addLabelTextField(gridPane, ++rowIndex, "Buyer address:", contract.getBuyerNodeAddress().getFullAddress());
addLabelTextField(gridPane, ++rowIndex, "Seller address:", contract.getSellerAddress().getFullAddress()); addLabelTextField(gridPane, ++rowIndex, "Seller address:", contract.getSellerNodeAddress().getFullAddress());
addLabelTextField(gridPane, ++rowIndex, "Selected arbitrator:", contract.arbitratorAddress.getFullAddress()); addLabelTextField(gridPane, ++rowIndex, "Selected arbitrator:", contract.arbitratorNodeAddress.getFullAddress());
addLabelTextFieldWithCopyIcon(gridPane, ++rowIndex, "Buyer payment details:", addLabelTextFieldWithCopyIcon(gridPane, ++rowIndex, "Buyer payment details:",
BSResources.get(contract.getBuyerPaymentAccountContractData().getPaymentDetails())).second.setMouseTransparent(false); BSResources.get(contract.getBuyerPaymentAccountContractData().getPaymentDetails())).second.setMouseTransparent(false);
addLabelTextField(gridPane, ++rowIndex, "Seller payment details:", addLabelTextField(gridPane, ++rowIndex, "Seller payment details:",

View file

@ -172,7 +172,7 @@ public class OfferDetailsPopup extends Popup {
acceptedCountries.setTooltip(tooltip); acceptedCountries.setTooltip(tooltip);
} }
} }
addLabelTextField(gridPane, ++rowIndex, "Accepted arbitrators:", formatter.arbitratorAddressesToString(offer.getArbitratorAddresses())); addLabelTextField(gridPane, ++rowIndex, "Accepted arbitrators:", formatter.arbitratorAddressesToString(offer.getArbitratorNodeAddresses()));
if (offer.getOfferFeePaymentTxID() != null) if (offer.getOfferFeePaymentTxID() != null)
addLabelTxIdTextField(gridPane, ++rowIndex, "Offer fee transaction ID:", offer.getOfferFeePaymentTxID()); addLabelTxIdTextField(gridPane, ++rowIndex, "Offer fee transaction ID:", offer.getOfferFeePaymentTxID());

View file

@ -133,7 +133,7 @@ public class TradeDetailsPopup extends Popup {
addTitledGroupBg(gridPane, ++rowIndex, rows, "Details", Layout.GROUP_DISTANCE); addTitledGroupBg(gridPane, ++rowIndex, rows, "Details", Layout.GROUP_DISTANCE);
addLabelTextField(gridPane, rowIndex, "Trade ID:", trade.getId(), Layout.FIRST_ROW_AND_GROUP_DISTANCE); addLabelTextField(gridPane, rowIndex, "Trade ID:", trade.getId(), Layout.FIRST_ROW_AND_GROUP_DISTANCE);
addLabelTextField(gridPane, ++rowIndex, "Trade date:", formatter.formatDateTime(trade.getDate())); addLabelTextField(gridPane, ++rowIndex, "Trade date:", formatter.formatDateTime(trade.getDate()));
addLabelTextField(gridPane, ++rowIndex, "Selected arbitrator:", trade.getArbitratorAddress().getFullAddress()); addLabelTextField(gridPane, ++rowIndex, "Selected arbitrator:", trade.getArbitratorNodeAddress().getFullAddress());
if (contract != null) { if (contract != null) {
if (buyerPaymentAccountContractData != null) { if (buyerPaymentAccountContractData != null) {

View file

@ -20,7 +20,7 @@ package io.bitsquare.gui.util;
import io.bitsquare.btc.BitcoinNetwork; import io.bitsquare.btc.BitcoinNetwork;
import io.bitsquare.locale.Country; import io.bitsquare.locale.Country;
import io.bitsquare.locale.LanguageUtil; import io.bitsquare.locale.LanguageUtil;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.trade.offer.Offer; import io.bitsquare.trade.offer.Offer;
import io.bitsquare.user.Preferences; import io.bitsquare.user.Preferences;
import org.bitcoinj.core.Coin; import org.bitcoinj.core.Coin;
@ -301,8 +301,8 @@ public class BSFormatter {
} }
public String arbitratorAddressesToString(List<Address> addresses) { public String arbitratorAddressesToString(List<NodeAddress> nodeAddresses) {
return addresses.stream().map(e -> e.getFullAddress()).collect(Collectors.joining(", ")); return nodeAddresses.stream().map(e -> e.getFullAddress()).collect(Collectors.joining(", "));
} }
public String languageCodesToString(List<String> languageLocales) { public String languageCodesToString(List<String> languageLocales) {

View file

@ -2,7 +2,7 @@ package io.bitsquare.crypto;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.common.crypto.SealedAndSigned; import io.bitsquare.common.crypto.SealedAndSigned;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.messaging.MailboxMessage; import io.bitsquare.p2p.messaging.MailboxMessage;
import java.util.Arrays; import java.util.Arrays;
@ -21,7 +21,7 @@ public final class SealedAndSignedMessage implements MailboxMessage {
} }
@Override @Override
public Address getSenderAddress() { public NodeAddress getSenderNodeAddress() {
return null; return null;
} }

View file

@ -5,17 +5,17 @@ import io.bitsquare.common.crypto.Hash;
import java.io.Serializable; import java.io.Serializable;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class Address implements Serializable { public class NodeAddress implements Serializable {
public final String hostName; public final String hostName;
public final int port; public final int port;
transient private byte[] addressPrefixHash; transient private byte[] addressPrefixHash;
public Address(String hostName, int port) { public NodeAddress(String hostName, int port) {
this.hostName = hostName; this.hostName = hostName;
this.port = port; this.port = port;
} }
public Address(String fullAddress) { public NodeAddress(String fullAddress) {
final String[] split = fullAddress.split(Pattern.quote(":")); final String[] split = fullAddress.split(Pattern.quote(":"));
this.hostName = split[0]; this.hostName = split[0];
this.port = Integer.parseInt(split[1]); this.port = Integer.parseInt(split[1]);
@ -35,12 +35,12 @@ public class Address implements Serializable {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (!(o instanceof Address)) return false; if (!(o instanceof NodeAddress)) return false;
Address address = (Address) o; NodeAddress nodeAddress = (NodeAddress) o;
if (port != address.port) return false; if (port != nodeAddress.port) return false;
return !(hostName != null ? !hostName.equals(address.hostName) : address.hostName != null); return !(hostName != null ? !hostName.equals(nodeAddress.hostName) : nodeAddress.hostName != null);
} }

View file

@ -62,22 +62,22 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
private final CopyOnWriteArraySet<DecryptedMailboxListener> decryptedMailboxListeners = new CopyOnWriteArraySet<>(); private final CopyOnWriteArraySet<DecryptedMailboxListener> decryptedMailboxListeners = new CopyOnWriteArraySet<>();
protected final CopyOnWriteArraySet<P2PServiceListener> p2pServiceListeners = new CopyOnWriteArraySet<>(); protected final CopyOnWriteArraySet<P2PServiceListener> p2pServiceListeners = new CopyOnWriteArraySet<>();
private final Map<DecryptedMsgWithPubKey, ProtectedMailboxData> mailboxMap = new HashMap<>(); private final Map<DecryptedMsgWithPubKey, ProtectedMailboxData> mailboxMap = new HashMap<>();
private final Set<Address> authenticatedPeerAddresses = new HashSet<>(); private final Set<NodeAddress> authenticatedPeerNodeAddresses = new HashSet<>();
private final CopyOnWriteArraySet<Runnable> shutDownResultHandlers = new CopyOnWriteArraySet<>(); private final CopyOnWriteArraySet<Runnable> shutDownResultHandlers = new CopyOnWriteArraySet<>();
protected final BooleanProperty hiddenServicePublished = new SimpleBooleanProperty(); protected final BooleanProperty hiddenServicePublished = new SimpleBooleanProperty();
private final BooleanProperty requestingDataCompleted = new SimpleBooleanProperty(); private final BooleanProperty requestingDataCompleted = new SimpleBooleanProperty();
protected final BooleanProperty notAuthenticated = new SimpleBooleanProperty(true); protected final BooleanProperty notAuthenticated = new SimpleBooleanProperty(true);
private final IntegerProperty numAuthenticatedPeers = new SimpleIntegerProperty(0); private final IntegerProperty numAuthenticatedPeers = new SimpleIntegerProperty(0);
private Address seedNodeOfInitialDataRequest; private NodeAddress seedNodeOfInitialDataRequest;
private volatile boolean shutDownInProgress; private volatile boolean shutDownInProgress;
private boolean shutDownComplete; private boolean shutDownComplete;
@SuppressWarnings("FieldCanBeLocal") @SuppressWarnings("FieldCanBeLocal")
private MonadicBinding<Boolean> readyForAuthenticationBinding; private MonadicBinding<Boolean> readyForAuthenticationBinding;
private final Storage<Address> dbStorage; private final Storage<NodeAddress> dbStorage;
private Address myOnionAddress; private NodeAddress myOnionNodeAddress;
protected RequestDataManager requestDataManager; protected RequestDataManager requestDataManager;
protected Set<Address> seedNodeAddresses; protected Set<NodeAddress> seedNodeNodeAddresses;
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@ -112,11 +112,11 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
Log.traceCall(); Log.traceCall();
// lets check if we have already stored our onion address // lets check if we have already stored our onion address
Address persistedOnionAddress = dbStorage.initAndGetPersisted("myOnionAddress"); NodeAddress persistedOnionNodeAddress = dbStorage.initAndGetPersisted("myOnionAddress");
if (persistedOnionAddress != null) if (persistedOnionNodeAddress != null)
this.myOnionAddress = persistedOnionAddress; this.myOnionNodeAddress = persistedOnionNodeAddress;
seedNodeAddresses = seedNodesRepository.getSeedNodeAddresses(useLocalhost, networkId); seedNodeNodeAddresses = seedNodesRepository.getSeedNodeAddresses(useLocalhost, networkId);
// network node // network node
networkNode = useLocalhost ? new LocalhostNetworkNode(port) : new TorNetworkNode(port, torDir); networkNode = useLocalhost ? new LocalhostNetworkNode(port) : new TorNetworkNode(port, torDir);
@ -125,7 +125,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
// peer group // peer group
peerManager = getNewPeerManager(); peerManager = getNewPeerManager();
peerManager.setSeedNodeAddresses(seedNodeAddresses); peerManager.setSeedNodeAddresses(seedNodeNodeAddresses);
peerManager.addAuthenticationListener(this); peerManager.addAuthenticationListener(this);
// P2P network data storage // P2P network data storage
@ -146,9 +146,9 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
} }
@Override @Override
public void onDataReceived(Address address) { public void onDataReceived(NodeAddress nodeAddress) {
if (!requestingDataCompleted.get()) { if (!requestingDataCompleted.get()) {
seedNodeOfInitialDataRequest = address; seedNodeOfInitialDataRequest = nodeAddress;
requestingDataCompleted.set(true); requestingDataCompleted.set(true);
} }
p2pServiceListeners.stream().forEach(e -> e.onRequestingDataCompleted()); p2pServiceListeners.stream().forEach(e -> e.onRequestingDataCompleted());
@ -247,20 +247,20 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
@Override @Override
public void onTorNodeReady() { public void onTorNodeReady() {
Log.traceCall(); Log.traceCall();
requestDataManager.requestDataFromSeedNodes(seedNodeAddresses); requestDataManager.requestDataFromSeedNodes(seedNodeNodeAddresses);
p2pServiceListeners.stream().forEach(e -> e.onTorNodeReady()); p2pServiceListeners.stream().forEach(e -> e.onTorNodeReady());
} }
@Override @Override
public void onHiddenServicePublished() { public void onHiddenServicePublished() {
Log.traceCall(); Log.traceCall();
checkArgument(networkNode.getAddress() != null, "Address must be set when we have the hidden service ready"); checkArgument(networkNode.getNodeAddress() != null, "Address must be set when we have the hidden service ready");
if (myOnionAddress != null) { if (myOnionNodeAddress != null) {
checkArgument(networkNode.getAddress().equals(myOnionAddress), checkArgument(networkNode.getNodeAddress().equals(myOnionNodeAddress),
"If we are a seed node networkNode.getAddress() must be same as myOnionAddress."); "If we are a seed node networkNode.getAddress() must be same as myOnionAddress.");
} else { } else {
myOnionAddress = networkNode.getAddress(); myOnionNodeAddress = networkNode.getNodeAddress();
dbStorage.queueUpForSave(myOnionAddress); dbStorage.queueUpForSave(myOnionNodeAddress);
} }
hiddenServicePublished.set(true); hiddenServicePublished.set(true);
@ -292,8 +292,8 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
@Override @Override
public void onDisconnect(Reason reason, Connection connection) { public void onDisconnect(Reason reason, Connection connection) {
Log.traceCall(); Log.traceCall();
connection.getPeerAddressOptional().ifPresent(peerAddresses -> authenticatedPeerAddresses.remove(peerAddresses)); connection.getPeerAddressOptional().ifPresent(peerAddresses -> authenticatedPeerNodeAddresses.remove(peerAddresses));
numAuthenticatedPeers.set(authenticatedPeerAddresses.size()); numAuthenticatedPeers.set(authenticatedPeerNodeAddresses.size());
} }
@Override @Override
@ -306,16 +306,16 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Override @Override
public void onPeerAuthenticated(Address peerAddress, Connection connection) { public void onPeerAuthenticated(NodeAddress peerNodeAddress, Connection connection) {
Log.traceCall(); Log.traceCall();
authenticatedPeerAddresses.add(peerAddress); authenticatedPeerNodeAddresses.add(peerNodeAddress);
if (notAuthenticated.get()) { if (notAuthenticated.get()) {
notAuthenticated.set(false); notAuthenticated.set(false);
p2pServiceListeners.stream().forEach(e -> e.onFirstPeerAuthenticated()); p2pServiceListeners.stream().forEach(e -> e.onFirstPeerAuthenticated());
} }
numAuthenticatedPeers.set(authenticatedPeerAddresses.size()); numAuthenticatedPeers.set(authenticatedPeerNodeAddresses.size());
} }
@ -377,25 +377,25 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
// MailMessages // MailMessages
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public void sendEncryptedMailMessage(Address peerAddress, PubKeyRing pubKeyRing, MailMessage message, public void sendEncryptedMailMessage(NodeAddress peerNodeAddress, PubKeyRing pubKeyRing, MailMessage message,
SendMailMessageListener sendMailMessageListener) { SendMailMessageListener sendMailMessageListener) {
Log.traceCall(); Log.traceCall();
checkNotNull(peerAddress, "PeerAddress must not be null (sendEncryptedMailMessage)"); checkNotNull(peerNodeAddress, "PeerAddress must not be null (sendEncryptedMailMessage)");
try { try {
checkAuthentication(); checkAuthentication();
if (!authenticatedPeerAddresses.contains(peerAddress)) if (!authenticatedPeerNodeAddresses.contains(peerNodeAddress))
peerManager.authenticateToDirectMessagePeer(peerAddress, peerManager.authenticateToDirectMessagePeer(peerNodeAddress,
() -> doSendEncryptedMailMessage(peerAddress, pubKeyRing, message, sendMailMessageListener), () -> doSendEncryptedMailMessage(peerNodeAddress, pubKeyRing, message, sendMailMessageListener),
() -> sendMailMessageListener.onFault()); () -> sendMailMessageListener.onFault());
else else
doSendEncryptedMailMessage(peerAddress, pubKeyRing, message, sendMailMessageListener); doSendEncryptedMailMessage(peerNodeAddress, pubKeyRing, message, sendMailMessageListener);
} catch (AuthenticationException e) { } catch (AuthenticationException e) {
log.error(e.getMessage()); log.error(e.getMessage());
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
private void doSendEncryptedMailMessage(Address peerAddress, PubKeyRing pubKeyRing, MailMessage message, private void doSendEncryptedMailMessage(NodeAddress peerNodeAddress, PubKeyRing pubKeyRing, MailMessage message,
SendMailMessageListener sendMailMessageListener) { SendMailMessageListener sendMailMessageListener) {
Log.traceCall(); Log.traceCall();
checkArgument(optionalEncryptionService.isPresent(), "EncryptionService not set. Seems that is called on a seed node which must not happen."); checkArgument(optionalEncryptionService.isPresent(), "EncryptionService not set. Seems that is called on a seed node which must not happen.");
@ -404,8 +404,8 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
"Encrypt message:\nmessage={}" "Encrypt message:\nmessage={}"
+ "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n", message); + "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n", message);
SealedAndSignedMessage sealedAndSignedMessage = new SealedAndSignedMessage( SealedAndSignedMessage sealedAndSignedMessage = new SealedAndSignedMessage(
optionalEncryptionService.get().encryptAndSign(pubKeyRing, message), peerAddress.getAddressPrefixHash()); optionalEncryptionService.get().encryptAndSign(pubKeyRing, message), peerNodeAddress.getAddressPrefixHash());
SettableFuture<Connection> future = networkNode.sendMessage(peerAddress, sealedAndSignedMessage); SettableFuture<Connection> future = networkNode.sendMessage(peerNodeAddress, sealedAndSignedMessage);
Futures.addCallback(future, new FutureCallback<Connection>() { Futures.addCallback(future, new FutureCallback<Connection>() {
@Override @Override
public void onSuccess(@Nullable Connection connection) { public void onSuccess(@Nullable Connection connection) {
@ -443,14 +443,14 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
sealedAndSignedMessage.sealedAndSigned); sealedAndSignedMessage.sealedAndSigned);
if (decryptedMsgWithPubKey.message instanceof MailboxMessage) { if (decryptedMsgWithPubKey.message instanceof MailboxMessage) {
MailboxMessage mailboxMessage = (MailboxMessage) decryptedMsgWithPubKey.message; MailboxMessage mailboxMessage = (MailboxMessage) decryptedMsgWithPubKey.message;
Address senderAddress = mailboxMessage.getSenderAddress(); NodeAddress senderNodeAddress = mailboxMessage.getSenderNodeAddress();
checkNotNull(senderAddress, "senderAddress must not be null for mailbox messages"); checkNotNull(senderNodeAddress, "senderAddress must not be null for mailbox messages");
mailboxMap.put(decryptedMsgWithPubKey, mailboxData); mailboxMap.put(decryptedMsgWithPubKey, mailboxData);
log.trace("Decryption of SealedAndSignedMessage succeeded. senderAddress=" log.trace("Decryption of SealedAndSignedMessage succeeded. senderAddress="
+ senderAddress + " / my address=" + getAddress()); + senderNodeAddress + " / my address=" + getAddress());
decryptedMailboxListeners.stream().forEach( decryptedMailboxListeners.stream().forEach(
e -> e.onMailboxMessageAdded(decryptedMsgWithPubKey, senderAddress)); e -> e.onMailboxMessageAdded(decryptedMsgWithPubKey, senderNodeAddress));
} else { } else {
log.warn("tryDecryptMailboxData: Expected MailboxMessage but got other type. " + log.warn("tryDecryptMailboxData: Expected MailboxMessage but got other type. " +
"decryptedMsgWithPubKey.message=", decryptedMsgWithPubKey.message); "decryptedMsgWithPubKey.message=", decryptedMsgWithPubKey.message);
@ -466,22 +466,22 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
} }
} }
public void sendEncryptedMailboxMessage(Address peerAddress, PubKeyRing peersPubKeyRing, public void sendEncryptedMailboxMessage(NodeAddress peerNodeAddress, PubKeyRing peersPubKeyRing,
MailboxMessage message, SendMailboxMessageListener sendMailboxMessageListener) { MailboxMessage message, SendMailboxMessageListener sendMailboxMessageListener) {
Log.traceCall("message " + message); Log.traceCall("message " + message);
checkNotNull(peerAddress, "PeerAddress must not be null (sendEncryptedMailboxMessage)"); checkNotNull(peerNodeAddress, "PeerAddress must not be null (sendEncryptedMailboxMessage)");
checkArgument(optionalKeyRing.isPresent(), "keyRing not set. Seems that is called on a seed node which must not happen."); checkArgument(optionalKeyRing.isPresent(), "keyRing not set. Seems that is called on a seed node which must not happen.");
checkArgument(!optionalKeyRing.get().getPubKeyRing().equals(peersPubKeyRing), "We got own keyring instead of that from peer"); checkArgument(!optionalKeyRing.get().getPubKeyRing().equals(peersPubKeyRing), "We got own keyring instead of that from peer");
try { try {
checkAuthentication(); checkAuthentication();
if (authenticatedPeerAddresses.contains(peerAddress)) { if (authenticatedPeerNodeAddresses.contains(peerNodeAddress)) {
trySendEncryptedMailboxMessage(peerAddress, peersPubKeyRing, message, sendMailboxMessageListener); trySendEncryptedMailboxMessage(peerNodeAddress, peersPubKeyRing, message, sendMailboxMessageListener);
} else { } else {
peerManager.authenticateToDirectMessagePeer(peerAddress, peerManager.authenticateToDirectMessagePeer(peerNodeAddress,
() -> trySendEncryptedMailboxMessage(peerAddress, peersPubKeyRing, message, sendMailboxMessageListener), () -> trySendEncryptedMailboxMessage(peerNodeAddress, peersPubKeyRing, message, sendMailboxMessageListener),
() -> { () -> {
log.info("We cannot authenticate to peer. Peer might be offline. We will store message in mailbox."); log.info("We cannot authenticate to peer. Peer might be offline. We will store message in mailbox.");
trySendEncryptedMailboxMessage(peerAddress, peersPubKeyRing, message, sendMailboxMessageListener); trySendEncryptedMailboxMessage(peerNodeAddress, peersPubKeyRing, message, sendMailboxMessageListener);
}); });
} }
} catch (AuthenticationException e) { } catch (AuthenticationException e) {
@ -492,7 +492,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
} }
// send message and if it fails (peer offline) we store the data to the network // send message and if it fails (peer offline) we store the data to the network
private void trySendEncryptedMailboxMessage(Address peerAddress, PubKeyRing peersPubKeyRing, private void trySendEncryptedMailboxMessage(NodeAddress peerNodeAddress, PubKeyRing peersPubKeyRing,
MailboxMessage message, SendMailboxMessageListener sendMailboxMessageListener) { MailboxMessage message, SendMailboxMessageListener sendMailboxMessageListener) {
Log.traceCall(); Log.traceCall();
checkArgument(optionalKeyRing.isPresent(), "keyRing not set. Seems that is called on a seed node which must not happen."); checkArgument(optionalKeyRing.isPresent(), "keyRing not set. Seems that is called on a seed node which must not happen.");
@ -502,8 +502,8 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
"Encrypt message:\nmessage={}" "Encrypt message:\nmessage={}"
+ "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n", message); + "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n", message);
SealedAndSignedMessage sealedAndSignedMessage = new SealedAndSignedMessage( SealedAndSignedMessage sealedAndSignedMessage = new SealedAndSignedMessage(
optionalEncryptionService.get().encryptAndSign(peersPubKeyRing, message), peerAddress.getAddressPrefixHash()); optionalEncryptionService.get().encryptAndSign(peersPubKeyRing, message), peerNodeAddress.getAddressPrefixHash());
SettableFuture<Connection> future = networkNode.sendMessage(peerAddress, sealedAndSignedMessage); SettableFuture<Connection> future = networkNode.sendMessage(peerNodeAddress, sealedAndSignedMessage);
Futures.addCallback(future, new FutureCallback<Connection>() { Futures.addCallback(future, new FutureCallback<Connection>() {
@Override @Override
public void onSuccess(@Nullable Connection connection) { public void onSuccess(@Nullable Connection connection) {
@ -516,7 +516,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
log.trace("SendEncryptedMailboxMessage onFailure"); log.trace("SendEncryptedMailboxMessage onFailure");
log.debug(throwable.toString()); log.debug(throwable.toString());
log.info("We cannot send message to peer. Peer might be offline. We will store message in mailbox."); log.info("We cannot send message to peer. Peer might be offline. We will store message in mailbox.");
log.trace("create MailboxEntry with peerAddress " + peerAddress); log.trace("create MailboxEntry with peerAddress " + peerNodeAddress);
PublicKey receiverStoragePublicKey = peersPubKeyRing.getSignaturePubKey(); PublicKey receiverStoragePublicKey = peersPubKeyRing.getSignaturePubKey();
addMailboxData(new ExpirableMailboxPayload(sealedAndSignedMessage, addMailboxData(new ExpirableMailboxPayload(sealedAndSignedMessage,
optionalKeyRing.get().getSignatureKeyPair().getPublic(), optionalKeyRing.get().getSignatureKeyPair().getPublic(),
@ -541,7 +541,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
expirableMailboxPayload, expirableMailboxPayload,
optionalKeyRing.get().getSignatureKeyPair(), optionalKeyRing.get().getSignatureKeyPair(),
receiversPublicKey); receiversPublicKey);
dataStorage.add(protectedMailboxData, networkNode.getAddress()); dataStorage.add(protectedMailboxData, networkNode.getNodeAddress());
} catch (AuthenticationException e) { } catch (AuthenticationException e) {
log.error(e.getMessage()); log.error(e.getMessage());
//TODO check if boolean return type can avoid throwing an exception //TODO check if boolean return type can avoid throwing an exception
@ -568,7 +568,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
expirableMailboxPayload, expirableMailboxPayload,
optionalKeyRing.get().getSignatureKeyPair(), optionalKeyRing.get().getSignatureKeyPair(),
receiversPubKey); receiversPubKey);
dataStorage.removeMailboxData(protectedMailboxData, networkNode.getAddress()); dataStorage.removeMailboxData(protectedMailboxData, networkNode.getNodeAddress());
} catch (CryptoException e) { } catch (CryptoException e) {
log.error("Signing at getDataWithSignedSeqNr failed. That should never happen."); log.error("Signing at getDataWithSignedSeqNr failed. That should never happen.");
} }
@ -609,9 +609,9 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
checkAuthentication(); checkAuthentication();
ProtectedData protectedData = dataStorage.getDataWithSignedSeqNr(expirablePayload, optionalKeyRing.get().getSignatureKeyPair()); ProtectedData protectedData = dataStorage.getDataWithSignedSeqNr(expirablePayload, optionalKeyRing.get().getSignatureKeyPair());
if (rePublish) if (rePublish)
return dataStorage.rePublish(protectedData, networkNode.getAddress()); return dataStorage.rePublish(protectedData, networkNode.getNodeAddress());
else else
return dataStorage.add(protectedData, networkNode.getAddress()); return dataStorage.add(protectedData, networkNode.getNodeAddress());
} catch (AuthenticationException e) { } catch (AuthenticationException e) {
log.error(e.getMessage()); log.error(e.getMessage());
return false; return false;
@ -627,7 +627,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
try { try {
checkAuthentication(); checkAuthentication();
ProtectedData protectedData = dataStorage.getDataWithSignedSeqNr(expirablePayload, optionalKeyRing.get().getSignatureKeyPair()); ProtectedData protectedData = dataStorage.getDataWithSignedSeqNr(expirablePayload, optionalKeyRing.get().getSignatureKeyPair());
return dataStorage.remove(protectedData, networkNode.getAddress()); return dataStorage.remove(protectedData, networkNode.getNodeAddress());
} catch (AuthenticationException e) { } catch (AuthenticationException e) {
log.error(e.getMessage()); log.error(e.getMessage());
return false; return false;
@ -687,12 +687,12 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
return peerManager; return peerManager;
} }
public Address getAddress() { public NodeAddress getAddress() {
return networkNode.getAddress(); return networkNode.getNodeAddress();
} }
public Set<Address> getAuthenticatedPeerAddresses() { public Set<NodeAddress> getAuthenticatedPeerNodeAddresses() {
return authenticatedPeerAddresses; return authenticatedPeerNodeAddresses;
} }
@NotNull @NotNull
@ -710,8 +710,8 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
private boolean verifyAddressPrefixHash(SealedAndSignedMessage sealedAndSignedMessage) { private boolean verifyAddressPrefixHash(SealedAndSignedMessage sealedAndSignedMessage) {
if (myOnionAddress != null) { if (myOnionNodeAddress != null) {
byte[] blurredAddressHash = myOnionAddress.getAddressPrefixHash(); byte[] blurredAddressHash = myOnionNodeAddress.getAddressPrefixHash();
return blurredAddressHash != null && return blurredAddressHash != null &&
Arrays.equals(blurredAddressHash, sealedAndSignedMessage.addressPrefixHash); Arrays.equals(blurredAddressHash, sealedAndSignedMessage.addressPrefixHash);
} else { } else {
@ -722,7 +722,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
private void checkAuthentication() throws AuthenticationException { private void checkAuthentication() throws AuthenticationException {
Log.traceCall(); Log.traceCall();
if (authenticatedPeerAddresses.isEmpty()) if (authenticatedPeerNodeAddresses.isEmpty())
throw new AuthenticationException("You must be authenticated before adding data to the P2P network."); throw new AuthenticationException("You must be authenticated before adding data to the P2P network.");
} }
} }

View file

@ -17,15 +17,15 @@ public class SeedNodeP2PService extends P2PService {
private static final Logger log = LoggerFactory.getLogger(SeedNodeP2PService.class); private static final Logger log = LoggerFactory.getLogger(SeedNodeP2PService.class);
public SeedNodeP2PService(SeedNodesRepository seedNodesRepository, public SeedNodeP2PService(SeedNodesRepository seedNodesRepository,
Address mySeedNodeAddress, NodeAddress mySeedNodeNodeAddress,
File torDir, File torDir,
boolean useLocalhost, boolean useLocalhost,
int networkId, int networkId,
File storageDir) { File storageDir) {
super(seedNodesRepository, mySeedNodeAddress.port, torDir, useLocalhost, networkId, storageDir, null, null); super(seedNodesRepository, mySeedNodeNodeAddress.port, torDir, useLocalhost, networkId, storageDir, null, null);
// we remove ourselves from the list of seed nodes // we remove ourselves from the list of seed nodes
seedNodeAddresses.remove(mySeedNodeAddress); seedNodeNodeAddresses.remove(mySeedNodeNodeAddress);
} }
@Override @Override

View file

@ -1,8 +1,8 @@
package io.bitsquare.p2p.messaging; package io.bitsquare.p2p.messaging;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
public interface DecryptedMailListener { public interface DecryptedMailListener {
void onMailMessage(DecryptedMsgWithPubKey decryptedMsgWithPubKey, Address peerAddress); void onMailMessage(DecryptedMsgWithPubKey decryptedMsgWithPubKey, NodeAddress peerNodeAddress);
} }

View file

@ -1,8 +1,8 @@
package io.bitsquare.p2p.messaging; package io.bitsquare.p2p.messaging;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
public interface DecryptedMailboxListener { public interface DecryptedMailboxListener {
void onMailboxMessageAdded(DecryptedMsgWithPubKey decryptedMsgWithPubKey, Address senderAddress); void onMailboxMessageAdded(DecryptedMsgWithPubKey decryptedMsgWithPubKey, NodeAddress senderNodeAddress);
} }

View file

@ -18,8 +18,8 @@
package io.bitsquare.p2p.messaging; package io.bitsquare.p2p.messaging;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
public interface MailboxMessage extends MailMessage { public interface MailboxMessage extends MailMessage {
Address getSenderAddress(); NodeAddress getSenderNodeAddress();
} }

View file

@ -6,8 +6,8 @@ import io.bitsquare.app.Log;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.common.ByteArrayUtils; import io.bitsquare.common.ByteArrayUtils;
import io.bitsquare.common.UserThread; import io.bitsquare.common.UserThread;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message; import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.Utils; import io.bitsquare.p2p.Utils;
import io.bitsquare.p2p.network.messages.CloseConnectionMessage; import io.bitsquare.p2p.network.messages.CloseConnectionMessage;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -56,7 +56,7 @@ public class Connection implements MessageListener {
private ObjectOutputStream objectOutputStream; private ObjectOutputStream objectOutputStream;
// mutable data, set from other threads but not changed internally. // mutable data, set from other threads but not changed internally.
private Optional<Address> peerAddressOptional = Optional.empty(); private Optional<NodeAddress> peerAddressOptional = Optional.empty();
private volatile boolean isAuthenticated; private volatile boolean isAuthenticated;
private volatile boolean stopped; private volatile boolean stopped;
@ -170,10 +170,10 @@ public class Connection implements MessageListener {
sharedSpace.reportIllegalRequest(illegalRequest); sharedSpace.reportIllegalRequest(illegalRequest);
} }
public synchronized void setPeerAddress(Address peerAddress) { public synchronized void setPeerAddress(NodeAddress peerNodeAddress) {
Log.traceCall(); Log.traceCall();
checkNotNull(peerAddress, "peerAddress must not be null"); checkNotNull(peerNodeAddress, "peerAddress must not be null");
peerAddressOptional = Optional.of(peerAddress); peerAddressOptional = Optional.of(peerNodeAddress);
} }
@ -193,11 +193,11 @@ public class Connection implements MessageListener {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Nullable @Nullable
public synchronized Address getPeerAddress() { public synchronized NodeAddress getPeerAddress() {
return peerAddressOptional.isPresent() ? peerAddressOptional.get() : null; return peerAddressOptional.isPresent() ? peerAddressOptional.get() : null;
} }
public synchronized Optional<Address> getPeerAddressOptional() { public synchronized Optional<NodeAddress> getPeerAddressOptional() {
return peerAddressOptional; return peerAddressOptional;
} }

View file

@ -9,7 +9,7 @@ import com.msopentech.thali.java.toronionproxy.JavaOnionProxyManager;
import io.bitsquare.app.Log; import io.bitsquare.app.Log;
import io.bitsquare.common.UserThread; import io.bitsquare.common.UserThread;
import io.bitsquare.common.util.Utilities; import io.bitsquare.common.util.Utilities;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.nucleo.net.HiddenServiceDescriptor; import io.nucleo.net.HiddenServiceDescriptor;
import io.nucleo.net.TorNode; import io.nucleo.net.TorNode;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -29,7 +29,7 @@ public class LocalhostNetworkNode extends NetworkNode {
private static volatile int simulateTorDelayTorNode = 100; private static volatile int simulateTorDelayTorNode = 100;
private static volatile int simulateTorDelayHiddenService = 500; private static volatile int simulateTorDelayHiddenService = 500;
private Address address; private NodeAddress nodeAddress;
public static void setSimulateTorDelayTorNode(int simulateTorDelayTorNode) { public static void setSimulateTorDelayTorNode(int simulateTorDelayTorNode) {
LocalhostNetworkNode.simulateTorDelayTorNode = simulateTorDelayTorNode; LocalhostNetworkNode.simulateTorDelayTorNode = simulateTorDelayTorNode;
@ -72,7 +72,7 @@ public class LocalhostNetworkNode extends NetworkNode {
log.error("Exception at startServer: " + e.getMessage()); log.error("Exception at startServer: " + e.getMessage());
} }
address = new Address("localhost", servicePort); nodeAddress = new NodeAddress("localhost", servicePort);
setupListeners.stream().forEach(e -> e.onHiddenServicePublished()); setupListeners.stream().forEach(e -> e.onHiddenServicePublished());
}); });
@ -82,15 +82,15 @@ public class LocalhostNetworkNode extends NetworkNode {
@Override @Override
@Nullable @Nullable
public Address getAddress() { public NodeAddress getNodeAddress() {
return address; return nodeAddress;
} }
// Called from NetworkNode thread // Called from NetworkNode thread
@Override @Override
protected Socket createSocket(Address peerAddress) throws IOException { protected Socket createSocket(NodeAddress peerNodeAddress) throws IOException {
Log.traceCall(); Log.traceCall();
return new Socket(peerAddress.hostName, peerAddress.port); return new Socket(peerNodeAddress.hostName, peerNodeAddress.port);
} }

View file

@ -4,8 +4,8 @@ import com.google.common.util.concurrent.*;
import io.bitsquare.app.Log; import io.bitsquare.app.Log;
import io.bitsquare.common.UserThread; import io.bitsquare.common.UserThread;
import io.bitsquare.common.util.Utilities; import io.bitsquare.common.util.Utilities;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message; import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -63,11 +63,11 @@ public abstract class NetworkNode implements MessageListener, ConnectionListener
abstract public void start(@Nullable SetupListener setupListener); abstract public void start(@Nullable SetupListener setupListener);
public SettableFuture<Connection> sendMessage(@NotNull Address peerAddress, Message message) { public SettableFuture<Connection> sendMessage(@NotNull NodeAddress peerNodeAddress, Message message) {
Log.traceCall("peerAddress: " + peerAddress + " / message: " + message); Log.traceCall("peerAddress: " + peerNodeAddress + " / message: " + message);
checkNotNull(peerAddress, "peerAddress must not be null"); checkNotNull(peerNodeAddress, "peerAddress must not be null");
Optional<Connection> outboundConnectionOptional = lookupOutboundConnection(peerAddress); Optional<Connection> outboundConnectionOptional = lookupOutboundConnection(peerNodeAddress);
Connection connection = outboundConnectionOptional.isPresent() ? outboundConnectionOptional.get() : null; Connection connection = outboundConnectionOptional.isPresent() ? outboundConnectionOptional.get() : null;
if (connection != null) if (connection != null)
log.trace("We have found a connection in outBoundConnections. Connection.uid=" + connection.getUid()); log.trace("We have found a connection in outBoundConnections. Connection.uid=" + connection.getUid());
@ -79,7 +79,7 @@ public abstract class NetworkNode implements MessageListener, ConnectionListener
} }
if (connection == null) { if (connection == null) {
Optional<Connection> inboundConnectionOptional = lookupInboundConnection(peerAddress); Optional<Connection> inboundConnectionOptional = lookupInboundConnection(peerNodeAddress);
if (inboundConnectionOptional.isPresent()) connection = inboundConnectionOptional.get(); if (inboundConnectionOptional.isPresent()) connection = inboundConnectionOptional.get();
if (connection != null) if (connection != null)
log.trace("We have found a connection in inBoundConnections. Connection.uid=" + connection.getUid()); log.trace("We have found a connection in inBoundConnections. Connection.uid=" + connection.getUid());
@ -89,27 +89,27 @@ public abstract class NetworkNode implements MessageListener, ConnectionListener
return sendMessage(connection, message); return sendMessage(connection, message);
} else { } else {
log.trace("We have not found any connection for peerAddress {}. " + log.trace("We have not found any connection for peerAddress {}. " +
"We will create a new outbound connection.", peerAddress); "We will create a new outbound connection.", peerNodeAddress);
final SettableFuture<Connection> resultFuture = SettableFuture.create(); final SettableFuture<Connection> resultFuture = SettableFuture.create();
final boolean[] timeoutOccurred = new boolean[1]; final boolean[] timeoutOccurred = new boolean[1];
timeoutOccurred[0] = false; timeoutOccurred[0] = false;
ListenableFuture<Connection> future = executorService.submit(() -> { ListenableFuture<Connection> future = executorService.submit(() -> {
Thread.currentThread().setName("NetworkNode:SendMessage-to-" + peerAddress); Thread.currentThread().setName("NetworkNode:SendMessage-to-" + peerNodeAddress);
try { try {
// can take a while when using tor // can take a while when using tor
Socket socket = createSocket(peerAddress); Socket socket = createSocket(peerNodeAddress);
if (timeoutOccurred[0]) if (timeoutOccurred[0])
throw new TimeoutException("Timeout occurred when tried to create Socket to peer: " + peerAddress); throw new TimeoutException("Timeout occurred when tried to create Socket to peer: " + peerNodeAddress);
Connection newConnection = new Connection(socket, NetworkNode.this, NetworkNode.this); Connection newConnection = new Connection(socket, NetworkNode.this, NetworkNode.this);
newConnection.setPeerAddress(peerAddress); newConnection.setPeerAddress(peerNodeAddress);
outBoundConnections.add(newConnection); outBoundConnections.add(newConnection);
log.info("\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" + log.info("\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" +
"NetworkNode created new outbound connection:" "NetworkNode created new outbound connection:"
+ "\npeerAddress=" + peerAddress + "\npeerAddress=" + peerNodeAddress
+ "\nconnection.uid=" + newConnection.getUid() + "\nconnection.uid=" + newConnection.getUid()
+ "\nmessage=" + message + "\nmessage=" + message
+ "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"); + "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n");
@ -333,20 +333,20 @@ public abstract class NetworkNode implements MessageListener, ConnectionListener
executorService.submit(server); executorService.submit(server);
} }
private Optional<Connection> lookupOutboundConnection(Address peerAddress) { private Optional<Connection> lookupOutboundConnection(NodeAddress peerNodeAddress) {
// Log.traceCall("search for " + peerAddress.toString() + " / outBoundConnections " + outBoundConnections); // Log.traceCall("search for " + peerAddress.toString() + " / outBoundConnections " + outBoundConnections);
return outBoundConnections.stream() return outBoundConnections.stream()
.filter(e -> e.getPeerAddressOptional().isPresent() && peerAddress.equals(e.getPeerAddressOptional().get())).findAny(); .filter(e -> e.getPeerAddressOptional().isPresent() && peerNodeAddress.equals(e.getPeerAddressOptional().get())).findAny();
} }
private Optional<Connection> lookupInboundConnection(Address peerAddress) { private Optional<Connection> lookupInboundConnection(NodeAddress peerNodeAddress) {
// Log.traceCall("search for " + peerAddress.toString() + " / inBoundConnections " + inBoundConnections); // Log.traceCall("search for " + peerAddress.toString() + " / inBoundConnections " + inBoundConnections);
return inBoundConnections.stream() return inBoundConnections.stream()
.filter(e -> e.getPeerAddressOptional().isPresent() && peerAddress.equals(e.getPeerAddressOptional().get())).findAny(); .filter(e -> e.getPeerAddressOptional().isPresent() && peerNodeAddress.equals(e.getPeerAddressOptional().get())).findAny();
} }
abstract protected Socket createSocket(Address peerAddress) throws IOException; abstract protected Socket createSocket(NodeAddress peerNodeAddress) throws IOException;
@Nullable @Nullable
abstract public Address getAddress(); abstract public NodeAddress getNodeAddress();
} }

View file

@ -9,7 +9,7 @@ import com.msopentech.thali.java.toronionproxy.JavaOnionProxyManager;
import io.bitsquare.app.Log; import io.bitsquare.app.Log;
import io.bitsquare.common.UserThread; import io.bitsquare.common.UserThread;
import io.bitsquare.common.util.Utilities; import io.bitsquare.common.util.Utilities;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.Utils; import io.bitsquare.p2p.Utils;
import io.nucleo.net.HiddenServiceDescriptor; import io.nucleo.net.HiddenServiceDescriptor;
import io.nucleo.net.JavaTorNode; import io.nucleo.net.JavaTorNode;
@ -91,19 +91,19 @@ public class TorNetworkNode extends NetworkNode {
@Override @Override
@Nullable @Nullable
public Address getAddress() { public NodeAddress getNodeAddress() {
if (hiddenServiceDescriptor != null) if (hiddenServiceDescriptor != null)
return new Address(hiddenServiceDescriptor.getFullAddress()); return new NodeAddress(hiddenServiceDescriptor.getFullAddress());
else else
return null; return null;
} }
@Override @Override
protected Socket createSocket(Address peerAddress) throws IOException { protected Socket createSocket(NodeAddress peerNodeAddress) throws IOException {
Log.traceCall(); Log.traceCall();
checkArgument(peerAddress.hostName.endsWith(".onion"), "PeerAddress is not an onion address"); checkArgument(peerNodeAddress.hostName.endsWith(".onion"), "PeerAddress is not an onion address");
return torNetworkNode.connectToHiddenService(peerAddress.hostName, peerAddress.port); return torNetworkNode.connectToHiddenService(peerNodeAddress.hostName, peerNodeAddress.port);
} }
//TODO simplify //TODO simplify

View file

@ -1,15 +1,15 @@
package io.bitsquare.p2p.network.messages; package io.bitsquare.p2p.network.messages;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message; import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
public final class CloseConnectionMessage implements Message { public final class CloseConnectionMessage implements Message {
// That object is sent over the wire, so we need to take care of version compatibility. // That object is sent over the wire, so we need to take care of version compatibility.
private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION; private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION;
private final int networkId = Version.getNetworkId(); private final int networkId = Version.getNetworkId();
public Address peerAddress; public NodeAddress peerNodeAddress;
public CloseConnectionMessage() { public CloseConnectionMessage() {
} }

View file

@ -5,8 +5,8 @@ import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.SettableFuture; import com.google.common.util.concurrent.SettableFuture;
import io.bitsquare.app.Log; import io.bitsquare.app.Log;
import io.bitsquare.common.UserThread; import io.bitsquare.common.UserThread;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message; import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.network.Connection; import io.bitsquare.p2p.network.Connection;
import io.bitsquare.p2p.network.ConnectionPriority; import io.bitsquare.p2p.network.ConnectionPriority;
import io.bitsquare.p2p.network.MessageListener; import io.bitsquare.p2p.network.MessageListener;
@ -33,8 +33,8 @@ public class AuthenticationHandshake implements MessageListener {
private static final Logger log = LoggerFactory.getLogger(AuthenticationHandshake.class); private static final Logger log = LoggerFactory.getLogger(AuthenticationHandshake.class);
private final NetworkNode networkNode; private final NetworkNode networkNode;
private final Address myAddress; private final NodeAddress myNodeAddress;
private final Address peerAddress; private final NodeAddress peerNodeAddress;
private final Supplier<Set<ReportedPeer>> authenticatedAndReportedPeersSupplier; private final Supplier<Set<ReportedPeer>> authenticatedAndReportedPeersSupplier;
private final BiConsumer<HashSet<ReportedPeer>, Connection> addReportedPeersConsumer; private final BiConsumer<HashSet<ReportedPeer>, Connection> addReportedPeersConsumer;
@ -50,16 +50,16 @@ public class AuthenticationHandshake implements MessageListener {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public AuthenticationHandshake(NetworkNode networkNode, public AuthenticationHandshake(NetworkNode networkNode,
Address myAddress, NodeAddress myNodeAddress,
Address peerAddress, NodeAddress peerNodeAddress,
Supplier<Set<ReportedPeer>> authenticatedAndReportedPeersSupplier, Supplier<Set<ReportedPeer>> authenticatedAndReportedPeersSupplier,
BiConsumer<HashSet<ReportedPeer>, Connection> addReportedPeersConsumer) { BiConsumer<HashSet<ReportedPeer>, Connection> addReportedPeersConsumer) {
Log.traceCall("peerAddress " + peerAddress); Log.traceCall("peerAddress " + peerNodeAddress);
this.authenticatedAndReportedPeersSupplier = authenticatedAndReportedPeersSupplier; this.authenticatedAndReportedPeersSupplier = authenticatedAndReportedPeersSupplier;
this.addReportedPeersConsumer = addReportedPeersConsumer; this.addReportedPeersConsumer = addReportedPeersConsumer;
this.networkNode = networkNode; this.networkNode = networkNode;
this.myAddress = myAddress; this.myNodeAddress = myNodeAddress;
this.peerAddress = peerAddress; this.peerNodeAddress = peerNodeAddress;
startAuthTs = System.currentTimeMillis(); startAuthTs = System.currentTimeMillis();
networkNode.addMessageListener(this); networkNode.addMessageListener(this);
@ -79,7 +79,7 @@ public class AuthenticationHandshake implements MessageListener {
if (!stopped) { if (!stopped) {
if (message instanceof AuthenticationMessage) { if (message instanceof AuthenticationMessage) {
// We are listening on all connections, so we need to filter out only our peer // We are listening on all connections, so we need to filter out only our peer
if (((AuthenticationMessage) message).senderAddress.equals(peerAddress)) { if (((AuthenticationMessage) message).senderNodeAddress.equals(peerNodeAddress)) {
Log.traceCall(message.toString()); Log.traceCall(message.toString());
if (timeoutTimer != null) if (timeoutTimer != null)
@ -90,23 +90,23 @@ public class AuthenticationHandshake implements MessageListener {
AuthenticationChallenge authenticationChallenge = (AuthenticationChallenge) message; AuthenticationChallenge authenticationChallenge = (AuthenticationChallenge) message;
// We need to set the address to the connection, otherwise we will not find the connection when sending // We need to set the address to the connection, otherwise we will not find the connection when sending
// the next message and we would create a new outbound connection instead using the inbound. // the next message and we would create a new outbound connection instead using the inbound.
connection.setPeerAddress(authenticationChallenge.senderAddress); connection.setPeerAddress(authenticationChallenge.senderNodeAddress);
// We use the active connectionType if we started the authentication request to another peer // We use the active connectionType if we started the authentication request to another peer
connection.setConnectionPriority(ConnectionPriority.ACTIVE); connection.setConnectionPriority(ConnectionPriority.ACTIVE);
log.trace("Received authenticationChallenge from " + peerAddress); log.trace("Received authenticationChallenge from " + peerNodeAddress);
boolean verified = nonce != 0 && nonce == authenticationChallenge.requesterNonce; boolean verified = nonce != 0 && nonce == authenticationChallenge.requesterNonce;
if (verified) { if (verified) {
AuthenticationFinalResponse authenticationFinalResponse = new AuthenticationFinalResponse(myAddress, AuthenticationFinalResponse authenticationFinalResponse = new AuthenticationFinalResponse(myNodeAddress,
authenticationChallenge.responderNonce, authenticationChallenge.responderNonce,
new HashSet<>(authenticatedAndReportedPeersSupplier.get())); new HashSet<>(authenticatedAndReportedPeersSupplier.get()));
SettableFuture<Connection> future = networkNode.sendMessage(peerAddress, authenticationFinalResponse); SettableFuture<Connection> future = networkNode.sendMessage(peerNodeAddress, authenticationFinalResponse);
log.trace("Sent AuthenticationFinalResponse {} to {}", authenticationFinalResponse, peerAddress); log.trace("Sent AuthenticationFinalResponse {} to {}", authenticationFinalResponse, peerNodeAddress);
Futures.addCallback(future, new FutureCallback<Connection>() { Futures.addCallback(future, new FutureCallback<Connection>() {
@Override @Override
public void onSuccess(Connection connection) { public void onSuccess(Connection connection) {
log.trace("Successfully sent AuthenticationFinalResponse to {}", peerAddress); log.trace("Successfully sent AuthenticationFinalResponse to {}", peerNodeAddress);
log.info("AuthenticationComplete: Peer with address " + peerAddress log.info("AuthenticationComplete: Peer with address " + peerNodeAddress
+ " authenticated (" + connection.getUid() + "). Took " + " authenticated (" + connection.getUid() + "). Took "
+ (System.currentTimeMillis() - startAuthTs) + " ms."); + (System.currentTimeMillis() - startAuthTs) + " ms.");
completed(connection); completed(connection);
@ -128,17 +128,17 @@ public class AuthenticationHandshake implements MessageListener {
// the current authentication turn gets terminated as well // the current authentication turn gets terminated as well
log.warn("Verification of nonce failed. Maybe we got an old authenticationChallenge " + log.warn("Verification of nonce failed. Maybe we got an old authenticationChallenge " +
"from a timed out request" + "from a timed out request" +
"\nnonce={} / peerAddress={} / authenticationChallenge={}", nonce, peerAddress, authenticationChallenge); "\nnonce={} / peerAddress={} / authenticationChallenge={}", nonce, peerNodeAddress, authenticationChallenge);
//failed(new AuthenticationException("Verification of nonce failed. AuthenticationChallenge=" + authenticationChallenge + " / nonceMap=" + nonce)); //failed(new AuthenticationException("Verification of nonce failed. AuthenticationChallenge=" + authenticationChallenge + " / nonceMap=" + nonce));
} }
} else if (message instanceof AuthenticationFinalResponse) { } else if (message instanceof AuthenticationFinalResponse) {
// Responding peer // Responding peer
AuthenticationFinalResponse authenticationFinalResponse = (AuthenticationFinalResponse) message; AuthenticationFinalResponse authenticationFinalResponse = (AuthenticationFinalResponse) message;
log.trace("Received AuthenticationFinalResponse from " + peerAddress + " at " + myAddress); log.trace("Received AuthenticationFinalResponse from " + peerNodeAddress + " at " + myNodeAddress);
boolean verified = nonce != 0 && nonce == authenticationFinalResponse.responderNonce; boolean verified = nonce != 0 && nonce == authenticationFinalResponse.responderNonce;
if (verified) { if (verified) {
addReportedPeersConsumer.accept(authenticationFinalResponse.reportedPeers, connection); addReportedPeersConsumer.accept(authenticationFinalResponse.reportedPeers, connection);
log.info("AuthenticationComplete: Peer with address " + peerAddress log.info("AuthenticationComplete: Peer with address " + peerNodeAddress
+ " authenticated (" + connection.getUid() + "). Took " + " authenticated (" + connection.getUid() + "). Took "
+ (System.currentTimeMillis() - startAuthTs) + " ms."); + (System.currentTimeMillis() - startAuthTs) + " ms.");
completed(connection); completed(connection);
@ -149,14 +149,14 @@ public class AuthenticationHandshake implements MessageListener {
// the current authentication turn gets terminated as well // the current authentication turn gets terminated as well
log.warn("Verification of nonce failed. Maybe we got an old authenticationFinalResponse " + log.warn("Verification of nonce failed. Maybe we got an old authenticationFinalResponse " +
"from a timed out request" + "from a timed out request" +
"\nnonce={} / peerAddress={} / authenticationChallenge={}", nonce, peerAddress, authenticationFinalResponse); "\nnonce={} / peerAddress={} / authenticationChallenge={}", nonce, peerNodeAddress, authenticationFinalResponse);
log.warn("Verification of nonce failed. nonce={} / peerAddress={} / authenticationFinalResponse={}", nonce, peerAddress, authenticationFinalResponse); log.warn("Verification of nonce failed. nonce={} / peerAddress={} / authenticationFinalResponse={}", nonce, peerNodeAddress, authenticationFinalResponse);
//failed(new AuthenticationException("Verification of nonce failed. getPeersMessage=" + authenticationFinalResponse + " / nonce=" + nonce)); //failed(new AuthenticationException("Verification of nonce failed. getPeersMessage=" + authenticationFinalResponse + " / nonce=" + nonce));
} }
} else if (message instanceof AuthenticationRejection) { } else if (message instanceof AuthenticationRejection) {
// Any peer // Any peer
failed(new AuthenticationException("Authentication to peer " failed(new AuthenticationException("Authentication to peer "
+ ((AuthenticationRejection) message).senderAddress + ((AuthenticationRejection) message).senderNodeAddress
+ " rejected because of a race conditions.")); + " rejected because of a race conditions."));
} }
} }
@ -164,7 +164,7 @@ public class AuthenticationHandshake implements MessageListener {
} else { } else {
// TODO leave that for debugging for now, but remove it once the network is tested sufficiently // TODO leave that for debugging for now, but remove it once the network is tested sufficiently
log.info("AuthenticationHandshake (peerAddress={}) already shut down but still got onMessage called. " + log.info("AuthenticationHandshake (peerAddress={}) already shut down but still got onMessage called. " +
"That can happen because of Thread mapping.", peerAddress); "That can happen because of Thread mapping.", peerNodeAddress);
log.debug("message={}", message); log.debug("message={}", message);
log.debug("connection={}", connection); log.debug("connection={}", connection);
return; return;
@ -177,21 +177,21 @@ public class AuthenticationHandshake implements MessageListener {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public SettableFuture<Connection> requestAuthentication() { public SettableFuture<Connection> requestAuthentication() {
Log.traceCall("peerAddress " + peerAddress); Log.traceCall("peerAddress " + peerNodeAddress);
// Requesting peer // Requesting peer
if (stopped) { if (stopped) {
// TODO leave that for debugging for now, but remove it once the network is tested sufficiently // TODO leave that for debugging for now, but remove it once the network is tested sufficiently
log.warn("AuthenticationHandshake (peerAddress={}) already shut down but still got requestAuthentication called. That must not happen.", peerAddress); log.warn("AuthenticationHandshake (peerAddress={}) already shut down but still got requestAuthentication called. That must not happen.", peerNodeAddress);
} }
resultFutureOptional = Optional.of(SettableFuture.create()); resultFutureOptional = Optional.of(SettableFuture.create());
AuthenticationRequest authenticationRequest = new AuthenticationRequest(myAddress, getAndSetNonce()); AuthenticationRequest authenticationRequest = new AuthenticationRequest(myNodeAddress, getAndSetNonce());
SettableFuture<Connection> future = networkNode.sendMessage(peerAddress, authenticationRequest); SettableFuture<Connection> future = networkNode.sendMessage(peerNodeAddress, authenticationRequest);
Futures.addCallback(future, new FutureCallback<Connection>() { Futures.addCallback(future, new FutureCallback<Connection>() {
@Override @Override
public void onSuccess(Connection connection) { public void onSuccess(Connection connection) {
log.trace("send AuthenticationRequest to " + peerAddress + " succeeded."); log.trace("send AuthenticationRequest to " + peerNodeAddress + " succeeded.");
// We protect that connection from getting closed by maintenance cleanup... // We protect that connection from getting closed by maintenance cleanup...
connection.setConnectionPriority(ConnectionPriority.AUTH_REQUEST); connection.setConnectionPriority(ConnectionPriority.AUTH_REQUEST);
@ -199,7 +199,7 @@ public class AuthenticationHandshake implements MessageListener {
@Override @Override
public void onFailure(@NotNull Throwable throwable) { public void onFailure(@NotNull Throwable throwable) {
log.info("Send AuthenticationRequest to " + peerAddress + " failed. " + log.info("Send AuthenticationRequest to " + peerNodeAddress + " failed. " +
"It might be that the peer went offline.\nException:" + throwable.getMessage()); "It might be that the peer went offline.\nException:" + throwable.getMessage());
failed(throwable); failed(throwable);
} }
@ -209,7 +209,7 @@ public class AuthenticationHandshake implements MessageListener {
timeoutTimer.cancel(); timeoutTimer.cancel();
timeoutTimer = UserThread.runAfter(() -> failed(new AuthenticationException("Authentication to peer " timeoutTimer = UserThread.runAfter(() -> failed(new AuthenticationException("Authentication to peer "
+ peerAddress + peerNodeAddress
+ " failed because of a timeout. " + + " failed because of a timeout. " +
"We did not get an AuthenticationChallenge message responded after 30 sec.")), 30); "We did not get an AuthenticationChallenge message responded after 30 sec.")), 30);
@ -223,12 +223,12 @@ public class AuthenticationHandshake implements MessageListener {
public SettableFuture<Connection> respondToAuthenticationRequest(AuthenticationRequest authenticationRequest, public SettableFuture<Connection> respondToAuthenticationRequest(AuthenticationRequest authenticationRequest,
Connection connection) { Connection connection) {
Log.traceCall("peerAddress " + peerAddress); Log.traceCall("peerAddress " + peerNodeAddress);
// Responding peer // Responding peer
if (stopped) { if (stopped) {
// TODO leave that for debugging for now, but remove it once the network is tested sufficiently // TODO leave that for debugging for now, but remove it once the network is tested sufficiently
log.warn("AuthenticationHandshake (peerAddress={}) already shut down but still got respondToAuthenticationRequest called. That must not happen.", peerAddress); log.warn("AuthenticationHandshake (peerAddress={}) already shut down but still got respondToAuthenticationRequest called. That must not happen.", peerNodeAddress);
log.warn("authenticationRequest={}", authenticationRequest); log.warn("authenticationRequest={}", authenticationRequest);
log.warn("connection={}", connection); log.warn("connection={}", connection);
} }
@ -236,7 +236,7 @@ public class AuthenticationHandshake implements MessageListener {
resultFutureOptional = Optional.of(SettableFuture.create()); resultFutureOptional = Optional.of(SettableFuture.create());
log.info("We shut down inbound connection from peer {} to establish a new " + log.info("We shut down inbound connection from peer {} to establish a new " +
"connection with his reported address to verify if his address is correct.", peerAddress); "connection with his reported address to verify if his address is correct.", peerNodeAddress);
connection.shutDown(() -> { connection.shutDown(() -> {
if (shutDownTimer != null) if (shutDownTimer != null)
@ -246,14 +246,14 @@ public class AuthenticationHandshake implements MessageListener {
if (!stopped) { if (!stopped) {
// we delay a bit as listeners for connection.onDisconnect are on other threads and might lead to // we delay a bit as listeners for connection.onDisconnect are on other threads and might lead to
// inconsistent state // inconsistent state
log.trace("respondToAuthenticationRequest: connection.shutDown complete. peerAddress=" + peerAddress + " / myAddress=" + myAddress); log.trace("respondToAuthenticationRequest: connection.shutDown complete. peerAddress=" + peerNodeAddress + " / myAddress=" + myNodeAddress);
// we send additionally the reported and authenticated peers to save one message in the protocol. // we send additionally the reported and authenticated peers to save one message in the protocol.
AuthenticationChallenge authenticationChallenge = new AuthenticationChallenge(myAddress, AuthenticationChallenge authenticationChallenge = new AuthenticationChallenge(myNodeAddress,
authenticationRequest.requesterNonce, authenticationRequest.requesterNonce,
getAndSetNonce(), getAndSetNonce(),
new HashSet<>(authenticatedAndReportedPeersSupplier.get())); new HashSet<>(authenticatedAndReportedPeersSupplier.get()));
SettableFuture<Connection> future = networkNode.sendMessage(peerAddress, authenticationChallenge); SettableFuture<Connection> future = networkNode.sendMessage(peerNodeAddress, authenticationChallenge);
Futures.addCallback(future, new FutureCallback<Connection>() { Futures.addCallback(future, new FutureCallback<Connection>() {
@Override @Override
public void onSuccess(Connection connection) { public void onSuccess(Connection connection) {
@ -266,7 +266,7 @@ public class AuthenticationHandshake implements MessageListener {
@Override @Override
public void onFailure(@NotNull Throwable throwable) { public void onFailure(@NotNull Throwable throwable) {
log.warn("Failure at sending AuthenticationChallenge to {}. It might be that the peer went offline. Exception={}", peerAddress, throwable.getMessage()); log.warn("Failure at sending AuthenticationChallenge to {}. It might be that the peer went offline. Exception={}", peerNodeAddress, throwable.getMessage());
failed(throwable); failed(throwable);
} }
}); });
@ -275,14 +275,14 @@ public class AuthenticationHandshake implements MessageListener {
timeoutTimer.cancel(); timeoutTimer.cancel();
timeoutTimer = UserThread.runAfter(() -> failed(new AuthenticationException("Authentication of peer " timeoutTimer = UserThread.runAfter(() -> failed(new AuthenticationException("Authentication of peer "
+ peerAddress + peerNodeAddress
+ " failed because of a timeout. " + + " failed because of a timeout. " +
"We did not get an AuthenticationFinalResponse message responded after 30 sec.\n" + "We did not get an AuthenticationFinalResponse message responded after 30 sec.\n" +
"")), 30, TimeUnit.SECONDS); "")), 30, TimeUnit.SECONDS);
} else { } else {
log.info("AuthenticationHandshake (peerAddress={}) already shut down before we could sent " + log.info("AuthenticationHandshake (peerAddress={}) already shut down before we could sent " +
"AuthenticationChallenge. That might happen in rare cases.", peerAddress); "AuthenticationChallenge. That might happen in rare cases.", peerNodeAddress);
} }
}, 2000, TimeUnit.MILLISECONDS); // Don't set the delay too short as the CloseConnectionMessage might arrive too late at the peer }, 2000, TimeUnit.MILLISECONDS); // Don't set the delay too short as the CloseConnectionMessage might arrive too late at the peer
}); });
@ -294,10 +294,10 @@ public class AuthenticationHandshake implements MessageListener {
// Cancel // Cancel
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public void cancel(Address peerAddress) { public void cancel(NodeAddress peerNodeAddress) {
Log.traceCall(); Log.traceCall();
failed(new AuthenticationException("Authentication to peer " failed(new AuthenticationException("Authentication to peer "
+ peerAddress + peerNodeAddress
+ " canceled because of a race conditions.")); + " canceled because of a race conditions."));
} }
@ -343,7 +343,7 @@ public class AuthenticationHandshake implements MessageListener {
} }
private void shutDown() { private void shutDown() {
Log.traceCall("peerAddress = " + peerAddress); Log.traceCall("peerAddress = " + peerNodeAddress);
stopped = true; stopped = true;
if (timeoutTimer != null) if (timeoutTimer != null)

View file

@ -1,8 +1,8 @@
package io.bitsquare.p2p.peers; package io.bitsquare.p2p.peers;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.network.Connection; import io.bitsquare.p2p.network.Connection;
public interface AuthenticationListener { public interface AuthenticationListener {
void onPeerAuthenticated(Address peerAddress, Connection connection); void onPeerAuthenticated(NodeAddress peerNodeAddress, Connection connection);
} }

View file

@ -1,6 +1,6 @@
package io.bitsquare.p2p.peers; package io.bitsquare.p2p.peers;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.network.Connection; import io.bitsquare.p2p.network.Connection;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -11,19 +11,19 @@ public class Peer {
private static final Logger log = LoggerFactory.getLogger(Peer.class); private static final Logger log = LoggerFactory.getLogger(Peer.class);
public final Connection connection; public final Connection connection;
public final Address address; public final NodeAddress nodeAddress;
public final long pingNonce; public final long pingNonce;
public Peer(Connection connection, Address address) { public Peer(Connection connection, NodeAddress nodeAddress) {
this.connection = connection; this.connection = connection;
this.address = address; this.nodeAddress = nodeAddress;
pingNonce = new Random().nextLong(); pingNonce = new Random().nextLong();
} }
@Override @Override
public int hashCode() { public int hashCode() {
return address != null ? address.hashCode() : 0; return nodeAddress != null ? nodeAddress.hashCode() : 0;
} }
@Override @Override
@ -33,13 +33,13 @@ public class Peer {
Peer peer = (Peer) o; Peer peer = (Peer) o;
return !(address != null ? !address.equals(peer.address) : peer.address != null); return !(nodeAddress != null ? !nodeAddress.equals(peer.nodeAddress) : peer.nodeAddress != null);
} }
@Override @Override
public String toString() { public String toString() {
return "Peer{" + return "Peer{" +
"address=" + address + "address=" + nodeAddress +
", pingNonce=" + pingNonce + ", pingNonce=" + pingNonce +
", connection=" + connection + ", connection=" + connection +
'}'; '}';

View file

@ -7,8 +7,8 @@ import com.google.common.util.concurrent.SettableFuture;
import io.bitsquare.app.Log; import io.bitsquare.app.Log;
import io.bitsquare.common.UserThread; import io.bitsquare.common.UserThread;
import io.bitsquare.common.util.Utilities; import io.bitsquare.common.util.Utilities;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message; import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.network.Connection; import io.bitsquare.p2p.network.Connection;
import io.bitsquare.p2p.network.MessageListener; import io.bitsquare.p2p.network.MessageListener;
import io.bitsquare.p2p.network.NetworkNode; import io.bitsquare.p2p.network.NetworkNode;
@ -34,8 +34,8 @@ public class PeerExchangeManager implements MessageListener {
private final NetworkNode networkNode; private final NetworkNode networkNode;
private final Supplier<Set<ReportedPeer>> authenticatedAndReportedPeersSupplier; private final Supplier<Set<ReportedPeer>> authenticatedAndReportedPeersSupplier;
private final Supplier<Map<Address, Peer>> authenticatedPeersSupplier; private final Supplier<Map<NodeAddress, Peer>> authenticatedPeersSupplier;
private final Consumer<Address> removePeerConsumer; private final Consumer<NodeAddress> removePeerConsumer;
private final BiConsumer<HashSet<ReportedPeer>, Connection> addReportedPeersConsumer; private final BiConsumer<HashSet<ReportedPeer>, Connection> addReportedPeersConsumer;
private final ScheduledThreadPoolExecutor executor; private final ScheduledThreadPoolExecutor executor;
@ -46,8 +46,8 @@ public class PeerExchangeManager implements MessageListener {
public PeerExchangeManager(NetworkNode networkNode, public PeerExchangeManager(NetworkNode networkNode,
Supplier<Set<ReportedPeer>> authenticatedAndReportedPeersSupplier, Supplier<Set<ReportedPeer>> authenticatedAndReportedPeersSupplier,
Supplier<Map<Address, Peer>> authenticatedPeersSupplier, Supplier<Map<NodeAddress, Peer>> authenticatedPeersSupplier,
Consumer<Address> removePeerConsumer, Consumer<NodeAddress> removePeerConsumer,
BiConsumer<HashSet<ReportedPeer>, Connection> addReportedPeersConsumer) { BiConsumer<HashSet<ReportedPeer>, Connection> addReportedPeersConsumer) {
this.networkNode = networkNode; this.networkNode = networkNode;
this.authenticatedAndReportedPeersSupplier = authenticatedAndReportedPeersSupplier; this.authenticatedAndReportedPeersSupplier = authenticatedAndReportedPeersSupplier;
@ -94,7 +94,7 @@ public class PeerExchangeManager implements MessageListener {
@Override @Override
public void onFailure(@NotNull Throwable throwable) { public void onFailure(@NotNull Throwable throwable) {
log.info("GetPeersResponse sending failed " + throwable.getMessage()); log.info("GetPeersResponse sending failed " + throwable.getMessage());
removePeerConsumer.accept(getPeersRequestMessage.senderAddress); removePeerConsumer.accept(getPeersRequestMessage.senderNodeAddress);
} }
}); });
addReportedPeersConsumer.accept(reportedPeers, connection); addReportedPeersConsumer.accept(reportedPeers, connection);
@ -115,7 +115,7 @@ public class PeerExchangeManager implements MessageListener {
connectedPeersList.stream() connectedPeersList.stream()
.forEach(e -> { .forEach(e -> {
SettableFuture<Connection> future = networkNode.sendMessage(e.connection, SettableFuture<Connection> future = networkNode.sendMessage(e.connection,
new GetPeersRequest(networkNode.getAddress(), new HashSet<>(authenticatedAndReportedPeersSupplier.get()))); new GetPeersRequest(networkNode.getNodeAddress(), new HashSet<>(authenticatedAndReportedPeersSupplier.get())));
Futures.addCallback(future, new FutureCallback<Connection>() { Futures.addCallback(future, new FutureCallback<Connection>() {
@Override @Override
public void onSuccess(Connection connection) { public void onSuccess(Connection connection) {
@ -125,7 +125,7 @@ public class PeerExchangeManager implements MessageListener {
@Override @Override
public void onFailure(@NotNull Throwable throwable) { public void onFailure(@NotNull Throwable throwable) {
log.info("sendGetPeersRequest sending failed " + throwable.getMessage()); log.info("sendGetPeersRequest sending failed " + throwable.getMessage());
removePeerConsumer.accept(e.address); removePeerConsumer.accept(e.nodeAddress);
} }
}); });
}); });

View file

@ -7,8 +7,8 @@ import com.google.common.util.concurrent.SettableFuture;
import io.bitsquare.app.Log; import io.bitsquare.app.Log;
import io.bitsquare.common.UserThread; import io.bitsquare.common.UserThread;
import io.bitsquare.common.util.Utilities; import io.bitsquare.common.util.Utilities;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message; import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.network.*; import io.bitsquare.p2p.network.*;
import io.bitsquare.p2p.peers.messages.auth.AuthenticationRejection; import io.bitsquare.p2p.peers.messages.auth.AuthenticationRejection;
import io.bitsquare.p2p.peers.messages.auth.AuthenticationRequest; import io.bitsquare.p2p.peers.messages.auth.AuthenticationRequest;
@ -64,12 +64,12 @@ public class PeerManager implements MessageListener, ConnectionListener {
private Storage<HashSet<ReportedPeer>> dbStorage; private Storage<HashSet<ReportedPeer>> dbStorage;
private final CopyOnWriteArraySet<AuthenticationListener> authenticationListeners = new CopyOnWriteArraySet<>(); private final CopyOnWriteArraySet<AuthenticationListener> authenticationListeners = new CopyOnWriteArraySet<>();
protected final Map<Address, Peer> authenticatedPeers = new HashMap<>(); protected final Map<NodeAddress, Peer> authenticatedPeers = new HashMap<>();
private final HashSet<ReportedPeer> reportedPeers = new HashSet<>(); private final HashSet<ReportedPeer> reportedPeers = new HashSet<>();
private final HashSet<ReportedPeer> persistedPeers = new HashSet<>(); private final HashSet<ReportedPeer> persistedPeers = new HashSet<>();
protected final Map<Address, AuthenticationHandshake> authenticationHandshakes = new HashMap<>(); protected final Map<NodeAddress, AuthenticationHandshake> authenticationHandshakes = new HashMap<>();
protected final List<Address> remainingSeedNodes = new ArrayList<>(); protected final List<NodeAddress> remainingSeedNodes = new ArrayList<>();
protected Optional<Set<Address>> seedNodeAddressesOptional = Optional.empty(); protected Optional<Set<NodeAddress>> seedNodeAddressesOptional = Optional.empty();
protected Timer authenticateToRemainingSeedNodeTimer, authenticateToRemainingReportedPeerTimer; protected Timer authenticateToRemainingSeedNodeTimer, authenticateToRemainingReportedPeerTimer;
@ -163,33 +163,33 @@ public class PeerManager implements MessageListener, ConnectionListener {
// API // API
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public void broadcast(DataBroadcastMessage message, @Nullable Address sender) { public void broadcast(DataBroadcastMessage message, @Nullable NodeAddress sender) {
Log.traceCall("Sender " + sender + ". Message " + message.toString()); Log.traceCall("Sender " + sender + ". Message " + message.toString());
if (authenticatedPeers.values().size() > 0) { if (authenticatedPeers.values().size() > 0) {
log.info("Broadcast message to {} peers. Message: {}", authenticatedPeers.values().size(), message); log.info("Broadcast message to {} peers. Message: {}", authenticatedPeers.values().size(), message);
authenticatedPeers.values().stream() authenticatedPeers.values().stream()
.filter(e -> !e.address.equals(sender)) .filter(e -> !e.nodeAddress.equals(sender))
.forEach(peer -> { .forEach(peer -> {
if (authenticatedPeers.containsValue(peer)) { if (authenticatedPeers.containsValue(peer)) {
final Address address = peer.address; final NodeAddress nodeAddress = peer.nodeAddress;
log.trace("Broadcast message from " + getMyAddress() + " to " + address + "."); log.trace("Broadcast message from " + getMyAddress() + " to " + nodeAddress + ".");
SettableFuture<Connection> future = networkNode.sendMessage(address, message); SettableFuture<Connection> future = networkNode.sendMessage(nodeAddress, message);
Futures.addCallback(future, new FutureCallback<Connection>() { Futures.addCallback(future, new FutureCallback<Connection>() {
@Override @Override
public void onSuccess(Connection connection) { public void onSuccess(Connection connection) {
log.trace("Broadcast from " + getMyAddress() + " to " + address + " succeeded."); log.trace("Broadcast from " + getMyAddress() + " to " + nodeAddress + " succeeded.");
} }
@Override @Override
public void onFailure(@NotNull Throwable throwable) { public void onFailure(@NotNull Throwable throwable) {
log.info("Broadcast failed. " + throwable.getMessage()); log.info("Broadcast failed. " + throwable.getMessage());
UserThread.execute(() -> removePeer(address)); UserThread.execute(() -> removePeer(nodeAddress));
} }
}); });
} else { } else {
log.debug("Peer is not in our authenticated list anymore. " + log.debug("Peer is not in our authenticated list anymore. " +
"That can happen as we use a stream loop for the broadcast. " + "That can happen as we use a stream loop for the broadcast. " +
"Peer.address={}", peer.address); "Peer.address={}", peer.nodeAddress);
} }
}); });
} else { } else {
@ -225,39 +225,39 @@ public class PeerManager implements MessageListener, ConnectionListener {
private void processAuthenticationRequest(AuthenticationRequest message, final Connection connection) { private void processAuthenticationRequest(AuthenticationRequest message, final Connection connection) {
Log.traceCall(message.toString()); Log.traceCall(message.toString());
Address peerAddress = message.senderAddress; NodeAddress peerNodeAddress = message.senderNodeAddress;
// We set the address to the connection, otherwise we will not find the connection when sending // We set the address to the connection, otherwise we will not find the connection when sending
// a reject message and we would create a new outbound connection instead using the inbound. // a reject message and we would create a new outbound connection instead using the inbound.
connection.setPeerAddress(message.senderAddress); connection.setPeerAddress(message.senderNodeAddress);
if (!authenticatedPeers.containsKey(peerAddress)) { if (!authenticatedPeers.containsKey(peerNodeAddress)) {
AuthenticationHandshake authenticationHandshake; AuthenticationHandshake authenticationHandshake;
if (!authenticationHandshakes.containsKey(peerAddress)) { if (!authenticationHandshakes.containsKey(peerNodeAddress)) {
log.info("We got an incoming AuthenticationRequest for the peerAddress {}. " + log.info("We got an incoming AuthenticationRequest for the peerAddress {}. " +
"We create an AuthenticationHandshake.", peerAddress); "We create an AuthenticationHandshake.", peerNodeAddress);
// We protect that connection from getting closed by maintenance cleanup... // We protect that connection from getting closed by maintenance cleanup...
connection.setConnectionPriority(ConnectionPriority.AUTH_REQUEST); connection.setConnectionPriority(ConnectionPriority.AUTH_REQUEST);
authenticationHandshake = new AuthenticationHandshake(networkNode, authenticationHandshake = new AuthenticationHandshake(networkNode,
getMyAddress(), getMyAddress(),
peerAddress, peerNodeAddress,
() -> getAuthenticatedAndReportedPeers(), () -> getAuthenticatedAndReportedPeers(),
(newReportedPeers, connection1) -> addToReportedPeers(newReportedPeers, connection1) (newReportedPeers, connection1) -> addToReportedPeers(newReportedPeers, connection1)
); );
authenticationHandshakes.put(peerAddress, authenticationHandshake); authenticationHandshakes.put(peerNodeAddress, authenticationHandshake);
SettableFuture<Connection> future = authenticationHandshake.respondToAuthenticationRequest(message, connection); SettableFuture<Connection> future = authenticationHandshake.respondToAuthenticationRequest(message, connection);
Futures.addCallback(future, new FutureCallback<Connection>() { Futures.addCallback(future, new FutureCallback<Connection>() {
@Override @Override
public void onSuccess(Connection connection) { public void onSuccess(Connection connection) {
log.info("We got the peer ({}) who requested authentication authenticated.", peerAddress); log.info("We got the peer ({}) who requested authentication authenticated.", peerNodeAddress);
handleAuthenticationSuccess(connection, peerAddress); handleAuthenticationSuccess(connection, peerNodeAddress);
} }
@Override @Override
public void onFailure(@NotNull Throwable throwable) { public void onFailure(@NotNull Throwable throwable) {
log.info("Authentication with peer who requested authentication failed.\n" + log.info("Authentication with peer who requested authentication failed.\n" +
"That can happen if the peer went offline. " + throwable.getMessage()); "That can happen if the peer went offline. " + throwable.getMessage());
handleAuthenticationFailure(peerAddress, throwable); handleAuthenticationFailure(peerNodeAddress, throwable);
} }
} }
); );
@ -265,28 +265,28 @@ public class PeerManager implements MessageListener, ConnectionListener {
log.info("We got an incoming AuthenticationRequest but we have started ourselves already " + log.info("We got an incoming AuthenticationRequest but we have started ourselves already " +
"an authentication handshake for that peerAddress ({}).\n" + "an authentication handshake for that peerAddress ({}).\n" +
"We terminate such race conditions by rejecting and cancelling the authentication on both " + "We terminate such race conditions by rejecting and cancelling the authentication on both " +
"peers.", peerAddress); "peers.", peerNodeAddress);
rejectAuthenticationRequest(peerAddress); rejectAuthenticationRequest(peerNodeAddress);
authenticationHandshakes.get(peerAddress).cancel(peerAddress); authenticationHandshakes.get(peerNodeAddress).cancel(peerNodeAddress);
authenticationHandshakes.remove(peerAddress); authenticationHandshakes.remove(peerNodeAddress);
} }
} else { } else {
log.info("We got an incoming AuthenticationRequest but we are already authenticated to peer {}.\n" + log.info("We got an incoming AuthenticationRequest but we are already authenticated to peer {}.\n" +
"That should not happen. " + "That should not happen. " +
"We reject the request.", peerAddress); "We reject the request.", peerNodeAddress);
rejectAuthenticationRequest(peerAddress); rejectAuthenticationRequest(peerNodeAddress);
if (authenticationHandshakes.containsKey(peerAddress)) { if (authenticationHandshakes.containsKey(peerNodeAddress)) {
authenticationHandshakes.get(peerAddress).cancel(peerAddress); authenticationHandshakes.get(peerNodeAddress).cancel(peerNodeAddress);
authenticationHandshakes.remove(peerAddress); authenticationHandshakes.remove(peerNodeAddress);
} }
} }
} }
private void rejectAuthenticationRequest(Address peerAddress) { private void rejectAuthenticationRequest(NodeAddress peerNodeAddress) {
Log.traceCall(); Log.traceCall();
networkNode.sendMessage(peerAddress, new AuthenticationRejection(getMyAddress())); networkNode.sendMessage(peerNodeAddress, new AuthenticationRejection(getMyAddress()));
} }
@ -294,45 +294,45 @@ public class PeerManager implements MessageListener, ConnectionListener {
// Authentication to seed node // Authentication to seed node
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
public void setSeedNodeAddresses(Set<Address> seedNodeAddresses) { public void setSeedNodeAddresses(Set<NodeAddress> seedNodeNodeAddresses) {
seedNodeAddressesOptional = Optional.of(seedNodeAddresses); seedNodeAddressesOptional = Optional.of(seedNodeNodeAddresses);
checkArgument(!seedNodeAddressesOptional.get().isEmpty(), checkArgument(!seedNodeAddressesOptional.get().isEmpty(),
"seedNodeAddresses must not be empty"); "seedNodeAddresses must not be empty");
} }
public void authenticateToSeedNode(Address peerAddress) { public void authenticateToSeedNode(NodeAddress peerNodeAddress) {
Log.traceCall(); Log.traceCall();
checkArgument(seedNodeAddressesOptional.isPresent(), checkArgument(seedNodeAddressesOptional.isPresent(),
"seedNodeAddresses must be set before calling authenticateToSeedNode"); "seedNodeAddresses must be set before calling authenticateToSeedNode");
remainingSeedNodes.remove(peerAddress); remainingSeedNodes.remove(peerNodeAddress);
remainingSeedNodes.addAll(seedNodeAddressesOptional.get()); remainingSeedNodes.addAll(seedNodeAddressesOptional.get());
authenticateToFirstSeedNode(peerAddress); authenticateToFirstSeedNode(peerNodeAddress);
startCheckSeedNodeConnectionTask(); startCheckSeedNodeConnectionTask();
} }
protected void authenticateToFirstSeedNode(Address peerAddress) { protected void authenticateToFirstSeedNode(NodeAddress peerNodeAddress) {
Log.traceCall(); Log.traceCall();
if (!enoughConnections()) { if (!enoughConnections()) {
if (!authenticationHandshakes.containsKey(peerAddress)) { if (!authenticationHandshakes.containsKey(peerNodeAddress)) {
log.info("We try to authenticate to seed node {}.", peerAddress); log.info("We try to authenticate to seed node {}.", peerNodeAddress);
authenticate(peerAddress, new FutureCallback<Connection>() { authenticate(peerNodeAddress, new FutureCallback<Connection>() {
@Override @Override
public void onSuccess(Connection connection) { public void onSuccess(Connection connection) {
log.info("We got our first seed node authenticated. " + log.info("We got our first seed node authenticated. " +
"We try to authenticate to reported peers."); "We try to authenticate to reported peers.");
handleAuthenticationSuccess(connection, peerAddress); handleAuthenticationSuccess(connection, peerNodeAddress);
onFirstSeedNodeAuthenticated(); onFirstSeedNodeAuthenticated();
} }
@Override @Override
public void onFailure(@NotNull Throwable throwable) { public void onFailure(@NotNull Throwable throwable) {
log.info("Authentication to " + peerAddress + " failed at authenticateToFirstSeedNode." + log.info("Authentication to " + peerNodeAddress + " failed at authenticateToFirstSeedNode." +
"\nThat is expected if seed node is offline." + "\nThat is expected if seed node is offline." +
"\nException:" + throwable.toString()); "\nException:" + throwable.toString());
handleAuthenticationFailure(peerAddress, throwable); handleAuthenticationFailure(peerNodeAddress, throwable);
Optional<Address> seedNodeOptional = getAndRemoveNotAuthenticatingSeedNode(); Optional<NodeAddress> seedNodeOptional = getAndRemoveNotAuthenticatingSeedNode();
if (seedNodeOptional.isPresent()) { if (seedNodeOptional.isPresent()) {
log.info("We try another random seed node for authenticateToFirstSeedNode."); log.info("We try another random seed node for authenticateToFirstSeedNode.");
authenticateToFirstSeedNode(seedNodeOptional.get()); authenticateToFirstSeedNode(seedNodeOptional.get());
@ -367,28 +367,28 @@ public class PeerManager implements MessageListener, ConnectionListener {
} }
if (!enoughConnections()) { if (!enoughConnections()) {
Optional<Address> seedNodeOptional = getAndRemoveNotAuthenticatingSeedNode(); Optional<NodeAddress> seedNodeOptional = getAndRemoveNotAuthenticatingSeedNode();
if (seedNodeOptional.isPresent()) { if (seedNodeOptional.isPresent()) {
Address peerAddress = seedNodeOptional.get(); NodeAddress peerNodeAddress = seedNodeOptional.get();
if (!authenticationHandshakes.containsKey(peerAddress)) { if (!authenticationHandshakes.containsKey(peerNodeAddress)) {
log.info("We try to authenticate to a randomly selected seed node {}.", peerAddress); log.info("We try to authenticate to a randomly selected seed node {}.", peerNodeAddress);
authenticate(peerAddress, new FutureCallback<Connection>() { authenticate(peerNodeAddress, new FutureCallback<Connection>() {
@Override @Override
public void onSuccess(Connection connection) { public void onSuccess(Connection connection) {
log.info("We got a seed node authenticated. " + log.info("We got a seed node authenticated. " +
"We try to authenticate to reported peers."); "We try to authenticate to reported peers.");
handleAuthenticationSuccess(connection, peerAddress); handleAuthenticationSuccess(connection, peerNodeAddress);
onRemainingSeedNodeAuthenticated(); onRemainingSeedNodeAuthenticated();
} }
@Override @Override
public void onFailure(@NotNull Throwable throwable) { public void onFailure(@NotNull Throwable throwable) {
log.info("Authentication to " + peerAddress + " failed at authenticateToRemainingSeedNode." + log.info("Authentication to " + peerNodeAddress + " failed at authenticateToRemainingSeedNode." +
"\nThat is expected if the seed node is offline." + "\nThat is expected if the seed node is offline." +
"\nException:" + throwable.toString()); "\nException:" + throwable.toString());
handleAuthenticationFailure(peerAddress, throwable); handleAuthenticationFailure(peerNodeAddress, throwable);
log.info("We try authenticateToRemainingSeedNode again."); log.info("We try authenticateToRemainingSeedNode again.");
authenticateToRemainingSeedNode(); authenticateToRemainingSeedNode();
@ -462,7 +462,7 @@ public class PeerManager implements MessageListener, ConnectionListener {
resetRemainingSeedNodes(); resetRemainingSeedNodes();
if (!remainingSeedNodes.isEmpty()) { if (!remainingSeedNodes.isEmpty()) {
if (seedNodeAddressesOptional.isPresent()) { if (seedNodeAddressesOptional.isPresent()) {
Optional<Address> authSeedNodeOptional = authenticatedPeers.keySet().stream() Optional<NodeAddress> authSeedNodeOptional = authenticatedPeers.keySet().stream()
.filter(e -> seedNodeAddressesOptional.get().contains(e)).findAny(); .filter(e -> seedNodeAddressesOptional.get().contains(e)).findAny();
if (authSeedNodeOptional.isPresent()) { if (authSeedNodeOptional.isPresent()) {
log.info("We are at least to one seed node connected."); log.info("We are at least to one seed node connected.");
@ -503,26 +503,26 @@ public class PeerManager implements MessageListener, ConnectionListener {
if (reportedPeersAvailable()) { if (reportedPeersAvailable()) {
Optional<ReportedPeer> reportedPeer = getAndRemoveNotAuthenticatingReportedPeer(); Optional<ReportedPeer> reportedPeer = getAndRemoveNotAuthenticatingReportedPeer();
if (reportedPeer.isPresent()) { if (reportedPeer.isPresent()) {
Address peerAddress = reportedPeer.get().address; NodeAddress peerNodeAddress = reportedPeer.get().nodeAddress;
if (!authenticationHandshakes.containsKey(peerAddress)) { if (!authenticationHandshakes.containsKey(peerNodeAddress)) {
log.info("We try to authenticate to peer {}.", peerAddress); log.info("We try to authenticate to peer {}.", peerNodeAddress);
authenticate(peerAddress, new FutureCallback<Connection>() { authenticate(peerNodeAddress, new FutureCallback<Connection>() {
@Override @Override
public void onSuccess(Connection connection) { public void onSuccess(Connection connection) {
log.info("We got a peer authenticated. " + log.info("We got a peer authenticated. " +
"We try if there are more reported peers available to authenticate."); "We try if there are more reported peers available to authenticate.");
handleAuthenticationSuccess(connection, peerAddress); handleAuthenticationSuccess(connection, peerNodeAddress);
authenticateToRemainingReportedPeer(); authenticateToRemainingReportedPeer();
} }
@Override @Override
public void onFailure(@NotNull Throwable throwable) { public void onFailure(@NotNull Throwable throwable) {
log.info("Authentication to " + peerAddress + " failed at authenticateToRemainingReportedPeer." + log.info("Authentication to " + peerNodeAddress + " failed at authenticateToRemainingReportedPeer." +
"\nThat is expected if the peer is offline." + "\nThat is expected if the peer is offline." +
"\nException:" + throwable.toString()); "\nException:" + throwable.toString());
handleAuthenticationFailure(peerAddress, throwable); handleAuthenticationFailure(peerNodeAddress, throwable);
log.info("We try another random seed node for authentication."); log.info("We try another random seed node for authentication.");
authenticateToRemainingReportedPeer(); authenticateToRemainingReportedPeer();
@ -584,18 +584,18 @@ public class PeerManager implements MessageListener, ConnectionListener {
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// Priority is set when we receive a decrypted mail message as those are used for direct messages // Priority is set when we receive a decrypted mail message as those are used for direct messages
public void authenticateToDirectMessagePeer(Address peerAddress, public void authenticateToDirectMessagePeer(NodeAddress peerNodeAddress,
@Nullable Runnable completeHandler, @Nullable Runnable completeHandler,
@Nullable Runnable faultHandler) { @Nullable Runnable faultHandler) {
Log.traceCall(peerAddress.getFullAddress()); Log.traceCall(peerNodeAddress.getFullAddress());
if (authenticatedPeers.containsKey(peerAddress)) { if (authenticatedPeers.containsKey(peerNodeAddress)) {
log.warn("We have that peer already authenticated. That should never happen. peerAddress={}", peerAddress); log.warn("We have that peer already authenticated. That should never happen. peerAddress={}", peerNodeAddress);
if (completeHandler != null) if (completeHandler != null)
completeHandler.run(); completeHandler.run();
} else if (authenticationHandshakes.containsKey(peerAddress)) { } else if (authenticationHandshakes.containsKey(peerNodeAddress)) {
log.info("We are in the process to authenticate to that peer. peerAddress={}", peerAddress); log.info("We are in the process to authenticate to that peer. peerAddress={}", peerNodeAddress);
Optional<SettableFuture<Connection>> resultFutureOptional = authenticationHandshakes.get(peerAddress).getResultFutureOptional(); Optional<SettableFuture<Connection>> resultFutureOptional = authenticationHandshakes.get(peerNodeAddress).getResultFutureOptional();
if (resultFutureOptional.isPresent()) { if (resultFutureOptional.isPresent()) {
Futures.addCallback(resultFutureOptional.get(), new FutureCallback<Connection>() { Futures.addCallback(resultFutureOptional.get(), new FutureCallback<Connection>() {
@Override @Override
@ -612,29 +612,29 @@ public class PeerManager implements MessageListener, ConnectionListener {
}); });
} else { } else {
log.warn("We are in the process to authenticate to that peer but the future object is not set. " + log.warn("We are in the process to authenticate to that peer but the future object is not set. " +
"That should not happen. peerAddress={}", peerAddress); "That should not happen. peerAddress={}", peerNodeAddress);
if (faultHandler != null) if (faultHandler != null)
faultHandler.run(); faultHandler.run();
} }
} else { } else {
log.info("We try to authenticate to peer {} for sending a private message.", peerAddress); log.info("We try to authenticate to peer {} for sending a private message.", peerNodeAddress);
authenticate(peerAddress, new FutureCallback<Connection>() { authenticate(peerNodeAddress, new FutureCallback<Connection>() {
@Override @Override
public void onSuccess(Connection connection) { public void onSuccess(Connection connection) {
log.info("We got a new peer for sending a private message authenticated."); log.info("We got a new peer for sending a private message authenticated.");
handleAuthenticationSuccess(connection, peerAddress); handleAuthenticationSuccess(connection, peerNodeAddress);
if (completeHandler != null) if (completeHandler != null)
completeHandler.run(); completeHandler.run();
} }
@Override @Override
public void onFailure(@NotNull Throwable throwable) { public void onFailure(@NotNull Throwable throwable) {
log.error("Authentication to " + peerAddress + " for sending a private message failed at authenticateToDirectMessagePeer." + log.error("Authentication to " + peerNodeAddress + " for sending a private message failed at authenticateToDirectMessagePeer." +
"\nSeems that the peer is offline." + "\nSeems that the peer is offline." +
"\nException:" + throwable.toString()); "\nException:" + throwable.toString());
handleAuthenticationFailure(peerAddress, throwable); handleAuthenticationFailure(peerNodeAddress, throwable);
if (faultHandler != null) if (faultHandler != null)
faultHandler.run(); faultHandler.run();
} }
@ -647,38 +647,38 @@ public class PeerManager implements MessageListener, ConnectionListener {
// Authentication private methods // Authentication private methods
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
private void authenticate(Address peerAddress, FutureCallback<Connection> futureCallback) { private void authenticate(NodeAddress peerNodeAddress, FutureCallback<Connection> futureCallback) {
Log.traceCall(peerAddress.getFullAddress()); Log.traceCall(peerNodeAddress.getFullAddress());
checkArgument(!authenticationHandshakes.containsKey(peerAddress), checkArgument(!authenticationHandshakes.containsKey(peerNodeAddress),
"An authentication handshake is already created for that peerAddress (" + peerAddress + ")"); "An authentication handshake is already created for that peerAddress (" + peerNodeAddress + ")");
log.info("We create an AuthenticationHandshake to authenticate to peer {}.", peerAddress); log.info("We create an AuthenticationHandshake to authenticate to peer {}.", peerNodeAddress);
AuthenticationHandshake authenticationHandshake = new AuthenticationHandshake(networkNode, AuthenticationHandshake authenticationHandshake = new AuthenticationHandshake(networkNode,
getMyAddress(), getMyAddress(),
peerAddress, peerNodeAddress,
() -> getAuthenticatedAndReportedPeers(), () -> getAuthenticatedAndReportedPeers(),
(newReportedPeers, connection) -> addToReportedPeers(newReportedPeers, connection) (newReportedPeers, connection) -> addToReportedPeers(newReportedPeers, connection)
); );
authenticationHandshakes.put(peerAddress, authenticationHandshake); authenticationHandshakes.put(peerNodeAddress, authenticationHandshake);
SettableFuture<Connection> authenticationFuture = authenticationHandshake.requestAuthentication(); SettableFuture<Connection> authenticationFuture = authenticationHandshake.requestAuthentication();
Futures.addCallback(authenticationFuture, futureCallback); Futures.addCallback(authenticationFuture, futureCallback);
} }
private void handleAuthenticationSuccess(Connection connection, Address peerAddress) { private void handleAuthenticationSuccess(Connection connection, NodeAddress peerNodeAddress) {
Log.traceCall(peerAddress.getFullAddress()); Log.traceCall(peerNodeAddress.getFullAddress());
log.info("\n\n############################################################\n" + log.info("\n\n############################################################\n" +
"We are authenticated to:" + "We are authenticated to:" +
"\nconnection=" + connection.getUid() "\nconnection=" + connection.getUid()
+ "\nmyAddress=" + getMyAddress() + "\nmyAddress=" + getMyAddress()
+ "\npeerAddress= " + peerAddress + "\npeerAddress= " + peerNodeAddress
+ "\n############################################################\n"); + "\n############################################################\n");
removeFromAuthenticationHandshakes(peerAddress); removeFromAuthenticationHandshakes(peerNodeAddress);
connection.setPeerAddress(peerAddress); connection.setPeerAddress(peerNodeAddress);
connection.setAuthenticated(); connection.setAuthenticated();
authenticatedPeers.put(peerAddress, new Peer(connection, peerAddress)); authenticatedPeers.put(peerNodeAddress, new Peer(connection, peerNodeAddress));
removeFromReportedPeers(peerAddress); removeFromReportedPeers(peerNodeAddress);
authenticationListeners.stream().forEach(e -> e.onPeerAuthenticated(peerAddress, connection)); authenticationListeners.stream().forEach(e -> e.onPeerAuthenticated(peerNodeAddress, connection));
printAuthenticatedPeers(); printAuthenticatedPeers();
@ -686,40 +686,40 @@ public class PeerManager implements MessageListener, ConnectionListener {
checkIfConnectedPeersExceeds(MAX_CONNECTIONS_LOW_PRIORITY + 2); checkIfConnectedPeersExceeds(MAX_CONNECTIONS_LOW_PRIORITY + 2);
} }
void handleAuthenticationFailure(@Nullable Address peerAddress, Throwable throwable) { void handleAuthenticationFailure(@Nullable NodeAddress peerNodeAddress, Throwable throwable) {
if (throwable instanceof AuthenticationException) if (throwable instanceof AuthenticationException)
removeFromAuthenticationHandshakes(peerAddress); removeFromAuthenticationHandshakes(peerNodeAddress);
else else
removePeer(peerAddress); removePeer(peerNodeAddress);
} }
void removePeer(@Nullable Address peerAddress) { void removePeer(@Nullable NodeAddress peerNodeAddress) {
Log.traceCall("peerAddress=" + peerAddress); Log.traceCall("peerAddress=" + peerNodeAddress);
if (peerAddress != null) { if (peerNodeAddress != null) {
removeFromAuthenticationHandshakes(peerAddress); removeFromAuthenticationHandshakes(peerNodeAddress);
removeFromReportedPeers(peerAddress); removeFromReportedPeers(peerNodeAddress);
removeFromAuthenticatedPeers(peerAddress); removeFromAuthenticatedPeers(peerNodeAddress);
removeFromPersistedPeers(peerAddress); removeFromPersistedPeers(peerNodeAddress);
} }
} }
private void removeFromReportedPeers(Address peerAddress) { private void removeFromReportedPeers(NodeAddress peerNodeAddress) {
reportedPeers.remove(new ReportedPeer(peerAddress)); reportedPeers.remove(new ReportedPeer(peerNodeAddress));
} }
private void removeFromAuthenticationHandshakes(Address peerAddress) { private void removeFromAuthenticationHandshakes(NodeAddress peerNodeAddress) {
if (authenticationHandshakes.containsKey(peerAddress)) if (authenticationHandshakes.containsKey(peerNodeAddress))
authenticationHandshakes.remove(peerAddress); authenticationHandshakes.remove(peerNodeAddress);
} }
private void removeFromAuthenticatedPeers(Address peerAddress) { private void removeFromAuthenticatedPeers(NodeAddress peerNodeAddress) {
if (authenticatedPeers.containsKey(peerAddress)) if (authenticatedPeers.containsKey(peerNodeAddress))
authenticatedPeers.remove(peerAddress); authenticatedPeers.remove(peerNodeAddress);
printAuthenticatedPeers(); printAuthenticatedPeers();
} }
private void removeFromPersistedPeers(Address peerAddress) { private void removeFromPersistedPeers(NodeAddress peerNodeAddress) {
ReportedPeer reportedPeer = new ReportedPeer(peerAddress); ReportedPeer reportedPeer = new ReportedPeer(peerNodeAddress);
if (persistedPeers.contains(reportedPeer)) { if (persistedPeers.contains(reportedPeer)) {
persistedPeers.remove(reportedPeer); persistedPeers.remove(reportedPeer);
@ -740,7 +740,7 @@ public class PeerManager implements MessageListener, ConnectionListener {
} }
private boolean remainingSeedNodesAvailable() { private boolean remainingSeedNodesAvailable() {
List<Address> list = new ArrayList<>(remainingSeedNodes); List<NodeAddress> list = new ArrayList<>(remainingSeedNodes);
authenticationHandshakes.keySet().stream().forEach(e -> list.remove(e)); authenticationHandshakes.keySet().stream().forEach(e -> list.remove(e));
authenticatedPeers.keySet().stream().forEach(e -> list.remove(e)); authenticatedPeers.keySet().stream().forEach(e -> list.remove(e));
return !list.isEmpty(); return !list.isEmpty();
@ -824,15 +824,15 @@ public class PeerManager implements MessageListener, ConnectionListener {
public Set<ReportedPeer> getAuthenticatedAndReportedPeers() { public Set<ReportedPeer> getAuthenticatedAndReportedPeers() {
Set<ReportedPeer> all = new HashSet<>(reportedPeers); Set<ReportedPeer> all = new HashSet<>(reportedPeers);
Set<ReportedPeer> authenticated = authenticatedPeers.values().stream() Set<ReportedPeer> authenticated = authenticatedPeers.values().stream()
.filter(e -> e.address != null) .filter(e -> e.nodeAddress != null)
.filter(e -> !seedNodeAddressesOptional.isPresent() || !seedNodeAddressesOptional.get().contains(e.address)) .filter(e -> !seedNodeAddressesOptional.isPresent() || !seedNodeAddressesOptional.get().contains(e.nodeAddress))
.map(e -> new ReportedPeer(e.address, new Date())) .map(e -> new ReportedPeer(e.nodeAddress, new Date()))
.collect(Collectors.toSet()); .collect(Collectors.toSet());
all.addAll(authenticated); all.addAll(authenticated);
return all; return all;
} }
public Map<Address, Peer> getAuthenticatedPeers() { public Map<NodeAddress, Peer> getAuthenticatedPeers() {
return authenticatedPeers; return authenticatedPeers;
} }
@ -840,8 +840,8 @@ public class PeerManager implements MessageListener, ConnectionListener {
return persistedPeers; return persistedPeers;
} }
public boolean isInAuthenticationProcess(Address address) { public boolean isInAuthenticationProcess(NodeAddress nodeAddress) {
return authenticationHandshakes.containsKey(address); return authenticationHandshakes.containsKey(nodeAddress);
} }
@ -859,18 +859,18 @@ public class PeerManager implements MessageListener, ConnectionListener {
} else { } else {
// In case we have one of the peers already we adjust the lastActivityDate by adjusting the date to the mid // In case we have one of the peers already we adjust the lastActivityDate by adjusting the date to the mid
// of the lastActivityDate of our already stored peer and the reported one // of the lastActivityDate of our already stored peer and the reported one
Map<Address, ReportedPeer> reportedPeersMap = reportedPeers.stream() Map<NodeAddress, ReportedPeer> reportedPeersMap = reportedPeers.stream()
.collect(Collectors.toMap(e -> e.address, Function.identity())); .collect(Collectors.toMap(e -> e.nodeAddress, Function.identity()));
Set<ReportedPeer> adjustedReportedPeers = new HashSet<>(); Set<ReportedPeer> adjustedReportedPeers = new HashSet<>();
reportedPeersToAdd.stream() reportedPeersToAdd.stream()
.filter(e -> !e.address.equals(getMyAddress())) .filter(e -> !e.nodeAddress.equals(getMyAddress()))
.filter(e -> !seedNodeAddressesOptional.isPresent() || !seedNodeAddressesOptional.get().contains(e.address)) .filter(e -> !seedNodeAddressesOptional.isPresent() || !seedNodeAddressesOptional.get().contains(e.nodeAddress))
.filter(e -> !authenticatedPeers.containsKey(e.address)) .filter(e -> !authenticatedPeers.containsKey(e.nodeAddress))
.forEach(e -> { .forEach(e -> {
if (reportedPeersMap.containsKey(e.address)) { if (reportedPeersMap.containsKey(e.nodeAddress)) {
long adjustedTime = (e.lastActivityDate.getTime() + long adjustedTime = (e.lastActivityDate.getTime() +
reportedPeersMap.get(e.address).lastActivityDate.getTime()) / 2; reportedPeersMap.get(e.nodeAddress).lastActivityDate.getTime()) / 2;
adjustedReportedPeers.add(new ReportedPeer(e.address, adjustedReportedPeers.add(new ReportedPeer(e.nodeAddress,
new Date(adjustedTime))); new Date(adjustedTime)));
} else { } else {
adjustedReportedPeers.add(e); adjustedReportedPeers.add(e);
@ -927,8 +927,8 @@ public class PeerManager implements MessageListener, ConnectionListener {
} }
@Nullable @Nullable
Address getMyAddress() { NodeAddress getMyAddress() {
return networkNode.getAddress(); return networkNode.getNodeAddress();
} }
private ReportedPeer getAndRemoveRandomReportedPeer(List<ReportedPeer> list) { private ReportedPeer getAndRemoveRandomReportedPeer(List<ReportedPeer> list) {
@ -942,20 +942,20 @@ public class PeerManager implements MessageListener, ConnectionListener {
authenticatedPeers.keySet().stream().forEach(e -> list.remove(new ReportedPeer(e))); authenticatedPeers.keySet().stream().forEach(e -> list.remove(new ReportedPeer(e)));
if (!list.isEmpty()) { if (!list.isEmpty()) {
ReportedPeer reportedPeer = getAndRemoveRandomReportedPeer(list); ReportedPeer reportedPeer = getAndRemoveRandomReportedPeer(list);
removeFromReportedPeers(reportedPeer.address); removeFromReportedPeers(reportedPeer.nodeAddress);
return Optional.of(reportedPeer); return Optional.of(reportedPeer);
} else { } else {
return Optional.empty(); return Optional.empty();
} }
} }
protected Address getAndRemoveRandomAddress(List<Address> list) { protected NodeAddress getAndRemoveRandomAddress(List<NodeAddress> list) {
checkArgument(!list.isEmpty(), "List must not be empty"); checkArgument(!list.isEmpty(), "List must not be empty");
return list.remove(new Random().nextInt(list.size())); return list.remove(new Random().nextInt(list.size()));
} }
private Optional<Address> getAndRemoveNotAuthenticatingSeedNode() { private Optional<NodeAddress> getAndRemoveNotAuthenticatingSeedNode() {
authenticationHandshakes.keySet().stream().forEach(e -> remainingSeedNodes.remove(e)); authenticationHandshakes.keySet().stream().forEach(e -> remainingSeedNodes.remove(e));
authenticatedPeers.keySet().stream().forEach(e -> remainingSeedNodes.remove(e)); authenticatedPeers.keySet().stream().forEach(e -> remainingSeedNodes.remove(e));
if (remainingSeedNodesAvailable()) if (remainingSeedNodesAvailable())
@ -977,7 +977,7 @@ public class PeerManager implements MessageListener, ConnectionListener {
if (!authenticatedPeers.isEmpty()) { if (!authenticatedPeers.isEmpty()) {
StringBuilder result = new StringBuilder("\n\n------------------------------------------------------------\n" + StringBuilder result = new StringBuilder("\n\n------------------------------------------------------------\n" +
"Authenticated peers for node " + getMyAddress() + ":"); "Authenticated peers for node " + getMyAddress() + ":");
authenticatedPeers.values().stream().forEach(e -> result.append("\n").append(e.address)); authenticatedPeers.values().stream().forEach(e -> result.append("\n").append(e.nodeAddress));
result.append("\n------------------------------------------------------------\n"); result.append("\n------------------------------------------------------------\n");
log.info(result.toString()); log.info(result.toString());
} }

View file

@ -1,7 +1,7 @@
package io.bitsquare.p2p.peers; package io.bitsquare.p2p.peers;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date; import java.util.Date;
@ -10,16 +10,16 @@ public class ReportedPeer implements Serializable {
// That object is sent over the wire, so we need to take care of version compatibility. // That object is sent over the wire, so we need to take care of version compatibility.
private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION; private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION;
public final Address address; public final NodeAddress nodeAddress;
public final Date lastActivityDate; public final Date lastActivityDate;
public ReportedPeer(Address address, Date lastActivityDate) { public ReportedPeer(NodeAddress nodeAddress, Date lastActivityDate) {
this.address = address; this.nodeAddress = nodeAddress;
this.lastActivityDate = lastActivityDate; this.lastActivityDate = lastActivityDate;
} }
public ReportedPeer(Address address) { public ReportedPeer(NodeAddress nodeAddress) {
this(address, null); this(nodeAddress, null);
} }
// We don't use the lastActivityDate for identity // We don't use the lastActivityDate for identity
@ -30,20 +30,20 @@ public class ReportedPeer implements Serializable {
ReportedPeer that = (ReportedPeer) o; ReportedPeer that = (ReportedPeer) o;
return !(address != null ? !address.equals(that.address) : that.address != null); return !(nodeAddress != null ? !nodeAddress.equals(that.nodeAddress) : that.nodeAddress != null);
} }
// We don't use the lastActivityDate for identity // We don't use the lastActivityDate for identity
@Override @Override
public int hashCode() { public int hashCode() {
return address != null ? address.hashCode() : 0; return nodeAddress != null ? nodeAddress.hashCode() : 0;
} }
@Override @Override
public String toString() { public String toString() {
return "ReportedPeer{" + return "ReportedPeer{" +
"address=" + address + "address=" + nodeAddress +
", lastActivityDate=" + lastActivityDate + ", lastActivityDate=" + lastActivityDate +
'}'; '}';
} }

View file

@ -5,8 +5,8 @@ import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.SettableFuture; import com.google.common.util.concurrent.SettableFuture;
import io.bitsquare.app.Log; import io.bitsquare.app.Log;
import io.bitsquare.common.UserThread; import io.bitsquare.common.UserThread;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message; import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.network.Connection; import io.bitsquare.p2p.network.Connection;
import io.bitsquare.p2p.network.ConnectionPriority; import io.bitsquare.p2p.network.ConnectionPriority;
import io.bitsquare.p2p.network.MessageListener; import io.bitsquare.p2p.network.MessageListener;
@ -40,7 +40,7 @@ public class RequestDataManager implements MessageListener, AuthenticationListen
void onNoPeersAvailable(); void onNoPeersAvailable();
void onDataReceived(Address seedNode); void onDataReceived(NodeAddress seedNode);
} }
@ -50,8 +50,8 @@ public class RequestDataManager implements MessageListener, AuthenticationListen
private final HashSet<ReportedPeer> persistedPeers = new HashSet<>(); private final HashSet<ReportedPeer> persistedPeers = new HashSet<>();
private final HashSet<ReportedPeer> remainingPersistedPeers = new HashSet<>(); private final HashSet<ReportedPeer> remainingPersistedPeers = new HashSet<>();
private Listener listener; private Listener listener;
private Optional<Address> optionalConnectedSeedNodeAddress = Optional.empty(); private Optional<NodeAddress> optionalConnectedSeedNodeAddress = Optional.empty();
private Collection<Address> seedNodeAddresses; private Collection<NodeAddress> seedNodeNodeAddresses;
protected Timer requestDataFromAuthenticatedSeedNodeTimer; protected Timer requestDataFromAuthenticatedSeedNodeTimer;
private Timer requestDataTimer, requestDataWithPersistedPeersTimer; private Timer requestDataTimer, requestDataWithPersistedPeersTimer;
private boolean doNotifyNoSeedNodeAvailableListener = true; private boolean doNotifyNoSeedNodeAvailableListener = true;
@ -88,23 +88,23 @@ public class RequestDataManager implements MessageListener, AuthenticationListen
this.listener = listener; this.listener = listener;
} }
public void requestDataFromSeedNodes(Collection<Address> seedNodeAddresses) { public void requestDataFromSeedNodes(Collection<NodeAddress> seedNodeNodeAddresses) {
checkNotNull(seedNodeAddresses, "requestDataFromSeedNodes: seedNodeAddresses must not be null."); checkNotNull(seedNodeNodeAddresses, "requestDataFromSeedNodes: seedNodeAddresses must not be null.");
checkArgument(!seedNodeAddresses.isEmpty(), "requestDataFromSeedNodes: seedNodeAddresses must not be empty."); checkArgument(!seedNodeNodeAddresses.isEmpty(), "requestDataFromSeedNodes: seedNodeAddresses must not be empty.");
this.seedNodeAddresses = seedNodeAddresses; this.seedNodeNodeAddresses = seedNodeNodeAddresses;
requestData(seedNodeAddresses); requestData(seedNodeNodeAddresses);
} }
private void requestData(Collection<Address> addresses) { private void requestData(Collection<NodeAddress> nodeAddresses) {
Log.traceCall(addresses.toString()); Log.traceCall(nodeAddresses.toString());
checkArgument(!addresses.isEmpty(), "requestData: addresses must not be empty."); checkArgument(!nodeAddresses.isEmpty(), "requestData: addresses must not be empty.");
stopRequestDataTimer(); stopRequestDataTimer();
List<Address> remainingAddresses = new ArrayList<>(addresses); List<NodeAddress> remainingNodeAddresses = new ArrayList<>(nodeAddresses);
Address candidate = remainingAddresses.get(new Random().nextInt(remainingAddresses.size())); NodeAddress candidate = remainingNodeAddresses.get(new Random().nextInt(remainingNodeAddresses.size()));
if (!peerManager.isInAuthenticationProcess(candidate)) { if (!peerManager.isInAuthenticationProcess(candidate)) {
// We only remove it if it is not in the process of authentication // We only remove it if it is not in the process of authentication
remainingAddresses.remove(candidate); remainingNodeAddresses.remove(candidate);
log.info("We try to send a GetAllDataMessage request to node. " + candidate); log.info("We try to send a GetAllDataMessage request to node. " + candidate);
SettableFuture<Connection> future = networkNode.sendMessage(candidate, new DataRequest()); SettableFuture<Connection> future = networkNode.sendMessage(candidate, new DataRequest());
@ -125,7 +125,7 @@ public class RequestDataManager implements MessageListener, AuthenticationListen
"That is expected if the node is offline. " + "That is expected if the node is offline. " +
"Exception:" + throwable.getMessage()); "Exception:" + throwable.getMessage());
if (!remainingAddresses.isEmpty()) { if (!remainingNodeAddresses.isEmpty()) {
log.info("There are more seed nodes available for requesting data. " + log.info("There are more seed nodes available for requesting data. " +
"We will try requestData again."); "We will try requestData again.");
@ -133,7 +133,7 @@ public class RequestDataManager implements MessageListener, AuthenticationListen
if (remainingPersistedPeers.contains(reportedPeer)) if (remainingPersistedPeers.contains(reportedPeer))
remainingPersistedPeers.remove(reportedPeer); remainingPersistedPeers.remove(reportedPeer);
requestData(remainingAddresses); requestData(remainingNodeAddresses);
} else { } else {
log.info("There is no seed node available for requesting data. " + log.info("There is no seed node available for requesting data. " +
"That is expected if no seed node is online.\n" + "That is expected if no seed node is online.\n" +
@ -144,12 +144,12 @@ public class RequestDataManager implements MessageListener, AuthenticationListen
} }
} }
}); });
} else if (!remainingAddresses.isEmpty()) { } else if (!remainingNodeAddresses.isEmpty()) {
log.info("The node ({}) is in the process of authentication.\n" + log.info("The node ({}) is in the process of authentication.\n" +
"We will try requestData again with the remaining addresses.", candidate); "We will try requestData again with the remaining addresses.", candidate);
remainingAddresses.remove(candidate); remainingNodeAddresses.remove(candidate);
if (!remainingAddresses.isEmpty()) { if (!remainingNodeAddresses.isEmpty()) {
requestData(remainingAddresses); requestData(remainingNodeAddresses);
} else { } else {
log.info("The node ({}) is in the process of authentication.\n" + log.info("The node ({}) is in the process of authentication.\n" +
"There are no more remaining addresses available.\n" + "There are no more remaining addresses available.\n" +
@ -176,11 +176,11 @@ public class RequestDataManager implements MessageListener, AuthenticationListen
listener.onNoSeedNodeAvailable(); listener.onNoSeedNodeAvailable();
} }
if (requestDataTimer == null) if (requestDataTimer == null)
requestDataTimer = UserThread.runAfterRandomDelay(() -> requestData(seedNodeAddresses), requestDataTimer = UserThread.runAfterRandomDelay(() -> requestData(seedNodeNodeAddresses),
10, 20, TimeUnit.SECONDS); 10, 20, TimeUnit.SECONDS);
} }
private void requestDataWithPersistedPeers(@Nullable Address failedPeer) { private void requestDataWithPersistedPeers(@Nullable NodeAddress failedPeer) {
Log.traceCall("failedPeer=" + failedPeer); Log.traceCall("failedPeer=" + failedPeer);
stopRequestDataWithPersistedPeersTimer(); stopRequestDataWithPersistedPeersTimer();
@ -199,11 +199,11 @@ public class RequestDataManager implements MessageListener, AuthenticationListen
boolean persistedPeersAvailable = false; boolean persistedPeersAvailable = false;
if (!remainingPersistedPeers.isEmpty()) { if (!remainingPersistedPeers.isEmpty()) {
Set<Address> persistedPeerAddresses = remainingPersistedPeers.stream().map(e -> e.address).collect(Collectors.toSet()); Set<NodeAddress> persistedPeerNodeAddresses = remainingPersistedPeers.stream().map(e -> e.nodeAddress).collect(Collectors.toSet());
if (!persistedPeerAddresses.isEmpty()) { if (!persistedPeerNodeAddresses.isEmpty()) {
log.info("We try to use persisted peers for requestData."); log.info("We try to use persisted peers for requestData.");
persistedPeersAvailable = true; persistedPeersAvailable = true;
requestData(persistedPeerAddresses); requestData(persistedPeerNodeAddresses);
} }
} }
@ -253,22 +253,22 @@ public class RequestDataManager implements MessageListener, AuthenticationListen
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Override @Override
public void onPeerAuthenticated(Address peerAddress, Connection connection) { public void onPeerAuthenticated(NodeAddress peerNodeAddress, Connection connection) {
optionalConnectedSeedNodeAddress.ifPresent(connectedSeedNodeAddress -> { optionalConnectedSeedNodeAddress.ifPresent(connectedSeedNodeAddress -> {
// We only request the data again if we have initiated the authentication (ConnectionPriority.ACTIVE) // We only request the data again if we have initiated the authentication (ConnectionPriority.ACTIVE)
// We delay a bit to be sure that the authentication state is applied to all listeners // We delay a bit to be sure that the authentication state is applied to all listeners
if (connectedSeedNodeAddress.equals(peerAddress) && connection.getConnectionPriority() == ConnectionPriority.ACTIVE) { if (connectedSeedNodeAddress.equals(peerNodeAddress) && connection.getConnectionPriority() == ConnectionPriority.ACTIVE) {
// We are the node (can be a seed node as well) which requested the authentication // We are the node (can be a seed node as well) which requested the authentication
if (requestDataFromAuthenticatedSeedNodeTimer == null) if (requestDataFromAuthenticatedSeedNodeTimer == null)
requestDataFromAuthenticatedSeedNodeTimer = UserThread.runAfter(() requestDataFromAuthenticatedSeedNodeTimer = UserThread.runAfter(()
-> requestDataFromAuthenticatedSeedNode(peerAddress, connection), 100, TimeUnit.MILLISECONDS); -> requestDataFromAuthenticatedSeedNode(peerNodeAddress, connection), 100, TimeUnit.MILLISECONDS);
} }
}); });
} }
// 5. Step after authentication to first seed node we request again the data // 5. Step after authentication to first seed node we request again the data
protected void requestDataFromAuthenticatedSeedNode(Address peerAddress, Connection connection) { protected void requestDataFromAuthenticatedSeedNode(NodeAddress peerNodeAddress, Connection connection) {
Log.traceCall(peerAddress.toString()); Log.traceCall(peerNodeAddress.toString());
stopRequestDataFromAuthenticatedSeedNodeTimer(); stopRequestDataFromAuthenticatedSeedNodeTimer();
@ -277,21 +277,21 @@ public class RequestDataManager implements MessageListener, AuthenticationListen
Futures.addCallback(future, new FutureCallback<Connection>() { Futures.addCallback(future, new FutureCallback<Connection>() {
@Override @Override
public void onSuccess(@Nullable Connection connection) { public void onSuccess(@Nullable Connection connection) {
log.info("requestDataFromAuthenticatedSeedNode from " + peerAddress + " succeeded."); log.info("requestDataFromAuthenticatedSeedNode from " + peerNodeAddress + " succeeded.");
} }
@Override @Override
public void onFailure(@NotNull Throwable throwable) { public void onFailure(@NotNull Throwable throwable) {
log.warn("requestDataFromAuthenticatedSeedNode from " + peerAddress + " failed. " + log.warn("requestDataFromAuthenticatedSeedNode from " + peerNodeAddress + " failed. " +
"Exception:" + throwable.getMessage() "Exception:" + throwable.getMessage()
+ "\nWe will try again to request data from any of our seed nodes."); + "\nWe will try again to request data from any of our seed nodes.");
// We will try again to request data from any of our seed nodes. // We will try again to request data from any of our seed nodes.
if (seedNodeAddresses != null && !seedNodeAddresses.isEmpty()) if (seedNodeNodeAddresses != null && !seedNodeNodeAddresses.isEmpty())
requestData(seedNodeAddresses); requestData(seedNodeNodeAddresses);
else else
log.error("seedNodeAddresses is null or empty. That must not happen. seedNodeAddresses=" log.error("seedNodeAddresses is null or empty. That must not happen. seedNodeAddresses="
+ seedNodeAddresses); + seedNodeNodeAddresses);
} }
}); });
} }

View file

@ -2,7 +2,7 @@ package io.bitsquare.p2p.peers;
import io.bitsquare.app.Log; import io.bitsquare.app.Log;
import io.bitsquare.common.UserThread; import io.bitsquare.common.UserThread;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.network.NetworkNode; import io.bitsquare.p2p.network.NetworkNode;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -27,8 +27,8 @@ public class SeedNodePeerManager extends PeerManager {
checkArgument(!seedNodeAddressesOptional.get().isEmpty(), checkArgument(!seedNodeAddressesOptional.get().isEmpty(),
"seedNodeAddresses must not be empty"); "seedNodeAddresses must not be empty");
remainingSeedNodes.addAll(seedNodeAddressesOptional.get()); remainingSeedNodes.addAll(seedNodeAddressesOptional.get());
Address peerAddress = getAndRemoveRandomAddress(remainingSeedNodes); NodeAddress peerNodeAddress = getAndRemoveRandomAddress(remainingSeedNodes);
authenticateToFirstSeedNode(peerAddress); authenticateToFirstSeedNode(peerNodeAddress);
startCheckSeedNodeConnectionTask(); startCheckSeedNodeConnectionTask();
} }

View file

@ -1,7 +1,7 @@
package io.bitsquare.p2p.peers; package io.bitsquare.p2p.peers;
import io.bitsquare.common.UserThread; import io.bitsquare.common.UserThread;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.network.Connection; import io.bitsquare.p2p.network.Connection;
import io.bitsquare.p2p.network.NetworkNode; import io.bitsquare.p2p.network.NetworkNode;
import io.bitsquare.p2p.storage.P2PDataStorage; import io.bitsquare.p2p.storage.P2PDataStorage;
@ -18,13 +18,13 @@ public class SeedNodeRequestDataManager extends RequestDataManager {
} }
@Override @Override
public void onPeerAuthenticated(Address peerAddress, Connection connection) { public void onPeerAuthenticated(NodeAddress peerNodeAddress, Connection connection) {
//TODO not clear which use case is handles here... //TODO not clear which use case is handles here...
if (dataStorage.getMap().isEmpty()) { if (dataStorage.getMap().isEmpty()) {
if (requestDataFromAuthenticatedSeedNodeTimer == null) if (requestDataFromAuthenticatedSeedNodeTimer == null)
requestDataFromAuthenticatedSeedNodeTimer = UserThread.runAfterRandomDelay(() requestDataFromAuthenticatedSeedNodeTimer = UserThread.runAfterRandomDelay(()
-> requestDataFromAuthenticatedSeedNode(peerAddress, connection), 2, 5, TimeUnit.SECONDS); -> requestDataFromAuthenticatedSeedNode(peerNodeAddress, connection), 2, 5, TimeUnit.SECONDS);
} }
super.onPeerAuthenticated(peerAddress, connection); super.onPeerAuthenticated(peerNodeAddress, connection);
} }
} }

View file

@ -1,7 +1,7 @@
package io.bitsquare.p2p.peers.messages.auth; package io.bitsquare.p2p.peers.messages.auth;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.peers.ReportedPeer; import io.bitsquare.p2p.peers.ReportedPeer;
import java.util.HashSet; import java.util.HashSet;
@ -14,8 +14,8 @@ public final class AuthenticationChallenge extends AuthenticationMessage {
public final long responderNonce; public final long responderNonce;
public final HashSet<ReportedPeer> reportedPeers; public final HashSet<ReportedPeer> reportedPeers;
public AuthenticationChallenge(Address senderAddress, long requesterNonce, long responderNonce, HashSet<ReportedPeer> reportedPeers) { public AuthenticationChallenge(NodeAddress senderNodeAddress, long requesterNonce, long responderNonce, HashSet<ReportedPeer> reportedPeers) {
super(senderAddress); super(senderNodeAddress);
this.requesterNonce = requesterNonce; this.requesterNonce = requesterNonce;
this.responderNonce = responderNonce; this.responderNonce = responderNonce;
this.reportedPeers = reportedPeers; this.reportedPeers = reportedPeers;

View file

@ -1,7 +1,7 @@
package io.bitsquare.p2p.peers.messages.auth; package io.bitsquare.p2p.peers.messages.auth;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.peers.ReportedPeer; import io.bitsquare.p2p.peers.ReportedPeer;
import java.util.HashSet; import java.util.HashSet;
@ -13,8 +13,8 @@ public final class AuthenticationFinalResponse extends AuthenticationMessage {
public final long responderNonce; public final long responderNonce;
public final HashSet<ReportedPeer> reportedPeers; public final HashSet<ReportedPeer> reportedPeers;
public AuthenticationFinalResponse(Address senderAddress, long responderNonce, HashSet<ReportedPeer> reportedPeers) { public AuthenticationFinalResponse(NodeAddress senderNodeAddress, long responderNonce, HashSet<ReportedPeer> reportedPeers) {
super(senderAddress); super(senderNodeAddress);
this.responderNonce = responderNonce; this.responderNonce = responderNonce;
this.reportedPeers = reportedPeers; this.reportedPeers = reportedPeers;
} }
@ -22,7 +22,7 @@ public final class AuthenticationFinalResponse extends AuthenticationMessage {
@Override @Override
public String toString() { public String toString() {
return "AuthenticationResponse{" + return "AuthenticationResponse{" +
"address=" + senderAddress + "address=" + senderNodeAddress +
", responderNonce=" + responderNonce + ", responderNonce=" + responderNonce +
", reportedPeers=" + reportedPeers + ", reportedPeers=" + reportedPeers +
super.toString() + "} "; super.toString() + "} ";

View file

@ -1,16 +1,16 @@
package io.bitsquare.p2p.peers.messages.auth; package io.bitsquare.p2p.peers.messages.auth;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message; import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
public abstract class AuthenticationMessage implements Message { public abstract class AuthenticationMessage implements Message {
private final int networkId = Version.getNetworkId(); private final int networkId = Version.getNetworkId();
public final Address senderAddress; public final NodeAddress senderNodeAddress;
public AuthenticationMessage(Address senderAddress) { public AuthenticationMessage(NodeAddress senderNodeAddress) {
this.senderAddress = senderAddress; this.senderNodeAddress = senderNodeAddress;
} }
@Override @Override
@ -20,7 +20,7 @@ public abstract class AuthenticationMessage implements Message {
@Override @Override
public String toString() { public String toString() {
return ", address=" + (senderAddress != null ? senderAddress.toString() : "") + return ", address=" + (senderNodeAddress != null ? senderNodeAddress.toString() : "") +
", networkId=" + networkId + ", networkId=" + networkId +
'}'; '}';
} }

View file

@ -1,14 +1,14 @@
package io.bitsquare.p2p.peers.messages.auth; package io.bitsquare.p2p.peers.messages.auth;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
public final class AuthenticationRejection extends AuthenticationMessage { public final class AuthenticationRejection extends AuthenticationMessage {
// That object is sent over the wire, so we need to take care of version compatibility. // That object is sent over the wire, so we need to take care of version compatibility.
private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION; private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION;
public AuthenticationRejection(Address senderAddress) { public AuthenticationRejection(NodeAddress senderNodeAddress) {
super(senderAddress); super(senderNodeAddress);
} }
@Override @Override

View file

@ -1,7 +1,7 @@
package io.bitsquare.p2p.peers.messages.auth; package io.bitsquare.p2p.peers.messages.auth;
import io.bitsquare.app.Version; import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address; import io.bitsquare.p2p.NodeAddress;
public final class AuthenticationRequest extends AuthenticationMessage { public final class AuthenticationRequest extends AuthenticationMessage {
// That object is sent over the wire, so we need to take care of version compatibility. // That object is sent over the wire, so we need to take care of version compatibility.
@ -9,15 +9,15 @@ public final class AuthenticationRequest extends AuthenticationMessage {
public final long requesterNonce; public final long requesterNonce;
public AuthenticationRequest(Address senderAddress, long requesterNonce) { public AuthenticationRequest(NodeAddress senderNodeAddress, long requesterNonce) {
super(senderAddress); super(senderNodeAddress);
this.requesterNonce = requesterNonce; this.requesterNonce = requesterNonce;
} }
@Override @Override
public String toString() { public String toString() {
return "AuthenticationRequest{" + return "AuthenticationRequest{" +
"senderAddress=" + senderAddress + "senderAddress=" + senderNodeAddress +
", requesterNonce=" + requesterNonce + ", requesterNonce=" + requesterNonce +
super.toString() + "} "; super.toString() + "} ";
} }

Some files were not shown because too many files have changed in this diff Show more