Cleanups, improve loggings

This commit is contained in:
Manfred Karrer 2016-02-01 13:26:41 +01:00
parent 186f85c44e
commit bee9d2c610
30 changed files with 200 additions and 161 deletions

View file

@ -354,7 +354,7 @@ public class Utilities {
URLConnection connection = URI.create(url).toURL().openConnection();
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setConnectTimeout(10 * 1000);
connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(10));
connection.addRequestProperty("User-Agent", userAgent);
connection.connect();
try (InputStream inputStream = connection.getInputStream()) {

View file

@ -21,12 +21,13 @@ import io.bitsquare.app.Version;
import io.bitsquare.p2p.storage.data.PubKeyProtectedExpirablePayload;
import java.security.PublicKey;
import java.util.concurrent.TimeUnit;
public final class Alert implements PubKeyProtectedExpirablePayload {
// That object is sent over the wire, so we need to take care of version compatibility.
private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION;
private static final long TTL = 10 * 24 * 60 * 60 * 1000; // 10 days
private static final long TTL = TimeUnit.DAYS.toMillis(10);
public final String message;
private String signatureAsBase64;

View file

@ -26,12 +26,13 @@ import java.security.PublicKey;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
public final class Arbitrator implements PubKeyProtectedExpirablePayload {
// 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 static final long TTL = 10 * 24 * 60 * 60 * 1000; // 10 days
public static final long TTL = TimeUnit.DAYS.toMillis(10);
// Persisted fields
private final byte[] btcPubKey;

View file

@ -117,7 +117,7 @@ public class WalletService {
Threading.USER_THREAD = UserThread.getExecutor();
Timer timeoutTimer = UserThread.runAfter(() -> {
exceptionHandler.handleException(new TimeoutException("Wallet did not initialize in " + STARTUP_TIMEOUT_SEC / 1000 + " seconds."));
exceptionHandler.handleException(new TimeoutException("Wallet did not initialize in " + STARTUP_TIMEOUT_SEC + " seconds."));
}, STARTUP_TIMEOUT_SEC);
// If seed is non-null it means we are restoring from backup.

View file

@ -26,6 +26,7 @@ import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@ -36,6 +37,7 @@ public class PaymentAccount implements Serializable {
private static final Logger log = LoggerFactory.getLogger(PaymentAccount.class);
protected final String id;
protected final Date creationDate;
protected final PaymentMethod paymentMethod;
protected String accountName;
protected final List<TradeCurrency> tradeCurrencies = new ArrayList<>();
@ -53,6 +55,7 @@ public class PaymentAccount implements Serializable {
public PaymentAccount(PaymentMethod paymentMethod) {
this.paymentMethod = paymentMethod;
id = UUID.randomUUID().toString();
creationDate = new Date();
}
@ -147,6 +150,10 @@ public class PaymentAccount implements Serializable {
return contractData.getMaxTradePeriod();
}
public Date getCreationDate() {
return creationDate;
}
///////////////////////////////////////////////////////////////////////////////////////////
// Util
@ -157,6 +164,7 @@ public class PaymentAccount implements Serializable {
return contractData.toString() + '\'' +
"PaymentAccount{" +
"id='" + id + '\'' +
", creationDate=" + creationDate +
", paymentMethod=" + paymentMethod +
", accountName='" + accountName + '\'' +
", tradeCurrencies=" + tradeCurrencies +

View file

@ -41,6 +41,7 @@ import java.io.IOException;
import java.security.PublicKey;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
@ -52,7 +53,7 @@ public final class Offer implements PubKeyProtectedExpirablePayload {
@JsonExclude
private static final Logger log = LoggerFactory.getLogger(Offer.class);
public static final long TTL = 10 * 60 * 1000; // 10 min.
public static final long TTL = TimeUnit.MINUTES.toMillis(10);
public final static String TAC_OFFERER = "When placing that offer I accept that anyone who fulfills my conditions can " +
"take that offer.";
public static final String TAC_TAKER = "With taking the offer I commit to the trade conditions as defined.";

View file

@ -286,6 +286,9 @@ public class Preferences implements Serializable {
if (txFeePerKB < Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.value)
throw new Exception("Transaction fee must be at least 5 satoshi/byte");
if (txFeePerKB < Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.value)
throw new Exception("Transaction fee must be at least 5 satoshi/byte");
this.txFeePerKB = txFeePerKB;
FeePolicy.setFeePerKb(Coin.valueOf(txFeePerKB));
storage.queueUpForSave();

View file

@ -59,6 +59,7 @@ public class SepaForm extends PaymentMethodForm {
public static int addFormForBuyer(GridPane gridPane, int gridRow, PaymentAccountContractData paymentAccountContractData) {
addLabelTextField(gridPane, ++gridRow, "Payment method:", BSResources.get(paymentAccountContractData.getPaymentMethodName()));
addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, "Account holder name:", ((SepaAccountContractData) paymentAccountContractData).getHolderName());
addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, "Country of bank:", CountryUtil.getNameByCode(paymentAccountContractData.getCountryCode()));
addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, "IBAN:", ((SepaAccountContractData) paymentAccountContractData).getIban());
addLabelTextFieldWithCopyIcon(gridPane, ++gridRow, "BIC/SWIFT:", ((SepaAccountContractData) paymentAccountContractData).getBic());
addAllowedPeriod(gridPane, ++gridRow, paymentAccountContractData);

View file

@ -45,6 +45,7 @@ class PaymentAccountDataModel extends ActivatableDataModel {
private void fillAndSortPaymentAccounts() {
paymentAccounts.setAll(user.getPaymentAccounts());
paymentAccounts.sort((o1, o2) -> o1.getCreationDate().compareTo(o2.getCreationDate()));
}
@Override

View file

@ -169,7 +169,7 @@ public class StartPaymentView extends TradeStepDetailsView {
statusProgressIndicator.setProgress(-1);
statusLabel.setWrapText(true);
statusLabel.setPrefWidth(220);
statusLabel.setPrefWidth(160);
statusLabel.setText("Sending message to your trading partner.\n" +
"Please wait until you get the confirmation that the message has arrived.");

View file

@ -63,7 +63,7 @@ public class PreferencesView extends ActivatableViewAndModel<GridPane, Preferenc
blockExplorerComboBox = addLabelComboBox(root, ++gridRow, "Bitcoin block explorer:").second;
transactionFeeInputTextField = addLabelInputTextField(root, ++gridRow, "Transaction fee (satoshi/byte):").second;
transactionFeeFocusedListener = (o, oldValue, newValue) -> {
model.onFocusOutTransactionFeeTextField(oldValue, newValue, transactionFeeInputTextField.getText());
model.onFocusOutTransactionFeeTextField(oldValue, newValue);
};
addTitledGroupBg(root, ++gridRow, 5, "Display options", Layout.GROUP_DISTANCE);

View file

@ -58,7 +58,7 @@ class PreferencesViewModel extends ActivatableViewModel {
@Override
protected void activate() {
transactionFeePerByte.set(String.valueOf(preferences.getTxFeePerKB() / 1000));
transactionFeePerByte.set(String.valueOf(preferences.getTxFeePerKB() / 1024));
}
@Override
@ -105,14 +105,15 @@ class PreferencesViewModel extends ActivatableViewModel {
preferences.setPreferredLocale(new Locale(code, preferences.getPreferredLocale().getCountry()));
}
public void onFocusOutTransactionFeeTextField(Boolean oldValue, Boolean newValue, String text) {
public void onFocusOutTransactionFeeTextField(Boolean oldValue, Boolean newValue) {
if (oldValue && !newValue) {
try {
preferences.setTxFeePerKB(Long.valueOf(transactionFeePerByte.get()) * 1000);
preferences.setTxFeePerKB(Long.parseLong(transactionFeePerByte.get()) * 1024);
} catch (Exception e) {
log.warn("Error at onFocusOutTransactionFeeTextField: " + e.getMessage());
new Popup().warning(e.getMessage())
.onClose(() -> UserThread.runAfter(
() -> transactionFeePerByte.set(String.valueOf(preferences.getTxFeePerKB() / 1000)),
() -> transactionFeePerByte.set(String.valueOf(preferences.getTxFeePerKB() / 1024)),
100, TimeUnit.MILLISECONDS))
.show();
}

View file

@ -36,6 +36,7 @@ import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class BSFormatter {
@ -340,7 +341,7 @@ public class BSFormatter {
public String getDateFromBlocks(long blocks) {
DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.SHORT, locale);
Date date = new Date(new Date().getTime() + blocks * 10 * 60 * 1000);
Date date = new Date(new Date().getTime() + blocks * TimeUnit.MINUTES.toMillis(10));
return dateFormatter.format(date) + " " + timeFormatter.format(date);
}

View file

@ -43,7 +43,7 @@ import java.nio.file.attribute.PosixFilePermission;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* This is where all the fun is, this is the class that handles the heavy work.
@ -62,8 +62,8 @@ public abstract class OnionProxyManager {
private static final String[] EVENTS_HS = {"EXTENDED", "CIRC", "ORCONN", "INFO", "NOTICE", "WARN", "ERR", "HS_DESC"};
private static final String OWNER = "__OwningControllerProcess";
private static final int COOKIE_TIMEOUT = 3 * 1000; // Milliseconds
private static final int HOSTNAME_TIMEOUT = 30 * 1000; // Milliseconds
private static final long COOKIE_TIMEOUT_IN_SEC = 10;
private static final long HOSTNAME_TIMEOUT_IN_SEC = 30;
private static final Logger LOG = LoggerFactory.getLogger(OnionProxyManager.class);
protected final OnionProxyContext onionProxyContext;
@ -247,7 +247,7 @@ public abstract class OnionProxyManager {
controlConnection.setConf(config);
controlConnection.saveConf();
// Wait for the hostname file to be created/updated
if (!hostNameFileObserver.poll(HOSTNAME_TIMEOUT, MILLISECONDS)) {
if (!hostNameFileObserver.poll(HOSTNAME_TIMEOUT_IN_SEC, SECONDS)) {
FileUtilities.listFilesToLog(hostnameFile.getParentFile());
throw new RuntimeException("Wait for hidden service hostname file to be created expired.");
}
@ -455,7 +455,7 @@ public abstract class OnionProxyManager {
}
// Wait for the auth cookie file to be created/updated
if (!cookieObserver.poll(COOKIE_TIMEOUT, MILLISECONDS)) {
if (!cookieObserver.poll(COOKIE_TIMEOUT_IN_SEC, SECONDS)) {
LOG.warn("Auth cookie not created");
FileUtilities.listFilesToLog(workingDirectory);
return false;

View file

@ -219,7 +219,7 @@ public class Node {
public void run() {
{
try {
socket.setSoTimeout(60 * 1000);
socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(60));
} catch (SocketException e2) {
e2.printStackTrace();
try {

View file

@ -39,7 +39,7 @@ public class Connection implements MessageListener {
private static final int MSG_THROTTLE_PER_SEC = 10; // With MAX_MSG_SIZE of 100kb results in bandwidth of 10 mbit/sec
private static final int MSG_THROTTLE_PER_10SEC = 50; // With MAX_MSG_SIZE of 100kb results in bandwidth of 5 mbit/sec for 10 sec
//timeout on blocking Socket operations like ServerSocket.accept() or SocketInputStream.read()
private static final int SOCKET_TIMEOUT = 30 * 60 * 1000; // 30 min.
private static final int SOCKET_TIMEOUT = (int) TimeUnit.MINUTES.toMillis(30);
public static int getMaxMsgSize() {
return MAX_MSG_SIZE;
@ -205,16 +205,20 @@ public class Connection implements MessageListener {
long now = System.currentTimeMillis();
boolean violated = false;
if (messageTimeStamps.size() >= MSG_THROTTLE_PER_SEC) {
// check if we got more than 10 msg per sec.
long compareTo = messageTimeStamps.get(messageTimeStamps.size() - MSG_THROTTLE_PER_SEC);
violated = now - compareTo < 1000;
// check if we got more than 10 (MSG_THROTTLE_PER_SEC) msg per sec.
long compareValue = messageTimeStamps.get(messageTimeStamps.size() - MSG_THROTTLE_PER_SEC);
// if duration < 1 sec we received too much messages
violated = now - compareValue < TimeUnit.SECONDS.toMillis(1);
}
if (messageTimeStamps.size() >= MSG_THROTTLE_PER_10SEC) {
if (!violated) {
// check if we got more than 50 msg per 10 sec.
long compareTo = messageTimeStamps.get(messageTimeStamps.size() - MSG_THROTTLE_PER_10SEC);
violated = violated || now - compareTo < 10000;
// we limit to max 50 entries
long compareValue = messageTimeStamps.get(messageTimeStamps.size() - MSG_THROTTLE_PER_10SEC);
// if duration < 10 sec we received too much messages
violated = now - compareValue < TimeUnit.SECONDS.toMillis(10);
}
// we limit to max 50 (MSG_THROTTLE_PER_10SEC) entries
messageTimeStamps.remove(0);
}

View file

@ -17,7 +17,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.concurrent.TimeUnit;
@ -73,24 +72,12 @@ public class PeerExchangeHandshake implements MessageListener {
// API
///////////////////////////////////////////////////////////////////////////////////////////
public void requestReportedPeers(NodeAddress nodeAddress, List<NodeAddress> remainingNodeAddresses) {
Log.traceCall("nodeAddress=" + nodeAddress);
Log.traceCall("this=" + this);
checkNotNull(networkNode.getNodeAddress(), "My node address must not be null at requestReportedPeers");
checkArgument(timeoutTimer == null, "requestData must not be called twice.");
timeoutTimer = UserThread.runAfter(() -> {
log.info("timeoutTimer called on " + this);
peerManager.shutDownConnection(nodeAddress);
shutDown();
listener.onFault("A timeout occurred");
},
20, TimeUnit.SECONDS);
GetPeersRequest getPeersRequest = new GetPeersRequest(networkNode.getNodeAddress(), nonce,
getReportedPeers(nodeAddress));
SettableFuture<Connection> future = networkNode.sendMessage(nodeAddress,
getPeersRequest);
public void requestReportedPeers(NodeAddress nodeAddress) {
Log.traceCall("nodeAddress=" + nodeAddress + " / this=" + this);
checkNotNull(networkNode.getNodeAddress(), "PeerExchangeHandshake.requestReportedPeers: My node address must " +
"not be null at requestReportedPeers");
GetPeersRequest getPeersRequest = new GetPeersRequest(networkNode.getNodeAddress(), nonce, getReportedPeers(nodeAddress));
SettableFuture<Connection> future = networkNode.sendMessage(nodeAddress, getPeersRequest);
Futures.addCallback(future, new FutureCallback<Connection>() {
@Override
public void onSuccess(Connection connection) {
@ -100,8 +87,8 @@ public class PeerExchangeHandshake implements MessageListener {
@Override
public void onFailure(@NotNull Throwable throwable) {
String errorMessage = "Sending getPeersRequest to " + nodeAddress +
" failed. That is expected if the peer is offline. getPeersRequest=" + getPeersRequest + "." +
"Exception: " + throwable.getMessage();
" failed. That is expected if the peer is offline.\ngetPeersRequest=" + getPeersRequest +
".\nException=" + throwable.getMessage();
log.info(errorMessage);
peerManager.shutDownConnection(nodeAddress);
@ -109,31 +96,37 @@ public class PeerExchangeHandshake implements MessageListener {
listener.onFault(errorMessage);
}
});
}
public void onGetPeersRequest(GetPeersRequest message, final Connection connection) {
Log.traceCall("message=" + message);
Log.traceCall("this=" + this);
checkArgument(timeoutTimer == null, "requestData must not be called twice.");
checkArgument(timeoutTimer == null, "requestReportedPeers must not be called twice.");
timeoutTimer = UserThread.runAfter(() -> {
String errorMessage = "A timeout occurred at sending getPeersRequest:" + getPeersRequest + " for nodeAddress:" + nodeAddress;
log.info(errorMessage + " / PeerExchangeHandshake=" +
PeerExchangeHandshake.this);
log.info("timeoutTimer called on " + this);
peerManager.shutDownConnection(connection);
peerManager.shutDownConnection(nodeAddress);
shutDown();
listener.onFault("A timeout occurred");
listener.onFault(errorMessage);
},
20, TimeUnit.SECONDS);
}
public void onGetPeersRequest(GetPeersRequest getPeersRequest, final Connection connection) {
Log.traceCall("getPeersRequest=" + getPeersRequest + " / connection=" + connection + " / this=" + this);
GetPeersRequest getPeersRequest = message;
HashSet<ReportedPeer> reportedPeers = getPeersRequest.reportedPeers;
StringBuilder result = new StringBuilder("Received peers:");
/* StringBuilder result = new StringBuilder("Received peers:");
reportedPeers.stream().forEach(e -> result.append("\n").append(e));
log.trace(result.toString());
log.trace(result.toString());*/
log.trace("reportedPeers.size=" + reportedPeers.size());
checkArgument(connection.getPeersNodeAddressOptional().isPresent(),
"The peers address must have been already set at the moment");
GetPeersResponse getPeersResponse = new GetPeersResponse(getPeersRequest.nonce,
getReportedPeers(connection.getPeersNodeAddressOptional().get()));
SettableFuture<Connection> future = networkNode.sendMessage(connection,
new GetPeersResponse(getPeersRequest.nonce,
getReportedPeers(connection.getPeersNodeAddressOptional().get())));
getPeersResponse);
Futures.addCallback(future, new FutureCallback<Connection>() {
@Override
public void onSuccess(Connection connection) {
@ -154,6 +147,20 @@ public class PeerExchangeHandshake implements MessageListener {
listener.onFault(errorMessage);
}
});
checkArgument(timeoutTimer == null, "onGetPeersRequest must not be called twice.");
timeoutTimer = UserThread.runAfter(() -> {
String errorMessage = "A timeout occurred at sending getPeersResponse:" + getPeersResponse + " on connection:" + connection;
log.info(errorMessage + " / PeerExchangeHandshake=" +
PeerExchangeHandshake.this);
log.info("timeoutTimer called. this=" + this);
peerManager.shutDownConnection(connection);
shutDown();
listener.onFault(errorMessage);
},
20, TimeUnit.SECONDS);
peerManager.addToReportedPeers(reportedPeers, connection);
}
@ -180,8 +187,9 @@ public class PeerExchangeHandshake implements MessageListener {
shutDown();
listener.onComplete();
} else {
log.debug("Nonce not matching. That happens if we get a response after a canceled handshake " +
"(timeout). We drop that message. nonce={} / requestNonce={}",
log.debug("Nonce not matching. That can happen rarely if we get a response after a canceled handshake " +
"(timeout causes connection close but peer might have sent a msg before connection " +
"was closed).\nWe drop that message. nonce={} / requestNonce={}",
nonce, getPeersResponse.requestNonce);
}
}

View file

@ -108,14 +108,13 @@ public class PeerExchangeManager implements MessageListener, ConnectionListener
new PeerExchangeHandshake.Listener() {
@Override
public void onComplete() {
log.trace("PeerExchangeHandshake of inbound connection complete. Connection= {}",
connection);
log.trace("PeerExchangeHandshake of inbound connection complete. Connection={}", connection);
}
@Override
public void onFault(String errorMessage) {
log.trace("PeerExchangeHandshake of outbound connection failed. {} connection= {}",
errorMessage, connection);
log.trace("PeerExchangeHandshake of outbound connection failed.\nerrorMessage={}\n" +
"connection={}", errorMessage, connection);
peerManager.penalizeUnreachablePeer(connection);
}
});
@ -136,16 +135,15 @@ public class PeerExchangeManager implements MessageListener, ConnectionListener
new PeerExchangeHandshake.Listener() {
@Override
public void onComplete() {
log.trace("PeerExchangeHandshake of outbound connection complete. nodeAddress= {}",
nodeAddress);
log.trace("PeerExchangeHandshake of outbound connection complete. nodeAddress={}", nodeAddress);
peerExchangeHandshakeMap.remove(nodeAddress);
connectToMorePeers();
}
@Override
public void onFault(String errorMessage) {
log.trace("PeerExchangeHandshake of outbound connection failed. {} nodeAddress= {}",
errorMessage, nodeAddress);
log.trace("PeerExchangeHandshake of outbound connection failed.\nerrorMessage={}\n" +
"nodeAddress={}", errorMessage, nodeAddress);
peerExchangeHandshakeMap.remove(nodeAddress);
peerManager.penalizeUnreachablePeer(nodeAddress);
@ -164,10 +162,11 @@ public class PeerExchangeManager implements MessageListener, ConnectionListener
}
});
peerExchangeHandshakeMap.put(nodeAddress, peerExchangeHandshake);
peerExchangeHandshake.requestReportedPeers(nodeAddress, remainingNodeAddresses);
peerExchangeHandshake.requestReportedPeers(nodeAddress);
} else {
log.trace("We have started already a peerExchangeHandshake to peer. " +
"That can happen by the timers calls. We ignore that call. " +
//TODO check when that happens
log.warn("We have started already a peerExchangeHandshake. " +
"We ignore that call. " +
"nodeAddress=" + nodeAddress);
}
}
@ -204,9 +203,9 @@ public class PeerExchangeManager implements MessageListener, ConnectionListener
confirmedConnections.stream()
.filter(c -> c.getPeersNodeAddressOptional().isPresent() &&
c instanceof OutboundConnection &&
new Date().getTime() - c.getLastActivityDate().getTime() > 10 * 60 * 1000)
new Date().getTime() - c.getLastActivityDate().getTime() > TimeUnit.MINUTES.toMillis(10))
.forEach(c -> {
log.trace("Call requestReportedPeers from maintainConnections");
log.trace("Call requestReportedPeers on a confirmedConnection by the maintainConnections call");
requestReportedPeers(c.getPeersNodeAddressOptional().get(), new ArrayList<>());
});
}

View file

@ -5,7 +5,7 @@ import io.bitsquare.common.UserThread;
import io.bitsquare.p2p.Message;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.network.*;
import io.bitsquare.p2p.peers.messages.data.UpdateDataRequest;
import io.bitsquare.p2p.peers.messages.data.GetUpdatedDataRequest;
import io.bitsquare.storage.Storage;
import javafx.beans.value.ChangeListener;
import org.slf4j.Logger;
@ -13,6 +13,7 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
@ -43,8 +44,7 @@ public class PeerManager implements ConnectionListener, MessageListener {
private static final int MAX_REPORTED_PEERS = 1000;
private static final int MAX_PERSISTED_PEERS = 500;
private static final long DAY = 24 * 60 * 60 * 1000; // max age for reported peers is 14 days
private static final long MAX_AGE = 14 * DAY; // max age for reported peers is 14 days
private static final long MAX_AGE = TimeUnit.DAYS.toMillis(14); // max age for reported peers is 14 days
private final NetworkNode networkNode;
@ -138,7 +138,7 @@ public class PeerManager implements ConnectionListener, MessageListener {
public void onMessage(Message message, Connection connection) {
// In case a seed node connects to another seed node we get his address at the DataRequest triggered from
// RequestDataManager.updateDataFromConnectedSeedNode
if (message instanceof UpdateDataRequest) {
if (message instanceof GetUpdatedDataRequest) {
Optional<NodeAddress> peersNodeAddressOptional = connection.getPeersNodeAddressOptional();
if (peersNodeAddressOptional.isPresent() &&
seedNodeAddresses.contains(peersNodeAddressOptional.get()))

View file

@ -5,6 +5,7 @@ import io.bitsquare.p2p.NodeAddress;
import java.io.Serializable;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class ReportedPeer implements Serializable {
// That object is sent over the wire, so we need to take care of version compatibility.
@ -21,7 +22,7 @@ public class ReportedPeer implements Serializable {
public void penalizeLastActivityDate() {
if (lastActivityDate != null) {
long now = new Date().getTime();
long diff = Math.max(24 * 60 * 60 * 1000, now - lastActivityDate.getTime());
long diff = Math.max(TimeUnit.DAYS.toMillis(1), now - lastActivityDate.getTime());
long reduced = now - diff * 2;
lastActivityDate = new Date(reduced);
}

View file

@ -10,10 +10,10 @@ import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.network.Connection;
import io.bitsquare.p2p.network.MessageListener;
import io.bitsquare.p2p.network.NetworkNode;
import io.bitsquare.p2p.peers.messages.data.DataRequest;
import io.bitsquare.p2p.peers.messages.data.DataResponse;
import io.bitsquare.p2p.peers.messages.data.PreliminaryDataRequest;
import io.bitsquare.p2p.peers.messages.data.UpdateDataRequest;
import io.bitsquare.p2p.peers.messages.data.GetDataRequest;
import io.bitsquare.p2p.peers.messages.data.GetDataResponse;
import io.bitsquare.p2p.peers.messages.data.GetUpdatedDataRequest;
import io.bitsquare.p2p.peers.messages.data.PreliminaryGetDataRequest;
import io.bitsquare.p2p.storage.P2PDataStorage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@ -80,73 +80,66 @@ public class RequestDataHandshake implements MessageListener {
public void requestData(NodeAddress nodeAddress) {
Log.traceCall("nodeAddress=" + nodeAddress);
checkArgument(timeoutTimer == null, "requestData must not be called twice.");
timeoutTimer = UserThread.runAfter(() -> {
log.info("timeoutTimer called");
peerManager.shutDownConnection(nodeAddress);
shutDown();
listener.onFault("A timeout occurred");
},
10, TimeUnit.SECONDS);
Message dataRequest;
GetDataRequest getDataRequest;
if (networkNode.getNodeAddress() == null)
dataRequest = new PreliminaryDataRequest(nonce);
getDataRequest = new PreliminaryGetDataRequest(nonce);
else
dataRequest = new UpdateDataRequest(networkNode.getNodeAddress(), nonce);
getDataRequest = new GetUpdatedDataRequest(networkNode.getNodeAddress(), nonce);
log.info("We send a {} to peer {}. ", dataRequest.getClass().getSimpleName(), nodeAddress);
log.info("We send a {} to peer {}. ", getDataRequest.getClass().getSimpleName(), nodeAddress);
SettableFuture<Connection> future = networkNode.sendMessage(nodeAddress, dataRequest);
SettableFuture<Connection> future = networkNode.sendMessage(nodeAddress, getDataRequest);
Futures.addCallback(future, new FutureCallback<Connection>() {
@Override
public void onSuccess(@Nullable Connection connection) {
log.trace("Send " + dataRequest + " to " + nodeAddress + " succeeded.");
log.trace("Send " + getDataRequest + " to " + nodeAddress + " succeeded.");
}
@Override
public void onFailure(@NotNull Throwable throwable) {
String errorMessage = "Sending dataRequest to " + nodeAddress +
" failed. That is expected if the peer is offline. dataRequest=" + dataRequest + "." +
"Exception: " + throwable.getMessage();
String errorMessage = "Sending getDataRequest to " + nodeAddress +
" failed. That is expected if the peer is offline.\n" +
"getDataRequest=" + getDataRequest + "." +
"\nException=" + throwable.getMessage();
log.info(errorMessage);
peerManager.shutDownConnection(nodeAddress);
shutDown();
listener.onFault(errorMessage);
}
});
checkArgument(timeoutTimer == null, "requestData must not be called twice.");
timeoutTimer = UserThread.runAfter(() -> {
String errorMessage = "A timeout occurred at sending getDataRequest:" + getDataRequest +
" on nodeAddress:" + nodeAddress;
log.info(errorMessage + " / RequestDataHandshake=" +
RequestDataHandshake.this);
peerManager.shutDownConnection(nodeAddress);
shutDown();
listener.onFault(errorMessage);
},
10, TimeUnit.SECONDS);
}
public void onDataRequest(Message message, final Connection connection) {
Log.traceCall(message.toString() + " / connection=" + connection);
checkArgument(timeoutTimer == null, "requestData must not be called twice.");
timeoutTimer = UserThread.runAfter(() -> {
log.info("timeoutTimer called");
peerManager.shutDownConnection(connection);
shutDown();
listener.onFault("A timeout occurred");
},
10, TimeUnit.SECONDS);
DataRequest dataRequest = (DataRequest) message;
DataResponse dataResponse = new DataResponse(new HashSet<>(dataStorage.getMap().values()), dataRequest.getNonce());
SettableFuture<Connection> future = networkNode.sendMessage(connection, dataResponse);
GetDataResponse getDataResponse = new GetDataResponse(new HashSet<>(dataStorage.getMap().values()),
((GetDataRequest) message).getNonce());
SettableFuture<Connection> future = networkNode.sendMessage(connection, getDataResponse);
Futures.addCallback(future, new FutureCallback<Connection>() {
@Override
public void onSuccess(Connection connection) {
log.trace("Send DataResponse to {} succeeded. dataResponse={}",
connection.getPeersNodeAddressOptional(), dataResponse);
log.trace("Send DataResponse to {} succeeded. getDataResponse={}",
connection.getPeersNodeAddressOptional(), getDataResponse);
shutDown();
listener.onComplete();
}
@Override
public void onFailure(@NotNull Throwable throwable) {
String errorMessage = "Sending dataRequest to " + connection +
" failed. That is expected if the peer is offline. dataRequest=" + dataRequest + "." +
String errorMessage = "Sending getDataRequest to " + connection +
" failed. That is expected if the peer is offline. getDataResponse=" + getDataResponse + "." +
"Exception: " + throwable.getMessage();
log.info(errorMessage);
@ -155,6 +148,18 @@ public class RequestDataHandshake implements MessageListener {
listener.onFault(errorMessage);
}
});
checkArgument(timeoutTimer == null, "requestData must not be called twice.");
timeoutTimer = UserThread.runAfter(() -> {
String errorMessage = "A timeout occurred for getDataResponse:" + getDataResponse +
" on connection:" + connection;
log.info(errorMessage + " / RequestDataHandshake=" +
RequestDataHandshake.this);
peerManager.shutDownConnection(connection);
shutDown();
listener.onFault(errorMessage);
},
10, TimeUnit.SECONDS);
}
///////////////////////////////////////////////////////////////////////////////////////////
@ -163,25 +168,26 @@ public class RequestDataHandshake implements MessageListener {
@Override
public void onMessage(Message message, Connection connection) {
if (message instanceof DataResponse) {
if (message instanceof GetDataResponse) {
Log.traceCall(message.toString() + " / connection=" + connection);
DataResponse dataResponse = (DataResponse) message;
if (dataResponse.requestNonce == nonce) {
GetDataResponse getDataResponse = (GetDataResponse) message;
if (getDataResponse.requestNonce == nonce) {
stopTimeoutTimer();
// connection.getPeersNodeAddressOptional() is not present at the first call
log.debug("connection.getPeersNodeAddressOptional() " + connection.getPeersNodeAddressOptional());
connection.getPeersNodeAddressOptional().ifPresent(peersNodeAddress -> {
((DataResponse) message).dataSet.stream()
.forEach(e -> dataStorage.add(e, peersNodeAddress));
});
checkArgument(connection.getPeersNodeAddressOptional().isPresent(),
"RequestDataHandshake.onMessage: connection.getPeersNodeAddressOptional() must be present " +
"at that moment");
((GetDataResponse) message).dataSet.stream()
.forEach(protectedData -> dataStorage.add(protectedData,
connection.getPeersNodeAddressOptional().get()));
shutDown();
listener.onComplete();
} else {
log.debug("Nonce not matching. That happens if we get a response after a canceled handshake " +
"(timeout). We drop that message. nonce={} / requestNonce={}",
nonce, dataResponse.requestNonce);
log.debug("Nonce not matching. That can happen rarely if we get a response after a canceled " +
"handshake (timeout causes connection close but peer might have sent a msg before " +
"connection was closed).\n" +
"We drop that message. nonce={} / requestNonce={}",
nonce, getDataResponse.requestNonce);
}
}
}

View file

@ -7,7 +7,7 @@ import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.network.Connection;
import io.bitsquare.p2p.network.MessageListener;
import io.bitsquare.p2p.network.NetworkNode;
import io.bitsquare.p2p.peers.messages.data.DataRequest;
import io.bitsquare.p2p.peers.messages.data.GetDataRequest;
import io.bitsquare.p2p.storage.P2PDataStorage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -113,19 +113,19 @@ public class RequestDataManager implements MessageListener {
@Override
public void onMessage(Message message, Connection connection) {
if (message instanceof DataRequest) {
if (message instanceof GetDataRequest) {
RequestDataHandshake requestDataHandshake = new RequestDataHandshake(networkNode, dataStorage, peerManager,
new RequestDataHandshake.Listener() {
@Override
public void onComplete() {
log.trace("RequestDataHandshake of inbound connection complete. Connection= {}",
log.trace("requestDataHandshake of inbound connection complete. Connection={}",
connection);
}
@Override
public void onFault(String errorMessage) {
log.trace("RequestDataHandshake of inbound connection failed. {} Connection= {}",
errorMessage, connection);
log.trace("requestDataHandshake of inbound connection failed.\nConnection={}\n" +
"ErrorMessage={}", connection, errorMessage);
peerManager.penalizeUnreachablePeer(connection);
}
});
@ -145,7 +145,7 @@ public class RequestDataManager implements MessageListener {
new RequestDataHandshake.Listener() {
@Override
public void onComplete() {
log.trace("RequestDataHandshake of outbound connection complete. nodeAddress= {}",
log.trace("RequestDataHandshake of outbound connection complete. nodeAddress={}",
nodeAddress);
stopRequestDataTimer();
@ -169,8 +169,8 @@ public class RequestDataManager implements MessageListener {
@Override
public void onFault(String errorMessage) {
log.trace("RequestDataHandshake of outbound connection failed. {} nodeAddress= {}",
errorMessage, nodeAddress);
log.trace("requestDataHandshake of outbound connection failed.\nnodeAddress={}\n" +
"ErrorMessage={}", nodeAddress, errorMessage);
peerManager.penalizeUnreachablePeer(nodeAddress);
@ -198,7 +198,6 @@ public class RequestDataManager implements MessageListener {
Collections.shuffle(list);
list.addAll(getFilteredAndSortedList(peerManager.getReportedPeers(), list));
list.addAll(getFilteredAndSortedList(peerManager.getPersistedPeers(), list));
log.trace("Sorted and filtered list: list=" + list);
checkArgument(!list.isEmpty(), "seedNodeAddresses must not be empty.");
NodeAddress nextCandidate = list.get(0);
list.remove(nextCandidate);
@ -221,7 +220,7 @@ public class RequestDataManager implements MessageListener {
requestDataHandshakeMap.put(nodeAddress, requestDataHandshake);
requestDataHandshake.requestData(nodeAddress);
} else {
log.warn("We have started already a requestDataHandshake to peer. " + nodeAddress);
log.warn("We have started already a requestDataHandshake to peer. nodeAddress=" + nodeAddress);
}
}

View file

@ -1,5 +0,0 @@
package io.bitsquare.p2p.peers.messages.data;
public interface DataRequest {
long getNonce();
}

View file

@ -0,0 +1,7 @@
package io.bitsquare.p2p.peers.messages.data;
import io.bitsquare.p2p.Message;
public interface GetDataRequest extends Message {
long getNonce();
}

View file

@ -6,7 +6,7 @@ import io.bitsquare.p2p.storage.data.ProtectedData;
import java.util.HashSet;
public final class DataResponse implements Message {
public final class GetDataResponse 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();
@ -14,7 +14,7 @@ public final class DataResponse implements Message {
public final HashSet<ProtectedData> dataSet;
public final long requestNonce;
public DataResponse(HashSet<ProtectedData> dataSet, long requestNonce) {
public GetDataResponse(HashSet<ProtectedData> dataSet, long requestNonce) {
this.dataSet = dataSet;
this.requestNonce = requestNonce;
}
@ -27,9 +27,9 @@ public final class DataResponse implements Message {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof DataResponse)) return false;
if (!(o instanceof GetDataResponse)) return false;
DataResponse that = (DataResponse) o;
GetDataResponse that = (GetDataResponse) o;
return !(dataSet != null ? !dataSet.equals(that.dataSet) : that.dataSet != null);
@ -42,7 +42,7 @@ public final class DataResponse implements Message {
@Override
public String toString() {
return "DataResponse{" +
return "GetDataResponse{" +
"networkId=" + networkId +
", dataSet=" + dataSet +
", requestNonce=" + requestNonce +

View file

@ -4,7 +4,7 @@ import io.bitsquare.app.Version;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.p2p.network.messages.SendersNodeAddressMessage;
public final class UpdateDataRequest implements SendersNodeAddressMessage, DataRequest {
public final class GetUpdatedDataRequest implements SendersNodeAddressMessage, GetDataRequest {
// 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;
@ -12,7 +12,7 @@ public final class UpdateDataRequest implements SendersNodeAddressMessage, DataR
private final NodeAddress senderNodeAddress;
private final long nonce;
public UpdateDataRequest(NodeAddress senderNodeAddress, long nonce) {
public GetUpdatedDataRequest(NodeAddress senderNodeAddress, long nonce) {
this.senderNodeAddress = senderNodeAddress;
this.nonce = nonce;
}
@ -34,7 +34,7 @@ public final class UpdateDataRequest implements SendersNodeAddressMessage, DataR
@Override
public String toString() {
return "DataRequest{" +
return "GetUpdatedDataRequest{" +
"senderNodeAddress=" + senderNodeAddress +
", networkId=" + networkId +
", nonce=" + nonce +

View file

@ -3,14 +3,14 @@ package io.bitsquare.p2p.peers.messages.data;
import io.bitsquare.app.Version;
import io.bitsquare.p2p.network.messages.AnonymousMessage;
public final class PreliminaryDataRequest implements AnonymousMessage, DataRequest {
public final class PreliminaryGetDataRequest implements AnonymousMessage, GetDataRequest {
// 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();
private final long nonce;
public PreliminaryDataRequest(long nonce) {
public PreliminaryGetDataRequest(long nonce) {
this.nonce = nonce;
}
@ -26,7 +26,7 @@ public final class PreliminaryDataRequest implements AnonymousMessage, DataReque
@Override
public String toString() {
return "PreliminaryDataRequest{" +
return "PreliminaryGetDataRequest{" +
"networkId=" + networkId +
", nonce=" + nonce +
'}';

View file

@ -38,7 +38,7 @@ public class P2PDataStorage implements MessageListener {
private static final Logger log = LoggerFactory.getLogger(P2PDataStorage.class);
@VisibleForTesting
public static int CHECK_TTL_INTERVAL = new Random().nextInt(1000) + 10 * 60 * 1000; // 10-11 min.
public static int CHECK_TTL_INTERVAL = new Random().nextInt(1000) + (int) TimeUnit.MINUTES.toMillis(10); // 10-11 min.
private final Broadcaster broadcaster;
private final Map<ByteArray, ProtectedData> map = new HashMap<>();

View file

@ -4,12 +4,13 @@ import io.bitsquare.app.Version;
import io.bitsquare.crypto.PrefixedSealedAndSignedMessage;
import java.security.PublicKey;
import java.util.concurrent.TimeUnit;
public final class ExpirableMailboxPayload implements ExpirablePayload {
// That object is sent over the wire, so we need to take care of version compatibility.
private static final long serialVersionUID = Version.NETWORK_PROTOCOL_VERSION;
private static final long TTL = 10 * 24 * 60 * 60 * 1000; // 10 days
private static final long TTL = TimeUnit.DAYS.toMillis(10);
public final PrefixedSealedAndSignedMessage prefixedSealedAndSignedMessage;
public final PublicKey senderStoragePublicKey;

View file

@ -30,6 +30,7 @@ import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
//TODO P2P network tests are outdated
@Ignore
@ -60,7 +61,7 @@ public class ProtectedDataStorageTest {
dir2.mkdir();
UserThread.setExecutor(Executors.newSingleThreadExecutor());
P2PDataStorage.CHECK_TTL_INTERVAL = 10 * 60 * 1000;
P2PDataStorage.CHECK_TTL_INTERVAL = (int) TimeUnit.MINUTES.toMillis(10);
keyRing1 = new KeyRing(new KeyStorage(dir1));