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

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

View file

@ -5,17 +5,17 @@ import io.bitsquare.common.crypto.Hash;
import java.io.Serializable;
import java.util.regex.Pattern;
public class Address implements Serializable {
public class NodeAddress implements Serializable {
public final String hostName;
public final int port;
transient private byte[] addressPrefixHash;
public Address(String hostName, int port) {
public NodeAddress(String hostName, int port) {
this.hostName = hostName;
this.port = port;
}
public Address(String fullAddress) {
public NodeAddress(String fullAddress) {
final String[] split = fullAddress.split(Pattern.quote(":"));
this.hostName = split[0];
this.port = Integer.parseInt(split[1]);
@ -35,12 +35,12 @@ public class Address implements Serializable {
@Override
public boolean equals(Object o) {
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;
return !(hostName != null ? !hostName.equals(address.hostName) : address.hostName != null);
if (port != nodeAddress.port) return false;
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<>();
protected final CopyOnWriteArraySet<P2PServiceListener> p2pServiceListeners = new CopyOnWriteArraySet<>();
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<>();
protected final BooleanProperty hiddenServicePublished = new SimpleBooleanProperty();
private final BooleanProperty requestingDataCompleted = new SimpleBooleanProperty();
protected final BooleanProperty notAuthenticated = new SimpleBooleanProperty(true);
private final IntegerProperty numAuthenticatedPeers = new SimpleIntegerProperty(0);
private Address seedNodeOfInitialDataRequest;
private NodeAddress seedNodeOfInitialDataRequest;
private volatile boolean shutDownInProgress;
private boolean shutDownComplete;
@SuppressWarnings("FieldCanBeLocal")
private MonadicBinding<Boolean> readyForAuthenticationBinding;
private final Storage<Address> dbStorage;
private Address myOnionAddress;
private final Storage<NodeAddress> dbStorage;
private NodeAddress myOnionNodeAddress;
protected RequestDataManager requestDataManager;
protected Set<Address> seedNodeAddresses;
protected Set<NodeAddress> seedNodeNodeAddresses;
///////////////////////////////////////////////////////////////////////////////////////////
@ -112,11 +112,11 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
Log.traceCall();
// lets check if we have already stored our onion address
Address persistedOnionAddress = dbStorage.initAndGetPersisted("myOnionAddress");
if (persistedOnionAddress != null)
this.myOnionAddress = persistedOnionAddress;
NodeAddress persistedOnionNodeAddress = dbStorage.initAndGetPersisted("myOnionAddress");
if (persistedOnionNodeAddress != null)
this.myOnionNodeAddress = persistedOnionNodeAddress;
seedNodeAddresses = seedNodesRepository.getSeedNodeAddresses(useLocalhost, networkId);
seedNodeNodeAddresses = seedNodesRepository.getSeedNodeAddresses(useLocalhost, networkId);
// network node
networkNode = useLocalhost ? new LocalhostNetworkNode(port) : new TorNetworkNode(port, torDir);
@ -125,7 +125,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
// peer group
peerManager = getNewPeerManager();
peerManager.setSeedNodeAddresses(seedNodeAddresses);
peerManager.setSeedNodeAddresses(seedNodeNodeAddresses);
peerManager.addAuthenticationListener(this);
// P2P network data storage
@ -146,9 +146,9 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
}
@Override
public void onDataReceived(Address address) {
public void onDataReceived(NodeAddress nodeAddress) {
if (!requestingDataCompleted.get()) {
seedNodeOfInitialDataRequest = address;
seedNodeOfInitialDataRequest = nodeAddress;
requestingDataCompleted.set(true);
}
p2pServiceListeners.stream().forEach(e -> e.onRequestingDataCompleted());
@ -247,20 +247,20 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
@Override
public void onTorNodeReady() {
Log.traceCall();
requestDataManager.requestDataFromSeedNodes(seedNodeAddresses);
requestDataManager.requestDataFromSeedNodes(seedNodeNodeAddresses);
p2pServiceListeners.stream().forEach(e -> e.onTorNodeReady());
}
@Override
public void onHiddenServicePublished() {
Log.traceCall();
checkArgument(networkNode.getAddress() != null, "Address must be set when we have the hidden service ready");
if (myOnionAddress != null) {
checkArgument(networkNode.getAddress().equals(myOnionAddress),
checkArgument(networkNode.getNodeAddress() != null, "Address must be set when we have the hidden service ready");
if (myOnionNodeAddress != null) {
checkArgument(networkNode.getNodeAddress().equals(myOnionNodeAddress),
"If we are a seed node networkNode.getAddress() must be same as myOnionAddress.");
} else {
myOnionAddress = networkNode.getAddress();
dbStorage.queueUpForSave(myOnionAddress);
myOnionNodeAddress = networkNode.getNodeAddress();
dbStorage.queueUpForSave(myOnionNodeAddress);
}
hiddenServicePublished.set(true);
@ -292,8 +292,8 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
@Override
public void onDisconnect(Reason reason, Connection connection) {
Log.traceCall();
connection.getPeerAddressOptional().ifPresent(peerAddresses -> authenticatedPeerAddresses.remove(peerAddresses));
numAuthenticatedPeers.set(authenticatedPeerAddresses.size());
connection.getPeerAddressOptional().ifPresent(peerAddresses -> authenticatedPeerNodeAddresses.remove(peerAddresses));
numAuthenticatedPeers.set(authenticatedPeerNodeAddresses.size());
}
@Override
@ -306,16 +306,16 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
///////////////////////////////////////////////////////////////////////////////////////////
@Override
public void onPeerAuthenticated(Address peerAddress, Connection connection) {
public void onPeerAuthenticated(NodeAddress peerNodeAddress, Connection connection) {
Log.traceCall();
authenticatedPeerAddresses.add(peerAddress);
authenticatedPeerNodeAddresses.add(peerNodeAddress);
if (notAuthenticated.get()) {
notAuthenticated.set(false);
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
///////////////////////////////////////////////////////////////////////////////////////////
public void sendEncryptedMailMessage(Address peerAddress, PubKeyRing pubKeyRing, MailMessage message,
public void sendEncryptedMailMessage(NodeAddress peerNodeAddress, PubKeyRing pubKeyRing, MailMessage message,
SendMailMessageListener sendMailMessageListener) {
Log.traceCall();
checkNotNull(peerAddress, "PeerAddress must not be null (sendEncryptedMailMessage)");
checkNotNull(peerNodeAddress, "PeerAddress must not be null (sendEncryptedMailMessage)");
try {
checkAuthentication();
if (!authenticatedPeerAddresses.contains(peerAddress))
peerManager.authenticateToDirectMessagePeer(peerAddress,
() -> doSendEncryptedMailMessage(peerAddress, pubKeyRing, message, sendMailMessageListener),
if (!authenticatedPeerNodeAddresses.contains(peerNodeAddress))
peerManager.authenticateToDirectMessagePeer(peerNodeAddress,
() -> doSendEncryptedMailMessage(peerNodeAddress, pubKeyRing, message, sendMailMessageListener),
() -> sendMailMessageListener.onFault());
else
doSendEncryptedMailMessage(peerAddress, pubKeyRing, message, sendMailMessageListener);
doSendEncryptedMailMessage(peerNodeAddress, pubKeyRing, message, sendMailMessageListener);
} catch (AuthenticationException e) {
log.error(e.getMessage());
throw new RuntimeException(e);
}
}
private void doSendEncryptedMailMessage(Address peerAddress, PubKeyRing pubKeyRing, MailMessage message,
private void doSendEncryptedMailMessage(NodeAddress peerNodeAddress, PubKeyRing pubKeyRing, MailMessage message,
SendMailMessageListener sendMailMessageListener) {
Log.traceCall();
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={}"
+ "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n", message);
SealedAndSignedMessage sealedAndSignedMessage = new SealedAndSignedMessage(
optionalEncryptionService.get().encryptAndSign(pubKeyRing, message), peerAddress.getAddressPrefixHash());
SettableFuture<Connection> future = networkNode.sendMessage(peerAddress, sealedAndSignedMessage);
optionalEncryptionService.get().encryptAndSign(pubKeyRing, message), peerNodeAddress.getAddressPrefixHash());
SettableFuture<Connection> future = networkNode.sendMessage(peerNodeAddress, sealedAndSignedMessage);
Futures.addCallback(future, new FutureCallback<Connection>() {
@Override
public void onSuccess(@Nullable Connection connection) {
@ -443,14 +443,14 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
sealedAndSignedMessage.sealedAndSigned);
if (decryptedMsgWithPubKey.message instanceof MailboxMessage) {
MailboxMessage mailboxMessage = (MailboxMessage) decryptedMsgWithPubKey.message;
Address senderAddress = mailboxMessage.getSenderAddress();
checkNotNull(senderAddress, "senderAddress must not be null for mailbox messages");
NodeAddress senderNodeAddress = mailboxMessage.getSenderNodeAddress();
checkNotNull(senderNodeAddress, "senderAddress must not be null for mailbox messages");
mailboxMap.put(decryptedMsgWithPubKey, mailboxData);
log.trace("Decryption of SealedAndSignedMessage succeeded. senderAddress="
+ senderAddress + " / my address=" + getAddress());
+ senderNodeAddress + " / my address=" + getAddress());
decryptedMailboxListeners.stream().forEach(
e -> e.onMailboxMessageAdded(decryptedMsgWithPubKey, senderAddress));
e -> e.onMailboxMessageAdded(decryptedMsgWithPubKey, senderNodeAddress));
} else {
log.warn("tryDecryptMailboxData: Expected MailboxMessage but got other type. " +
"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) {
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.get().getPubKeyRing().equals(peersPubKeyRing), "We got own keyring instead of that from peer");
try {
checkAuthentication();
if (authenticatedPeerAddresses.contains(peerAddress)) {
trySendEncryptedMailboxMessage(peerAddress, peersPubKeyRing, message, sendMailboxMessageListener);
if (authenticatedPeerNodeAddresses.contains(peerNodeAddress)) {
trySendEncryptedMailboxMessage(peerNodeAddress, peersPubKeyRing, message, sendMailboxMessageListener);
} else {
peerManager.authenticateToDirectMessagePeer(peerAddress,
() -> trySendEncryptedMailboxMessage(peerAddress, peersPubKeyRing, message, sendMailboxMessageListener),
peerManager.authenticateToDirectMessagePeer(peerNodeAddress,
() -> trySendEncryptedMailboxMessage(peerNodeAddress, peersPubKeyRing, message, sendMailboxMessageListener),
() -> {
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) {
@ -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
private void trySendEncryptedMailboxMessage(Address peerAddress, PubKeyRing peersPubKeyRing,
private void trySendEncryptedMailboxMessage(NodeAddress peerNodeAddress, PubKeyRing peersPubKeyRing,
MailboxMessage message, SendMailboxMessageListener sendMailboxMessageListener) {
Log.traceCall();
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={}"
+ "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n", message);
SealedAndSignedMessage sealedAndSignedMessage = new SealedAndSignedMessage(
optionalEncryptionService.get().encryptAndSign(peersPubKeyRing, message), peerAddress.getAddressPrefixHash());
SettableFuture<Connection> future = networkNode.sendMessage(peerAddress, sealedAndSignedMessage);
optionalEncryptionService.get().encryptAndSign(peersPubKeyRing, message), peerNodeAddress.getAddressPrefixHash());
SettableFuture<Connection> future = networkNode.sendMessage(peerNodeAddress, sealedAndSignedMessage);
Futures.addCallback(future, new FutureCallback<Connection>() {
@Override
public void onSuccess(@Nullable Connection connection) {
@ -516,7 +516,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
log.trace("SendEncryptedMailboxMessage onFailure");
log.debug(throwable.toString());
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();
addMailboxData(new ExpirableMailboxPayload(sealedAndSignedMessage,
optionalKeyRing.get().getSignatureKeyPair().getPublic(),
@ -541,7 +541,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
expirableMailboxPayload,
optionalKeyRing.get().getSignatureKeyPair(),
receiversPublicKey);
dataStorage.add(protectedMailboxData, networkNode.getAddress());
dataStorage.add(protectedMailboxData, networkNode.getNodeAddress());
} catch (AuthenticationException e) {
log.error(e.getMessage());
//TODO check if boolean return type can avoid throwing an exception
@ -568,7 +568,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
expirableMailboxPayload,
optionalKeyRing.get().getSignatureKeyPair(),
receiversPubKey);
dataStorage.removeMailboxData(protectedMailboxData, networkNode.getAddress());
dataStorage.removeMailboxData(protectedMailboxData, networkNode.getNodeAddress());
} catch (CryptoException e) {
log.error("Signing at getDataWithSignedSeqNr failed. That should never happen.");
}
@ -609,9 +609,9 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
checkAuthentication();
ProtectedData protectedData = dataStorage.getDataWithSignedSeqNr(expirablePayload, optionalKeyRing.get().getSignatureKeyPair());
if (rePublish)
return dataStorage.rePublish(protectedData, networkNode.getAddress());
return dataStorage.rePublish(protectedData, networkNode.getNodeAddress());
else
return dataStorage.add(protectedData, networkNode.getAddress());
return dataStorage.add(protectedData, networkNode.getNodeAddress());
} catch (AuthenticationException e) {
log.error(e.getMessage());
return false;
@ -627,7 +627,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
try {
checkAuthentication();
ProtectedData protectedData = dataStorage.getDataWithSignedSeqNr(expirablePayload, optionalKeyRing.get().getSignatureKeyPair());
return dataStorage.remove(protectedData, networkNode.getAddress());
return dataStorage.remove(protectedData, networkNode.getNodeAddress());
} catch (AuthenticationException e) {
log.error(e.getMessage());
return false;
@ -687,12 +687,12 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
return peerManager;
}
public Address getAddress() {
return networkNode.getAddress();
public NodeAddress getAddress() {
return networkNode.getNodeAddress();
}
public Set<Address> getAuthenticatedPeerAddresses() {
return authenticatedPeerAddresses;
public Set<NodeAddress> getAuthenticatedPeerNodeAddresses() {
return authenticatedPeerNodeAddresses;
}
@NotNull
@ -710,8 +710,8 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
///////////////////////////////////////////////////////////////////////////////////////////
private boolean verifyAddressPrefixHash(SealedAndSignedMessage sealedAndSignedMessage) {
if (myOnionAddress != null) {
byte[] blurredAddressHash = myOnionAddress.getAddressPrefixHash();
if (myOnionNodeAddress != null) {
byte[] blurredAddressHash = myOnionNodeAddress.getAddressPrefixHash();
return blurredAddressHash != null &&
Arrays.equals(blurredAddressHash, sealedAndSignedMessage.addressPrefixHash);
} else {
@ -722,7 +722,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
private void checkAuthentication() throws AuthenticationException {
Log.traceCall();
if (authenticatedPeerAddresses.isEmpty())
if (authenticatedPeerNodeAddresses.isEmpty())
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);
public SeedNodeP2PService(SeedNodesRepository seedNodesRepository,
Address mySeedNodeAddress,
NodeAddress mySeedNodeNodeAddress,
File torDir,
boolean useLocalhost,
int networkId,
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
seedNodeAddresses.remove(mySeedNodeAddress);
seedNodeNodeAddresses.remove(mySeedNodeNodeAddress);
}
@Override

View file

@ -1,8 +1,8 @@
package io.bitsquare.p2p.messaging;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.NodeAddress;
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;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.NodeAddress;
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;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.NodeAddress;
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.common.ByteArrayUtils;
import io.bitsquare.common.UserThread;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.Utils;
import io.bitsquare.p2p.network.messages.CloseConnectionMessage;
import org.jetbrains.annotations.Nullable;
@ -56,7 +56,7 @@ public class Connection implements MessageListener {
private ObjectOutputStream objectOutputStream;
// 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 stopped;
@ -170,10 +170,10 @@ public class Connection implements MessageListener {
sharedSpace.reportIllegalRequest(illegalRequest);
}
public synchronized void setPeerAddress(Address peerAddress) {
public synchronized void setPeerAddress(NodeAddress peerNodeAddress) {
Log.traceCall();
checkNotNull(peerAddress, "peerAddress must not be null");
peerAddressOptional = Optional.of(peerAddress);
checkNotNull(peerNodeAddress, "peerAddress must not be null");
peerAddressOptional = Optional.of(peerNodeAddress);
}
@ -193,11 +193,11 @@ public class Connection implements MessageListener {
///////////////////////////////////////////////////////////////////////////////////////////
@Nullable
public synchronized Address getPeerAddress() {
public synchronized NodeAddress getPeerAddress() {
return peerAddressOptional.isPresent() ? peerAddressOptional.get() : null;
}
public synchronized Optional<Address> getPeerAddressOptional() {
public synchronized Optional<NodeAddress> getPeerAddressOptional() {
return peerAddressOptional;
}

View file

@ -9,7 +9,7 @@ import com.msopentech.thali.java.toronionproxy.JavaOnionProxyManager;
import io.bitsquare.app.Log;
import io.bitsquare.common.UserThread;
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.TorNode;
import org.jetbrains.annotations.NotNull;
@ -29,7 +29,7 @@ public class LocalhostNetworkNode extends NetworkNode {
private static volatile int simulateTorDelayTorNode = 100;
private static volatile int simulateTorDelayHiddenService = 500;
private Address address;
private NodeAddress nodeAddress;
public static void setSimulateTorDelayTorNode(int simulateTorDelayTorNode) {
LocalhostNetworkNode.simulateTorDelayTorNode = simulateTorDelayTorNode;
@ -72,7 +72,7 @@ public class LocalhostNetworkNode extends NetworkNode {
log.error("Exception at startServer: " + e.getMessage());
}
address = new Address("localhost", servicePort);
nodeAddress = new NodeAddress("localhost", servicePort);
setupListeners.stream().forEach(e -> e.onHiddenServicePublished());
});
@ -82,15 +82,15 @@ public class LocalhostNetworkNode extends NetworkNode {
@Override
@Nullable
public Address getAddress() {
return address;
public NodeAddress getNodeAddress() {
return nodeAddress;
}
// Called from NetworkNode thread
@Override
protected Socket createSocket(Address peerAddress) throws IOException {
protected Socket createSocket(NodeAddress peerNodeAddress) throws IOException {
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.common.UserThread;
import io.bitsquare.common.util.Utilities;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
@ -63,11 +63,11 @@ public abstract class NetworkNode implements MessageListener, ConnectionListener
abstract public void start(@Nullable SetupListener setupListener);
public SettableFuture<Connection> sendMessage(@NotNull Address peerAddress, Message message) {
Log.traceCall("peerAddress: " + peerAddress + " / message: " + message);
checkNotNull(peerAddress, "peerAddress must not be null");
public SettableFuture<Connection> sendMessage(@NotNull NodeAddress peerNodeAddress, Message message) {
Log.traceCall("peerAddress: " + peerNodeAddress + " / message: " + message);
checkNotNull(peerNodeAddress, "peerAddress must not be null");
Optional<Connection> outboundConnectionOptional = lookupOutboundConnection(peerAddress);
Optional<Connection> outboundConnectionOptional = lookupOutboundConnection(peerNodeAddress);
Connection connection = outboundConnectionOptional.isPresent() ? outboundConnectionOptional.get() : null;
if (connection != null)
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) {
Optional<Connection> inboundConnectionOptional = lookupInboundConnection(peerAddress);
Optional<Connection> inboundConnectionOptional = lookupInboundConnection(peerNodeAddress);
if (inboundConnectionOptional.isPresent()) connection = inboundConnectionOptional.get();
if (connection != null)
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);
} else {
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 boolean[] timeoutOccurred = new boolean[1];
timeoutOccurred[0] = false;
ListenableFuture<Connection> future = executorService.submit(() -> {
Thread.currentThread().setName("NetworkNode:SendMessage-to-" + peerAddress);
Thread.currentThread().setName("NetworkNode:SendMessage-to-" + peerNodeAddress);
try {
// can take a while when using tor
Socket socket = createSocket(peerAddress);
Socket socket = createSocket(peerNodeAddress);
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);
newConnection.setPeerAddress(peerAddress);
newConnection.setPeerAddress(peerNodeAddress);
outBoundConnections.add(newConnection);
log.info("\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" +
"NetworkNode created new outbound connection:"
+ "\npeerAddress=" + peerAddress
+ "\npeerAddress=" + peerNodeAddress
+ "\nconnection.uid=" + newConnection.getUid()
+ "\nmessage=" + message
+ "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n");
@ -333,20 +333,20 @@ public abstract class NetworkNode implements MessageListener, ConnectionListener
executorService.submit(server);
}
private Optional<Connection> lookupOutboundConnection(Address peerAddress) {
private Optional<Connection> lookupOutboundConnection(NodeAddress peerNodeAddress) {
// Log.traceCall("search for " + peerAddress.toString() + " / outBoundConnections " + outBoundConnections);
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);
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
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.common.UserThread;
import io.bitsquare.common.util.Utilities;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.Utils;
import io.nucleo.net.HiddenServiceDescriptor;
import io.nucleo.net.JavaTorNode;
@ -91,19 +91,19 @@ public class TorNetworkNode extends NetworkNode {
@Override
@Nullable
public Address getAddress() {
public NodeAddress getNodeAddress() {
if (hiddenServiceDescriptor != null)
return new Address(hiddenServiceDescriptor.getFullAddress());
return new NodeAddress(hiddenServiceDescriptor.getFullAddress());
else
return null;
}
@Override
protected Socket createSocket(Address peerAddress) throws IOException {
protected Socket createSocket(NodeAddress peerNodeAddress) throws IOException {
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

View file

@ -1,15 +1,15 @@
package io.bitsquare.p2p.network.messages;
import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
public final class CloseConnectionMessage implements Message {
// 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 final int networkId = Version.getNetworkId();
public Address peerAddress;
public NodeAddress peerNodeAddress;
public CloseConnectionMessage() {
}

View file

@ -5,8 +5,8 @@ import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.SettableFuture;
import io.bitsquare.app.Log;
import io.bitsquare.common.UserThread;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.network.Connection;
import io.bitsquare.p2p.network.ConnectionPriority;
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 final NetworkNode networkNode;
private final Address myAddress;
private final Address peerAddress;
private final NodeAddress myNodeAddress;
private final NodeAddress peerNodeAddress;
private final Supplier<Set<ReportedPeer>> authenticatedAndReportedPeersSupplier;
private final BiConsumer<HashSet<ReportedPeer>, Connection> addReportedPeersConsumer;
@ -50,16 +50,16 @@ public class AuthenticationHandshake implements MessageListener {
///////////////////////////////////////////////////////////////////////////////////////////
public AuthenticationHandshake(NetworkNode networkNode,
Address myAddress,
Address peerAddress,
NodeAddress myNodeAddress,
NodeAddress peerNodeAddress,
Supplier<Set<ReportedPeer>> authenticatedAndReportedPeersSupplier,
BiConsumer<HashSet<ReportedPeer>, Connection> addReportedPeersConsumer) {
Log.traceCall("peerAddress " + peerAddress);
Log.traceCall("peerAddress " + peerNodeAddress);
this.authenticatedAndReportedPeersSupplier = authenticatedAndReportedPeersSupplier;
this.addReportedPeersConsumer = addReportedPeersConsumer;
this.networkNode = networkNode;
this.myAddress = myAddress;
this.peerAddress = peerAddress;
this.myNodeAddress = myNodeAddress;
this.peerNodeAddress = peerNodeAddress;
startAuthTs = System.currentTimeMillis();
networkNode.addMessageListener(this);
@ -79,7 +79,7 @@ public class AuthenticationHandshake implements MessageListener {
if (!stopped) {
if (message instanceof AuthenticationMessage) {
// 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());
if (timeoutTimer != null)
@ -90,23 +90,23 @@ public class AuthenticationHandshake implements MessageListener {
AuthenticationChallenge authenticationChallenge = (AuthenticationChallenge) message;
// 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.
connection.setPeerAddress(authenticationChallenge.senderAddress);
connection.setPeerAddress(authenticationChallenge.senderNodeAddress);
// We use the active connectionType if we started the authentication request to another peer
connection.setConnectionPriority(ConnectionPriority.ACTIVE);
log.trace("Received authenticationChallenge from " + peerAddress);
log.trace("Received authenticationChallenge from " + peerNodeAddress);
boolean verified = nonce != 0 && nonce == authenticationChallenge.requesterNonce;
if (verified) {
AuthenticationFinalResponse authenticationFinalResponse = new AuthenticationFinalResponse(myAddress,
AuthenticationFinalResponse authenticationFinalResponse = new AuthenticationFinalResponse(myNodeAddress,
authenticationChallenge.responderNonce,
new HashSet<>(authenticatedAndReportedPeersSupplier.get()));
SettableFuture<Connection> future = networkNode.sendMessage(peerAddress, authenticationFinalResponse);
log.trace("Sent AuthenticationFinalResponse {} to {}", authenticationFinalResponse, peerAddress);
SettableFuture<Connection> future = networkNode.sendMessage(peerNodeAddress, authenticationFinalResponse);
log.trace("Sent AuthenticationFinalResponse {} to {}", authenticationFinalResponse, peerNodeAddress);
Futures.addCallback(future, new FutureCallback<Connection>() {
@Override
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 "
+ (System.currentTimeMillis() - startAuthTs) + " ms.");
completed(connection);
@ -128,17 +128,17 @@ public class AuthenticationHandshake implements MessageListener {
// the current authentication turn gets terminated as well
log.warn("Verification of nonce failed. Maybe we got an old authenticationChallenge " +
"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));
}
} else if (message instanceof AuthenticationFinalResponse) {
// Responding peer
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;
if (verified) {
addReportedPeersConsumer.accept(authenticationFinalResponse.reportedPeers, connection);
log.info("AuthenticationComplete: Peer with address " + peerAddress
log.info("AuthenticationComplete: Peer with address " + peerNodeAddress
+ " authenticated (" + connection.getUid() + "). Took "
+ (System.currentTimeMillis() - startAuthTs) + " ms.");
completed(connection);
@ -149,14 +149,14 @@ public class AuthenticationHandshake implements MessageListener {
// the current authentication turn gets terminated as well
log.warn("Verification of nonce failed. Maybe we got an old authenticationFinalResponse " +
"from a timed out request" +
"\nnonce={} / peerAddress={} / authenticationChallenge={}", nonce, peerAddress, authenticationFinalResponse);
log.warn("Verification of nonce failed. nonce={} / peerAddress={} / authenticationFinalResponse={}", nonce, peerAddress, authenticationFinalResponse);
"\nnonce={} / peerAddress={} / authenticationChallenge={}", nonce, peerNodeAddress, authenticationFinalResponse);
log.warn("Verification of nonce failed. nonce={} / peerAddress={} / authenticationFinalResponse={}", nonce, peerNodeAddress, authenticationFinalResponse);
//failed(new AuthenticationException("Verification of nonce failed. getPeersMessage=" + authenticationFinalResponse + " / nonce=" + nonce));
}
} else if (message instanceof AuthenticationRejection) {
// Any peer
failed(new AuthenticationException("Authentication to peer "
+ ((AuthenticationRejection) message).senderAddress
+ ((AuthenticationRejection) message).senderNodeAddress
+ " rejected because of a race conditions."));
}
}
@ -164,7 +164,7 @@ public class AuthenticationHandshake implements MessageListener {
} else {
// 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. " +
"That can happen because of Thread mapping.", peerAddress);
"That can happen because of Thread mapping.", peerNodeAddress);
log.debug("message={}", message);
log.debug("connection={}", connection);
return;
@ -177,21 +177,21 @@ public class AuthenticationHandshake implements MessageListener {
///////////////////////////////////////////////////////////////////////////////////////////
public SettableFuture<Connection> requestAuthentication() {
Log.traceCall("peerAddress " + peerAddress);
Log.traceCall("peerAddress " + peerNodeAddress);
// Requesting peer
if (stopped) {
// 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());
AuthenticationRequest authenticationRequest = new AuthenticationRequest(myAddress, getAndSetNonce());
SettableFuture<Connection> future = networkNode.sendMessage(peerAddress, authenticationRequest);
AuthenticationRequest authenticationRequest = new AuthenticationRequest(myNodeAddress, getAndSetNonce());
SettableFuture<Connection> future = networkNode.sendMessage(peerNodeAddress, authenticationRequest);
Futures.addCallback(future, new FutureCallback<Connection>() {
@Override
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...
connection.setConnectionPriority(ConnectionPriority.AUTH_REQUEST);
@ -199,7 +199,7 @@ public class AuthenticationHandshake implements MessageListener {
@Override
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());
failed(throwable);
}
@ -209,7 +209,7 @@ public class AuthenticationHandshake implements MessageListener {
timeoutTimer.cancel();
timeoutTimer = UserThread.runAfter(() -> failed(new AuthenticationException("Authentication to peer "
+ peerAddress
+ peerNodeAddress
+ " failed because of a timeout. " +
"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,
Connection connection) {
Log.traceCall("peerAddress " + peerAddress);
Log.traceCall("peerAddress " + peerNodeAddress);
// Responding peer
if (stopped) {
// 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("connection={}", connection);
}
@ -236,7 +236,7 @@ public class AuthenticationHandshake implements MessageListener {
resultFutureOptional = Optional.of(SettableFuture.create());
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(() -> {
if (shutDownTimer != null)
@ -246,14 +246,14 @@ public class AuthenticationHandshake implements MessageListener {
if (!stopped) {
// we delay a bit as listeners for connection.onDisconnect are on other threads and might lead to
// 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.
AuthenticationChallenge authenticationChallenge = new AuthenticationChallenge(myAddress,
AuthenticationChallenge authenticationChallenge = new AuthenticationChallenge(myNodeAddress,
authenticationRequest.requesterNonce,
getAndSetNonce(),
new HashSet<>(authenticatedAndReportedPeersSupplier.get()));
SettableFuture<Connection> future = networkNode.sendMessage(peerAddress, authenticationChallenge);
SettableFuture<Connection> future = networkNode.sendMessage(peerNodeAddress, authenticationChallenge);
Futures.addCallback(future, new FutureCallback<Connection>() {
@Override
public void onSuccess(Connection connection) {
@ -266,7 +266,7 @@ public class AuthenticationHandshake implements MessageListener {
@Override
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);
}
});
@ -275,14 +275,14 @@ public class AuthenticationHandshake implements MessageListener {
timeoutTimer.cancel();
timeoutTimer = UserThread.runAfter(() -> failed(new AuthenticationException("Authentication of peer "
+ peerAddress
+ peerNodeAddress
+ " failed because of a timeout. " +
"We did not get an AuthenticationFinalResponse message responded after 30 sec.\n" +
"")), 30, TimeUnit.SECONDS);
} else {
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
});
@ -294,10 +294,10 @@ public class AuthenticationHandshake implements MessageListener {
// Cancel
///////////////////////////////////////////////////////////////////////////////////////////
public void cancel(Address peerAddress) {
public void cancel(NodeAddress peerNodeAddress) {
Log.traceCall();
failed(new AuthenticationException("Authentication to peer "
+ peerAddress
+ peerNodeAddress
+ " canceled because of a race conditions."));
}
@ -343,7 +343,7 @@ public class AuthenticationHandshake implements MessageListener {
}
private void shutDown() {
Log.traceCall("peerAddress = " + peerAddress);
Log.traceCall("peerAddress = " + peerNodeAddress);
stopped = true;
if (timeoutTimer != null)

View file

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

View file

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

View file

@ -1,7 +1,7 @@
package io.bitsquare.p2p.peers;
import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.NodeAddress;
import java.io.Serializable;
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.
private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION;
public final Address address;
public final NodeAddress nodeAddress;
public final Date lastActivityDate;
public ReportedPeer(Address address, Date lastActivityDate) {
this.address = address;
public ReportedPeer(NodeAddress nodeAddress, Date lastActivityDate) {
this.nodeAddress = nodeAddress;
this.lastActivityDate = lastActivityDate;
}
public ReportedPeer(Address address) {
this(address, null);
public ReportedPeer(NodeAddress nodeAddress) {
this(nodeAddress, null);
}
// We don't use the lastActivityDate for identity
@ -30,20 +30,20 @@ public class ReportedPeer implements Serializable {
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
@Override
public int hashCode() {
return address != null ? address.hashCode() : 0;
return nodeAddress != null ? nodeAddress.hashCode() : 0;
}
@Override
public String toString() {
return "ReportedPeer{" +
"address=" + address +
"address=" + nodeAddress +
", lastActivityDate=" + lastActivityDate +
'}';
}

View file

@ -5,8 +5,8 @@ import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.SettableFuture;
import io.bitsquare.app.Log;
import io.bitsquare.common.UserThread;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.network.Connection;
import io.bitsquare.p2p.network.ConnectionPriority;
import io.bitsquare.p2p.network.MessageListener;
@ -40,7 +40,7 @@ public class RequestDataManager implements MessageListener, AuthenticationListen
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> remainingPersistedPeers = new HashSet<>();
private Listener listener;
private Optional<Address> optionalConnectedSeedNodeAddress = Optional.empty();
private Collection<Address> seedNodeAddresses;
private Optional<NodeAddress> optionalConnectedSeedNodeAddress = Optional.empty();
private Collection<NodeAddress> seedNodeNodeAddresses;
protected Timer requestDataFromAuthenticatedSeedNodeTimer;
private Timer requestDataTimer, requestDataWithPersistedPeersTimer;
private boolean doNotifyNoSeedNodeAvailableListener = true;
@ -88,23 +88,23 @@ public class RequestDataManager implements MessageListener, AuthenticationListen
this.listener = listener;
}
public void requestDataFromSeedNodes(Collection<Address> seedNodeAddresses) {
checkNotNull(seedNodeAddresses, "requestDataFromSeedNodes: seedNodeAddresses must not be null.");
checkArgument(!seedNodeAddresses.isEmpty(), "requestDataFromSeedNodes: seedNodeAddresses must not be empty.");
public void requestDataFromSeedNodes(Collection<NodeAddress> seedNodeNodeAddresses) {
checkNotNull(seedNodeNodeAddresses, "requestDataFromSeedNodes: seedNodeAddresses must not be null.");
checkArgument(!seedNodeNodeAddresses.isEmpty(), "requestDataFromSeedNodes: seedNodeAddresses must not be empty.");
this.seedNodeAddresses = seedNodeAddresses;
requestData(seedNodeAddresses);
this.seedNodeNodeAddresses = seedNodeNodeAddresses;
requestData(seedNodeNodeAddresses);
}
private void requestData(Collection<Address> addresses) {
Log.traceCall(addresses.toString());
checkArgument(!addresses.isEmpty(), "requestData: addresses must not be empty.");
private void requestData(Collection<NodeAddress> nodeAddresses) {
Log.traceCall(nodeAddresses.toString());
checkArgument(!nodeAddresses.isEmpty(), "requestData: addresses must not be empty.");
stopRequestDataTimer();
List<Address> remainingAddresses = new ArrayList<>(addresses);
Address candidate = remainingAddresses.get(new Random().nextInt(remainingAddresses.size()));
List<NodeAddress> remainingNodeAddresses = new ArrayList<>(nodeAddresses);
NodeAddress candidate = remainingNodeAddresses.get(new Random().nextInt(remainingNodeAddresses.size()));
if (!peerManager.isInAuthenticationProcess(candidate)) {
// 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);
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. " +
"Exception:" + throwable.getMessage());
if (!remainingAddresses.isEmpty()) {
if (!remainingNodeAddresses.isEmpty()) {
log.info("There are more seed nodes available for requesting data. " +
"We will try requestData again.");
@ -133,7 +133,7 @@ public class RequestDataManager implements MessageListener, AuthenticationListen
if (remainingPersistedPeers.contains(reportedPeer))
remainingPersistedPeers.remove(reportedPeer);
requestData(remainingAddresses);
requestData(remainingNodeAddresses);
} else {
log.info("There is no seed node available for requesting data. " +
"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" +
"We will try requestData again with the remaining addresses.", candidate);
remainingAddresses.remove(candidate);
if (!remainingAddresses.isEmpty()) {
requestData(remainingAddresses);
remainingNodeAddresses.remove(candidate);
if (!remainingNodeAddresses.isEmpty()) {
requestData(remainingNodeAddresses);
} else {
log.info("The node ({}) is in the process of authentication.\n" +
"There are no more remaining addresses available.\n" +
@ -176,11 +176,11 @@ public class RequestDataManager implements MessageListener, AuthenticationListen
listener.onNoSeedNodeAvailable();
}
if (requestDataTimer == null)
requestDataTimer = UserThread.runAfterRandomDelay(() -> requestData(seedNodeAddresses),
requestDataTimer = UserThread.runAfterRandomDelay(() -> requestData(seedNodeNodeAddresses),
10, 20, TimeUnit.SECONDS);
}
private void requestDataWithPersistedPeers(@Nullable Address failedPeer) {
private void requestDataWithPersistedPeers(@Nullable NodeAddress failedPeer) {
Log.traceCall("failedPeer=" + failedPeer);
stopRequestDataWithPersistedPeersTimer();
@ -199,11 +199,11 @@ public class RequestDataManager implements MessageListener, AuthenticationListen
boolean persistedPeersAvailable = false;
if (!remainingPersistedPeers.isEmpty()) {
Set<Address> persistedPeerAddresses = remainingPersistedPeers.stream().map(e -> e.address).collect(Collectors.toSet());
if (!persistedPeerAddresses.isEmpty()) {
Set<NodeAddress> persistedPeerNodeAddresses = remainingPersistedPeers.stream().map(e -> e.nodeAddress).collect(Collectors.toSet());
if (!persistedPeerNodeAddresses.isEmpty()) {
log.info("We try to use persisted peers for requestData.");
persistedPeersAvailable = true;
requestData(persistedPeerAddresses);
requestData(persistedPeerNodeAddresses);
}
}
@ -253,22 +253,22 @@ public class RequestDataManager implements MessageListener, AuthenticationListen
///////////////////////////////////////////////////////////////////////////////////////////
@Override
public void onPeerAuthenticated(Address peerAddress, Connection connection) {
public void onPeerAuthenticated(NodeAddress peerNodeAddress, Connection connection) {
optionalConnectedSeedNodeAddress.ifPresent(connectedSeedNodeAddress -> {
// 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
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
if (requestDataFromAuthenticatedSeedNodeTimer == null)
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
protected void requestDataFromAuthenticatedSeedNode(Address peerAddress, Connection connection) {
Log.traceCall(peerAddress.toString());
protected void requestDataFromAuthenticatedSeedNode(NodeAddress peerNodeAddress, Connection connection) {
Log.traceCall(peerNodeAddress.toString());
stopRequestDataFromAuthenticatedSeedNodeTimer();
@ -277,21 +277,21 @@ public class RequestDataManager implements MessageListener, AuthenticationListen
Futures.addCallback(future, new FutureCallback<Connection>() {
@Override
public void onSuccess(@Nullable Connection connection) {
log.info("requestDataFromAuthenticatedSeedNode from " + peerAddress + " succeeded.");
log.info("requestDataFromAuthenticatedSeedNode from " + peerNodeAddress + " succeeded.");
}
@Override
public void onFailure(@NotNull Throwable throwable) {
log.warn("requestDataFromAuthenticatedSeedNode from " + peerAddress + " failed. " +
log.warn("requestDataFromAuthenticatedSeedNode from " + peerNodeAddress + " failed. " +
"Exception:" + throwable.getMessage()
+ "\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.
if (seedNodeAddresses != null && !seedNodeAddresses.isEmpty())
requestData(seedNodeAddresses);
if (seedNodeNodeAddresses != null && !seedNodeNodeAddresses.isEmpty())
requestData(seedNodeNodeAddresses);
else
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.common.UserThread;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.network.NetworkNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -27,8 +27,8 @@ public class SeedNodePeerManager extends PeerManager {
checkArgument(!seedNodeAddressesOptional.get().isEmpty(),
"seedNodeAddresses must not be empty");
remainingSeedNodes.addAll(seedNodeAddressesOptional.get());
Address peerAddress = getAndRemoveRandomAddress(remainingSeedNodes);
authenticateToFirstSeedNode(peerAddress);
NodeAddress peerNodeAddress = getAndRemoveRandomAddress(remainingSeedNodes);
authenticateToFirstSeedNode(peerNodeAddress);
startCheckSeedNodeConnectionTask();
}

View file

@ -1,7 +1,7 @@
package io.bitsquare.p2p.peers;
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.NetworkNode;
import io.bitsquare.p2p.storage.P2PDataStorage;
@ -18,13 +18,13 @@ public class SeedNodeRequestDataManager extends RequestDataManager {
}
@Override
public void onPeerAuthenticated(Address peerAddress, Connection connection) {
public void onPeerAuthenticated(NodeAddress peerNodeAddress, Connection connection) {
//TODO not clear which use case is handles here...
if (dataStorage.getMap().isEmpty()) {
if (requestDataFromAuthenticatedSeedNodeTimer == null)
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;
import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.peers.ReportedPeer;
import java.util.HashSet;
@ -14,8 +14,8 @@ public final class AuthenticationChallenge extends AuthenticationMessage {
public final long responderNonce;
public final HashSet<ReportedPeer> reportedPeers;
public AuthenticationChallenge(Address senderAddress, long requesterNonce, long responderNonce, HashSet<ReportedPeer> reportedPeers) {
super(senderAddress);
public AuthenticationChallenge(NodeAddress senderNodeAddress, long requesterNonce, long responderNonce, HashSet<ReportedPeer> reportedPeers) {
super(senderNodeAddress);
this.requesterNonce = requesterNonce;
this.responderNonce = responderNonce;
this.reportedPeers = reportedPeers;

View file

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

View file

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

View file

@ -1,14 +1,14 @@
package io.bitsquare.p2p.peers.messages.auth;
import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.NodeAddress;
public final class AuthenticationRejection extends AuthenticationMessage {
// 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;
public AuthenticationRejection(Address senderAddress) {
super(senderAddress);
public AuthenticationRejection(NodeAddress senderNodeAddress) {
super(senderNodeAddress);
}
@Override

View file

@ -1,7 +1,7 @@
package io.bitsquare.p2p.peers.messages.auth;
import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.NodeAddress;
public final class AuthenticationRequest extends AuthenticationMessage {
// 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 AuthenticationRequest(Address senderAddress, long requesterNonce) {
super(senderAddress);
public AuthenticationRequest(NodeAddress senderNodeAddress, long requesterNonce) {
super(senderNodeAddress);
this.requesterNonce = requesterNonce;
}
@Override
public String toString() {
return "AuthenticationRequest{" +
"senderAddress=" + senderAddress +
"senderAddress=" + senderNodeAddress +
", requesterNonce=" + requesterNonce +
super.toString() + "} ";
}

View file

@ -1,7 +1,7 @@
package io.bitsquare.p2p.peers.messages.peers;
import io.bitsquare.app.Version;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.peers.ReportedPeer;
import java.util.HashSet;
@ -10,18 +10,18 @@ public final class GetPeersRequest extends PeerExchangeMessage {
// 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;
public final Address senderAddress;
public final NodeAddress senderNodeAddress;
public final HashSet<ReportedPeer> reportedPeers;
public GetPeersRequest(Address senderAddress, HashSet<ReportedPeer> reportedPeers) {
this.senderAddress = senderAddress;
public GetPeersRequest(NodeAddress senderNodeAddress, HashSet<ReportedPeer> reportedPeers) {
this.senderNodeAddress = senderNodeAddress;
this.reportedPeers = reportedPeers;
}
@Override
public String toString() {
return "GetPeersRequest{" +
"senderAddress=" + senderAddress +
"senderAddress=" + senderNodeAddress +
", reportedPeers=" + reportedPeers +
super.toString() + "} ";
}

View file

@ -4,7 +4,7 @@ import com.google.common.annotations.VisibleForTesting;
import io.bitsquare.app.Log;
import io.bitsquare.app.Version;
import io.bitsquare.common.UserThread;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.P2PService;
import io.bitsquare.p2p.P2PServiceListener;
import io.bitsquare.p2p.SeedNodeP2PService;
@ -26,9 +26,9 @@ import static com.google.common.base.Preconditions.checkArgument;
public class SeedNode {
private static final Logger log = LoggerFactory.getLogger(SeedNode.class);
private Address mySeedNodeAddress = new Address("localhost:8001");
private NodeAddress mySeedNodeNodeAddress = new NodeAddress("localhost:8001");
private boolean useLocalhost = false;
private Set<Address> progArgSeedNodes;
private Set<NodeAddress> progArgSeedNodes;
private SeedNodeP2PService seedNodeP2PService;
private boolean stopped;
private final String defaultUserDataDir;
@ -54,7 +54,7 @@ public class SeedNode {
if (args.length > 0) {
String arg0 = args[0];
checkArgument(arg0.contains(":") && arg0.split(":").length == 2 && arg0.split(":")[1].length() > 3, "Wrong program argument: " + arg0);
mySeedNodeAddress = new Address(arg0);
mySeedNodeNodeAddress = new NodeAddress(arg0);
if (args.length > 1) {
String arg1 = args[1];
int networkId = Integer.parseInt(arg1);
@ -84,9 +84,9 @@ public class SeedNode {
list.forEach(e -> {
checkArgument(e.contains(":") && e.split(":").length == 2 && e.split(":")[1].length() == 4,
"Wrong program argument");
progArgSeedNodes.add(new Address(e));
progArgSeedNodes.add(new NodeAddress(e));
});
progArgSeedNodes.remove(mySeedNodeAddress);
progArgSeedNodes.remove(mySeedNodeNodeAddress);
} else if (args.length > 5) {
log.error("Too many program arguments." +
"\nProgram arguments: myAddress (incl. port) bitcoinNetworkId " +
@ -100,20 +100,20 @@ public class SeedNode {
}
public void createAndStartP2PService(boolean useDetailedLogging) {
createAndStartP2PService(mySeedNodeAddress, useLocalhost, Version.getNetworkId(), useDetailedLogging, progArgSeedNodes, null);
createAndStartP2PService(mySeedNodeNodeAddress, useLocalhost, Version.getNetworkId(), useDetailedLogging, progArgSeedNodes, null);
}
@VisibleForTesting
public void createAndStartP2PService(Address mySeedNodeAddress,
public void createAndStartP2PService(NodeAddress mySeedNodeNodeAddress,
boolean useLocalhost,
int networkId,
boolean useDetailedLogging,
@Nullable Set<Address> progArgSeedNodes,
@Nullable Set<NodeAddress> progArgSeedNodes,
@Nullable P2PServiceListener listener) {
Log.traceCall();
Path appPath = Paths.get(defaultUserDataDir,
"Bitsquare_seed_node_" + String.valueOf(mySeedNodeAddress.getFullAddress().replace(":", "_")));
"Bitsquare_seed_node_" + String.valueOf(mySeedNodeNodeAddress.getFullAddress().replace(":", "_")));
String logPath = Paths.get(appPath.toString(), "logs").toString();
Log.setup(logPath, useDetailedLogging);
@ -122,9 +122,9 @@ public class SeedNode {
SeedNodesRepository seedNodesRepository = new SeedNodesRepository();
if (progArgSeedNodes != null && !progArgSeedNodes.isEmpty()) {
if (useLocalhost)
seedNodesRepository.setLocalhostSeedNodeAddresses(progArgSeedNodes);
seedNodesRepository.setLocalhostSeedNodeNodeAddresses(progArgSeedNodes);
else
seedNodesRepository.setTorSeedNodeAddresses(progArgSeedNodes);
seedNodesRepository.setTorSeedNodeNodeAddresses(progArgSeedNodes);
}
File storageDir = Paths.get(appPath.toString(), "db").toFile();
@ -135,7 +135,7 @@ public class SeedNode {
if (torDir.mkdirs())
log.info("Created torDir at " + torDir.getAbsolutePath());
seedNodeP2PService = new SeedNodeP2PService(seedNodesRepository, mySeedNodeAddress, torDir, useLocalhost, networkId, storageDir);
seedNodeP2PService = new SeedNodeP2PService(seedNodesRepository, mySeedNodeNodeAddress, torDir, useLocalhost, networkId, storageDir);
seedNodeP2PService.start(listener);
}

View file

@ -1,7 +1,7 @@
package io.bitsquare.p2p.seed;
import com.google.common.collect.Sets;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.NodeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -14,55 +14,55 @@ public class SeedNodesRepository {
// mainnet use port 8000
// testnet use port 8001
// regtest use port 8002
private Set<Address> torSeedNodeAddresses = Sets.newHashSet(
private Set<NodeAddress> torSeedNodeNodeAddresses = Sets.newHashSet(
// mainnet
new Address("lih5zsr2bvxi24pk.onion:8000"),
new Address("s5xpstlooosehtxm.onion:8000"),
new Address("izs5oz7i5ta7c2ir.onion:8000"),
new NodeAddress("lih5zsr2bvxi24pk.onion:8000"),
new NodeAddress("s5xpstlooosehtxm.onion:8000"),
new NodeAddress("izs5oz7i5ta7c2ir.onion:8000"),
// testnet
new Address("znmy44wcstn2rkva.onion:8001"),
new Address("zvn7umikgxml6x6h.onion:8001"),
new Address("wnfxmrmsyeeos2dy.onion:8001"),
new NodeAddress("znmy44wcstn2rkva.onion:8001"),
new NodeAddress("zvn7umikgxml6x6h.onion:8001"),
new NodeAddress("wnfxmrmsyeeos2dy.onion:8001"),
// regtest
new Address("rxdkppp3vicnbgqt.onion:8002"),
new Address("brmbf6mf67d2hlm4.onion:8002"),
new Address("mfla72c4igh5ta2t.onion:8002")
new NodeAddress("rxdkppp3vicnbgqt.onion:8002"),
new NodeAddress("brmbf6mf67d2hlm4.onion:8002"),
new NodeAddress("mfla72c4igh5ta2t.onion:8002")
);
private Set<Address> localhostSeedNodeAddresses = Sets.newHashSet(
private Set<NodeAddress> localhostSeedNodeNodeAddresses = Sets.newHashSet(
// mainnet
new Address("localhost:2000"),
new Address("localhost:3000"),
new Address("localhost:4000"),
new NodeAddress("localhost:2000"),
new NodeAddress("localhost:3000"),
new NodeAddress("localhost:4000"),
// testnet
new Address("localhost:2001"),
new Address("localhost:3001"),
new Address("localhost:4001"),
new NodeAddress("localhost:2001"),
new NodeAddress("localhost:3001"),
new NodeAddress("localhost:4001"),
// regtest
new Address("localhost:2002"),
new Address("localhost:3002"),
new Address("localhost:4002")
new NodeAddress("localhost:2002"),
new NodeAddress("localhost:3002"),
new NodeAddress("localhost:4002")
);
public Set<Address> getSeedNodeAddresses(boolean useLocalhost, int networkId) {
public Set<NodeAddress> getSeedNodeAddresses(boolean useLocalhost, int networkId) {
String networkIdAsString = String.valueOf(networkId);
Set<Address> addresses = useLocalhost ? localhostSeedNodeAddresses : torSeedNodeAddresses;
Set<Address> filtered = addresses.stream()
Set<NodeAddress> nodeAddresses = useLocalhost ? localhostSeedNodeNodeAddresses : torSeedNodeNodeAddresses;
Set<NodeAddress> filtered = nodeAddresses.stream()
.filter(e -> String.valueOf(e.port).endsWith(networkIdAsString)).collect(Collectors.toSet());
log.info("SeedNodeAddresses (useLocalhost={}) for networkId {}:\nnetworkId={}", useLocalhost, networkId, filtered);
return filtered;
}
public void setTorSeedNodeAddresses(Set<Address> torSeedNodeAddresses) {
this.torSeedNodeAddresses = torSeedNodeAddresses;
public void setTorSeedNodeNodeAddresses(Set<NodeAddress> torSeedNodeNodeAddresses) {
this.torSeedNodeNodeAddresses = torSeedNodeNodeAddresses;
}
public void setLocalhostSeedNodeAddresses(Set<Address> localhostSeedNodeAddresses) {
this.localhostSeedNodeAddresses = localhostSeedNodeAddresses;
public void setLocalhostSeedNodeNodeAddresses(Set<NodeAddress> localhostSeedNodeNodeAddresses) {
this.localhostSeedNodeNodeAddresses = localhostSeedNodeNodeAddresses;
}
}

View file

@ -9,8 +9,8 @@ import io.bitsquare.common.crypto.CryptoException;
import io.bitsquare.common.crypto.Hash;
import io.bitsquare.common.crypto.Sig;
import io.bitsquare.common.util.Utilities;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.network.Connection;
import io.bitsquare.p2p.network.IllegalRequest;
import io.bitsquare.p2p.network.MessageListener;
@ -134,17 +134,17 @@ public class P2PDataStorage implements MessageListener {
MoreExecutors.shutdownAndAwaitTermination(removeExpiredEntriesExecutor, 500, TimeUnit.MILLISECONDS);
}
public boolean add(ProtectedData protectedData, @Nullable Address sender) {
public boolean add(ProtectedData protectedData, @Nullable NodeAddress sender) {
Log.traceCall();
return doAdd(protectedData, sender, false);
}
public boolean rePublish(ProtectedData protectedData, @Nullable Address sender) {
public boolean rePublish(ProtectedData protectedData, @Nullable NodeAddress sender) {
Log.traceCall();
return doAdd(protectedData, sender, true);
}
private boolean doAdd(ProtectedData protectedData, @Nullable Address sender, boolean rePublish) {
private boolean doAdd(ProtectedData protectedData, @Nullable NodeAddress sender, boolean rePublish) {
Log.traceCall();
ByteArray hashOfPayload = getHashAsByteArray(protectedData.expirablePayload);
boolean result = checkPublicKeys(protectedData, true)
@ -184,7 +184,7 @@ public class P2PDataStorage implements MessageListener {
return result;
}
public boolean remove(ProtectedData protectedData, @Nullable Address sender) {
public boolean remove(ProtectedData protectedData, @Nullable NodeAddress sender) {
Log.traceCall();
ByteArray hashOfPayload = getHashAsByteArray(protectedData.expirablePayload);
boolean containsKey = map.containsKey(hashOfPayload);
@ -209,7 +209,7 @@ public class P2PDataStorage implements MessageListener {
return result;
}
public boolean removeMailboxData(ProtectedMailboxData protectedMailboxData, @Nullable Address sender) {
public boolean removeMailboxData(ProtectedMailboxData protectedMailboxData, @Nullable NodeAddress sender) {
Log.traceCall();
ByteArray hashOfData = getHashAsByteArray(protectedMailboxData.expirablePayload);
boolean containsKey = map.containsKey(hashOfData);
@ -368,7 +368,7 @@ public class P2PDataStorage implements MessageListener {
}
}
private void broadcast(DataBroadcastMessage message, @Nullable Address sender) {
private void broadcast(DataBroadcastMessage message, @Nullable NodeAddress sender) {
Log.traceCall(message.toString());
peerManager.broadcast(message, sender);
}

View file

@ -21,7 +21,7 @@ package io.bitsquare.crypto;
import io.bitsquare.app.Version;
import io.bitsquare.common.crypto.*;
import io.bitsquare.common.util.Utilities;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.messaging.DecryptedMsgWithPubKey;
import io.bitsquare.p2p.messaging.MailboxMessage;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
@ -88,7 +88,7 @@ final class TestMessage implements MailboxMessage {
}
@Override
public Address getSenderAddress() {
public NodeAddress getSenderNodeAddress() {
return null;
}

View file

@ -37,7 +37,7 @@ public class P2PServiceTest {
private static final Logger log = LoggerFactory.getLogger(P2PServiceTest.class);
boolean useLocalhost = true;
private Set<Address> seedNodes;
private Set<NodeAddress> seedNodes;
private int sleepTime;
private KeyRing keyRing1, keyRing2, keyRing3;
private EncryptionService encryptionService1, encryptionService2, encryptionService3;
@ -71,15 +71,15 @@ public class P2PServiceTest {
seedNodes = new HashSet<>();
if (useLocalhost) {
seedNodes.add(new Address("localhost:8001"));
seedNodes.add(new Address("localhost:8002"));
seedNodes.add(new Address("localhost:8003"));
seedNodes.add(new NodeAddress("localhost:8001"));
seedNodes.add(new NodeAddress("localhost:8002"));
seedNodes.add(new NodeAddress("localhost:8003"));
sleepTime = 100;
} else {
seedNodes.add(new Address("3omjuxn7z73pxoee.onion:8001"));
seedNodes.add(new Address("j24fxqyghjetgpdx.onion:8002"));
seedNodes.add(new Address("45367tl6unwec6kw.onion:8003"));
seedNodes.add(new NodeAddress("3omjuxn7z73pxoee.onion:8001"));
seedNodes.add(new NodeAddress("j24fxqyghjetgpdx.onion:8002"));
seedNodes.add(new NodeAddress("45367tl6unwec6kw.onion:8003"));
sleepTime = 1000;
}
@ -290,7 +290,7 @@ public class P2PServiceTest {
SealedAndSignedMessage sealedAndSignedMessage = (SealedAndSignedMessage) message;
DecryptedMsgWithPubKey decryptedMsgWithPubKey = encryptionService2.decryptAndVerify(sealedAndSignedMessage.sealedAndSigned);
Assert.assertEquals(mockMessage, decryptedMsgWithPubKey.message);
Assert.assertEquals(p2PService2.getAddress(), ((MailboxMessage) decryptedMsgWithPubKey.message).getSenderAddress());
Assert.assertEquals(p2PService2.getAddress(), ((MailboxMessage) decryptedMsgWithPubKey.message).getSenderNodeAddress());
latch2.countDown();
} catch (CryptoException e) {
e.printStackTrace();
@ -335,7 +335,7 @@ public class P2PServiceTest {
);
CountDownLatch latch2 = new CountDownLatch(1);
p2PService2.sendEncryptedMailboxMessage(
new Address("localhost:8003"),
new NodeAddress("localhost:8003"),
keyRing3.getPubKeyRing(),
mockMessage,
new SendMailboxMessageListener() {
@ -367,7 +367,7 @@ public class P2PServiceTest {
p2PService3.addDecryptedMailboxListener((decryptedMessageWithPubKey, senderAddress) -> {
log.debug("decryptedMessageWithPubKey " + decryptedMessageWithPubKey.toString());
Assert.assertEquals(mockMessage, decryptedMessageWithPubKey.message);
Assert.assertEquals(p2PService2.getAddress(), ((MailboxMessage) decryptedMessageWithPubKey.message).getSenderAddress());
Assert.assertEquals(p2PService2.getAddress(), ((MailboxMessage) decryptedMessageWithPubKey.message).getSenderNodeAddress());
latch3.countDown();
});
latch3.await();

View file

@ -62,25 +62,25 @@ public class TestUtils {
return result;
}
public static SeedNode getAndStartSeedNode(int port, boolean useLocalhost, Set<Address> seedNodes) throws InterruptedException {
public static SeedNode getAndStartSeedNode(int port, boolean useLocalhost, Set<NodeAddress> seedNodes) throws InterruptedException {
SeedNode seedNode;
if (useLocalhost) {
seedNodes.add(new Address("localhost:8001"));
seedNodes.add(new Address("localhost:8002"));
seedNodes.add(new Address("localhost:8003"));
seedNodes.add(new NodeAddress("localhost:8001"));
seedNodes.add(new NodeAddress("localhost:8002"));
seedNodes.add(new NodeAddress("localhost:8003"));
sleepTime = 100;
seedNode = new SeedNode("test_dummy_dir");
} else {
seedNodes.add(new Address("3omjuxn7z73pxoee.onion:8001"));
seedNodes.add(new Address("j24fxqyghjetgpdx.onion:8002"));
seedNodes.add(new Address("45367tl6unwec6kw.onion:8003"));
seedNodes.add(new NodeAddress("3omjuxn7z73pxoee.onion:8001"));
seedNodes.add(new NodeAddress("j24fxqyghjetgpdx.onion:8002"));
seedNodes.add(new NodeAddress("45367tl6unwec6kw.onion:8003"));
sleepTime = 10000;
seedNode = new SeedNode("test_dummy_dir");
}
CountDownLatch latch = new CountDownLatch(1);
seedNode.createAndStartP2PService(new Address("localhost", port), useLocalhost, 2, true,
seedNode.createAndStartP2PService(new NodeAddress("localhost", port), useLocalhost, 2, true,
seedNodes, new P2PServiceListener() {
@Override
public void onRequestingDataCompleted() {
@ -117,15 +117,15 @@ public class TestUtils {
}
public static P2PService getAndAuthenticateP2PService(int port, EncryptionService encryptionService, KeyRing keyRing,
boolean useLocalhost, Set<Address> seedNodes)
boolean useLocalhost, Set<NodeAddress> seedNodes)
throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
SeedNodesRepository seedNodesRepository = new SeedNodesRepository();
if (seedNodes != null && !seedNodes.isEmpty()) {
if (useLocalhost)
seedNodesRepository.setLocalhostSeedNodeAddresses(seedNodes);
seedNodesRepository.setLocalhostSeedNodeNodeAddresses(seedNodes);
else
seedNodesRepository.setTorSeedNodeAddresses(seedNodes);
seedNodesRepository.setTorSeedNodeNodeAddresses(seedNodes);
}
P2PService p2PService = new P2PService(seedNodesRepository, port, new File("seed_node_" + port), useLocalhost,

View file

@ -1,19 +1,19 @@
package io.bitsquare.p2p.mocks;
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.storage.data.ExpirablePayload;
public final class MockMailboxMessage implements MailboxMessage, ExpirablePayload {
private final int networkId = Version.getNetworkId();
public String msg;
public Address senderAddress;
public NodeAddress senderNodeAddress;
public long ttl;
public MockMailboxMessage(String msg, Address senderAddress) {
public MockMailboxMessage(String msg, NodeAddress senderNodeAddress) {
this.msg = msg;
this.senderAddress = senderAddress;
this.senderNodeAddress = senderNodeAddress;
}
@Override
@ -50,7 +50,7 @@ public final class MockMailboxMessage implements MailboxMessage, ExpirablePayloa
}
@Override
public Address getSenderAddress() {
return senderAddress;
public NodeAddress getSenderNodeAddress() {
return senderNodeAddress;
}
}

View file

@ -1,6 +1,6 @@
package io.bitsquare.p2p.network;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.peers.messages.auth.AuthenticationRequest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.Before;
@ -77,8 +77,8 @@ public class LocalhostNetworkNodeTest {
});
startupLatch.await();
node2.sendMessage(new Address("localhost", 9001), new AuthenticationRequest(new Address("localhost", 9002), 1));
node1.sendMessage(new Address("localhost", 9002), new AuthenticationRequest(new Address("localhost", 9001), 1));
node2.sendMessage(new NodeAddress("localhost", 9001), new AuthenticationRequest(new NodeAddress("localhost", 9002), 1));
node1.sendMessage(new NodeAddress("localhost", 9002), new AuthenticationRequest(new NodeAddress("localhost", 9001), 1));
msgLatch.await();
CountDownLatch shutDownLatch = new CountDownLatch(2);

View file

@ -86,7 +86,7 @@ public class TorNetworkNodeTest {
latch.countDown();
}
});
SettableFuture<Connection> future = node2.sendMessage(node1.getAddress(), new MockMessage("msg1"));
SettableFuture<Connection> future = node2.sendMessage(node1.getNodeAddress(), new MockMessage("msg1"));
Futures.addCallback(future, new FutureCallback<Connection>() {
@Override
public void onSuccess(Connection connection) {
@ -165,7 +165,7 @@ public class TorNetworkNodeTest {
latch.countDown();
}
});
SettableFuture<Connection> future = node1.sendMessage(node2.getAddress(), new MockMessage("msg1"));
SettableFuture<Connection> future = node1.sendMessage(node2.getNodeAddress(), new MockMessage("msg1"));
Futures.addCallback(future, new FutureCallback<Connection>() {
@Override
public void onSuccess(Connection connection) {

View file

@ -1,6 +1,6 @@
package io.bitsquare.p2p.routing;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.P2PService;
import io.bitsquare.p2p.P2PServiceListener;
import io.bitsquare.p2p.network.LocalhostNetworkNode;
@ -25,7 +25,7 @@ public class PeerManagerTest {
boolean useLocalhost = true;
private CountDownLatch latch;
private Set<Address> seedNodes;
private Set<NodeAddress> seedNodes;
private int sleepTime;
private SeedNode seedNode1, seedNode2, seedNode3;
@ -39,13 +39,13 @@ public class PeerManagerTest {
if (useLocalhost) {
//seedNodes.add(new Address("localhost:8001"));
// seedNodes.add(new Address("localhost:8002"));
seedNodes.add(new Address("localhost:8003"));
seedNodes.add(new NodeAddress("localhost:8003"));
sleepTime = 100;
} else {
seedNodes.add(new Address("3omjuxn7z73pxoee.onion:8001"));
seedNodes.add(new Address("j24fxqyghjetgpdx.onion:8002"));
seedNodes.add(new Address("45367tl6unwec6kw.onion:8003"));
seedNodes.add(new NodeAddress("3omjuxn7z73pxoee.onion:8001"));
seedNodes.add(new NodeAddress("j24fxqyghjetgpdx.onion:8002"));
seedNodes.add(new NodeAddress("45367tl6unwec6kw.onion:8003"));
sleepTime = 1000;
}
}
@ -76,11 +76,11 @@ public class PeerManagerTest {
LocalhostNetworkNode.setSimulateTorDelayTorNode(0);
LocalhostNetworkNode.setSimulateTorDelayHiddenService(0);
seedNodes = new HashSet<>();
Address address = new Address("localhost:8001");
seedNodes.add(address);
NodeAddress nodeAddress = new NodeAddress("localhost:8001");
seedNodes.add(nodeAddress);
seedNode1 = new SeedNode("test_dummy_dir");
latch = new CountDownLatch(2);
seedNode1.createAndStartP2PService(address, useLocalhost, 2, true,
seedNode1.createAndStartP2PService(nodeAddress, useLocalhost, 2, true,
seedNodes, new P2PServiceListener() {
@Override
public void onRequestingDataCompleted() {
@ -124,15 +124,15 @@ public class PeerManagerTest {
LocalhostNetworkNode.setSimulateTorDelayTorNode(0);
LocalhostNetworkNode.setSimulateTorDelayHiddenService(0);
seedNodes = new HashSet<>();
Address address1 = new Address("localhost:8001");
seedNodes.add(address1);
Address address2 = new Address("localhost:8002");
seedNodes.add(address2);
NodeAddress nodeAddress1 = new NodeAddress("localhost:8001");
seedNodes.add(nodeAddress1);
NodeAddress nodeAddress2 = new NodeAddress("localhost:8002");
seedNodes.add(nodeAddress2);
latch = new CountDownLatch(6);
seedNode1 = new SeedNode("test_dummy_dir");
seedNode1.createAndStartP2PService(address1, useLocalhost, 2, true, seedNodes, new P2PServiceListener() {
seedNode1.createAndStartP2PService(nodeAddress1, useLocalhost, 2, true, seedNodes, new P2PServiceListener() {
@Override
public void onRequestingDataCompleted() {
latch.countDown();
@ -170,7 +170,7 @@ public class PeerManagerTest {
Thread.sleep(500);
seedNode2 = new SeedNode("test_dummy_dir");
seedNode2.createAndStartP2PService(address2, useLocalhost, 2, true, seedNodes, new P2PServiceListener() {
seedNode2.createAndStartP2PService(nodeAddress2, useLocalhost, 2, true, seedNodes, new P2PServiceListener() {
@Override
public void onRequestingDataCompleted() {
latch.countDown();
@ -407,7 +407,7 @@ public class PeerManagerTest {
SeedNode seedNode = new SeedNode("test_dummy_dir");
latch = new CountDownLatch(1);
seedNode.createAndStartP2PService(new Address("localhost", port), useLocalhost, 2, true, seedNodes, new P2PServiceListener() {
seedNode.createAndStartP2PService(new NodeAddress("localhost", port), useLocalhost, 2, true, seedNodes, new P2PServiceListener() {
@Override
public void onRequestingDataCompleted() {
latch.countDown();

View file

@ -5,7 +5,7 @@ import io.bitsquare.common.crypto.*;
import io.bitsquare.common.util.Utilities;
import io.bitsquare.crypto.EncryptionService;
import io.bitsquare.crypto.SealedAndSignedMessage;
import io.bitsquare.p2p.Address;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.TestUtils;
import io.bitsquare.p2p.mocks.MockMessage;
import io.bitsquare.p2p.network.NetworkNode;
@ -35,7 +35,7 @@ public class ProtectedDataStorageTest {
private static final Logger log = LoggerFactory.getLogger(ProtectedDataStorageTest.class);
boolean useClearNet = true;
private Set<Address> seedNodes = new HashSet<>();
private Set<NodeAddress> seedNodes = new HashSet<>();
private NetworkNode networkNode1;
private PeerManager peerManager1;
private EncryptionService encryptionService1, encryptionService2;