Add bootstrap info to splash screen, user final wehn possible, cleanup

This commit is contained in:
Manfred Karrer 2014-11-06 09:21:53 +01:00
parent dbbe7cec49
commit c7524edef3
40 changed files with 238 additions and 148 deletions

View file

@ -460,7 +460,7 @@ public class Notification {
return onNotificationPressedProperty().get();
}
private ObjectProperty<EventHandler<NotificationEvent>> onNotificationPressed = new
private final ObjectProperty<EventHandler<NotificationEvent>> onNotificationPressed = new
ObjectPropertyBase<EventHandler<NotificationEvent>>() {
@Override
public Object getBean() {
@ -485,7 +485,7 @@ public class Notification {
return onShowNotificationProperty().get();
}
private ObjectProperty<EventHandler<NotificationEvent>> onShowNotification = new
private final ObjectProperty<EventHandler<NotificationEvent>> onShowNotification = new
ObjectPropertyBase<EventHandler<NotificationEvent>>() {
@Override
public Object getBean() {
@ -510,7 +510,7 @@ public class Notification {
return onHideNotificationProperty().get();
}
private ObjectProperty<EventHandler<NotificationEvent>> onHideNotification = new
private final ObjectProperty<EventHandler<NotificationEvent>> onHideNotification = new
ObjectPropertyBase<EventHandler<NotificationEvent>>() {
@Override
public Object getBean() {

View file

@ -31,7 +31,7 @@ public abstract class AbstractBitsquareModule extends AbstractModule {
private final Set<AbstractBitsquareModule> modules = Sets.newHashSet();
public AbstractBitsquareModule(Properties properties) {
protected AbstractBitsquareModule(Properties properties) {
this.properties = properties;
}

View file

@ -33,13 +33,13 @@ optional arguments:
*/
public class ArgumentParser {
public static String PEER_ID_FLAG = "peerid";
public static String PORT_FLAG = "port";
public static String INTERFACE_HINT_FLAG = "interface";
public static String NAME_FLAG = "name";
public static final String PEER_ID_FLAG = "peerid";
public static final String PORT_FLAG = "port";
public static final String INTERFACE_HINT_FLAG = "interface";
public static final String NAME_FLAG = "name";
public static Integer PORT_DEFAULT = 5000;
public static String PEER_ID_DEFAULT = BootstrapNode.DIGITAL_OCEAN1.getId();
private static final Integer PORT_DEFAULT = 5000;
private static final String PEER_ID_DEFAULT = BootstrapNode.DIGITAL_OCEAN1.getId();
private final net.sourceforge.argparse4j.inf.ArgumentParser parser;

View file

@ -18,5 +18,5 @@
package io.bitsquare.btc;
public enum BitcoinNetwork {
MAINNET, TESTNET, REGTEST;
MAINNET, TESTNET, REGTEST
}

View file

@ -77,6 +77,8 @@ import javax.inject.Named;
import javafx.application.Platform;
import javafx.util.Pair;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -186,7 +188,7 @@ public class WalletFacade {
walletAppKit.addListener(new Service.Listener() {
@Override
public void failed(Service.State from, Throwable failure) {
public void failed(@NotNull Service.State from, @NotNull Throwable failure) {
walletAppKit = null;
// TODO show error popup
//crashAlert(failure);

View file

@ -38,8 +38,8 @@ public class SystemTray {
private static final String ICON_HI_RES = "/images/system_tray_icon@2x.png";
private static final String ICON_LO_RES = "/images/system_tray_icon.png";
public static final String SHOW_WINDOW_LABEL = "Show exchange window";
public static final String HIDE_WINDOW_LABEL = "Hide exchange window";
private static final String SHOW_WINDOW_LABEL = "Show exchange window";
private static final String HIDE_WINDOW_LABEL = "Hide exchange window";
private final Stage stage;
private final Runnable onExit;

View file

@ -23,6 +23,7 @@ import io.bitsquare.gui.UIModel;
import io.bitsquare.gui.util.Profiler;
import io.bitsquare.msg.MessageFacade;
import io.bitsquare.msg.listeners.BootstrapListener;
import io.bitsquare.network.BootstrapState;
import io.bitsquare.persistence.Persistence;
import io.bitsquare.trade.Trade;
import io.bitsquare.trade.TradeManager;
@ -44,6 +45,8 @@ import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.MapChangeListener;
import javafx.collections.ObservableList;
@ -62,11 +65,13 @@ class MainModel extends UIModel {
private boolean messageFacadeInited;
private boolean walletFacadeInited;
private boolean facadesInitialised;
final BooleanProperty backendReady = new SimpleBooleanProperty();
final DoubleProperty networkSyncProgress = new SimpleDoubleProperty(-1);
final IntegerProperty numPendingTrades = new SimpleIntegerProperty(0);
private boolean facadesInitialised;
final StringProperty bootstrapState = new SimpleStringProperty();
///////////////////////////////////////////////////////////////////////////////////////////
// Constructor
@ -122,6 +127,11 @@ class MainModel extends UIModel {
public void onFailed(Throwable throwable) {
log.error(throwable.toString());
}
@Override
public void onBootstrapStateChanged(BootstrapState bootstrapState) {
MainModel.this.bootstrapState.set(bootstrapState.getMessage());
}
});
Profiler.printMsgWithTime("MainModel.initFacades");

View file

@ -42,15 +42,17 @@ import org.slf4j.LoggerFactory;
class MainPM extends PresentationModel<MainModel> {
private static final Logger log = LoggerFactory.getLogger(MainPM.class);
private BSFormatter formatter;
private final BSFormatter formatter;
final BooleanProperty backendReady = new SimpleBooleanProperty();
final StringProperty bankAccountsComboBoxPrompt = new SimpleStringProperty();
final BooleanProperty bankAccountsComboBoxDisable = new SimpleBooleanProperty();
final StringProperty splashScreenInfoText = new SimpleStringProperty();
final StringProperty bootstrapState = new SimpleStringProperty();
final StringProperty bitcoinSyncState = new SimpleStringProperty("Initializing");
final IntegerProperty numPendingTrades = new SimpleIntegerProperty();
final DoubleProperty networkSyncProgress = new SimpleDoubleProperty();
///////////////////////////////////////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////////////////////////////////////
@ -61,11 +63,11 @@ class MainPM extends PresentationModel<MainModel> {
this.formatter = formatter;
}
///////////////////////////////////////////////////////////////////////////////////////////
// Lifecycle
///////////////////////////////////////////////////////////////////////////////////////////
@SuppressWarnings("EmptyMethod")
@Override
public void initialize() {
@ -75,16 +77,13 @@ class MainPM extends PresentationModel<MainModel> {
networkSyncProgress.bind(model.networkSyncProgress);
numPendingTrades.bind(model.numPendingTrades);
model.networkSyncProgress.addListener((ov, oldValue, newValue) -> {
if ((double) newValue > 0.0)
splashScreenInfoText.set("Synchronise with network " + formatter.formatToPercent((double)
newValue));
else if ((double) newValue == 1)
splashScreenInfoText.set("Synchronise with network completed.");
else
splashScreenInfoText.set("Synchronise with network...");
});
splashScreenInfoText.set("Synchronise with network...");
model.bootstrapState.addListener((ov, oldValue, newValue) ->
bootstrapState.set("Connection to P2P network: " + newValue));
bootstrapState.set(model.bootstrapState.get());
model.networkSyncProgress.addListener((ov, oldValue, newValue) -> updateBitcoinSyncState((double) newValue));
updateBitcoinSyncState(model.networkSyncProgress.get());
model.getBankAccounts().addListener((ListChangeListener<BankAccount>) change -> {
bankAccountsComboBoxDisable.set(change.getList().isEmpty());
@ -145,4 +144,19 @@ class MainPM extends PresentationModel<MainModel> {
};
}
///////////////////////////////////////////////////////////////////////////////////////////
// Private
///////////////////////////////////////////////////////////////////////////////////////////
private void updateBitcoinSyncState(double value) {
if (value > 0.0)
bitcoinSyncState.set("Synchronizing with bitcoin network: " +
formatter.formatToPercent(value));
else if (value == 1)
bitcoinSyncState.set("Synchronizing with bitcoin network completed.");
else
bitcoinSyncState.set("Synchronizing with bitcoin network...");
}
}

View file

@ -47,6 +47,7 @@ import javafx.scene.effect.*;
import javafx.scene.image.*;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.scene.text.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -167,7 +168,7 @@ public class MainViewCB extends ViewCB<MainPM> {
((StackPane) root).getChildren().addAll(baseApplicationContainer, splashScreen);
baseApplicationContainer.setCenter(getApplicationContainer());
Platform.runLater(() -> onSplashScreenAdded());
Platform.runLater(this::onSplashScreenAdded);
}
private void onSplashScreenAdded() {
@ -285,16 +286,35 @@ public class MainViewCB extends ViewCB<MainPM> {
ImageView logo = new ImageView();
logo.setId("image-splash-logo");
Label loadingLabel = new Label();
loadingLabel.setAlignment(Pos.CENTER);
loadingLabel.setPadding(new Insets(60, 0, 0, 0));
loadingLabel.textProperty().bind(presentationModel.splashScreenInfoText);
Label bitcoinSyncStateLabel = new Label();
bitcoinSyncStateLabel.textProperty().bind(presentationModel.bitcoinSyncState);
ProgressBar progressBar = new ProgressBar();
progressBar.setPrefWidth(240);
progressBar.progressProperty().bind(presentationModel.networkSyncProgress);
ProgressBar btcProgressIndicator = new ProgressBar(-1);
btcProgressIndicator.setPrefWidth(120);
btcProgressIndicator.progressProperty().bind(presentationModel.networkSyncProgress);
vBox.getChildren().addAll(logo, loadingLabel, progressBar);
HBox btcBox = new HBox();
btcBox.setSpacing(10);
btcBox.setAlignment(Pos.CENTER);
btcBox.setPadding(new Insets(60, 0, 0, 0));
btcBox.getChildren().addAll(bitcoinSyncStateLabel, btcProgressIndicator);
Label bootstrapStateLabel = new Label();
bootstrapStateLabel.setWrapText(true);
bootstrapStateLabel.setMaxWidth(500);
bootstrapStateLabel.setTextAlignment(TextAlignment.CENTER);
bootstrapStateLabel.textProperty().bind(presentationModel.bootstrapState);
ProgressIndicator p2pProgressIndicator = new ProgressIndicator(-1);
p2pProgressIndicator.setMaxSize(24, 24);
HBox p2pBox = new HBox();
p2pBox.setSpacing(10);
p2pBox.setAlignment(Pos.CENTER);
p2pBox.setPadding(new Insets(10, 0, 0, 0));
p2pBox.getChildren().addAll(bootstrapStateLabel, p2pProgressIndicator);
vBox.getChildren().addAll(logo, btcBox, p2pBox);
return vBox;
}

View file

@ -53,7 +53,7 @@ public class ArbitratorBrowserViewCB extends CachedViewCB implements ArbitratorL
private final Settings settings;
private final Persistence persistence;
private MessageFacade messageFacade;
private final MessageFacade messageFacade;
private final List<Arbitrator> allArbitrators = new ArrayList<>();
private Arbitrator currentArbitrator;

View file

@ -38,13 +38,13 @@ public class ArbitratorProfileViewCB extends CachedViewCB {
private final Settings settings;
private final Persistence persistence;
private BSFormatter formatter;
private final BSFormatter formatter;
@FXML Label nameLabel;
@FXML TextField nameTextField, languagesTextField, reputationTextField,
feeTextField, methodsTextField,
idVerificationsTextField, webPageTextField;
feeTextField, methodsTextField, passiveServiceFeeTextField,
idVerificationsTextField, webPageTextField, maxTradeVolumeTextField;
@FXML TextArea descriptionTextArea;

View file

@ -68,7 +68,7 @@ public class ArbitratorRegistrationViewCB extends CachedViewCB {
private final WalletFacade walletFacade;
private final MessageFacade messageFacade;
private final User user;
private BSFormatter formatter;
private final BSFormatter formatter;
private Arbitrator arbitrator = new Arbitrator();
private boolean isEditMode;

View file

@ -68,7 +68,7 @@ public class FiatAccountViewCB extends CachedViewCB<FiatAccountPm> implements Co
@FXML ComboBox<BankAccount> selectionComboBox;
@FXML ComboBox<BankAccountType> typesComboBox;
@FXML ComboBox<Currency> currencyComboBox;
private OverlayManager overlayManager;
private final OverlayManager overlayManager;
///////////////////////////////////////////////////////////////////////////////////////////

View file

@ -59,7 +59,7 @@ class IrcAccountModel extends UIModel {
private final User user;
private final Settings settings;
private MessageFacade messageFacade;
private final MessageFacade messageFacade;
private final Persistence persistence;
final StringProperty nickName = new SimpleStringProperty();

View file

@ -123,17 +123,15 @@ public class IrcAccountViewCB extends CachedViewCB<IrcAccountPm> implements Cont
setupListeners();
setupBindings();
Platform.runLater(() -> {
Popups.openInfoPopup("Demo setup for simulating the banking transfer",
"For demo purposes we use a special setup so that users can simulate the banking transfer when " +
"meeting in an IRC chat room.\n" +
"You need to define your IRC nickname and later in the trade process you can find your " +
"trading partner with his IRC nickname in the chat room and simulate the bank transfer " +
"activities, which are:\n\n" +
"1. Bitcoin buyer indicates that he has started the bank transfer.\n\n" +
"2. Bitcoin seller confirms that he has received the national currency from the " +
"bank transfer.");
});
Platform.runLater(() -> Popups.openInfoPopup("Demo setup for simulating the banking transfer",
"For demo purposes we use a special setup so that users can simulate the banking transfer when " +
"meeting in an IRC chat room.\n" +
"You need to define your IRC nickname and later in the trade process you can find your " +
"trading partner with his IRC nickname in the chat room and simulate the bank transfer " +
"activities, which are:\n\n" +
"1. Bitcoin buyer indicates that he has started the bank transfer.\n\n" +
"2. Bitcoin seller confirms that he has received the national currency from the " +
"bank transfer."));
}
@SuppressWarnings("EmptyMethod")

View file

@ -47,7 +47,7 @@ class RegistrationPM extends PresentationModel<RegistrationModel> {
// That is needed for the addressTextField
final ObjectProperty<Address> address = new SimpleObjectProperty<>();
private BSFormatter formatter;
private final BSFormatter formatter;
///////////////////////////////////////////////////////////////////////////////////////////

View file

@ -32,7 +32,7 @@ class SeedWordsPM extends PresentationModel<SeedWordsModel> {
private static final Logger log = LoggerFactory.getLogger(SeedWordsPM.class);
final StringProperty seedWords = new SimpleStringProperty();
private BSFormatter formatter;
private final BSFormatter formatter;
///////////////////////////////////////////////////////////////////////////////////////////

View file

@ -52,8 +52,8 @@ public class AccountSettingsViewCB extends CachedViewCB {
private final Navigation navigation;
private Navigation.Listener listener;
@FXML VBox leftVBox;
@FXML AnchorPane content;
@FXML private VBox leftVBox;
@FXML private AnchorPane content;
///////////////////////////////////////////////////////////////////////////////////////////

View file

@ -46,7 +46,7 @@ public class TransactionsViewCB extends CachedViewCB {
private static final Logger log = LoggerFactory.getLogger(TransactionsViewCB.class);
private final WalletFacade walletFacade;
private BSFormatter formatter;
private final BSFormatter formatter;
private ObservableList<TransactionsListItem> transactionsListItems;
@FXML TableView<TransactionsListItem> table;

View file

@ -43,7 +43,7 @@ public class WithdrawalListItem {
private final AddressEntry addressEntry;
private final WalletFacade walletFacade;
private BSFormatter formatter;
private final BSFormatter formatter;
private final AddressConfidenceListener confidenceListener;
private final ConfidenceProgressIndicator progressIndicator;

View file

@ -64,7 +64,7 @@ public class WithdrawalViewCB extends CachedViewCB {
private final WalletFacade walletFacade;
private BSFormatter formatter;
private final BSFormatter formatter;
private final ObservableList<WithdrawalListItem> addressList = FXCollections.observableArrayList();
@FXML TableView<WithdrawalListItem> table;

View file

@ -37,7 +37,7 @@ class ClosedTradesModel extends UIModel {
private static final Logger log = LoggerFactory.getLogger(ClosedTradesModel.class);
private final TradeManager tradeManager;
private User user;
private final User user;
private final ObservableList<ClosedTradesListItem> list = FXCollections.observableArrayList();
private MapChangeListener<String, Trade> mapChangeListener;

View file

@ -38,7 +38,7 @@ class OffersModel extends UIModel {
private static final Logger log = LoggerFactory.getLogger(OffersModel.class);
private final TradeManager tradeManager;
private User user;
private final User user;
private final ObservableList<OfferListItem> list = FXCollections.observableArrayList();
private MapChangeListener<String, Offer> offerMapChangeListener;

View file

@ -226,10 +226,7 @@ class PendingTradesModel extends UIModel {
String fromAddress = addressEntry.getAddressString();
try {
walletFacade.sendFunds(fromAddress, toAddress, getAmountToWithdraw(), callback);
} catch (AddressFormatException e) {
e.printStackTrace();
log.error(e.getMessage());
} catch (InsufficientMoneyException e) {
} catch (AddressFormatException | InsufficientMoneyException e) {
e.printStackTrace();
log.error(e.getMessage());
}

View file

@ -55,7 +55,7 @@ public class PendingTradesPM extends PresentationModel<PendingTradesModel> {
private final BSFormatter formatter;
private InvalidationListener stateChangeListener;
private BtcAddressValidator btcAddressValidator;
private final BtcAddressValidator btcAddressValidator;
final StringProperty txId = new SimpleStringProperty();
final ObjectProperty<State> state = new SimpleObjectProperty<>();

View file

@ -61,7 +61,7 @@ public class PendingTradesViewCB extends CachedViewCB<PendingTradesPM> {
private ChangeListener<PendingTradesPM.State> offererStateChangeListener;
private ChangeListener<PendingTradesPM.State> takerStateChangeListener;
private ChangeListener<Throwable> faultChangeListener;
private Navigation navigation;
private final Navigation navigation;
@FXML ScrollPane scrollPane;
@FXML GridPane gridPane;

View file

@ -70,8 +70,8 @@ class CreateOfferModel extends UIModel {
private final WalletFacade walletFacade;
private final Settings settings;
private final User user;
private Persistence persistence;
private BSFormatter formatter;
private final Persistence persistence;
private final BSFormatter formatter;
private final String offerId;

View file

@ -50,7 +50,7 @@ class CreateOfferPM extends PresentationModel<CreateOfferModel> {
private static final Logger log = LoggerFactory.getLogger(CreateOfferPM.class);
private final BtcValidator btcValidator;
private BSFormatter formatter;
private final BSFormatter formatter;
private final FiatValidator fiatValidator;
final StringProperty amount = new SimpleStringProperty();

View file

@ -57,7 +57,7 @@ class OfferBookModel extends UIModel {
private final User user;
private final OfferBook offerBook;
private final Settings settings;
private BSFormatter formatter;
private final BSFormatter formatter;
private final TradeManager tradeManager;
private final FilteredList<OfferBookListItem> filteredItems;

View file

@ -42,7 +42,7 @@ class OfferBookPM extends PresentationModel<OfferBookModel> {
private static final Logger log = LoggerFactory.getLogger(OfferBookPM.class);
private final OptionalBtcValidator optionalBtcValidator;
private BSFormatter formatter;
private final BSFormatter formatter;
private final OptionalFiatValidator optionalFiatValidator;
final StringProperty amount = new SimpleStringProperty();

View file

@ -57,7 +57,7 @@ class TakeOfferModel extends UIModel {
private final TradeManager tradeManager;
private final WalletFacade walletFacade;
private final Settings settings;
private Persistence persistence;
private final Persistence persistence;
private Offer offer;
private AddressEntry addressEntry;

View file

@ -65,7 +65,7 @@ class TakeOfferPM extends PresentationModel<TakeOfferModel> {
final ObjectProperty<Address> address = new SimpleObjectProperty<>();
private final BtcValidator btcValidator;
private BSFormatter formatter;
private final BSFormatter formatter;
final StringProperty amount = new SimpleStringProperty();
final StringProperty volume = new SimpleStringProperty();

View file

@ -33,7 +33,7 @@ import org.slf4j.LoggerFactory;
*/
public final class BtcAddressValidator extends InputValidator {
private static final Logger log = LoggerFactory.getLogger(BtcAddressValidator.class);
private NetworkParameters networkParameters;
private final NetworkParameters networkParameters;
///////////////////////////////////////////////////////////////////////////////////////////

View file

@ -36,7 +36,7 @@ public abstract class ActorService extends Service<String> {
private final ActorSystem system;
private final Inbox inbox;
private ActorSelection actor;
private final ActorSelection actor;
private MessageHandler handler;
@ -71,12 +71,7 @@ public abstract class ActorService extends Service<String> {
if (result != null) {
System.out.println(result.toString());
if (handler != null) {
Application.invokeLater(new Runnable() {
@Override
public void run() {
handler.handle(result);
}
});
Application.invokeLater(() -> handler.handle(result));
}
}
} catch (Exception e) {

View file

@ -17,6 +17,7 @@
package io.bitsquare.msg;
import io.bitsquare.network.BootstrapState;
import io.bitsquare.network.Node;
import io.bitsquare.persistence.Persistence;
@ -32,13 +33,11 @@ import java.net.UnknownHostException;
import java.security.KeyPair;
import javax.annotation.concurrent.Immutable;
import javax.inject.Inject;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import net.tomp2p.dht.PeerBuilderDHT;
import net.tomp2p.dht.PeerDHT;
@ -66,7 +65,6 @@ import org.slf4j.LoggerFactory;
/**
* Creates a DHT peer and bootstrap to the network via a seed node
*/
@Immutable
public class BootstrappedPeerFactory {
private static final Logger log = LoggerFactory.getLogger(BootstrappedPeerFactory.class);
@ -76,7 +74,7 @@ public class BootstrappedPeerFactory {
private final Persistence persistence;
private final SettableFuture<PeerDHT> settableFuture = SettableFuture.create();
public final StringProperty connectionState = new SimpleStringProperty();
public final ObjectProperty<BootstrapState> bootstrapState = new SimpleObjectProperty<>();
private Peer peer;
private PeerDHT peerDHT;
@ -111,6 +109,7 @@ public class BootstrappedPeerFactory {
public ListenableFuture<PeerDHT> start(int port) {
try {
setState(BootstrapState.PEER_CREATION, "We create a P2P node.");
peer = new PeerBuilder(keyPair).ports(port).start();
peerDHT = new PeerBuilderDHT(peer).storageLayer(new StorageLayer(storage)).start();
@ -149,7 +148,6 @@ public class BootstrappedPeerFactory {
lastSuccessfulBootstrap = "default";
log.debug("lastSuccessfulBootstrap = " + lastSuccessfulBootstrap);
FutureDiscover futureDiscover;
// just temporary while port forwarding is not working
lastSuccessfulBootstrap = "default";
@ -167,7 +165,7 @@ public class BootstrappedPeerFactory {
break;
}
} catch (IOException e) {
setState("Cannot create peer with port: " + port + ". Exeption: " + e, false);
setState(BootstrapState.PEER_CREATION, "Cannot create peer with port: " + port + ". Exeption: " + e, false);
settableFuture.setException(e);
}
@ -176,19 +174,19 @@ public class BootstrappedPeerFactory {
// 1. Attempt: Try to discover our outside visible address
private void discover() {
setState(BootstrapState.DIRECT_INIT, "We are starting to bootstrap to a seed node.");
FutureDiscover futureDiscover = peer.discover().peerAddress(getBootstrapAddress()).start();
futureDiscover.addListener(new BaseFutureListener<BaseFuture>() {
@Override
public void operationComplete(BaseFuture future) throws Exception {
if (future.isSuccess()) {
setState("We are directly connected and visible to other peers: My address visible to " +
"the outside is " + futureDiscover.peerAddress());
setState(BootstrapState.DIRECT_SUCCESS, "We are directly connected and visible to other peers.");
persistence.write(BootstrappedPeerFactory.this, "lastSuccessfulBootstrap", "default");
settableFuture.set(peerDHT);
}
else {
setState("We are probably behind a NAT and not reachable to other peers. " +
"We try port forwarding as next step.");
setState(BootstrapState.DIRECT_NOT_SUCCEEDED, "We are probably behind a NAT and not reachable to " +
"other peers. We try to setup automatic port forwarding.");
tryPortForwarding();
}
@ -196,7 +194,7 @@ public class BootstrappedPeerFactory {
@Override
public void exceptionCaught(Throwable t) throws Exception {
setState("Exception at discover: " + t.getMessage(), false);
setState(BootstrapState.DIRECT_FAILED, "Exception at discover: " + t.getMessage(), false);
peerDHT.shutdown();
settableFuture.setException(t);
}
@ -205,6 +203,7 @@ public class BootstrappedPeerFactory {
// 2. Attempt: Try to set up port forwarding with UPNP and NAT-PMP
private void tryPortForwarding() {
setState(BootstrapState.NAT_INIT, "We are trying with automatic port forwarding.");
FutureDiscover futureDiscover = peer.discover().peerAddress(getBootstrapAddress()).start();
PeerNAT peerNAT = new PeerBuilderNAT(peer).start();
FutureNAT futureNAT = peerNAT.startSetupPortforwarding(futureDiscover);
@ -212,20 +211,21 @@ public class BootstrappedPeerFactory {
@Override
public void operationComplete(BaseFuture future) throws Exception {
if (future.isSuccess()) {
setState("Automatic port forwarding is setup. We need to run a discover again. Address = " +
futureNAT.peerAddress());
setState(BootstrapState.NAT_SETUP_DONE, "Automatic port forwarding is setup. " +
"We need to do a discover process again.");
// we need a second discover process
discoverAfterPortForwarding();
}
else {
setState("Port forwarding has failed. We try to use a relay as next step.");
setState(BootstrapState.NAT_NOT_SUCCEEDED, "Port forwarding has failed. " +
"We try to use a relay as next step.");
bootstrapWithRelay();
}
}
@Override
public void exceptionCaught(Throwable t) throws Exception {
setState("Exception at port forwarding: " + t.getMessage(), false);
setState(BootstrapState.NAT_FAILED, "Exception at port forwarding: " + t.getMessage(), false);
peerDHT.shutdown();
settableFuture.setException(t);
}
@ -239,14 +239,13 @@ public class BootstrappedPeerFactory {
@Override
public void operationComplete(BaseFuture future) throws Exception {
if (future.isSuccess()) {
setState("Discover with automatic port forwarding was successful. " +
"My address visible to the outside is = " + futureDiscover.peerAddress());
setState(BootstrapState.NAT_SUCCESS, "Discover with automatic port forwarding was successful.");
persistence.write(BootstrappedPeerFactory.this, "lastSuccessfulBootstrap", "portForwarding");
settableFuture.set(peerDHT);
}
else {
setState("Discover with automatic port forwarding has failed " + futureDiscover
.failedReason(), false);
setState(BootstrapState.NAT_FAILED, "Discover with automatic port forwarding has failed " +
futureDiscover.failedReason(), false);
persistence.write(BootstrappedPeerFactory.this, "lastSuccessfulBootstrap", "default");
peerDHT.shutdown();
settableFuture.setException(new Exception("Discover with automatic port forwarding failed " +
@ -256,7 +255,7 @@ public class BootstrappedPeerFactory {
@Override
public void exceptionCaught(Throwable t) throws Exception {
setState("Exception at discover: " + t, false);
setState(BootstrapState.NAT_FAILED, "Exception at discover: " + t, false);
persistence.write(BootstrappedPeerFactory.this, "lastSuccessfulBootstrap", "default");
peerDHT.shutdown();
settableFuture.setException(t);
@ -266,6 +265,7 @@ public class BootstrappedPeerFactory {
// 3. Attempt: We try to use another peer as relay
private void bootstrapWithRelay() {
setState(BootstrapState.RELAY_INIT, "We try to use another peer as relay.");
FutureDiscover futureDiscover = peer.discover().peerAddress(getBootstrapAddress()).start();
PeerNAT peerNAT = new PeerBuilderNAT(peer).start();
FutureNAT futureNAT = peerNAT.startSetupPortforwarding(futureDiscover);
@ -274,13 +274,13 @@ public class BootstrappedPeerFactory {
@Override
public void operationComplete(BaseFuture future) throws Exception {
if (future.isSuccess()) {
setState("Bootstrap using relay was successful. " +
"My address visible to the outside is = " + peerDHT.peerAddress());
setState(BootstrapState.RELAY_SUCCESS, "Bootstrap using relay was successful.");
persistence.write(BootstrappedPeerFactory.this, "lastSuccessfulBootstrap", "relay");
settableFuture.set(peerDHT);
}
else {
setState("Bootstrap using relay has failed " + futureRelayNAT.failedReason(), false);
setState(BootstrapState.RELAY_FAILED, "Bootstrap using relay has failed " + futureRelayNAT
.failedReason(), false);
persistence.write(BootstrappedPeerFactory.this, "lastSuccessfulBootstrap", "default");
futureRelayNAT.shutdown();
peerDHT.shutdown();
@ -291,14 +291,13 @@ public class BootstrappedPeerFactory {
@Override
public void exceptionCaught(Throwable t) throws Exception {
setState("Exception at bootstrapWithRelay: " + t, false);
setState(BootstrapState.RELAY_FAILED, "Exception at bootstrapWithRelay: " + t, false);
persistence.write(BootstrappedPeerFactory.this, "lastSuccessfulBootstrap", "default");
futureRelayNAT.shutdown();
peerDHT.shutdown();
settableFuture.setException(t);
}
});
}
private PeerAddress getBootstrapAddress() {
@ -313,15 +312,17 @@ public class BootstrappedPeerFactory {
}
}
private void setState(String state) {
setState(state, true);
private void setState(BootstrapState bootstrapState, String message) {
setState(bootstrapState, message, true);
}
private void setState(String state, boolean isSuccess) {
private void setState(BootstrapState bootstrapState, String message, boolean isSuccess) {
if (isSuccess)
log.info(state);
log.info(message);
else
log.error(state);
Platform.runLater(() -> connectionState.set(state));
log.error(message);
bootstrapState.setMessage(message);
Platform.runLater(() -> this.bootstrapState.set(bootstrapState));
}
}

View file

@ -17,6 +17,7 @@
package io.bitsquare.msg;
import io.bitsquare.msg.listeners.BootstrapListener;
import io.bitsquare.network.tomp2p.TomP2PPeer;
import com.google.common.util.concurrent.FutureCallback;
@ -38,6 +39,8 @@ import javax.annotation.Nullable;
import javax.inject.Inject;
import javafx.application.Platform;
import net.tomp2p.connection.DSASignatureFactory;
import net.tomp2p.connection.PeerConnection;
import net.tomp2p.dht.FutureGet;
@ -117,14 +120,29 @@ public class P2PNode {
bootstrappedPeerFactory.setKeyPair(keyPair);
}
public void start(int port, FutureCallback<PeerDHT> callback) {
public void start(int port, BootstrapListener bootstrapListener) {
useDiscStorage(useDiskStorage);
bootstrappedPeerFactory.setStorage(storage);
setupTimerForIPCheck();
ListenableFuture<PeerDHT> bootstrapComplete = bootstrap(port);
Futures.addCallback(bootstrapComplete, callback);
Futures.addCallback(bootstrapComplete, new FutureCallback<PeerDHT>() {
@Override
public void onSuccess(@Nullable PeerDHT result) {
log.debug("p2pNode.start success result = " + result);
Platform.runLater(bootstrapListener::onCompleted);
}
@Override
public void onFailure(@NotNull Throwable t) {
log.error(t.toString());
Platform.runLater(() -> bootstrapListener.onFailed(t));
}
});
bootstrappedPeerFactory.bootstrapState.addListener((ov, oldValue, newValue) ->
bootstrapListener.onBootstrapStateChanged(newValue));
}

View file

@ -30,8 +30,6 @@ import io.bitsquare.network.tomp2p.TomP2PPeer;
import io.bitsquare.offer.Offer;
import io.bitsquare.user.User;
import com.google.common.util.concurrent.FutureCallback;
import java.io.IOException;
import java.security.PublicKey;
@ -41,8 +39,6 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javafx.application.Platform;
@ -52,7 +48,6 @@ import javafx.beans.property.SimpleLongProperty;
import net.tomp2p.dht.FutureGet;
import net.tomp2p.dht.FuturePut;
import net.tomp2p.dht.FutureRemove;
import net.tomp2p.dht.PeerDHT;
import net.tomp2p.futures.BaseFuture;
import net.tomp2p.futures.BaseFutureAdapter;
import net.tomp2p.futures.BaseFutureListener;
@ -62,11 +57,10 @@ import net.tomp2p.peers.Number640;
import net.tomp2p.storage.Data;
import net.tomp2p.utils.Utils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* That facade delivers direct messaging and DHT functionality from the TomP2P library
* It is the translating domain specific functionality to the messaging layer.
@ -107,19 +101,7 @@ class TomP2PMessageFacade implements MessageFacade {
p2pNode.setMessageBroker(this);
p2pNode.setKeyPair(user.getMessageKeyPair());
p2pNode.start(port, new FutureCallback<PeerDHT>() {
@Override
public void onSuccess(@Nullable PeerDHT result) {
log.debug("p2pNode.start success result = " + result);
Platform.runLater(bootstrapListener::onCompleted);
}
@Override
public void onFailure(@NotNull Throwable t) {
log.error(t.toString());
Platform.runLater(() -> bootstrapListener.onFailed(t));
}
});
p2pNode.start(port, bootstrapListener);
}
public void shutDown() {
@ -244,7 +226,7 @@ class TomP2PMessageFacade implements MessageFacade {
if (offerDataObject instanceof Offer) {
log.trace("Remove offer from DHT was successful. Removed data: [key: " +
locationKey + ", " +
"offer: " + (Offer) offerDataObject + "]");
"offer: " + offerDataObject + "]");
offerBookListener.onOfferRemoved((Offer) offerDataObject);
}
} catch (ClassNotFoundException | IOException e) {
@ -537,8 +519,8 @@ class TomP2PMessageFacade implements MessageFacade {
invalidationTimestamp.set(timeStamp);
});
}
else {
//log.error("Get invalidationTimestamp from DHT failed. Data = " + data);
else if (data != null) {
log.error("Get invalidationTimestamp from DHT failed. Data = " + data);
}
}
else if (getFuture.data() == null) {

View file

@ -52,14 +52,12 @@ public class DHTManager extends AbstractActor {
return Props.create(DHTManager.class);
}
private Bindings bindings;
private Peer peer;
private PeerDHT peerDHT;
private PeerNAT peerNAT;
public DHTManager() {
receive(ReceiveBuilder
.match(InitializePeer.class, initializePeer -> doInitializePeer(initializePeer))
.match(InitializePeer.class, this::doInitializePeer)
.matchAny(o -> log.info("received unknown message")).build()
);
}
@ -68,7 +66,7 @@ public class DHTManager extends AbstractActor {
log.debug("Received message: {}", initializePeer);
try {
bindings = new Bindings();
Bindings bindings = new Bindings();
// TODO: @Steve: Is that needed that we restrict to IP4?
// bindings.addProtocol(StandardProtocolFamily.INET);
@ -77,7 +75,7 @@ public class DHTManager extends AbstractActor {
bindings.addInterface(initializePeer.getInterfaceHint());
}
peer = new PeerBuilder(initializePeer.getPeerId()).ports(initializePeer.getPort()).bindings(bindings)
Peer peer = new PeerBuilder(initializePeer.getPeerId()).ports(initializePeer.getPort()).bindings(bindings)
.start();
peer.objectDataReply((sender, request) -> {
log.debug("received request: ", request.toString());

View file

@ -17,9 +17,13 @@
package io.bitsquare.msg.listeners;
import io.bitsquare.network.BootstrapState;
public interface BootstrapListener {
public void onCompleted();
public void onFailed(Throwable throwable);
public void onBootstrapStateChanged(BootstrapState state);
}

View file

@ -0,0 +1,51 @@
/*
* This file is part of Bitsquare.
*
* Bitsquare is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bitsquare is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bitsquare. If not, see <http://www.gnu.org/licenses/>.
*/
package io.bitsquare.network;
/**
* NOT_SUCCEEDED means we will try the next step, FAILED is used for fatal failures which will terminate the bootstrap
*/
public enum BootstrapState {
PEER_CREATION,
PEER_CREATION_FAILED,
DIRECT_INIT,
DIRECT_SUCCESS,
DIRECT_NOT_SUCCEEDED,
DIRECT_FAILED,
NAT_INIT,
NAT_SETUP_DONE,
NAT_SUCCESS,
NAT_NOT_SUCCEEDED,
NAT_FAILED,
RELAY_INIT,
RELAY_SUCCESS,
RELAY_FAILED;
private String message;
BootstrapState() {
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}