mirror of
https://github.com/haveno-dex/haveno.git
synced 2025-04-19 23:36:00 -04:00
Cleanups, improve loggings
This commit is contained in:
parent
bee9d2c610
commit
406bcd31ef
@ -146,14 +146,14 @@ public final class Arbitrator implements PubKeyProtectedExpirablePayload {
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Arbitrator{" +
|
||||
"arbitratorAddress=" + arbitratorNodeAddress +
|
||||
", languageCodes=" + languageCodes +
|
||||
", btcAddress='" + btcAddress + '\'' +
|
||||
", registrationDate=" + registrationDate +
|
||||
", btcPubKey.hashCode()=" + Arrays.toString(btcPubKey).hashCode() +
|
||||
", pubKeyRing.hashCode()=" + pubKeyRing.hashCode() +
|
||||
", registrationSignature.hashCode()='" + registrationSignature.hashCode() + '\'' +
|
||||
", registrationPubKey.hashCode()=" + Arrays.toString(registrationPubKey).hashCode() +
|
||||
"\n\tarbitratorAddress=" + arbitratorNodeAddress +
|
||||
"\n\tlanguageCodes=" + languageCodes +
|
||||
"\n\tbtcAddress='" + btcAddress + '\'' +
|
||||
"\n\tregistrationDate=" + registrationDate +
|
||||
"\n\tbtcPubKey.hashCode()=" + Arrays.toString(btcPubKey).hashCode() +
|
||||
"\n\tpubKeyRing.hashCode()=" + pubKeyRing.hashCode() +
|
||||
"\n\tregistrationSignature.hashCode()='" + registrationSignature.hashCode() + '\'' +
|
||||
"\n\tregistrationPubKey.hashCode()=" + Arrays.toString(registrationPubKey).hashCode() +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
@ -159,29 +159,6 @@ public class Contract implements Serializable {
|
||||
return sellerNodeAddress;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Contract{" +
|
||||
"offer=" + offer +
|
||||
", tradeAmount=" + tradeAmount +
|
||||
", takeOfferFeeTxID='" + takeOfferFeeTxID + '\'' +
|
||||
", arbitratorAddress=" + arbitratorNodeAddress +
|
||||
", isBuyerOffererAndSellerTaker=" + isBuyerOffererAndSellerTaker +
|
||||
", offererAccountId='" + offererAccountId + '\'' +
|
||||
", takerAccountId='" + takerAccountId + '\'' +
|
||||
", offererPaymentAccountContractData=" + offererPaymentAccountContractData +
|
||||
", takerPaymentAccountContractData=" + takerPaymentAccountContractData +
|
||||
", offererPubKeyRing=" + offererPubKeyRing +
|
||||
", takerPubKeyRing=" + takerPubKeyRing +
|
||||
", buyerAddress=" + buyerNodeAddress +
|
||||
", sellerAddress=" + sellerNodeAddress +
|
||||
", offererPayoutAddressString='" + offererPayoutAddressString + '\'' +
|
||||
", takerPayoutAddressString='" + takerPayoutAddressString + '\'' +
|
||||
", offererBtcPubKey=" + Arrays.toString(offererBtcPubKey) +
|
||||
", takerBtcPubKey=" + Arrays.toString(takerBtcPubKey) +
|
||||
'}';
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
@ -243,4 +220,26 @@ public class Contract implements Serializable {
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Contract{" +
|
||||
"\n\toffer=" + offer +
|
||||
"\n\ttradeAmount=" + tradeAmount +
|
||||
"\n\ttakeOfferFeeTxID='" + takeOfferFeeTxID + '\'' +
|
||||
"\n\tarbitratorAddress=" + arbitratorNodeAddress +
|
||||
"\n\tisBuyerOffererAndSellerTaker=" + isBuyerOffererAndSellerTaker +
|
||||
"\n\toffererAccountId='" + offererAccountId + '\'' +
|
||||
"\n\ttakerAccountId='" + takerAccountId + '\'' +
|
||||
"\n\toffererPaymentAccountContractData=" + offererPaymentAccountContractData +
|
||||
"\n\ttakerPaymentAccountContractData=" + takerPaymentAccountContractData +
|
||||
"\n\toffererPubKeyRing=" + offererPubKeyRing +
|
||||
"\n\ttakerPubKeyRing=" + takerPubKeyRing +
|
||||
"\n\tbuyerAddress=" + buyerNodeAddress +
|
||||
"\n\tsellerAddress=" + sellerNodeAddress +
|
||||
"\n\toffererPayoutAddressString='" + offererPayoutAddressString + '\'' +
|
||||
"\n\ttakerPayoutAddressString='" + takerPayoutAddressString + '\'' +
|
||||
"\n\toffererBtcPubKey=" + Arrays.toString(offererBtcPubKey) +
|
||||
"\n\ttakerBtcPubKey=" + Arrays.toString(takerBtcPubKey) +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
@ -137,7 +137,7 @@ abstract public class Trade implements Tradable, Model, Serializable {
|
||||
///////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// Transient/Immutable
|
||||
transient private ObjectProperty<State> processStateProperty;
|
||||
transient private ObjectProperty<State> stateProperty;
|
||||
transient private ObjectProperty<DisputeState> disputeStateProperty;
|
||||
transient private ObjectProperty<TradePeriodState> tradePeriodStateProperty;
|
||||
// Trades are saved in the TradeList
|
||||
@ -242,7 +242,7 @@ abstract public class Trade implements Tradable, Model, Serializable {
|
||||
}
|
||||
|
||||
protected void initStateProperties() {
|
||||
processStateProperty = new SimpleObjectProperty<>(state);
|
||||
stateProperty = new SimpleObjectProperty<>(state);
|
||||
disputeStateProperty = new SimpleObjectProperty<>(disputeState);
|
||||
tradePeriodStateProperty = new SimpleObjectProperty<>(tradePeriodState);
|
||||
}
|
||||
@ -300,7 +300,7 @@ abstract public class Trade implements Tradable, Model, Serializable {
|
||||
|
||||
public void setState(State state) {
|
||||
this.state = state;
|
||||
processStateProperty.set(state);
|
||||
stateProperty.set(state);
|
||||
persist();
|
||||
persist();
|
||||
}
|
||||
@ -385,7 +385,7 @@ abstract public class Trade implements Tradable, Model, Serializable {
|
||||
|
||||
|
||||
public ReadOnlyObjectProperty<? extends State> stateProperty() {
|
||||
return processStateProperty;
|
||||
return stateProperty;
|
||||
}
|
||||
|
||||
public ReadOnlyObjectProperty<Coin> tradeAmountProperty() {
|
||||
@ -609,25 +609,31 @@ abstract public class Trade implements Tradable, Model, Serializable {
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Trade{" +
|
||||
"tradeAmount=" + tradeAmount +
|
||||
", tradingPeer=" + tradingPeerNodeAddress +
|
||||
", tradeAmountProperty=" + tradeAmountProperty +
|
||||
", tradeVolumeProperty=" + tradeVolumeProperty +
|
||||
", processStateProperty=" + processStateProperty +
|
||||
", storage=" + storage +
|
||||
", tradeProtocol=" + tradeProtocol +
|
||||
", offer=" + offer +
|
||||
", date=" + takeOfferDate +
|
||||
", processModel=" + processModel +
|
||||
", processState=" + state +
|
||||
", messageWithPubKey=" + decryptedMsgWithPubKey +
|
||||
", depositTx=" + depositTx +
|
||||
/* ", contract=" + contract +
|
||||
", contractAsJson='" + contractAsJson + '\'' +*/
|
||||
/* ", sellerContractSignature='" + sellerContractSignature + '\'' +
|
||||
", buyerContractSignature='" + buyerContractSignature + '\'' +*/
|
||||
", payoutTx=" + payoutTx +
|
||||
", errorMessage='" + errorMessage + '\'' +
|
||||
"\n\ttradeAmount=" + tradeAmount +
|
||||
"\n\ttradingPeerNodeAddress=" + tradingPeerNodeAddress +
|
||||
"\n\ttradeVolume=" + tradeVolumeProperty.get() +
|
||||
"\n\toffer=" + offer +
|
||||
"\n\tprocessModel=" + processModel +
|
||||
"\n\tdecryptedMsgWithPubKey=" + decryptedMsgWithPubKey +
|
||||
"\n\ttakeOfferDate=" + takeOfferDate +
|
||||
"\n\tstate=" + state +
|
||||
"\n\tdisputeState=" + disputeState +
|
||||
"\n\ttradePeriodState=" + tradePeriodState +
|
||||
"\n\tdepositTx=" + depositTx +
|
||||
"\n\tcontract=" + contract +
|
||||
/* "\n\tcontractAsJson='" + contractAsJson + '\'' +*/
|
||||
/* "\n\tcontractHash=" + Arrays.toString(contractHash) +*/
|
||||
"\n\ttakerContractSignature.hashCode()='" + takerContractSignature.hashCode() + '\'' +
|
||||
"\n\toffererContractSignature.hashCode()='" + offererContractSignature.hashCode() + '\'' +
|
||||
"\n\tpayoutTx=" + payoutTx +
|
||||
"\n\tlockTimeAsBlockHeight=" + lockTimeAsBlockHeight +
|
||||
"\n\topenDisputeTimeAsBlockHeight=" + openDisputeTimeAsBlockHeight +
|
||||
"\n\tcheckPaymentTimeAsBlockHeight=" + checkPaymentTimeAsBlockHeight +
|
||||
"\n\tarbitratorNodeAddress=" + arbitratorNodeAddress +
|
||||
"\n\ttakerPaymentAccountId='" + takerPaymentAccountId + '\'' +
|
||||
"\n\thalfTradePeriodReachedWarningDisplayed=" + halfTradePeriodReachedWarningDisplayed +
|
||||
"\n\ttradePeriodOverWarningDisplayed=" + tradePeriodOverWarningDisplayed +
|
||||
"\n\terrorMessage='" + errorMessage + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
@ -395,27 +395,27 @@ public final class Offer implements PubKeyProtectedExpirablePayload {
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Offer{" +
|
||||
"id='" + id + '\'' +
|
||||
", direction=" + direction +
|
||||
", currencyCode='" + currencyCode + '\'' +
|
||||
", date=" + date +
|
||||
", fiatPrice=" + fiatPrice +
|
||||
", amount=" + amount +
|
||||
", minAmount=" + minAmount +
|
||||
", offererAddress=" + offererNodeAddress +
|
||||
", pubKeyRing=" + pubKeyRing +
|
||||
", paymentMethodName='" + paymentMethodName + '\'' +
|
||||
", paymentMethodCountryCode='" + paymentMethodCountryCode + '\'' +
|
||||
", offererPaymentAccountId='" + offererPaymentAccountId + '\'' +
|
||||
", acceptedCountryCodes=" + acceptedCountryCodes +
|
||||
", arbitratorAddresses=" + arbitratorNodeAddresses +
|
||||
", offerFeePaymentTxID='" + offerFeePaymentTxID + '\'' +
|
||||
", state=" + state +
|
||||
", stateProperty=" + stateProperty +
|
||||
", availabilityProtocol=" + availabilityProtocol +
|
||||
", errorMessageProperty=" + errorMessageProperty +
|
||||
", TAC_OFFERER=" + TAC_OFFERER +
|
||||
", TAC_TAKER=" + TAC_TAKER +
|
||||
"\n\tid='" + id + '\'' +
|
||||
"\n\tdirection=" + direction +
|
||||
"\n\tcurrencyCode='" + currencyCode + '\'' +
|
||||
"\n\tdate=" + date +
|
||||
"\n\tfiatPrice=" + fiatPrice +
|
||||
"\n\tamount=" + amount +
|
||||
"\n\tminAmount=" + minAmount +
|
||||
"\n\toffererAddress=" + offererNodeAddress +
|
||||
"\n\tpubKeyRing=" + pubKeyRing +
|
||||
"\n\tpaymentMethodName='" + paymentMethodName + '\'' +
|
||||
"\n\tpaymentMethodCountryCode='" + paymentMethodCountryCode + '\'' +
|
||||
"\n\toffererPaymentAccountId='" + offererPaymentAccountId + '\'' +
|
||||
"\n\tacceptedCountryCodes=" + acceptedCountryCodes +
|
||||
"\n\tarbitratorAddresses=" + arbitratorNodeAddresses +
|
||||
"\n\tofferFeePaymentTxID='" + offerFeePaymentTxID + '\'' +
|
||||
"\n\tstate=" + state +
|
||||
"\n\tstateProperty=" + stateProperty +
|
||||
"\n\tavailabilityProtocol=" + availabilityProtocol +
|
||||
"\n\terrorMessageProperty=" + errorMessageProperty +
|
||||
"\n\tTAC_OFFERER=" + TAC_OFFERER +
|
||||
"\n\tTAC_TAKER=" + TAC_TAKER +
|
||||
'}';
|
||||
}
|
||||
|
||||
|
@ -110,6 +110,16 @@ public class OpenOffer implements Tradable, Serializable {
|
||||
timeoutTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "OpenOffer{" +
|
||||
"\n\ttimeoutTimer=" + timeoutTimer +
|
||||
"\n\toffer=" + offer +
|
||||
"\n\tstate=" + state +
|
||||
"\n\tstorage=" + storage +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -28,6 +28,7 @@ import io.bitsquare.payment.PaymentAccount;
|
||||
import io.bitsquare.payment.PaymentAccountContractData;
|
||||
import javafx.scene.control.TextField;
|
||||
import javafx.scene.layout.GridPane;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -73,7 +74,7 @@ public class AliPayForm extends PaymentMethodForm {
|
||||
protected void autoFillNameTextField() {
|
||||
if (autoFillCheckBox != null && autoFillCheckBox.isSelected()) {
|
||||
String accountNr = accountNrInputTextField.getText();
|
||||
accountNr = accountNr.substring(0, Math.min(5, accountNr.length())) + "...";
|
||||
accountNr = StringUtils.abbreviate(accountNr, 5);
|
||||
String method = BSResources.get(paymentAccount.getPaymentMethod().getId());
|
||||
accountNameTextField.setText(method.concat(", ").concat(accountNr));
|
||||
}
|
||||
|
@ -33,6 +33,7 @@ import javafx.scene.control.ComboBox;
|
||||
import javafx.scene.control.TextField;
|
||||
import javafx.scene.layout.GridPane;
|
||||
import javafx.util.StringConverter;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -88,7 +89,7 @@ public class BlockChainForm extends PaymentMethodForm {
|
||||
if (autoFillCheckBox != null && autoFillCheckBox.isSelected()) {
|
||||
String method = BSResources.get(paymentAccount.getPaymentMethod().getId());
|
||||
String address = addressInputTextField.getText();
|
||||
address = address.substring(0, Math.min(9, address.length())) + "...";
|
||||
address = StringUtils.abbreviate(address, 9);
|
||||
String currency = paymentAccount.getSingleTradeCurrency() != null ? paymentAccount.getSingleTradeCurrency().getCode() : "?";
|
||||
accountNameTextField.setText(method.concat(", ").concat(currency).concat(", ").concat(address));
|
||||
}
|
||||
|
@ -35,6 +35,7 @@ import javafx.scene.control.TextField;
|
||||
import javafx.scene.control.Tooltip;
|
||||
import javafx.scene.layout.FlowPane;
|
||||
import javafx.scene.layout.GridPane;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -117,7 +118,7 @@ public class OKPayForm extends PaymentMethodForm {
|
||||
protected void autoFillNameTextField() {
|
||||
if (autoFillCheckBox != null && autoFillCheckBox.isSelected()) {
|
||||
String accountNr = accountNrInputTextField.getText();
|
||||
accountNr = accountNr.substring(0, Math.min(5, accountNr.length())) + "...";
|
||||
accountNr = StringUtils.abbreviate(accountNr, 5);
|
||||
String method = BSResources.get(paymentAccount.getPaymentMethod().getId());
|
||||
accountNameTextField.setText(method.concat(", ").concat(accountNr));
|
||||
}
|
||||
|
@ -28,6 +28,7 @@ import io.bitsquare.payment.PerfectMoneyAccount;
|
||||
import io.bitsquare.payment.PerfectMoneyAccountContractData;
|
||||
import javafx.scene.control.TextField;
|
||||
import javafx.scene.layout.GridPane;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -75,7 +76,7 @@ public class PerfectMoneyForm extends PaymentMethodForm {
|
||||
protected void autoFillNameTextField() {
|
||||
if (autoFillCheckBox != null && autoFillCheckBox.isSelected()) {
|
||||
String accountNr = accountNrInputTextField.getText();
|
||||
accountNr = accountNr.substring(0, Math.min(5, accountNr.length())) + "...";
|
||||
accountNr = StringUtils.abbreviate(accountNr, 5);
|
||||
String method = BSResources.get(paymentAccount.getPaymentMethod().getId());
|
||||
accountNameTextField.setText(method.concat(", ").concat(accountNr));
|
||||
}
|
||||
|
@ -36,6 +36,7 @@ import javafx.scene.layout.FlowPane;
|
||||
import javafx.scene.layout.GridPane;
|
||||
import javafx.scene.text.TextAlignment;
|
||||
import javafx.util.StringConverter;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -220,7 +221,7 @@ public class SepaForm extends PaymentMethodForm {
|
||||
if (autoFillCheckBox != null && autoFillCheckBox.isSelected()) {
|
||||
String iban = ibanInputTextField.getText();
|
||||
if (iban.length() > 5)
|
||||
iban = "..." + iban.substring(iban.length() - 5, iban.length());
|
||||
iban = StringUtils.abbreviate(iban, 5);
|
||||
String method = BSResources.get(paymentAccount.getPaymentMethod().getId());
|
||||
String country = paymentAccount.getCountry() != null ? paymentAccount.getCountry().code : "?";
|
||||
String currency = paymentAccount.getSingleTradeCurrency() != null ? paymentAccount.getSingleTradeCurrency().getCode() : "?";
|
||||
|
@ -28,6 +28,7 @@ import io.bitsquare.payment.SwishAccount;
|
||||
import io.bitsquare.payment.SwishAccountContractData;
|
||||
import javafx.scene.control.TextField;
|
||||
import javafx.scene.layout.GridPane;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -82,7 +83,7 @@ public class SwishForm extends PaymentMethodForm {
|
||||
protected void autoFillNameTextField() {
|
||||
if (autoFillCheckBox != null && autoFillCheckBox.isSelected()) {
|
||||
String mobileNr = mobileNrInputTextField.getText();
|
||||
mobileNr = mobileNr.substring(0, Math.min(5, mobileNr.length())) + "...";
|
||||
mobileNr = StringUtils.abbreviate(mobileNr, 5);
|
||||
String method = BSResources.get(paymentAccount.getPaymentMethod().getId());
|
||||
accountNameTextField.setText(method.concat(", ").concat(mobileNr));
|
||||
}
|
||||
|
@ -34,6 +34,7 @@ import javafx.stage.Modality;
|
||||
import javafx.stage.Stage;
|
||||
import javafx.stage.StageStyle;
|
||||
import javafx.stage.Window;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.reactfx.util.FxTimer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@ -362,7 +363,7 @@ public class Popup {
|
||||
|
||||
protected void setTruncatedMessage() {
|
||||
if (message != null && message.length() > 800)
|
||||
truncatedMessage = message.substring(0, 800) + "...";
|
||||
truncatedMessage = StringUtils.abbreviate(message, 800);
|
||||
else
|
||||
truncatedMessage = message;
|
||||
}
|
||||
|
@ -321,7 +321,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
|
||||
@Override
|
||||
public void onMessage(Message message, Connection connection) {
|
||||
if (message instanceof PrefixedSealedAndSignedMessage) {
|
||||
Log.traceCall(message.toString());
|
||||
Log.traceCall(message.toString() + "\n\tconnection=" + connection);
|
||||
// Seed nodes don't have set the encryptionService
|
||||
if (optionalEncryptionService.isPresent()) {
|
||||
try {
|
||||
@ -334,9 +334,9 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
|
||||
DecryptedMsgWithPubKey decryptedMsgWithPubKey = optionalEncryptionService.get().decryptAndVerify(
|
||||
prefixedSealedAndSignedMessage.sealedAndSigned);
|
||||
|
||||
log.info("\n\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n" +
|
||||
log.info("\n\nDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD\n" +
|
||||
"Decrypted SealedAndSignedMessage:\ndecryptedMsgWithPubKey={}"
|
||||
+ "\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n", decryptedMsgWithPubKey);
|
||||
+ "\nDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD\n", decryptedMsgWithPubKey);
|
||||
connection.getPeersNodeAddressOptional().ifPresent(peersNodeAddress ->
|
||||
decryptedDirectMessageListeners.stream().forEach(
|
||||
e -> e.onDirectMessage(decryptedMsgWithPubKey, peersNodeAddress)));
|
||||
@ -389,9 +389,9 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
|
||||
checkArgument(optionalEncryptionService.isPresent(), "EncryptionService not set. Seems that is called on a seed node which must not happen.");
|
||||
checkNotNull(networkNode.getNodeAddress(), "networkNode.getNodeAddress() must not be null.");
|
||||
try {
|
||||
log.info("\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n" +
|
||||
log.info("\n\nEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\n" +
|
||||
"Encrypt message:\nmessage={}"
|
||||
+ "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n", message);
|
||||
+ "\nEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\n", message);
|
||||
PrefixedSealedAndSignedMessage prefixedSealedAndSignedMessage = new PrefixedSealedAndSignedMessage(networkNode.getNodeAddress(),
|
||||
optionalEncryptionService.get().encryptAndSign(pubKeyRing, message),
|
||||
peersNodeAddress.getAddressPrefixHash());
|
||||
@ -474,9 +474,9 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
|
||||
if (isBootstrapped()) {
|
||||
if (!networkNode.getAllConnections().isEmpty()) {
|
||||
try {
|
||||
log.info("\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n" +
|
||||
log.info("\n\nEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\n" +
|
||||
"Encrypt message:\nmessage={}"
|
||||
+ "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n", message);
|
||||
+ "\nEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\n", message);
|
||||
PrefixedSealedAndSignedMessage prefixedSealedAndSignedMessage = new PrefixedSealedAndSignedMessage(
|
||||
networkNode.getNodeAddress(),
|
||||
optionalEncryptionService.get().encryptAndSign(peersPubKeyRing, message),
|
||||
@ -609,7 +609,7 @@ public class P2PService implements SetupListener, MessageListener, ConnectionLis
|
||||
}
|
||||
} else {
|
||||
log.warn("decryptedMsgWithPubKey not found in mailboxMap. That should never happen." +
|
||||
"\ndecryptedMsgWithPubKey={}\nmailboxMap={}", decryptedMsgWithPubKey, mailboxMap);
|
||||
"\n\tdecryptedMsgWithPubKey={}\n\tmailboxMap={}", decryptedMsgWithPubKey, mailboxMap);
|
||||
}
|
||||
} else {
|
||||
throw new NetworkNotReadyException();
|
||||
|
@ -15,6 +15,7 @@ import io.bitsquare.p2p.network.messages.SendersNodeAddressMessage;
|
||||
import javafx.beans.property.ObjectProperty;
|
||||
import javafx.beans.property.ReadOnlyObjectProperty;
|
||||
import javafx.beans.property.SimpleObjectProperty;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@ -91,7 +92,6 @@ public class Connection implements MessageListener {
|
||||
|
||||
Connection(Socket socket, MessageListener messageListener, ConnectionListener connectionListener,
|
||||
@Nullable NodeAddress peersNodeAddress) {
|
||||
Log.traceCall();
|
||||
this.socket = socket;
|
||||
this.messageListener = messageListener;
|
||||
this.connectionListener = connectionListener;
|
||||
@ -107,8 +107,6 @@ public class Connection implements MessageListener {
|
||||
}
|
||||
|
||||
private void init(@Nullable NodeAddress peersNodeAddress) {
|
||||
Log.traceCall();
|
||||
|
||||
try {
|
||||
socket.setSoTimeout(SOCKET_TIMEOUT);
|
||||
// Need to access first the ObjectOutputStream otherwise the ObjectInputStream would block
|
||||
@ -135,7 +133,7 @@ public class Connection implements MessageListener {
|
||||
if (peersNodeAddress != null)
|
||||
setPeersNodeAddress(peersNodeAddress);
|
||||
|
||||
log.trace("\nNew connection created " + this.toString());
|
||||
log.trace("New connection created: " + this.toString());
|
||||
|
||||
UserThread.execute(() -> connectionListener.onConnection(this));
|
||||
}
|
||||
@ -148,7 +146,6 @@ public class Connection implements MessageListener {
|
||||
|
||||
// Called form various threads
|
||||
public void sendMessage(Message message) {
|
||||
Log.traceCall();
|
||||
if (!stopped) {
|
||||
try {
|
||||
String peersNodeAddress = peersNodeAddressOptional.isPresent() ? peersNodeAddressOptional.get().toString() : "null";
|
||||
@ -159,12 +156,12 @@ public class Connection implements MessageListener {
|
||||
"Sending direct message to peer" +
|
||||
"Write object to outputStream to peer: {} (uid={})\ntruncated message={}" +
|
||||
"\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n",
|
||||
peersNodeAddress, uid, message.toString().substring(0, Math.min(60, message.toString().length())));
|
||||
peersNodeAddress, uid, StringUtils.abbreviate(message.toString(), 100));
|
||||
} else {
|
||||
log.info("\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n" +
|
||||
"Write object to outputStream to peer: {} (uid={})\ntruncated message={}" +
|
||||
"\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n",
|
||||
peersNodeAddress, uid, message.toString().substring(0, Math.min(60, message.toString().length())));
|
||||
peersNodeAddress, uid, StringUtils.abbreviate(message.toString(), 100));
|
||||
}
|
||||
|
||||
Object objectToWrite;
|
||||
@ -196,9 +193,8 @@ public class Connection implements MessageListener {
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public void reportIllegalRequest(IllegalRequest illegalRequest) {
|
||||
Log.traceCall();
|
||||
sharedModel.reportIllegalRequest(illegalRequest);
|
||||
public void reportIllegalRequest(CorruptRequest corruptRequest) {
|
||||
sharedModel.reportInvalidRequest(corruptRequest);
|
||||
}
|
||||
|
||||
public boolean violatesThrottleLimit() {
|
||||
@ -208,7 +204,7 @@ public class Connection implements MessageListener {
|
||||
// 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);
|
||||
violated = now - compareValue < TimeUnit.SECONDS.toMillis(1);
|
||||
}
|
||||
|
||||
if (messageTimeStamps.size() >= MSG_THROTTLE_PER_10SEC) {
|
||||
@ -248,7 +244,6 @@ public class Connection implements MessageListener {
|
||||
}
|
||||
|
||||
private synchronized void setPeersNodeAddress(NodeAddress peerNodeAddress) {
|
||||
Log.traceCall(peerNodeAddress.toString());
|
||||
checkNotNull(peerNodeAddress, "peerAddress must not be null");
|
||||
peersNodeAddressOptional = Optional.of(peerNodeAddress);
|
||||
|
||||
@ -257,7 +252,7 @@ public class Connection implements MessageListener {
|
||||
log.info("\n\n############################################################\n" +
|
||||
"We got the peers node address set.\n" +
|
||||
"peersNodeAddress= " + peersNodeAddress +
|
||||
"\nuid=" + getUid() +
|
||||
"\nconnection.uid=" + getUid() +
|
||||
"\n############################################################\n");
|
||||
}
|
||||
|
||||
@ -321,13 +316,9 @@ public class Connection implements MessageListener {
|
||||
log.info("\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" +
|
||||
"ShutDown connection:"
|
||||
+ "\npeersNodeAddress=" + peersNodeAddress
|
||||
+ "\nlocalPort/port=" + sharedModel.getSocket().getLocalPort()
|
||||
+ "/" + sharedModel.getSocket().getPort()
|
||||
+ "\nuid=" + uid
|
||||
+ "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n");
|
||||
|
||||
log.trace("ShutDown connection requested. Connection=" + this.toString());
|
||||
|
||||
if (sendCloseConnectionMessage) {
|
||||
new Thread(() -> {
|
||||
Thread.currentThread().setName("Connection:SendCloseConnectionMessage-" + this.uid);
|
||||
@ -359,7 +350,6 @@ public class Connection implements MessageListener {
|
||||
}
|
||||
|
||||
private void doShutDown(@Nullable Runnable shutDownCompleteHandler) {
|
||||
Log.traceCall();
|
||||
ConnectionListener.Reason shutDownReason = sharedModel.getShutDownReason();
|
||||
if (shutDownReason == null)
|
||||
shutDownReason = ConnectionListener.Reason.SHUT_DOWN;
|
||||
@ -378,8 +368,7 @@ public class Connection implements MessageListener {
|
||||
MoreExecutors.shutdownAndAwaitTermination(singleThreadExecutor, 500, TimeUnit.MILLISECONDS);
|
||||
|
||||
log.debug("Connection shutdown complete " + this.toString());
|
||||
// keep UserThread.execute as its not clear if that is called from a non-UserThread
|
||||
|
||||
// Use UserThread.execute as its not clear if that is called from a non-UserThread
|
||||
if (shutDownCompleteHandler != null)
|
||||
UserThread.execute(shutDownCompleteHandler);
|
||||
}
|
||||
@ -413,6 +402,7 @@ public class Connection implements MessageListener {
|
||||
"peerAddress=" + peersNodeAddressOptional +
|
||||
", peerType=" + peerType +
|
||||
", uid='" + uid + '\'' +
|
||||
", lastActivityDate=" + getLastActivityDate() +
|
||||
'}';
|
||||
}
|
||||
|
||||
@ -443,7 +433,7 @@ public class Connection implements MessageListener {
|
||||
|
||||
private final Connection connection;
|
||||
private final Socket socket;
|
||||
private final ConcurrentHashMap<IllegalRequest, Integer> illegalRequests = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<CorruptRequest, Integer> corruptRequests = new ConcurrentHashMap<>();
|
||||
|
||||
// mutable
|
||||
private Date lastActivityDate;
|
||||
@ -451,43 +441,38 @@ public class Connection implements MessageListener {
|
||||
private ConnectionListener.Reason shutDownReason;
|
||||
|
||||
public SharedModel(Connection connection, Socket socket) {
|
||||
Log.traceCall();
|
||||
this.connection = connection;
|
||||
this.socket = socket;
|
||||
}
|
||||
|
||||
public synchronized void updateLastActivityDate() {
|
||||
Log.traceCall();
|
||||
lastActivityDate = new Date();
|
||||
}
|
||||
|
||||
public synchronized Date getLastActivityDate() {
|
||||
// Log.traceCall();
|
||||
return lastActivityDate;
|
||||
}
|
||||
|
||||
public void reportIllegalRequest(IllegalRequest illegalRequest) {
|
||||
Log.traceCall();
|
||||
log.warn("We got reported an illegal request " + illegalRequest);
|
||||
log.debug("connection={}" + this);
|
||||
int violations;
|
||||
if (illegalRequests.contains(illegalRequest))
|
||||
violations = illegalRequests.get(illegalRequest);
|
||||
public void reportInvalidRequest(CorruptRequest corruptRequest) {
|
||||
log.warn("We got reported an corrupt request " + corruptRequest + "\n\tconnection=" + this);
|
||||
int numCorruptRequests;
|
||||
if (corruptRequests.contains(corruptRequest))
|
||||
numCorruptRequests = corruptRequests.get(corruptRequest);
|
||||
else
|
||||
violations = 0;
|
||||
numCorruptRequests = 0;
|
||||
|
||||
violations++;
|
||||
illegalRequests.put(illegalRequest, violations);
|
||||
numCorruptRequests++;
|
||||
corruptRequests.put(corruptRequest, numCorruptRequests);
|
||||
|
||||
if (violations >= illegalRequest.maxTolerance) {
|
||||
log.warn("We close connection as we received too many invalid requests.\n" +
|
||||
"violations={}\n" +
|
||||
"illegalRequest={}\n" +
|
||||
"illegalRequests={}", violations, illegalRequest, illegalRequests.toString());
|
||||
log.debug("connection={}" + this);
|
||||
if (numCorruptRequests >= corruptRequest.maxTolerance) {
|
||||
log.warn("We close connection as we received too many corrupt requests.\n" +
|
||||
"numCorruptRequests={}\n\t" +
|
||||
"corruptRequest={}\n\t" +
|
||||
"corruptRequests={}\n\t" +
|
||||
"connection={}", numCorruptRequests, corruptRequest, corruptRequests.toString(), connection);
|
||||
shutDown();
|
||||
} else {
|
||||
illegalRequests.put(illegalRequest, ++violations);
|
||||
corruptRequests.put(corruptRequest, ++numCorruptRequests);
|
||||
}
|
||||
}
|
||||
|
||||
@ -500,16 +485,15 @@ public class Connection implements MessageListener {
|
||||
shutDownReason = ConnectionListener.Reason.RESET;
|
||||
} else if (e instanceof SocketTimeoutException || e instanceof TimeoutException) {
|
||||
shutDownReason = ConnectionListener.Reason.TIMEOUT;
|
||||
log.debug("TimeoutException at socket " + socket.toString());
|
||||
log.debug("connection={}" + this);
|
||||
log.debug("TimeoutException at socket " + socket.toString() + " on connection={}" + this);
|
||||
} else if (e instanceof EOFException) {
|
||||
shutDownReason = ConnectionListener.Reason.PEER_DISCONNECTED;
|
||||
} else if (e instanceof NoClassDefFoundError || e instanceof ClassNotFoundException) {
|
||||
shutDownReason = ConnectionListener.Reason.INCOMPATIBLE_DATA;
|
||||
} else {
|
||||
shutDownReason = ConnectionListener.Reason.UNKNOWN;
|
||||
log.warn("Exception at socket " + socket.toString());
|
||||
log.debug("connection={}" + this);
|
||||
log.warn("Unknown reason for exception at socket {} on connection={}\n\tException=",
|
||||
socket.toString(), this, e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
@ -517,24 +501,17 @@ public class Connection implements MessageListener {
|
||||
}
|
||||
|
||||
public void shutDown() {
|
||||
Log.traceCall();
|
||||
if (!stopped) {
|
||||
stopped = true;
|
||||
connection.shutDown(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public synchronized Socket getSocket() {
|
||||
return socket;
|
||||
}
|
||||
|
||||
public String getConnectionInfo() {
|
||||
return connection.toString();
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
Log.traceCall();
|
||||
this.stopped = true;
|
||||
}
|
||||
|
||||
@ -546,7 +523,7 @@ public class Connection implements MessageListener {
|
||||
public String toString() {
|
||||
return "SharedSpace{" +
|
||||
", socket=" + socket +
|
||||
", illegalRequests=" + illegalRequests +
|
||||
", illegalRequests=" + corruptRequests +
|
||||
", lastActivityDate=" + lastActivityDate +
|
||||
'}';
|
||||
}
|
||||
@ -570,7 +547,6 @@ public class Connection implements MessageListener {
|
||||
private volatile boolean stopped;
|
||||
|
||||
public InputHandler(SharedModel sharedModel, ObjectInputStream objectInputStream, String portInfo, MessageListener messageListener, boolean useCompression) {
|
||||
Log.traceCall();
|
||||
this.useCompression = useCompression;
|
||||
this.sharedModel = sharedModel;
|
||||
this.objectInputStream = objectInputStream;
|
||||
@ -579,7 +555,6 @@ public class Connection implements MessageListener {
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
Log.traceCall();
|
||||
stopped = true;
|
||||
try {
|
||||
objectInputStream.close();
|
||||
@ -590,23 +565,23 @@ public class Connection implements MessageListener {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
Log.traceCall();
|
||||
try {
|
||||
Thread.currentThread().setName("InputHandler-" + portInfo);
|
||||
while (!stopped && !Thread.currentThread().isInterrupted()) {
|
||||
try {
|
||||
log.trace("InputHandler waiting for incoming messages connection=" + sharedModel.getConnectionInfo());
|
||||
log.trace("InputHandler waiting for incoming messages.\n\tConnection=" + sharedModel.connection);
|
||||
Object rawInputObject = objectInputStream.readObject();
|
||||
log.trace("New data arrived at inputHandler.Connection=" + sharedModel.getConnectionInfo());
|
||||
|
||||
log.info("\n\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n" +
|
||||
"New data arrived at inputHandler.\nTruncated received object={}"
|
||||
"New data arrived at inputHandler of connection {}.\n" +
|
||||
"Received object (truncated)={}"
|
||||
+ "\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n",
|
||||
rawInputObject.toString().substring(0, Math.min(60, rawInputObject.toString().length())));
|
||||
sharedModel.connection,
|
||||
StringUtils.abbreviate(rawInputObject.toString(), 100));
|
||||
|
||||
int size = ByteArrayUtils.objectToByteArray(rawInputObject).length;
|
||||
if (size > getMaxMsgSize()) {
|
||||
sharedModel.reportIllegalRequest(IllegalRequest.MaxSizeExceeded);
|
||||
sharedModel.reportInvalidRequest(CorruptRequest.MaxSizeExceeded);
|
||||
return;
|
||||
}
|
||||
|
||||
@ -618,36 +593,36 @@ public class Connection implements MessageListener {
|
||||
//log.trace("Read object compressed data size: " + size);
|
||||
serializable = Utils.decompress(compressedObjectAsBytes);
|
||||
} else {
|
||||
sharedModel.reportIllegalRequest(IllegalRequest.InvalidDataType);
|
||||
sharedModel.reportInvalidRequest(CorruptRequest.InvalidDataType);
|
||||
}
|
||||
} else {
|
||||
if (rawInputObject instanceof Serializable) {
|
||||
serializable = (Serializable) rawInputObject;
|
||||
} else {
|
||||
sharedModel.reportIllegalRequest(IllegalRequest.InvalidDataType);
|
||||
sharedModel.reportInvalidRequest(CorruptRequest.InvalidDataType);
|
||||
}
|
||||
}
|
||||
//log.trace("Read object decompressed data size: " + ByteArrayUtils.objectToByteArray(serializable).length);
|
||||
|
||||
// compressed size might be bigger theoretically so we check again after decompression
|
||||
if (size > getMaxMsgSize()) {
|
||||
sharedModel.reportIllegalRequest(IllegalRequest.MaxSizeExceeded);
|
||||
sharedModel.reportInvalidRequest(CorruptRequest.MaxSizeExceeded);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sharedModel.connection.violatesThrottleLimit()) {
|
||||
sharedModel.reportIllegalRequest(IllegalRequest.ViolatedThrottleLimit);
|
||||
sharedModel.reportInvalidRequest(CorruptRequest.ViolatedThrottleLimit);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!(serializable instanceof Message)) {
|
||||
sharedModel.reportIllegalRequest(IllegalRequest.InvalidDataType);
|
||||
sharedModel.reportInvalidRequest(CorruptRequest.InvalidDataType);
|
||||
return;
|
||||
}
|
||||
|
||||
Message message = (Message) serializable;
|
||||
if (message.networkId() != Version.getNetworkId()) {
|
||||
sharedModel.reportIllegalRequest(IllegalRequest.WrongNetworkId);
|
||||
sharedModel.reportInvalidRequest(CorruptRequest.WrongNetworkId);
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
package io.bitsquare.p2p.network;
|
||||
|
||||
public enum IllegalRequest {
|
||||
public enum CorruptRequest {
|
||||
MaxSizeExceeded(1),
|
||||
InvalidDataType(0),
|
||||
WrongNetworkId(0),
|
||||
@ -8,7 +8,7 @@ public enum IllegalRequest {
|
||||
|
||||
public final int maxTolerance;
|
||||
|
||||
IllegalRequest(int maxTolerance) {
|
||||
CorruptRequest(int maxTolerance) {
|
||||
this.maxTolerance = maxTolerance;
|
||||
}
|
||||
}
|
@ -46,7 +46,6 @@ public abstract class NetworkNode implements MessageListener, ConnectionListener
|
||||
///////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
NetworkNode(int servicePort) {
|
||||
Log.traceCall();
|
||||
this.servicePort = servicePort;
|
||||
}
|
||||
|
||||
@ -57,7 +56,7 @@ public abstract class NetworkNode implements MessageListener, ConnectionListener
|
||||
abstract public void start(@Nullable SetupListener setupListener);
|
||||
|
||||
public SettableFuture<Connection> sendMessage(@NotNull NodeAddress peersNodeAddress, Message message) {
|
||||
Log.traceCall("peerAddress: " + peersNodeAddress + " / message: " + message);
|
||||
Log.traceCall("peersNodeAddress=" + peersNodeAddress + "\n\tmessage=" + message);
|
||||
checkNotNull(peersNodeAddress, "peerAddress must not be null");
|
||||
|
||||
Optional<Connection> outboundConnectionOptional = lookupOutboundConnection(peersNodeAddress);
|
||||
@ -81,7 +80,7 @@ public abstract class NetworkNode implements MessageListener, ConnectionListener
|
||||
if (connection != null) {
|
||||
return sendMessage(connection, message);
|
||||
} else {
|
||||
log.trace("We have not found any connection for peerAddress {}. " +
|
||||
log.trace("We have not found any connection for peerAddress {}.\n\t" +
|
||||
"We will create a new outbound connection.", peersNodeAddress);
|
||||
|
||||
final SettableFuture<Connection> resultFuture = SettableFuture.create();
|
||||
@ -128,7 +127,7 @@ public abstract class NetworkNode implements MessageListener, ConnectionListener
|
||||
}
|
||||
|
||||
public SettableFuture<Connection> sendMessage(Connection connection, Message message) {
|
||||
Log.traceCall("message: " + message + " to connection: " + connection);
|
||||
Log.traceCall("message=" + message + "\n\tconnection=" + connection);
|
||||
// connection.sendMessage might take a bit (compression, write to stream), so we use a thread to not block
|
||||
ListenableFuture<Connection> future = executorService.submit(() -> {
|
||||
Thread.currentThread().setName("NetworkNode:SendMessage-to-" + connection.getUid());
|
||||
@ -174,7 +173,6 @@ public abstract class NetworkNode implements MessageListener, ConnectionListener
|
||||
|
||||
public void shutDown(Runnable shutDownCompleteHandler) {
|
||||
Log.traceCall();
|
||||
log.info("Shutdown NetworkNode");
|
||||
if (!shutDownInProgress) {
|
||||
shutDownInProgress = true;
|
||||
if (server != null) {
|
||||
@ -195,7 +193,6 @@ public abstract class NetworkNode implements MessageListener, ConnectionListener
|
||||
///////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
void addSetupListener(SetupListener setupListener) {
|
||||
Log.traceCall();
|
||||
boolean isNewEntry = setupListeners.add(setupListener);
|
||||
if (!isNewEntry)
|
||||
log.warn("Try to add a setupListener which was already added.");
|
||||
@ -208,13 +205,11 @@ public abstract class NetworkNode implements MessageListener, ConnectionListener
|
||||
|
||||
@Override
|
||||
public void onConnection(Connection connection) {
|
||||
Log.traceCall("connection=" + connection);
|
||||
connectionListeners.stream().forEach(e -> e.onConnection(connection));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisconnect(Reason reason, Connection connection) {
|
||||
Log.traceCall("connection = " + connection);
|
||||
outBoundConnections.remove(connection);
|
||||
inBoundConnections.remove(connection);
|
||||
connectionListeners.stream().forEach(e -> e.onDisconnect(reason, connection));
|
||||
@ -222,7 +217,6 @@ public abstract class NetworkNode implements MessageListener, ConnectionListener
|
||||
|
||||
@Override
|
||||
public void onError(Throwable throwable) {
|
||||
Log.traceCall();
|
||||
connectionListeners.stream().forEach(e -> e.onError(throwable));
|
||||
}
|
||||
|
||||
@ -242,34 +236,29 @@ public abstract class NetworkNode implements MessageListener, ConnectionListener
|
||||
///////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
public void addConnectionListener(ConnectionListener connectionListener) {
|
||||
Log.traceCall();
|
||||
|
||||
boolean isNewEntry = connectionListeners.add(connectionListener);
|
||||
if (!isNewEntry)
|
||||
log.warn("Try to add a connectionListener which was already added.\nconnectionListener={}\nconnectionListeners={}"
|
||||
log.warn("Try to add a connectionListener which was already added.\n\tconnectionListener={}\n\tconnectionListeners={}"
|
||||
, connectionListener, connectionListeners);
|
||||
}
|
||||
|
||||
public void removeConnectionListener(ConnectionListener connectionListener) {
|
||||
Log.traceCall();
|
||||
boolean contained = connectionListeners.remove(connectionListener);
|
||||
if (!contained)
|
||||
log.debug("Try to remove a connectionListener which was never added. " +
|
||||
log.debug("Try to remove a connectionListener which was never added.\n\t" +
|
||||
"That might happen because of async behaviour of CopyOnWriteArraySet");
|
||||
}
|
||||
|
||||
public void addMessageListener(MessageListener messageListener) {
|
||||
Log.traceCall();
|
||||
boolean isNewEntry = messageListeners.add(messageListener);
|
||||
if (!isNewEntry)
|
||||
log.warn("Try to add a messageListener which was already added.");
|
||||
}
|
||||
|
||||
public void removeMessageListener(MessageListener messageListener) {
|
||||
Log.traceCall();
|
||||
boolean contained = messageListeners.remove(messageListener);
|
||||
if (!contained)
|
||||
log.debug("Try to remove a messageListener which was never added. " +
|
||||
log.debug("Try to remove a messageListener which was never added.\n\t" +
|
||||
"That might happen because of async behaviour of CopyOnWriteArraySet");
|
||||
}
|
||||
|
||||
@ -279,30 +268,25 @@ public abstract class NetworkNode implements MessageListener, ConnectionListener
|
||||
///////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
void createExecutorService() {
|
||||
Log.traceCall();
|
||||
executorService = Utilities.getListeningExecutorService("NetworkNode-" + servicePort, 20, 50, 120L);
|
||||
}
|
||||
|
||||
void startServer(ServerSocket serverSocket) {
|
||||
Log.traceCall();
|
||||
ConnectionListener startServerConnectionListener = new ConnectionListener() {
|
||||
@Override
|
||||
public void onConnection(Connection connection) {
|
||||
Log.traceCall("startServerConnectionListener connection=" + connection);
|
||||
inBoundConnections.add(connection);
|
||||
NetworkNode.this.onConnection(connection);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisconnect(Reason reason, Connection connection) {
|
||||
Log.traceCall("onDisconnect at incoming connection = " + connection);
|
||||
inBoundConnections.remove(connection);
|
||||
NetworkNode.this.onDisconnect(reason, connection);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Throwable throwable) {
|
||||
Log.traceCall();
|
||||
NetworkNode.this.onError(throwable);
|
||||
}
|
||||
};
|
||||
@ -313,13 +297,21 @@ public abstract class NetworkNode implements MessageListener, ConnectionListener
|
||||
}
|
||||
|
||||
private Optional<Connection> lookupOutboundConnection(NodeAddress peersNodeAddress) {
|
||||
Log.traceCall("search for " + peersNodeAddress.toString() + " / outBoundConnections " + outBoundConnections);
|
||||
StringBuilder sb = new StringBuilder("Lookup for peersNodeAddress=");
|
||||
sb.append(peersNodeAddress.toString()).append("/ outBoundConnections.size()=")
|
||||
.append(outBoundConnections.size()).append("/\n\toutBoundConnections=");
|
||||
outBoundConnections.stream().forEach(e -> sb.append(e).append("\n\t"));
|
||||
log.debug(sb.toString());
|
||||
return outBoundConnections.stream()
|
||||
.filter(e -> e.getPeersNodeAddressOptional().isPresent() && peersNodeAddress.equals(e.getPeersNodeAddressOptional().get())).findAny();
|
||||
}
|
||||
|
||||
private Optional<Connection> lookupInboundConnection(NodeAddress peersNodeAddress) {
|
||||
Log.traceCall("search for " + peersNodeAddress.toString() + " / inBoundConnections " + inBoundConnections);
|
||||
StringBuilder sb = new StringBuilder("Lookup for peersNodeAddress=");
|
||||
sb.append(peersNodeAddress.toString()).append("/ inBoundConnections.size()=")
|
||||
.append(inBoundConnections.size()).append("/\n\tinBoundConnections=");
|
||||
inBoundConnections.stream().forEach(e -> sb.append(e).append("\n\t"));
|
||||
log.debug(sb.toString());
|
||||
return inBoundConnections.stream()
|
||||
.filter(e -> e.getPeersNodeAddressOptional().isPresent() && peersNodeAddress.equals(e.getPeersNodeAddressOptional().get())).findAny();
|
||||
}
|
||||
|
@ -51,7 +51,6 @@ public class TorNetworkNode extends NetworkNode {
|
||||
|
||||
public TorNetworkNode(int servicePort, File torDir) {
|
||||
super(servicePort);
|
||||
Log.traceCall();
|
||||
this.torDir = torDir;
|
||||
}
|
||||
|
||||
@ -62,7 +61,6 @@ public class TorNetworkNode extends NetworkNode {
|
||||
|
||||
@Override
|
||||
public void start(@Nullable SetupListener setupListener) {
|
||||
Log.traceCall();
|
||||
if (setupListener != null)
|
||||
addSetupListener(setupListener);
|
||||
|
||||
@ -100,7 +98,6 @@ public class TorNetworkNode extends NetworkNode {
|
||||
|
||||
@Override
|
||||
protected Socket createSocket(NodeAddress peerNodeAddress) throws IOException {
|
||||
Log.traceCall();
|
||||
checkArgument(peerNodeAddress.hostName.endsWith(".onion"), "PeerAddress is not an onion address");
|
||||
|
||||
return torNetworkNode.connectToHiddenService(peerNodeAddress.hostName, peerNodeAddress.port);
|
||||
@ -158,7 +155,6 @@ public class TorNetworkNode extends NetworkNode {
|
||||
///////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
private void shutDownExecutorService() {
|
||||
Log.traceCall();
|
||||
shutDownTimeoutTimer.cancel();
|
||||
new Thread(() -> {
|
||||
Utilities.setThreadName("NetworkNode:shutDownExecutorService");
|
||||
@ -203,9 +199,7 @@ public class TorNetworkNode extends NetworkNode {
|
||||
Utilities.setThreadName("TorNetworkNode:CreateTorNode");
|
||||
long ts = System.currentTimeMillis();
|
||||
if (torDir.mkdirs())
|
||||
log.trace("Created directory for tor");
|
||||
log.info("TorDir = " + torDir.getAbsolutePath());
|
||||
log.trace("Create TorNode");
|
||||
log.trace("Created directory for tor at {}", torDir.getAbsolutePath());
|
||||
TorNode<JavaOnionProxyManager, JavaOnionProxyContext> torNode = new JavaTorNode(torDir);
|
||||
log.info("\n\n############################################################\n" +
|
||||
"TorNode created:" +
|
||||
@ -234,7 +228,6 @@ public class TorNetworkNode extends NetworkNode {
|
||||
Utilities.setThreadName("TorNetworkNode:CreateHiddenService");
|
||||
{
|
||||
long ts = System.currentTimeMillis();
|
||||
log.debug("Create hidden service");
|
||||
HiddenServiceDescriptor hiddenServiceDescriptor = torNode.createHiddenService(localPort, servicePort);
|
||||
torNode.addHiddenServiceReadyListener(hiddenServiceDescriptor, descriptor -> {
|
||||
log.info("\n\n############################################################\n" +
|
||||
|
@ -10,6 +10,7 @@ import io.bitsquare.p2p.network.NetworkNode;
|
||||
import io.bitsquare.p2p.storage.messages.DataBroadcastMessage;
|
||||
import javafx.beans.property.IntegerProperty;
|
||||
import javafx.beans.property.SimpleIntegerProperty;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
@ -37,7 +38,9 @@ public class Broadcaster {
|
||||
}
|
||||
|
||||
public void broadcast(DataBroadcastMessage message, @Nullable NodeAddress sender) {
|
||||
Log.traceCall("Sender " + sender + ". Message " + message.toString());
|
||||
|
||||
Log.traceCall("Sender=" + sender + "\n\t" +
|
||||
"Message=" + StringUtils.abbreviate(message.toString(), 100));
|
||||
numOfBroadcasts.set(0);
|
||||
Set<Connection> receivers = networkNode.getConfirmedConnections();
|
||||
if (!receivers.isEmpty()) {
|
||||
@ -45,27 +48,28 @@ public class Broadcaster {
|
||||
receivers.stream()
|
||||
.filter(connection -> !connection.getPeersNodeAddressOptional().get().equals(sender))
|
||||
.forEach(connection -> {
|
||||
NodeAddress nodeAddress = connection.getPeersNodeAddressOptional().get();
|
||||
log.trace("Broadcast message to " +
|
||||
connection.getPeersNodeAddressOptional().get() + ".");
|
||||
nodeAddress + ".");
|
||||
SettableFuture<Connection> future = networkNode.sendMessage(connection, message);
|
||||
Futures.addCallback(future, new FutureCallback<Connection>() {
|
||||
@Override
|
||||
public void onSuccess(Connection connection) {
|
||||
log.trace("Broadcast to " + connection + " succeeded.");
|
||||
log.trace("Broadcast to " + nodeAddress + " succeeded.");
|
||||
numOfBroadcasts.set(numOfBroadcasts.get() + 1);
|
||||
listeners.stream().forEach(listener -> {
|
||||
listener.onBroadcasted(message);
|
||||
});
|
||||
listeners.stream().forEach(listener -> listener.onBroadcasted(message));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(@NotNull Throwable throwable) {
|
||||
log.info("Broadcast failed. " + throwable.getMessage());
|
||||
log.info("Broadcast to " + nodeAddress + " failed.\n\t" +
|
||||
"ErrorMessage=" + throwable.getMessage());
|
||||
}
|
||||
});
|
||||
});
|
||||
} else {
|
||||
log.info("Message not broadcasted because we have no available peers yet. " +
|
||||
log.warn("Message not broadcasted because we have no available peers yet.\n\t" +
|
||||
"That should never happen as broadcast should not be called in such cases.\n" +
|
||||
"message = {}", message);
|
||||
}
|
||||
}
|
||||
|
@ -87,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.\ngetPeersRequest=" + getPeersRequest +
|
||||
".\nException=" + throwable.getMessage();
|
||||
" failed. That is expected if the peer is offline.\n\tgetPeersRequest=" + getPeersRequest +
|
||||
".\n\tException=" + throwable.getMessage();
|
||||
log.info(errorMessage);
|
||||
|
||||
peerManager.shutDownConnection(nodeAddress);
|
||||
@ -112,12 +112,12 @@ public class PeerExchangeHandshake implements MessageListener {
|
||||
}
|
||||
|
||||
public void onGetPeersRequest(GetPeersRequest getPeersRequest, final Connection connection) {
|
||||
Log.traceCall("getPeersRequest=" + getPeersRequest + " / connection=" + connection + " / this=" + this);
|
||||
Log.traceCall("getPeersRequest=" + getPeersRequest + "\n\tconnection=" + connection + "\n\tthis=" + this);
|
||||
|
||||
HashSet<ReportedPeer> reportedPeers = getPeersRequest.reportedPeers;
|
||||
|
||||
/* StringBuilder result = new StringBuilder("Received peers:");
|
||||
reportedPeers.stream().forEach(e -> result.append("\n").append(e));
|
||||
reportedPeers.stream().forEach(e -> result.append("\n\t").append(e));
|
||||
log.trace(result.toString());*/
|
||||
log.trace("reportedPeers.size=" + reportedPeers.size());
|
||||
|
||||
@ -172,7 +172,7 @@ public class PeerExchangeHandshake implements MessageListener {
|
||||
@Override
|
||||
public void onMessage(Message message, Connection connection) {
|
||||
if (message instanceof GetPeersResponse) {
|
||||
Log.traceCall(message.toString() + " / connection=" + connection);
|
||||
Log.traceCall(message.toString() + "\n\tconnection=" + connection);
|
||||
Log.traceCall("this=" + this);
|
||||
GetPeersResponse getPeersResponse = (GetPeersResponse) message;
|
||||
if (getPeersResponse.requestNonce == nonce) {
|
||||
@ -180,7 +180,7 @@ public class PeerExchangeHandshake implements MessageListener {
|
||||
|
||||
HashSet<ReportedPeer> reportedPeers = getPeersResponse.reportedPeers;
|
||||
StringBuilder result = new StringBuilder("Received peers:");
|
||||
reportedPeers.stream().forEach(e -> result.append("\n").append(e));
|
||||
reportedPeers.stream().forEach(e -> result.append("\n\t").append(e));
|
||||
log.trace(result.toString());
|
||||
peerManager.addToReportedPeers(reportedPeers, connection);
|
||||
|
||||
@ -189,7 +189,7 @@ public class PeerExchangeHandshake implements MessageListener {
|
||||
} else {
|
||||
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={}",
|
||||
"was closed).\n\tWe drop that message. nonce={} / requestNonce={}",
|
||||
nonce, getPeersResponse.requestNonce);
|
||||
}
|
||||
}
|
||||
|
@ -103,6 +103,7 @@ public class PeerExchangeManager implements MessageListener, ConnectionListener
|
||||
@Override
|
||||
public void onMessage(Message message, Connection connection) {
|
||||
if (message instanceof GetPeersRequest) {
|
||||
Log.traceCall(message.toString() + "\n\tconnection=" + connection);
|
||||
PeerExchangeHandshake peerExchangeHandshake = new PeerExchangeHandshake(networkNode,
|
||||
peerManager,
|
||||
new PeerExchangeHandshake.Listener() {
|
||||
@ -113,7 +114,7 @@ public class PeerExchangeManager implements MessageListener, ConnectionListener
|
||||
|
||||
@Override
|
||||
public void onFault(String errorMessage) {
|
||||
log.trace("PeerExchangeHandshake of outbound connection failed.\nerrorMessage={}\n" +
|
||||
log.trace("PeerExchangeHandshake of outbound connection failed.\n\terrorMessage={}\n\t" +
|
||||
"connection={}", errorMessage, connection);
|
||||
peerManager.penalizeUnreachablePeer(connection);
|
||||
}
|
||||
@ -142,7 +143,7 @@ public class PeerExchangeManager implements MessageListener, ConnectionListener
|
||||
|
||||
@Override
|
||||
public void onFault(String errorMessage) {
|
||||
log.trace("PeerExchangeHandshake of outbound connection failed.\nerrorMessage={}\n" +
|
||||
log.trace("PeerExchangeHandshake of outbound connection failed.\n\terrorMessage={}\n\t" +
|
||||
"nodeAddress={}", errorMessage, nodeAddress);
|
||||
|
||||
peerExchangeHandshakeMap.remove(nodeAddress);
|
||||
@ -153,7 +154,7 @@ public class PeerExchangeManager implements MessageListener, ConnectionListener
|
||||
requestReportedPeersFromRandomPeer(remainingNodeAddresses);
|
||||
} else {
|
||||
log.info("There is no remaining node available for requesting peers. " +
|
||||
"That is expected if no other node is online.\n" +
|
||||
"That is expected if no other node is online.\n\t" +
|
||||
"We will try again after a random pause.");
|
||||
if (connectToMorePeersTimer == null)
|
||||
connectToMorePeersTimer = UserThread.runAfterRandomDelay(
|
||||
|
@ -30,12 +30,14 @@ public class PeerManager implements ConnectionListener, MessageListener {
|
||||
private static int MIN_CONNECTIONS;
|
||||
private static int MAX_CONNECTIONS_EXTENDED_1;
|
||||
private static int MAX_CONNECTIONS_EXTENDED_2;
|
||||
private static int MAX_CONNECTIONS_EXTENDED_3;
|
||||
|
||||
public static void setMaxConnections(int maxConnections) {
|
||||
MAX_CONNECTIONS = maxConnections;
|
||||
MIN_CONNECTIONS = maxConnections - 4;
|
||||
MAX_CONNECTIONS_EXTENDED_1 = MAX_CONNECTIONS + 6;
|
||||
MAX_CONNECTIONS_EXTENDED_2 = MAX_CONNECTIONS_EXTENDED_1 + 6;
|
||||
MAX_CONNECTIONS_EXTENDED_1 = MAX_CONNECTIONS + 5;
|
||||
MAX_CONNECTIONS_EXTENDED_2 = MAX_CONNECTIONS + 10;
|
||||
MAX_CONNECTIONS_EXTENDED_3 = MAX_CONNECTIONS + 20;
|
||||
}
|
||||
|
||||
static {
|
||||
@ -139,6 +141,7 @@ public class PeerManager implements ConnectionListener, MessageListener {
|
||||
// In case a seed node connects to another seed node we get his address at the DataRequest triggered from
|
||||
// RequestDataManager.updateDataFromConnectedSeedNode
|
||||
if (message instanceof GetUpdatedDataRequest) {
|
||||
Log.traceCall(message.toString() + "\n\tconnection=" + connection);
|
||||
Optional<NodeAddress> peersNodeAddressOptional = connection.getPeersNodeAddressOptional();
|
||||
if (peersNodeAddressOptional.isPresent() &&
|
||||
seedNodeAddresses.contains(peersNodeAddressOptional.get()))
|
||||
@ -152,16 +155,16 @@ public class PeerManager implements ConnectionListener, MessageListener {
|
||||
///////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
private boolean checkMaxConnections(int limit) {
|
||||
Log.traceCall();
|
||||
Log.traceCall("limit=" + limit);
|
||||
stopCheckMaxConnectionsTimer();
|
||||
removeSuperfluousSeedNodes();
|
||||
Set<Connection> allConnections = networkNode.getAllConnections();
|
||||
int size = allConnections.size();
|
||||
log.info("We have {} connections open. Our limit is {}", size, limit);
|
||||
if (size > limit) {
|
||||
log.info("We have {} connections open. Our limit is {}", size, limit);
|
||||
log.info("Lets try to remove the inbound connections of type PEER.");
|
||||
|
||||
// Only InboundConnection, and PEER type connections
|
||||
log.info("We have too many connections open. We try to close some.\n\t" +
|
||||
"Lets try first to remove the inbound connections of type PEER.");
|
||||
List<Connection> candidates = allConnections.stream()
|
||||
.filter(e -> e instanceof InboundConnection)
|
||||
.filter(e -> e.getPeerType() == Connection.PeerType.PEER)
|
||||
@ -169,21 +172,34 @@ public class PeerManager implements ConnectionListener, MessageListener {
|
||||
|
||||
if (candidates.size() == 0) {
|
||||
log.info("No candidates found. We go to the next level and check if we exceed our " +
|
||||
"MAX_CONNECTIONS_NORMAL_PRIORITY limit of {}", MAX_CONNECTIONS_EXTENDED_1);
|
||||
"MAX_CONNECTIONS_EXTENDED_1 limit of {}", MAX_CONNECTIONS_EXTENDED_1);
|
||||
if (size > MAX_CONNECTIONS_EXTENDED_1) {
|
||||
log.info("Lets try to remove any connection of type PEER.");
|
||||
// Only PEER type connections
|
||||
candidates = allConnections.stream()
|
||||
.filter(e -> e.getPeerType() == Connection.PeerType.PEER)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (candidates.size() == 0) {
|
||||
log.info("No candidates found. We go to the next level and check if we exceed our " +
|
||||
"MAX_CONNECTIONS_HIGH_PRIORITY limit of {}", MAX_CONNECTIONS_EXTENDED_2);
|
||||
"MAX_CONNECTIONS_EXTENDED_2 limit of {}", MAX_CONNECTIONS_EXTENDED_2);
|
||||
if (size > MAX_CONNECTIONS_EXTENDED_2) {
|
||||
log.info("Lets try to remove any connection which is not of type DIRECT_MSG_PEER.");
|
||||
// All connections
|
||||
// All connections except DIRECT_MSG_PEER
|
||||
candidates = allConnections.stream()
|
||||
.filter(e -> e.getPeerType() != Connection.PeerType.DIRECT_MSG_PEER)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (candidates.size() == 0) {
|
||||
log.info("No candidates found. We go to the next level and check if we exceed our " +
|
||||
"MAX_CONNECTIONS_EXTENDED_3 limit of {}", MAX_CONNECTIONS_EXTENDED_3);
|
||||
if (size > MAX_CONNECTIONS_EXTENDED_3) {
|
||||
log.info("Lets try to remove any connection.");
|
||||
// All connections
|
||||
candidates = allConnections.stream()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -191,14 +207,15 @@ public class PeerManager implements ConnectionListener, MessageListener {
|
||||
|
||||
if (candidates.size() > 0) {
|
||||
candidates.sort((o1, o2) -> o1.getLastActivityDate().compareTo(o2.getLastActivityDate()));
|
||||
log.info("Candidates for shut down=" + candidates);
|
||||
log.info("Candidates.size() for shut down=" + candidates.size());
|
||||
Connection connection = candidates.remove(0);
|
||||
log.info("We are going to shut down the oldest connection with last activity date="
|
||||
+ connection.getLastActivityDate() + " / connection=" + connection);
|
||||
log.info("We are going to shut down the oldest connection. connection=" + connection.toString());
|
||||
connection.shutDown(() -> checkMaxConnections(limit));
|
||||
return true;
|
||||
} else {
|
||||
log.debug("No candidates found to remove. allConnections=", allConnections);
|
||||
log.warn("No candidates found to remove (That case should not be possible as we use in the " +
|
||||
"last case all connections).\n\t" +
|
||||
"allConnections=", allConnections);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
@ -208,6 +225,7 @@ public class PeerManager implements ConnectionListener, MessageListener {
|
||||
}
|
||||
|
||||
private void removeTooOldReportedPeers() {
|
||||
Log.traceCall();
|
||||
Set<ReportedPeer> reportedPeersToRemove = reportedPeers.stream()
|
||||
.filter(reportedPeer -> reportedPeer.lastActivityDate != null &&
|
||||
new Date().getTime() - reportedPeer.lastActivityDate.getTime() > MAX_AGE)
|
||||
@ -222,6 +240,7 @@ public class PeerManager implements ConnectionListener, MessageListener {
|
||||
}
|
||||
|
||||
private void removeSuperfluousSeedNodes() {
|
||||
Log.traceCall();
|
||||
Set<Connection> allConnections = networkNode.getAllConnections();
|
||||
if (allConnections.size() > MAX_CONNECTIONS_EXTENDED_1) {
|
||||
List<Connection> candidates = allConnections.stream()
|
||||
@ -230,10 +249,9 @@ public class PeerManager implements ConnectionListener, MessageListener {
|
||||
|
||||
if (candidates.size() > 1) {
|
||||
candidates.sort((o1, o2) -> o1.getLastActivityDate().compareTo(o2.getLastActivityDate()));
|
||||
log.info("Number of connections exceeding MAX_CONNECTIONS. Current size=" + candidates.size());
|
||||
log.info("Number of connections exceeding MAX_CONNECTIONS_EXTENDED_1. Current size=" + candidates.size());
|
||||
Connection connection = candidates.remove(0);
|
||||
log.info("We are going to shut down the oldest connection with last activity date="
|
||||
+ connection.getLastActivityDate() + " / connection=" + connection);
|
||||
log.info("We are going to shut down the oldest connection. connection=" + connection.toString());
|
||||
connection.shutDown(this::removeSuperfluousSeedNodes);
|
||||
}
|
||||
}
|
||||
@ -254,7 +272,6 @@ public class PeerManager implements ConnectionListener, MessageListener {
|
||||
}
|
||||
|
||||
public void addToReportedPeers(HashSet<ReportedPeer> reportedPeersToAdd, Connection connection) {
|
||||
Log.traceCall();
|
||||
// we disconnect misbehaving nodes trying to send too many peers
|
||||
// reported peers include the connected peers which is normally max. 10 but we give some headroom
|
||||
// for safety
|
||||
@ -330,7 +347,7 @@ public class PeerManager implements ConnectionListener, MessageListener {
|
||||
"Reported peers:");
|
||||
reportedPeers.stream().forEach(e -> result.append("\n").append(e));
|
||||
result.append("\n------------------------------------------------------------\n");
|
||||
log.debug(result.toString());
|
||||
log.trace(result.toString());
|
||||
log.info("Number of reported peers: {}", reportedPeers.size());
|
||||
}
|
||||
}
|
||||
@ -367,6 +384,7 @@ public class PeerManager implements ConnectionListener, MessageListener {
|
||||
}
|
||||
|
||||
public void penalizeUnreachablePeer(NodeAddress nodeAddress) {
|
||||
Log.traceCall("nodeAddress=" + nodeAddress);
|
||||
reportedPeers.stream()
|
||||
.filter(reportedPeer -> reportedPeer.nodeAddress.equals(nodeAddress))
|
||||
.findAny()
|
||||
@ -449,7 +467,7 @@ public class PeerManager implements ConnectionListener, MessageListener {
|
||||
removeFromPersistedPeers(toRemove);
|
||||
}
|
||||
} else {
|
||||
log.trace("No need to purge reported peers. We don't have more then {} reported peers yet.", MAX_REPORTED_PEERS);
|
||||
log.trace("No need to purge reported peers.\n\tWe don't have more then {} reported peers yet.", MAX_REPORTED_PEERS);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -98,9 +98,9 @@ public class RequestDataHandshake implements MessageListener {
|
||||
@Override
|
||||
public void onFailure(@NotNull Throwable throwable) {
|
||||
String errorMessage = "Sending getDataRequest to " + nodeAddress +
|
||||
" failed. That is expected if the peer is offline.\n" +
|
||||
" failed. That is expected if the peer is offline.\n\t" +
|
||||
"getDataRequest=" + getDataRequest + "." +
|
||||
"\nException=" + throwable.getMessage();
|
||||
"\n\tException=" + throwable.getMessage();
|
||||
log.info(errorMessage);
|
||||
peerManager.shutDownConnection(nodeAddress);
|
||||
shutDown();
|
||||
@ -122,7 +122,7 @@ public class RequestDataHandshake implements MessageListener {
|
||||
}
|
||||
|
||||
public void onDataRequest(Message message, final Connection connection) {
|
||||
Log.traceCall(message.toString() + " / connection=" + connection);
|
||||
Log.traceCall(message.toString() + "\n\tconnection=" + connection);
|
||||
|
||||
GetDataResponse getDataResponse = new GetDataResponse(new HashSet<>(dataStorage.getMap().values()),
|
||||
((GetDataRequest) message).getNonce());
|
||||
@ -169,7 +169,7 @@ public class RequestDataHandshake implements MessageListener {
|
||||
@Override
|
||||
public void onMessage(Message message, Connection connection) {
|
||||
if (message instanceof GetDataResponse) {
|
||||
Log.traceCall(message.toString() + " / connection=" + connection);
|
||||
Log.traceCall(message.toString() + "\n\tconnection=" + connection);
|
||||
GetDataResponse getDataResponse = (GetDataResponse) message;
|
||||
if (getDataResponse.requestNonce == nonce) {
|
||||
stopTimeoutTimer();
|
||||
@ -185,7 +185,7 @@ public class RequestDataHandshake implements MessageListener {
|
||||
} else {
|
||||
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" +
|
||||
"connection was closed).\n\t" +
|
||||
"We drop that message. nonce={} / requestNonce={}",
|
||||
nonce, getDataResponse.requestNonce);
|
||||
}
|
||||
|
@ -114,6 +114,7 @@ public class RequestDataManager implements MessageListener {
|
||||
@Override
|
||||
public void onMessage(Message message, Connection connection) {
|
||||
if (message instanceof GetDataRequest) {
|
||||
Log.traceCall(message.toString() + "\n\tconnection=" + connection);
|
||||
RequestDataHandshake requestDataHandshake = new RequestDataHandshake(networkNode, dataStorage, peerManager,
|
||||
new RequestDataHandshake.Listener() {
|
||||
@Override
|
||||
@ -124,7 +125,7 @@ public class RequestDataManager implements MessageListener {
|
||||
|
||||
@Override
|
||||
public void onFault(String errorMessage) {
|
||||
log.trace("requestDataHandshake of inbound connection failed.\nConnection={}\n" +
|
||||
log.trace("requestDataHandshake of inbound connection failed.\n\tConnection={}\n\t" +
|
||||
"ErrorMessage={}", connection, errorMessage);
|
||||
peerManager.penalizeUnreachablePeer(connection);
|
||||
}
|
||||
@ -169,7 +170,7 @@ public class RequestDataManager implements MessageListener {
|
||||
|
||||
@Override
|
||||
public void onFault(String errorMessage) {
|
||||
log.trace("requestDataHandshake of outbound connection failed.\nnodeAddress={}\n" +
|
||||
log.trace("requestDataHandshake of outbound connection failed.\n\tnodeAddress={}\n\t" +
|
||||
"ErrorMessage={}", nodeAddress, errorMessage);
|
||||
|
||||
peerManager.penalizeUnreachablePeer(nodeAddress);
|
||||
@ -182,7 +183,7 @@ public class RequestDataManager implements MessageListener {
|
||||
requestData(nextCandidate, remainingNodeAddresses);
|
||||
} else {
|
||||
log.info("There is no remaining node available for requesting data. " +
|
||||
"That is expected if no other node is online.\n" +
|
||||
"That is expected if no other node is online.\n\t" +
|
||||
"We will try to use reported peers (if no available we use persisted peers) " +
|
||||
"and try again to request data from our seed nodes after a random pause.");
|
||||
|
||||
|
@ -24,27 +24,11 @@ public final class GetDataResponse implements Message {
|
||||
return networkId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof GetDataResponse)) return false;
|
||||
|
||||
GetDataResponse that = (GetDataResponse) o;
|
||||
|
||||
return !(dataSet != null ? !dataSet.equals(that.dataSet) : that.dataSet != null);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return dataSet != null ? dataSet.hashCode() : 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "GetDataResponse{" +
|
||||
"networkId=" + networkId +
|
||||
", dataSet=" + dataSet +
|
||||
", dataSet.size()=" + dataSet.size() +
|
||||
", requestNonce=" + requestNonce +
|
||||
'}';
|
||||
}
|
||||
|
@ -35,10 +35,9 @@ public final class GetUpdatedDataRequest implements SendersNodeAddressMessage, G
|
||||
@Override
|
||||
public String toString() {
|
||||
return "GetUpdatedDataRequest{" +
|
||||
"senderNodeAddress=" + senderNodeAddress +
|
||||
", networkId=" + networkId +
|
||||
"networkId=" + networkId +
|
||||
", senderNodeAddress=" + senderNodeAddress +
|
||||
", nonce=" + nonce +
|
||||
'}';
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -30,9 +30,8 @@ public final class GetPeersRequest extends PeerExchangeMessage implements Sender
|
||||
public String toString() {
|
||||
return "GetPeersRequest{" +
|
||||
"senderNodeAddress=" + senderNodeAddress +
|
||||
", requestNonce=" + nonce +
|
||||
", nonce=" + nonce +
|
||||
", reportedPeers.size()=" + reportedPeers.size() +
|
||||
super.toString() + "} ";
|
||||
"} " + super.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -22,6 +22,6 @@ public final class GetPeersResponse extends PeerExchangeMessage {
|
||||
return "GetPeersResponse{" +
|
||||
"requestNonce=" + requestNonce +
|
||||
", reportedPeers.size()=" + reportedPeers.size() +
|
||||
super.toString() + "} ";
|
||||
"} " + super.toString();
|
||||
}
|
||||
}
|
||||
|
@ -13,7 +13,8 @@ public abstract class PeerExchangeMessage implements Message {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return ", networkId=" + networkId +
|
||||
return "PeerExchangeMessage{" +
|
||||
"networkId=" + networkId +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
@ -21,6 +21,7 @@ import io.bitsquare.p2p.storage.messages.DataBroadcastMessage;
|
||||
import io.bitsquare.p2p.storage.messages.RemoveDataMessage;
|
||||
import io.bitsquare.p2p.storage.messages.RemoveMailboxDataMessage;
|
||||
import io.bitsquare.storage.Storage;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -102,7 +103,7 @@ public class P2PDataStorage implements MessageListener {
|
||||
@Override
|
||||
public void onMessage(Message message, Connection connection) {
|
||||
if (message instanceof DataBroadcastMessage) {
|
||||
Log.traceCall(message.toString());
|
||||
Log.traceCall(message.toString() + "\n\tconnection=" + connection);
|
||||
log.trace("DataBroadcastMessage received " + message + " on connection " + connection);
|
||||
connection.getPeersNodeAddressOptional().ifPresent(peersNodeAddress -> {
|
||||
if (message instanceof AddDataMessage) {
|
||||
@ -161,8 +162,7 @@ public class P2PDataStorage implements MessageListener {
|
||||
|
||||
StringBuilder sb = new StringBuilder("\n\n------------------------------------------------------------\n");
|
||||
sb.append("Data set after addProtectedExpirableData (truncated)");
|
||||
map.values().stream().forEach(e -> sb.append("\n").append(e.toString()
|
||||
.substring(0, Math.min(50, e.toString().length()))).append("...\n"));
|
||||
map.values().stream().forEach(e -> sb.append("\n").append(StringUtils.abbreviate(e.toString(), 100)));
|
||||
sb.append("\n------------------------------------------------------------\n");
|
||||
log.trace(sb.toString());
|
||||
log.info("Data set after addProtectedExpirableData: size=" + map.values().size());
|
||||
@ -281,8 +281,7 @@ public class P2PDataStorage implements MessageListener {
|
||||
|
||||
StringBuilder sb = new StringBuilder("\n\n------------------------------------------------------------\n" +
|
||||
"Data set after removeProtectedExpirableData: (truncated)");
|
||||
map.values().stream().forEach(e -> sb.append("\n").append(e.toString()
|
||||
.substring(0, Math.min(50, e.toString().length()))).append("...\n"));
|
||||
map.values().stream().forEach(e -> sb.append("\n").append(StringUtils.abbreviate(e.toString(), 100)));
|
||||
sb.append("\n------------------------------------------------------------\n");
|
||||
log.trace(sb.toString());
|
||||
log.info("Data set after addProtectedExpirableData: size=" + map.values().size());
|
||||
@ -365,7 +364,6 @@ public class P2PDataStorage implements MessageListener {
|
||||
}
|
||||
|
||||
private void broadcast(DataBroadcastMessage message, @Nullable NodeAddress sender) {
|
||||
Log.traceCall(message.toString());
|
||||
broadcaster.broadcast(message, sender);
|
||||
}
|
||||
|
||||
|
@ -11,4 +11,12 @@ public class DataAndSeqNr implements Serializable {
|
||||
this.data = data;
|
||||
this.sequenceNumber = sequenceNumber;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "DataAndSeqNr{" +
|
||||
"data=" + data +
|
||||
", sequenceNumber=" + sequenceNumber +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
@ -45,9 +45,10 @@ public final class ExpirableMailboxPayload implements ExpirablePayload {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MailboxEntry{" +
|
||||
"hashCode=" + hashCode() +
|
||||
", sealedAndSignedMessage=" + prefixedSealedAndSignedMessage +
|
||||
return "ExpirableMailboxPayload{" +
|
||||
"prefixedSealedAndSignedMessage=" + prefixedSealedAndSignedMessage +
|
||||
", senderStoragePublicKey.hashCode()=" + senderStoragePublicKey.hashCode() +
|
||||
", receiverStoragePublicKey.hashCode()=" + receiverStoragePublicKey.hashCode() +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
@ -8,6 +8,7 @@ import org.slf4j.LoggerFactory;
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
import java.security.PublicKey;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
|
||||
public class ProtectedData implements Serializable {
|
||||
@ -49,10 +50,12 @@ public class ProtectedData implements Serializable {
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ProtectedData{" +
|
||||
"data=\n" + expirablePayload +
|
||||
", \nttl=" + ttl +
|
||||
", sequenceNumber=" + sequenceNumber +
|
||||
"expirablePayload=" + expirablePayload +
|
||||
", ttl=" + ttl +
|
||||
", date=" + date +
|
||||
"\n}";
|
||||
", sequenceNumber=" + sequenceNumber +
|
||||
", ownerStoragePubKey.hashCode()=" + ownerStoragePubKey.hashCode() +
|
||||
", signature.hashCode()=" + Arrays.toString(signature).hashCode() +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
@ -7,6 +7,7 @@ import org.slf4j.LoggerFactory;
|
||||
import java.io.IOException;
|
||||
import java.security.PublicKey;
|
||||
import java.util.Date;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class ProtectedMailboxData extends ProtectedData {
|
||||
private static final Logger log = LoggerFactory.getLogger(P2PDataStorage.class);
|
||||
@ -27,9 +28,14 @@ public class ProtectedMailboxData extends ProtectedData {
|
||||
// in case the reported creation date is in the future
|
||||
// we reset the date to the current time
|
||||
if (date.getTime() > new Date().getTime()) {
|
||||
log.warn("Date of object is in future. " +
|
||||
"That might be ok as clocks are not synced but could be also a spam attack. " +
|
||||
"date=" + date + " / now=" + new Date());
|
||||
if (date.getTime() > new Date().getTime() + TimeUnit.MINUTES.toMillis(1))
|
||||
log.warn("Date of object is more then a minute in future. " +
|
||||
"That might be ok as peers clocks are not synced but could be also a spam attack.\n" +
|
||||
"date=" + date + " / now=" + new Date());
|
||||
else
|
||||
log.debug("Date of object is slightly future. " +
|
||||
"That is probably because peers clocks are not synced.\n" +
|
||||
"date=" + date + " / now=" + new Date());
|
||||
date = new Date();
|
||||
}
|
||||
date = new Date();
|
||||
@ -46,11 +52,8 @@ public class ProtectedMailboxData extends ProtectedData {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MailboxData{" +
|
||||
"data=\n" + expirablePayload +
|
||||
", \nttl=" + ttl +
|
||||
", sequenceNumber=" + sequenceNumber +
|
||||
", date=" + date +
|
||||
"\n}";
|
||||
return "ProtectedMailboxData{" +
|
||||
"receiversPubKey.hashCode()=" + receiversPubKey.hashCode() +
|
||||
"} " + super.toString();
|
||||
}
|
||||
}
|
||||
|
5
pom.xml
5
pom.xml
@ -121,6 +121,11 @@
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
|
Loading…
x
Reference in New Issue
Block a user