Search in sources :

Example 1 with ResultHandler

use of bisq.common.handlers.ResultHandler in project bisq-core by bisq-network.

the class Offer method checkOfferAvailability.

// /////////////////////////////////////////////////////////////////////////////////////////
// Availability
// /////////////////////////////////////////////////////////////////////////////////////////
public void checkOfferAvailability(OfferAvailabilityModel model, ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler) {
    availabilityProtocol = new OfferAvailabilityProtocol(model, () -> {
        cancelAvailabilityRequest();
        resultHandler.handleResult();
    }, (errorMessage) -> {
        if (availabilityProtocol != null)
            availabilityProtocol.cancel();
        log.error(errorMessage);
        errorMessageHandler.handleErrorMessage(errorMessage);
    });
    availabilityProtocol.sendOfferAvailabilityRequest();
}
Also used : Altcoin(bisq.core.monetary.Altcoin) PubKeyRing(bisq.common.crypto.PubKeyRing) Setter(lombok.Setter) OfferAvailabilityModel(bisq.core.offer.availability.OfferAvailabilityModel) Getter(lombok.Getter) Utilities(bisq.common.util.Utilities) Coin(org.bitcoinj.core.Coin) SimpleStringProperty(javafx.beans.property.SimpleStringProperty) Date(java.util.Date) Volume(bisq.core.monetary.Volume) PersistablePayload(bisq.common.proto.persistable.PersistablePayload) PB(io.bisq.generated.protobuffer.PB) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) TradePriceOutOfToleranceException(bisq.core.exceptions.TradePriceOutOfToleranceException) ReadOnlyStringProperty(javafx.beans.property.ReadOnlyStringProperty) Map(java.util.Map) CurrencyUtil(bisq.core.locale.CurrencyUtil) ErrorMessageHandler(bisq.common.handlers.ErrorMessageHandler) NetworkPayload(bisq.common.proto.network.NetworkPayload) OfferAvailabilityProtocol(bisq.core.offer.availability.OfferAvailabilityProtocol) Nullable(javax.annotation.Nullable) ObjectProperty(javafx.beans.property.ObjectProperty) ResultHandler(bisq.common.handlers.ResultHandler) JsonExclude(bisq.common.util.JsonExclude) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Fiat(org.bitcoinj.utils.Fiat) PublicKey(java.security.PublicKey) MathUtils(bisq.common.util.MathUtils) PaymentMethod(bisq.core.payment.payload.PaymentMethod) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) PriceFeedService(bisq.core.provider.price.PriceFeedService) SimpleObjectProperty(javafx.beans.property.SimpleObjectProperty) NodeAddress(bisq.network.p2p.NodeAddress) Price(bisq.core.monetary.Price) Optional(java.util.Optional) KeyRing(bisq.common.crypto.KeyRing) StringProperty(javafx.beans.property.StringProperty) MarketPrice(bisq.core.provider.price.MarketPrice) OfferAvailabilityProtocol(bisq.core.offer.availability.OfferAvailabilityProtocol)

Example 2 with ResultHandler

use of bisq.common.handlers.ResultHandler in project bisq-desktop by bisq-network.

the class BuyerStep4View method doWithdrawal.

private void doWithdrawal(Coin amount, Coin fee) {
    String toAddress = withdrawAddressTextField.getText();
    ResultHandler resultHandler = this::handleTradeCompleted;
    FaultHandler faultHandler = (errorMessage, throwable) -> {
        useSavingsWalletButton.setDisable(false);
        withdrawToExternalWalletButton.setDisable(false);
        if (throwable != null && throwable.getMessage() != null)
            new Popup<>().error(errorMessage + "\n\n" + throwable.getMessage()).show();
        else
            new Popup<>().error(errorMessage).show();
    };
    if (model.dataModel.btcWalletService.isEncrypted()) {
        UserThread.runAfter(() -> model.dataModel.walletPasswordWindow.onAesKey(aesKey -> doWithdrawRequest(toAddress, amount, fee, aesKey, resultHandler, faultHandler)).show(), 300, TimeUnit.MILLISECONDS);
    } else
        doWithdrawRequest(toAddress, amount, fee, null, resultHandler, faultHandler);
}
Also used : Button(javafx.scene.control.Button) BtcWalletService(bisq.core.btc.wallet.BtcWalletService) Transaction(org.bitcoinj.core.Transaction) Coin(org.bitcoinj.core.Coin) Layout(bisq.desktop.util.Layout) ClosedTradesView(bisq.desktop.main.portfolio.closedtrades.ClosedTradesView) Notification(bisq.desktop.main.overlays.notifications.Notification) BSFormatter(bisq.desktop.util.BSFormatter) Tuple2(bisq.common.util.Tuple2) Insets(javafx.geometry.Insets) InputTextField(bisq.desktop.components.InputTextField) Res(bisq.core.locale.Res) KeyParameter(org.spongycastle.crypto.params.KeyParameter) TitledGroupBg(bisq.desktop.components.TitledGroupBg) GridPane(javafx.scene.layout.GridPane) PendingTradesViewModel(bisq.desktop.main.portfolio.pendingtrades.PendingTradesViewModel) AddressFormatException(org.bitcoinj.core.AddressFormatException) HBox(javafx.scene.layout.HBox) Popup(bisq.desktop.main.overlays.popups.Popup) AddressEntryException(bisq.core.btc.AddressEntryException) Label(javafx.scene.control.Label) FaultHandler(bisq.common.handlers.FaultHandler) AutoTooltipLabel(bisq.desktop.components.AutoTooltipLabel) InsufficientFundsException(bisq.core.btc.InsufficientFundsException) DontShowAgainLookup(bisq.core.user.DontShowAgainLookup) ResultHandler(bisq.common.handlers.ResultHandler) FormBuilder(bisq.desktop.util.FormBuilder) Log(bisq.common.app.Log) TradeStepView(bisq.desktop.main.portfolio.pendingtrades.steps.TradeStepView) TimeUnit(java.util.concurrent.TimeUnit) MainView(bisq.desktop.main.MainView) AddressEntry(bisq.core.btc.AddressEntry) DevEnv(bisq.common.app.DevEnv) AutoTooltipButton(bisq.desktop.components.AutoTooltipButton) UserThread(bisq.common.UserThread) BtcAddressValidator(bisq.desktop.util.validation.BtcAddressValidator) PortfolioView(bisq.desktop.main.portfolio.PortfolioView) Restrictions(bisq.core.btc.Restrictions) CoinUtil(bisq.core.util.CoinUtil) Popup(bisq.desktop.main.overlays.popups.Popup) ResultHandler(bisq.common.handlers.ResultHandler) FaultHandler(bisq.common.handlers.FaultHandler)

Example 3 with ResultHandler

use of bisq.common.handlers.ResultHandler in project bisq-api by mrosseel.

the class BisqProxy method paymentReceived.

public CompletableFuture<Void> paymentReceived(String tradeId) {
    final CompletableFuture<Void> futureResult = new CompletableFuture<>();
    Trade trade;
    try {
        trade = getTrade(tradeId);
    } catch (NotFoundException e) {
        return failFuture(futureResult, e);
    }
    if (!Trade.State.SELLER_RECEIVED_FIAT_PAYMENT_INITIATED_MSG.equals(trade.getState())) {
        return failFuture(futureResult, new ValidationException("Trade is not in the correct state to receive payment: " + trade.getState()));
    }
    TradeProtocol tradeProtocol = trade.getTradeProtocol();
    if (!(tradeProtocol instanceof SellerAsTakerProtocol || tradeProtocol instanceof SellerAsMakerProtocol)) {
        return failFuture(futureResult, new ValidationException("Trade is not in the correct state to receive payment: " + trade.getState()));
    }
    ResultHandler resultHandler = () -> futureResult.complete(null);
    ErrorMessageHandler errorResultHandler = message -> futureResult.completeExceptionally(new RuntimeException(message));
    // TODO I think we should check instance of tradeProtocol here instead of trade
    if (trade instanceof SellerAsMakerTrade) {
        ((SellerAsMakerProtocol) tradeProtocol).onFiatPaymentReceived(resultHandler, errorResultHandler);
    } else {
        ((SellerAsTakerProtocol) tradeProtocol).onFiatPaymentReceived(resultHandler, errorResultHandler);
    }
    return futureResult;
}
Also used : Arrays(java.util.Arrays) OpenOffer(bisq.core.offer.OpenOffer) User(bisq.core.user.User) PriceFeed(network.bisq.api.model.PriceFeed) Statistic(bisq.network.p2p.network.Statistic) ZoneOffset(java.time.ZoneOffset) KeyParameter(org.spongycastle.crypto.params.KeyParameter) ClosedTradableDetails(network.bisq.api.model.ClosedTradableDetails) CurrencyList(network.bisq.api.model.CurrencyList) WalletAddress(network.bisq.api.model.WalletAddress) AddressEntryException(bisq.core.btc.AddressEntryException) Offer(bisq.core.offer.Offer) ClosedTradableManager(bisq.core.trade.closed.ClosedTradableManager) SellerAsMakerProtocol(bisq.core.trade.protocol.SellerAsMakerProtocol) WalletTransactionList(network.bisq.api.model.WalletTransactionList) InsufficientFundsException(bisq.core.btc.InsufficientFundsException) Set(java.util.Set) TokenRegistry(network.bisq.api.service.TokenRegistry) BlockChainExplorer(bisq.core.user.BlockChainExplorer) TradeProtocol(bisq.core.trade.protocol.TradeProtocol) ZoneId(java.time.ZoneId) ECKey(org.bitcoinj.core.ECKey) Slf4j(lombok.extern.slf4j.Slf4j) Stream(java.util.stream.Stream) AddressEntry(bisq.core.btc.AddressEntry) WalletsSetup(bisq.core.btc.wallet.WalletsSetup) CryptoCurrency(bisq.core.locale.CryptoCurrency) Currency(network.bisq.api.model.Currency) TradeManager(bisq.core.trade.TradeManager) NodeAddress(bisq.network.p2p.NodeAddress) SellerAsTakerProtocol(bisq.core.trade.protocol.SellerAsTakerProtocol) CountryUtil(bisq.core.locale.CountryUtil) BuyerAsTakerProtocol(bisq.core.trade.protocol.BuyerAsTakerProtocol) TransactionOutput(org.bitcoinj.core.TransactionOutput) FeeService(bisq.core.provider.fee.FeeService) ObservableList(javafx.collections.ObservableList) PaymentAccountHelper(network.bisq.api.model.payment.PaymentAccountHelper) Restrictions(bisq.core.btc.Restrictions) Arbitrator(bisq.core.arbitration.Arbitrator) TransactionConfidence(org.bitcoinj.core.TransactionConfidence) Wallet(org.bitcoinj.wallet.Wallet) Peer(org.bitcoinj.core.Peer) ArrayList(java.util.ArrayList) ClosedTradableConverter(network.bisq.api.model.ClosedTradableConverter) OfferPayload(bisq.core.offer.OfferPayload) Country(bisq.core.locale.Country) BitcoinNetworkStatus(network.bisq.api.model.BitcoinNetworkStatus) WalletDetails(network.bisq.api.model.WalletDetails) Nullable(javax.annotation.Nullable) IOException(java.io.IOException) OfferBookService(bisq.core.offer.OfferBookService) Names(com.google.inject.name.Names) BisqEnvironment(bisq.core.app.BisqEnvironment) SeedWords(network.bisq.api.model.SeedWords) FutureCallback(com.google.common.util.concurrent.FutureCallback) File(java.io.File) OpenOfferManager(bisq.core.offer.OpenOfferManager) InputValidator(bisq.core.util.validation.InputValidator) PriceFeedService(bisq.core.provider.price.PriceFeedService) PaymentAccountList(network.bisq.api.model.PaymentAccountList) KeyRing(bisq.common.crypto.KeyRing) PreferencesAvailableValues(network.bisq.api.model.PreferencesAvailableValues) Transaction(org.bitcoinj.core.Transaction) Preferences(network.bisq.api.model.Preferences) Date(java.util.Date) Coin(org.bitcoinj.core.Coin) Key(com.google.inject.Key) AltCoinAddressValidator(bisq.core.payment.validation.AltCoinAddressValidator) VersionDetails(network.bisq.api.model.VersionDetails) Res(bisq.core.locale.Res) ErrorMessageHandler(bisq.common.handlers.ErrorMessageHandler) KeyCrypterScrypt(org.bitcoinj.crypto.KeyCrypterScrypt) PaymentAccountUtil.isPaymentAccountValidForOffer(bisq.core.payment.PaymentAccountUtil.isPaymentAccountValidForOffer) OfferUtil(bisq.core.offer.OfferUtil) P2PService(bisq.network.p2p.P2PService) Predicate(java.util.function.Predicate) ArbitratorManager(bisq.core.arbitration.ArbitratorManager) Collection(java.util.Collection) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) FileNotFoundException(java.io.FileNotFoundException) BsqWalletService(bisq.core.btc.wallet.BsqWalletService) AccountAgeWitnessService(bisq.core.payment.AccountAgeWitnessService) FileUtil(bisq.common.storage.FileUtil) List(java.util.List) PaymentAccount(bisq.core.payment.PaymentAccount) DeterministicSeed(org.bitcoinj.wallet.DeterministicSeed) DevEnv(bisq.common.app.DevEnv) MarketList(network.bisq.api.model.MarketList) AppOptionKeys(bisq.core.app.AppOptionKeys) LocalDate(java.time.LocalDate) Optional(java.util.Optional) Address(org.bitcoinj.core.Address) NotNull(org.jetbrains.annotations.NotNull) MarketPrice(bisq.core.provider.price.MarketPrice) BtcWalletService(bisq.core.btc.wallet.BtcWalletService) TradeCurrency(bisq.core.locale.TradeCurrency) SellerAsMakerTrade(bisq.core.trade.SellerAsMakerTrade) Getter(lombok.Getter) WalletService(bisq.core.btc.wallet.WalletService) CompletableFuture(java.util.concurrent.CompletableFuture) FiatCurrency(bisq.core.locale.FiatCurrency) WalletsManager(bisq.core.btc.wallet.WalletsManager) Tuple2(bisq.common.util.Tuple2) BuyerAsMakerProtocol(bisq.core.trade.protocol.BuyerAsMakerProtocol) P2PNetworkStatus(network.bisq.api.model.P2PNetworkStatus) Market(network.bisq.api.model.Market) CurrencyUtil(bisq.core.locale.CurrencyUtil) BitcoinNodes(bisq.core.btc.BitcoinNodes) Version(bisq.common.app.Version) CryptoCurrencyAccount(bisq.core.payment.CryptoCurrencyAccount) P2PNetworkConnection(network.bisq.api.model.P2PNetworkConnection) BuyerAsMakerTrade(bisq.core.trade.BuyerAsMakerTrade) Trade(bisq.core.trade.Trade) WalletAddressList(network.bisq.api.model.WalletAddressList) ResultHandler(bisq.common.handlers.ResultHandler) FailedTradesManager(bisq.core.trade.failed.FailedTradesManager) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) FileInputStream(java.io.FileInputStream) WalletTransaction(network.bisq.api.model.WalletTransaction) Injector(com.google.inject.Injector) Collectors.toList(java.util.stream.Collectors.toList) AuthResult(network.bisq.api.model.AuthResult) ValidationException(javax.validation.ValidationException) Storage(bisq.common.storage.Storage) Comparator(java.util.Comparator) Collections(java.util.Collections) CoinUtil(bisq.core.util.CoinUtil) InputStream(java.io.InputStream) SellerAsMakerTrade(bisq.core.trade.SellerAsMakerTrade) ValidationException(javax.validation.ValidationException) FileNotFoundException(java.io.FileNotFoundException) TradeProtocol(bisq.core.trade.protocol.TradeProtocol) ResultHandler(bisq.common.handlers.ResultHandler) ErrorMessageHandler(bisq.common.handlers.ErrorMessageHandler) SellerAsMakerTrade(bisq.core.trade.SellerAsMakerTrade) BuyerAsMakerTrade(bisq.core.trade.BuyerAsMakerTrade) Trade(bisq.core.trade.Trade) CompletableFuture(java.util.concurrent.CompletableFuture) SellerAsTakerProtocol(bisq.core.trade.protocol.SellerAsTakerProtocol) SellerAsMakerProtocol(bisq.core.trade.protocol.SellerAsMakerProtocol)

Example 4 with ResultHandler

use of bisq.common.handlers.ResultHandler in project bisq-core by bisq-network.

the class WalletsSetup method initialize.

// /////////////////////////////////////////////////////////////////////////////////////////
// Lifecycle
// /////////////////////////////////////////////////////////////////////////////////////////
public void initialize(@Nullable DeterministicSeed seed, ResultHandler resultHandler, ExceptionHandler exceptionHandler) {
    Log.traceCall();
    // Tell bitcoinj to execute event handlers on the JavaFX UI thread. This keeps things simple and means
    // we cannot forget to switch threads when adding event handlers. Unfortunately, the DownloadListener
    // we give to the app kit is currently an exception and runs on a library thread. It'll get fixed in
    // a future version.
    Threading.USER_THREAD = UserThread.getExecutor();
    Timer timeoutTimer = UserThread.runAfter(() -> exceptionHandler.handleException(new TimeoutException("Wallet did not initialize in " + STARTUP_TIMEOUT + " seconds.")), STARTUP_TIMEOUT);
    backupWallets();
    final Socks5Proxy socks5Proxy = preferences.getUseTorForBitcoinJ() ? socks5ProxyProvider.getSocks5Proxy() : null;
    log.info("Socks5Proxy for bitcoinj: socks5Proxy=" + socks5Proxy);
    walletConfig = new WalletConfig(params, socks5Proxy, walletDir, bisqEnvironment, userAgent, numConnectionForBtc, btcWalletFileName, BSQ_WALLET_FILE_NAME, SPV_CHAIN_FILE_NAME) {

        @Override
        protected void onSetupCompleted() {
            // We are here in the btcj thread Thread[ STARTING,5,main]
            super.onSetupCompleted();
            final PeerGroup peerGroup = walletConfig.peerGroup();
            // We don't want to get our node white list polluted with nodes from AddressMessage calls.
            if (preferences.getBitcoinNodes() != null && !preferences.getBitcoinNodes().isEmpty())
                peerGroup.setAddPeersFromAddressMessage(false);
            peerGroup.addConnectedEventListener((peer, peerCount) -> {
                // We get called here on our user thread
                numPeers.set(peerCount);
                connectedPeers.set(peerGroup.getConnectedPeers());
            });
            peerGroup.addDisconnectedEventListener((peer, peerCount) -> {
                // We get called here on our user thread
                numPeers.set(peerCount);
                connectedPeers.set(peerGroup.getConnectedPeers());
            });
            // Map to user thread
            UserThread.execute(() -> {
                addressEntryList.onWalletReady(walletConfig.getBtcWallet());
                timeoutTimer.stop();
                setupCompletedHandlers.stream().forEach(Runnable::run);
            });
            // onSetupCompleted in walletAppKit is not the called on the last invocations, so we add a bit of delay
            UserThread.runAfter(resultHandler::handleResult, 100, TimeUnit.MILLISECONDS);
        }
    };
    if (params == RegTestParams.get()) {
        walletConfig.setMinBroadcastConnections(1);
        if (regTestHost == RegTestHost.LOCALHOST) {
            walletConfig.setPeerNodesForLocalHost();
        } else if (regTestHost == RegTestHost.REG_TEST_SERVER) {
            walletConfig.setMinBroadcastConnections(1);
            configPeerNodesForRegTestServer();
        } else {
            configPeerNodes(socks5Proxy);
        }
    } else if (bisqEnvironment.isBitcoinLocalhostNodeRunning()) {
        walletConfig.setMinBroadcastConnections(1);
        walletConfig.setPeerNodesForLocalHost();
    } else {
        configPeerNodes(socks5Proxy);
    }
    walletConfig.setDownloadListener(downloadListener).setBlockingStartup(false);
    // If seed is non-null it means we are restoring from backup.
    walletConfig.setSeed(seed);
    walletConfig.addListener(new Service.Listener() {

        @Override
        public void failed(@NotNull Service.State from, @NotNull Throwable failure) {
            walletConfig = null;
            log.error("Service failure from state: {}; failure={}", from, failure);
            timeoutTimer.stop();
            UserThread.execute(() -> exceptionHandler.handleException(failure));
        }
    }, Threading.USER_THREAD);
    walletConfig.startAsync();
}
Also used : RegTestParams(org.bitcoinj.params.RegTestParams) Date(java.util.Date) TimeoutException(java.util.concurrent.TimeoutException) RegTestHost(bisq.core.btc.RegTestHost) StringUtils(org.apache.commons.lang3.StringUtils) InetAddress(java.net.InetAddress) NetworkParameters(org.bitcoinj.core.NetworkParameters) AddressEntryList(bisq.core.btc.AddressEntryList) SimpleIntegerProperty(javafx.beans.property.SimpleIntegerProperty) Socks5Proxy(com.runjva.sourceforge.jsocks.protocol.Socks5Proxy) Context(org.bitcoinj.core.Context) PeerGroup(org.bitcoinj.core.PeerGroup) BlockChain(org.bitcoinj.core.BlockChain) ReadOnlyDoubleProperty(javafx.beans.property.ReadOnlyDoubleProperty) Set(java.util.Set) DownloadProgressTracker(org.bitcoinj.core.listeners.DownloadProgressTracker) Collectors(java.util.stream.Collectors) ExceptionHandler(bisq.common.handlers.ExceptionHandler) FileUtil(bisq.common.storage.FileUtil) BooleanProperty(javafx.beans.property.BooleanProperty) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) DeterministicSeed(org.bitcoinj.wallet.DeterministicSeed) AddressEntry(bisq.core.btc.AddressEntry) Preferences(bisq.core.user.Preferences) UserThread(bisq.common.UserThread) ReadOnlyIntegerProperty(javafx.beans.property.ReadOnlyIntegerProperty) SimpleDoubleProperty(javafx.beans.property.SimpleDoubleProperty) Address(org.bitcoinj.core.Address) NotNull(org.jetbrains.annotations.NotNull) ReadOnlyObjectProperty(javafx.beans.property.ReadOnlyObjectProperty) Wallet(org.bitcoinj.wallet.Wallet) Timer(bisq.common.Timer) DoubleProperty(javafx.beans.property.DoubleProperty) Peer(org.bitcoinj.core.Peer) IntegerProperty(javafx.beans.property.IntegerProperty) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) ImmutableList(com.google.common.collect.ImmutableList) Socks5MultiDiscovery(bisq.network.Socks5MultiDiscovery) PeerAddress(org.bitcoinj.core.PeerAddress) Named(javax.inject.Named) Nullable(javax.annotation.Nullable) BitcoinNodes(bisq.core.btc.BitcoinNodes) ObjectProperty(javafx.beans.property.ObjectProperty) BtcNode(bisq.core.btc.BitcoinNodes.BtcNode) Socks5ProxyProvider(bisq.network.Socks5ProxyProvider) ResultHandler(bisq.common.handlers.ResultHandler) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Log(bisq.common.app.Log) IOException(java.io.IOException) BisqEnvironment(bisq.core.app.BisqEnvironment) BtcOptionKeys(bisq.core.btc.BtcOptionKeys) UnknownHostException(java.net.UnknownHostException) File(java.io.File) Threading(org.bitcoinj.utils.Threading) Service(com.google.common.util.concurrent.Service) TimeUnit(java.util.concurrent.TimeUnit) SimpleBooleanProperty(javafx.beans.property.SimpleBooleanProperty) SimpleObjectProperty(javafx.beans.property.SimpleObjectProperty) Paths(java.nio.file.Paths) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Timer(bisq.common.Timer) Socks5Proxy(com.runjva.sourceforge.jsocks.protocol.Socks5Proxy) PeerGroup(org.bitcoinj.core.PeerGroup) Service(com.google.common.util.concurrent.Service) TimeoutException(java.util.concurrent.TimeoutException)

Example 5 with ResultHandler

use of bisq.common.handlers.ResultHandler in project bisq-api by mrosseel.

the class BisqProxy method paymentStarted.

public CompletableFuture<Void> paymentStarted(String tradeId) {
    final CompletableFuture<Void> futureResult = new CompletableFuture<>();
    Trade trade;
    try {
        trade = getTrade(tradeId);
    } catch (NotFoundException e) {
        return failFuture(futureResult, e);
    }
    if (!Trade.State.DEPOSIT_CONFIRMED_IN_BLOCK_CHAIN.equals(trade.getState())) {
        return failFuture(futureResult, new ValidationException("Trade is not in the correct state to start payment: " + trade.getState()));
    }
    TradeProtocol tradeProtocol = trade.getTradeProtocol();
    ResultHandler resultHandler = () -> futureResult.complete(null);
    ErrorMessageHandler errorResultHandler = message -> futureResult.completeExceptionally(new RuntimeException(message));
    if (trade instanceof BuyerAsMakerTrade) {
        ((BuyerAsMakerProtocol) tradeProtocol).onFiatPaymentStarted(resultHandler, errorResultHandler);
    } else {
        ((BuyerAsTakerProtocol) tradeProtocol).onFiatPaymentStarted(resultHandler, errorResultHandler);
    }
    return futureResult;
}
Also used : Arrays(java.util.Arrays) OpenOffer(bisq.core.offer.OpenOffer) User(bisq.core.user.User) PriceFeed(network.bisq.api.model.PriceFeed) Statistic(bisq.network.p2p.network.Statistic) ZoneOffset(java.time.ZoneOffset) KeyParameter(org.spongycastle.crypto.params.KeyParameter) ClosedTradableDetails(network.bisq.api.model.ClosedTradableDetails) CurrencyList(network.bisq.api.model.CurrencyList) WalletAddress(network.bisq.api.model.WalletAddress) AddressEntryException(bisq.core.btc.AddressEntryException) Offer(bisq.core.offer.Offer) ClosedTradableManager(bisq.core.trade.closed.ClosedTradableManager) SellerAsMakerProtocol(bisq.core.trade.protocol.SellerAsMakerProtocol) WalletTransactionList(network.bisq.api.model.WalletTransactionList) InsufficientFundsException(bisq.core.btc.InsufficientFundsException) Set(java.util.Set) TokenRegistry(network.bisq.api.service.TokenRegistry) BlockChainExplorer(bisq.core.user.BlockChainExplorer) TradeProtocol(bisq.core.trade.protocol.TradeProtocol) ZoneId(java.time.ZoneId) ECKey(org.bitcoinj.core.ECKey) Slf4j(lombok.extern.slf4j.Slf4j) Stream(java.util.stream.Stream) AddressEntry(bisq.core.btc.AddressEntry) WalletsSetup(bisq.core.btc.wallet.WalletsSetup) CryptoCurrency(bisq.core.locale.CryptoCurrency) Currency(network.bisq.api.model.Currency) TradeManager(bisq.core.trade.TradeManager) NodeAddress(bisq.network.p2p.NodeAddress) SellerAsTakerProtocol(bisq.core.trade.protocol.SellerAsTakerProtocol) CountryUtil(bisq.core.locale.CountryUtil) BuyerAsTakerProtocol(bisq.core.trade.protocol.BuyerAsTakerProtocol) TransactionOutput(org.bitcoinj.core.TransactionOutput) FeeService(bisq.core.provider.fee.FeeService) ObservableList(javafx.collections.ObservableList) PaymentAccountHelper(network.bisq.api.model.payment.PaymentAccountHelper) Restrictions(bisq.core.btc.Restrictions) Arbitrator(bisq.core.arbitration.Arbitrator) TransactionConfidence(org.bitcoinj.core.TransactionConfidence) Wallet(org.bitcoinj.wallet.Wallet) Peer(org.bitcoinj.core.Peer) ArrayList(java.util.ArrayList) ClosedTradableConverter(network.bisq.api.model.ClosedTradableConverter) OfferPayload(bisq.core.offer.OfferPayload) Country(bisq.core.locale.Country) BitcoinNetworkStatus(network.bisq.api.model.BitcoinNetworkStatus) WalletDetails(network.bisq.api.model.WalletDetails) Nullable(javax.annotation.Nullable) IOException(java.io.IOException) OfferBookService(bisq.core.offer.OfferBookService) Names(com.google.inject.name.Names) BisqEnvironment(bisq.core.app.BisqEnvironment) SeedWords(network.bisq.api.model.SeedWords) FutureCallback(com.google.common.util.concurrent.FutureCallback) File(java.io.File) OpenOfferManager(bisq.core.offer.OpenOfferManager) InputValidator(bisq.core.util.validation.InputValidator) PriceFeedService(bisq.core.provider.price.PriceFeedService) PaymentAccountList(network.bisq.api.model.PaymentAccountList) KeyRing(bisq.common.crypto.KeyRing) PreferencesAvailableValues(network.bisq.api.model.PreferencesAvailableValues) Transaction(org.bitcoinj.core.Transaction) Preferences(network.bisq.api.model.Preferences) Date(java.util.Date) Coin(org.bitcoinj.core.Coin) Key(com.google.inject.Key) AltCoinAddressValidator(bisq.core.payment.validation.AltCoinAddressValidator) VersionDetails(network.bisq.api.model.VersionDetails) Res(bisq.core.locale.Res) ErrorMessageHandler(bisq.common.handlers.ErrorMessageHandler) KeyCrypterScrypt(org.bitcoinj.crypto.KeyCrypterScrypt) PaymentAccountUtil.isPaymentAccountValidForOffer(bisq.core.payment.PaymentAccountUtil.isPaymentAccountValidForOffer) OfferUtil(bisq.core.offer.OfferUtil) P2PService(bisq.network.p2p.P2PService) Predicate(java.util.function.Predicate) ArbitratorManager(bisq.core.arbitration.ArbitratorManager) Collection(java.util.Collection) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) FileNotFoundException(java.io.FileNotFoundException) BsqWalletService(bisq.core.btc.wallet.BsqWalletService) AccountAgeWitnessService(bisq.core.payment.AccountAgeWitnessService) FileUtil(bisq.common.storage.FileUtil) List(java.util.List) PaymentAccount(bisq.core.payment.PaymentAccount) DeterministicSeed(org.bitcoinj.wallet.DeterministicSeed) DevEnv(bisq.common.app.DevEnv) MarketList(network.bisq.api.model.MarketList) AppOptionKeys(bisq.core.app.AppOptionKeys) LocalDate(java.time.LocalDate) Optional(java.util.Optional) Address(org.bitcoinj.core.Address) NotNull(org.jetbrains.annotations.NotNull) MarketPrice(bisq.core.provider.price.MarketPrice) BtcWalletService(bisq.core.btc.wallet.BtcWalletService) TradeCurrency(bisq.core.locale.TradeCurrency) SellerAsMakerTrade(bisq.core.trade.SellerAsMakerTrade) Getter(lombok.Getter) WalletService(bisq.core.btc.wallet.WalletService) CompletableFuture(java.util.concurrent.CompletableFuture) FiatCurrency(bisq.core.locale.FiatCurrency) WalletsManager(bisq.core.btc.wallet.WalletsManager) Tuple2(bisq.common.util.Tuple2) BuyerAsMakerProtocol(bisq.core.trade.protocol.BuyerAsMakerProtocol) P2PNetworkStatus(network.bisq.api.model.P2PNetworkStatus) Market(network.bisq.api.model.Market) CurrencyUtil(bisq.core.locale.CurrencyUtil) BitcoinNodes(bisq.core.btc.BitcoinNodes) Version(bisq.common.app.Version) CryptoCurrencyAccount(bisq.core.payment.CryptoCurrencyAccount) P2PNetworkConnection(network.bisq.api.model.P2PNetworkConnection) BuyerAsMakerTrade(bisq.core.trade.BuyerAsMakerTrade) Trade(bisq.core.trade.Trade) WalletAddressList(network.bisq.api.model.WalletAddressList) ResultHandler(bisq.common.handlers.ResultHandler) FailedTradesManager(bisq.core.trade.failed.FailedTradesManager) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) FileInputStream(java.io.FileInputStream) WalletTransaction(network.bisq.api.model.WalletTransaction) Injector(com.google.inject.Injector) Collectors.toList(java.util.stream.Collectors.toList) AuthResult(network.bisq.api.model.AuthResult) ValidationException(javax.validation.ValidationException) Storage(bisq.common.storage.Storage) Comparator(java.util.Comparator) Collections(java.util.Collections) CoinUtil(bisq.core.util.CoinUtil) InputStream(java.io.InputStream) ValidationException(javax.validation.ValidationException) BuyerAsTakerProtocol(bisq.core.trade.protocol.BuyerAsTakerProtocol) FileNotFoundException(java.io.FileNotFoundException) TradeProtocol(bisq.core.trade.protocol.TradeProtocol) ResultHandler(bisq.common.handlers.ResultHandler) ErrorMessageHandler(bisq.common.handlers.ErrorMessageHandler) SellerAsMakerTrade(bisq.core.trade.SellerAsMakerTrade) BuyerAsMakerTrade(bisq.core.trade.BuyerAsMakerTrade) Trade(bisq.core.trade.Trade) CompletableFuture(java.util.concurrent.CompletableFuture) BuyerAsMakerProtocol(bisq.core.trade.protocol.BuyerAsMakerProtocol) BuyerAsMakerTrade(bisq.core.trade.BuyerAsMakerTrade)

Aggregations

ResultHandler (bisq.common.handlers.ResultHandler)5 AddressEntry (bisq.core.btc.AddressEntry)4 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)4 Date (java.util.Date)4 List (java.util.List)4 Nullable (javax.annotation.Nullable)4 Slf4j (lombok.extern.slf4j.Slf4j)4 DevEnv (bisq.common.app.DevEnv)3 KeyRing (bisq.common.crypto.KeyRing)3 ErrorMessageHandler (bisq.common.handlers.ErrorMessageHandler)3 FileUtil (bisq.common.storage.FileUtil)3 Tuple2 (bisq.common.util.Tuple2)3 BisqEnvironment (bisq.core.app.BisqEnvironment)3 AddressEntryException (bisq.core.btc.AddressEntryException)3 InsufficientFundsException (bisq.core.btc.InsufficientFundsException)3 Restrictions (bisq.core.btc.Restrictions)3 Coin (org.bitcoinj.core.Coin)3 UserThread (bisq.common.UserThread)2 Log (bisq.common.app.Log)2 Version (bisq.common.app.Version)2