Search in sources :

Example 21 with Coin

use of org.bitcoinj.core.Coin in project bitsquare by bitsquare.

the class SetupDepositBalanceListener method run.

@Override
protected void run() {
    try {
        runInterceptHook();
        WalletService walletService = processModel.getWalletService();
        Address address = walletService.getOrCreateAddressEntry(trade.getId(), AddressEntry.Context.RESERVED_FOR_TRADE).getAddress();
        balanceListener = new BalanceListener(address) {

            @Override
            public void onBalanceChanged(Coin balance, Transaction tx) {
                updateBalance(balance);
            }
        };
        walletService.addBalanceListener(balanceListener);
        tradeStateSubscription = EasyBind.subscribe(trade.stateProperty(), newValue -> {
            log.debug("tradeStateSubscription newValue " + newValue);
            if (newValue == Trade.State.OFFERER_RECEIVED_DEPOSIT_TX_PUBLISHED_MSG || newValue == Trade.State.DEPOSIT_SEEN_IN_NETWORK) {
                walletService.removeBalanceListener(balanceListener);
                UserThread.execute(this::unSubscribe);
            }
        });
        updateBalance(walletService.getBalanceForAddress(address));
        // we complete immediately, our object stays alive because the balanceListener is stored in the WalletService
        complete();
    } catch (Throwable t) {
        failed(t);
    }
}
Also used : OffererTrade(io.bitsquare.trade.OffererTrade) Transaction(org.bitcoinj.core.Transaction) Logger(org.slf4j.Logger) Coin(org.bitcoinj.core.Coin) UserThread(io.bitsquare.common.UserThread) TaskRunner(io.bitsquare.common.taskrunner.TaskRunner) LoggerFactory(org.slf4j.LoggerFactory) Trade(io.bitsquare.trade.Trade) TradeTask(io.bitsquare.trade.protocol.trade.tasks.TradeTask) Subscription(org.fxmisc.easybind.Subscription) BalanceListener(io.bitsquare.btc.listeners.BalanceListener) EasyBind(org.fxmisc.easybind.EasyBind) WalletService(io.bitsquare.btc.WalletService) Address(org.bitcoinj.core.Address) AddressEntry(io.bitsquare.btc.AddressEntry) Coin(org.bitcoinj.core.Coin) BalanceListener(io.bitsquare.btc.listeners.BalanceListener) Address(org.bitcoinj.core.Address) Transaction(org.bitcoinj.core.Transaction) WalletService(io.bitsquare.btc.WalletService)

Example 22 with Coin

use of org.bitcoinj.core.Coin in project bitsquare by bitsquare.

the class OffererCreatesAndSignsDepositTxAsSeller method run.

@Override
protected void run() {
    try {
        runInterceptHook();
        checkNotNull(trade.getTradeAmount(), "trade.getTradeAmount() must not be null");
        Offer offer = trade.getOffer();
        Coin sellerInputAmount = FeePolicy.getSecurityDeposit(offer).add(FeePolicy.getFixedTxFeeForTrades(offer)).add(trade.getTradeAmount());
        Coin msOutputAmount = sellerInputAmount.add(FeePolicy.getSecurityDeposit(offer));
        log.debug("\n\n------------------------------------------------------------\n" + "Contract as json\n" + trade.getContractAsJson() + "\n------------------------------------------------------------\n");
        byte[] contractHash = Hash.getHash(trade.getContractAsJson());
        trade.setContractHash(contractHash);
        WalletService walletService = processModel.getWalletService();
        String id = processModel.getOffer().getId();
        AddressEntry offererAddressEntry = walletService.getOrCreateAddressEntry(id, AddressEntry.Context.RESERVED_FOR_TRADE);
        AddressEntry sellerMultiSigAddressEntry = walletService.getOrCreateAddressEntry(id, AddressEntry.Context.MULTI_SIG);
        sellerMultiSigAddressEntry.setCoinLockedInMultiSig(sellerInputAmount.subtract(FeePolicy.getFixedTxFeeForTrades(offer)));
        Address changeAddress = walletService.getOrCreateAddressEntry(AddressEntry.Context.AVAILABLE).getAddress();
        PreparedDepositTxAndOffererInputs result = processModel.getTradeWalletService().offererCreatesAndSignsDepositTx(false, contractHash, sellerInputAmount, msOutputAmount, processModel.tradingPeer.getRawTransactionInputs(), processModel.tradingPeer.getChangeOutputValue(), processModel.tradingPeer.getChangeOutputAddress(), offererAddressEntry.getAddress(), changeAddress, processModel.tradingPeer.getMultiSigPubKey(), sellerMultiSigAddressEntry.getPubKey(), trade.getArbitratorPubKey());
        processModel.setPreparedDepositTx(result.depositTransaction);
        processModel.setRawTransactionInputs(result.rawOffererInputs);
        complete();
    } catch (Throwable t) {
        failed(t);
    }
}
Also used : Coin(org.bitcoinj.core.Coin) Address(org.bitcoinj.core.Address) Offer(io.bitsquare.trade.offer.Offer) AddressEntry(io.bitsquare.btc.AddressEntry) PreparedDepositTxAndOffererInputs(io.bitsquare.btc.data.PreparedDepositTxAndOffererInputs) WalletService(io.bitsquare.btc.WalletService)

Example 23 with Coin

use of org.bitcoinj.core.Coin in project bitsquare by bitsquare.

the class TakerCreatesDepositTxInputsAsSeller method run.

@Override
protected void run() {
    try {
        runInterceptHook();
        if (trade.getTradeAmount() != null) {
            Offer offer = trade.getOffer();
            Coin takerInputAmount = FeePolicy.getSecurityDeposit(offer).add(FeePolicy.getFixedTxFeeForTrades(offer)).add(trade.getTradeAmount());
            WalletService walletService = processModel.getWalletService();
            AddressEntry takersAddressEntry = walletService.getOrCreateAddressEntry(processModel.getOffer().getId(), AddressEntry.Context.RESERVED_FOR_TRADE);
            Address changeAddress = walletService.getOrCreateAddressEntry(AddressEntry.Context.AVAILABLE).getAddress();
            InputsAndChangeOutput result = processModel.getTradeWalletService().takerCreatesDepositsTxInputs(takerInputAmount, takersAddressEntry.getAddress(), changeAddress);
            processModel.setRawTransactionInputs(result.rawTransactionInputs);
            processModel.setChangeOutputValue(result.changeOutputValue);
            processModel.setChangeOutputAddress(result.changeOutputAddress);
            complete();
        } else {
            failed("trade.getTradeAmount() = null");
        }
    } catch (Throwable t) {
        failed(t);
    }
}
Also used : Coin(org.bitcoinj.core.Coin) Address(org.bitcoinj.core.Address) Offer(io.bitsquare.trade.offer.Offer) AddressEntry(io.bitsquare.btc.AddressEntry) InputsAndChangeOutput(io.bitsquare.btc.data.InputsAndChangeOutput) WalletService(io.bitsquare.btc.WalletService)

Example 24 with Coin

use of org.bitcoinj.core.Coin in project bitsquare by bitsquare.

the class MainViewModel method updateReservedBalance.

private void updateReservedBalance() {
    Coin sum = Coin.valueOf(openOfferManager.getOpenOffers().stream().map(openOffer -> {
        Address address = walletService.getOrCreateAddressEntry(openOffer.getId(), AddressEntry.Context.RESERVED_FOR_TRADE).getAddress();
        return walletService.getBalanceForAddress(address);
    }).mapToLong(Coin::getValue).sum());
    reservedBalance.set(formatter.formatCoinWithCode(sum));
}
Also used : Clock(io.bitsquare.common.Clock) OpenOffer(io.bitsquare.trade.offer.OpenOffer) PriceFeedService(io.bitsquare.btc.pricefeed.PriceFeedService) Popup(io.bitsquare.gui.main.overlays.popups.Popup) Transaction(org.bitcoinj.core.Transaction) MarketPrice(io.bitsquare.btc.pricefeed.MarketPrice) Coin(org.bitcoinj.core.Coin) Inject(com.google.inject.Inject) ViewModel(io.bitsquare.gui.common.model.ViewModel) LoggerFactory(org.slf4j.LoggerFactory) TradeCurrency(io.bitsquare.locale.TradeCurrency) Security(java.security.Security) TimeoutException(java.util.concurrent.TimeoutException) DisputeManager(io.bitsquare.arbitration.DisputeManager) BalanceWithConfirmationTextField(io.bitsquare.gui.components.BalanceWithConfirmationTextField) Trade(io.bitsquare.trade.Trade) GUIUtil(io.bitsquare.gui.util.GUIUtil) DevFlags(io.bitsquare.app.DevFlags) PaymentAccount(io.bitsquare.payment.PaymentAccount) NotificationCenter(io.bitsquare.gui.main.overlays.notifications.NotificationCenter) ListChangeListener(javafx.collections.ListChangeListener) Navigation(io.bitsquare.gui.Navigation) TradeWalletService(io.bitsquare.btc.TradeWalletService) BlockStoreException(org.bitcoinj.store.BlockStoreException) MonadicBinding(org.fxmisc.easybind.monadic.MonadicBinding) AddressEntry(io.bitsquare.btc.AddressEntry) WalletPasswordWindow(io.bitsquare.gui.main.overlays.windows.WalletPasswordWindow) FilterManager(io.bitsquare.filter.FilterManager) Subscription(org.fxmisc.easybind.Subscription) Collectors(java.util.stream.Collectors) PrivateNotificationManager(io.bitsquare.alert.PrivateNotificationManager) ConnectionListener(io.bitsquare.p2p.network.ConnectionListener) Preferences(io.bitsquare.user.Preferences) CryptoCurrencyAccount(io.bitsquare.payment.CryptoCurrencyAccount) Dispute(io.bitsquare.arbitration.Dispute) BalanceTextField(io.bitsquare.gui.components.BalanceTextField) Address(org.bitcoinj.core.Address) Ping(io.bitsquare.p2p.peers.keepalive.messages.Ping) ObservableList(javafx.collections.ObservableList) CurrencyUtil(io.bitsquare.locale.CurrencyUtil) io.bitsquare.common.crypto(io.bitsquare.common.crypto) PrivateNotification(io.bitsquare.alert.PrivateNotification) Version(io.bitsquare.app.Version) P2PServiceListener(io.bitsquare.p2p.P2PServiceListener) java.util(java.util) P2PService(io.bitsquare.p2p.P2PService) SetChangeListener(javafx.collections.SetChangeListener) FXCollections(javafx.collections.FXCollections) BitsquareApp(io.bitsquare.app.BitsquareApp) AddBitcoinNodesWindow(io.bitsquare.gui.main.overlays.windows.AddBitcoinNodesWindow) Connection(io.bitsquare.p2p.network.Connection) Timer(io.bitsquare.common.Timer) BalanceListener(io.bitsquare.btc.listeners.BalanceListener) OKPayAccount(io.bitsquare.payment.OKPayAccount) TradeManager(io.bitsquare.trade.TradeManager) User(io.bitsquare.user.User) WalletService(io.bitsquare.btc.WalletService) TacWindow(io.bitsquare.gui.main.overlays.windows.TacWindow) Alert(io.bitsquare.alert.Alert) DisplayAlertMessageWindow(io.bitsquare.gui.main.overlays.windows.DisplayAlertMessageWindow) Nullable(javax.annotation.Nullable) Log(io.bitsquare.app.Log) BSFormatter(io.bitsquare.gui.util.BSFormatter) javafx.beans.property(javafx.beans.property) Logger(org.slf4j.Logger) UserThread(io.bitsquare.common.UserThread) TxIdTextField(io.bitsquare.gui.components.TxIdTextField) Wallet(org.bitcoinj.core.Wallet) TimeUnit(java.util.concurrent.TimeUnit) EasyBind(org.fxmisc.easybind.EasyBind) OpenOfferManager(io.bitsquare.trade.offer.OpenOfferManager) ArbitratorManager(io.bitsquare.arbitration.ArbitratorManager) CloseConnectionReason(io.bitsquare.p2p.network.CloseConnectionReason) ChangeListener(javafx.beans.value.ChangeListener) AlertManager(io.bitsquare.alert.AlertManager) Coin(org.bitcoinj.core.Coin) Address(org.bitcoinj.core.Address)

Example 25 with Coin

use of org.bitcoinj.core.Coin in project bitsquare by bitsquare.

the class MainViewModel method onAllServicesInitialized.

private void onAllServicesInitialized() {
    Log.traceCall();
    clock.start();
    // disputeManager
    disputeManager.onAllServicesInitialized();
    disputeManager.getDisputesAsObservableList().addListener((ListChangeListener<Dispute>) change -> {
        change.next();
        onDisputesChangeListener(change.getAddedSubList(), change.getRemoved());
    });
    onDisputesChangeListener(disputeManager.getDisputesAsObservableList(), null);
    // tradeManager
    tradeManager.onAllServicesInitialized();
    tradeManager.getTrades().addListener((ListChangeListener<Trade>) c -> updateBalance());
    tradeManager.getTrades().addListener((ListChangeListener<Trade>) change -> onTradesChanged());
    onTradesChanged();
    // We handle the trade period here as we display a global popup if we reached dispute time
    tradesAndUIReady = EasyBind.combine(isSplashScreenRemoved, tradeManager.pendingTradesInitializedProperty(), (a, b) -> a && b);
    tradesAndUIReady.subscribe((observable, oldValue, newValue) -> {
        if (newValue)
            applyTradePeriodState();
    });
    // walletService
    walletService.addBalanceListener(new BalanceListener() {

        @Override
        public void onBalanceChanged(Coin balance, Transaction tx) {
            updateBalance();
        }
    });
    openOfferManager.getOpenOffers().addListener((ListChangeListener<OpenOffer>) c -> updateBalance());
    tradeManager.getTrades().addListener((ListChangeListener<Trade>) c -> updateBalance());
    openOfferManager.onAllServicesInitialized();
    arbitratorManager.onAllServicesInitialized();
    alertManager.alertMessageProperty().addListener((observable, oldValue, newValue) -> displayAlertIfPresent(newValue));
    privateNotificationManager.privateNotificationProperty().addListener((observable, oldValue, newValue) -> displayPrivateNotification(newValue));
    displayAlertIfPresent(alertManager.alertMessageProperty().get());
    p2PService.onAllServicesInitialized();
    setupBtcNumPeersWatcher();
    setupP2PNumPeersWatcher();
    updateBalance();
    if (DevFlags.DEV_MODE) {
        preferences.setShowOwnOffersInOfferBook(true);
        if (user.getPaymentAccounts().isEmpty())
            setupDevDummyPaymentAccounts();
    }
    setupMarketPriceFeed();
    swapPendingOfferFundingEntries();
    fillPriceFeedComboBoxItems();
    showAppScreen.set(true);
    // We want to test if the client is compiled with the correct crypto provider (BountyCastle) 
    // and if the unlimited Strength for cryptographic keys is set.
    // If users compile themselves they might miss that step and then would get an exception in the trade.
    // To avoid that we add here at startup a sample encryption and signing to see if it don't causes an exception.
    // See: https://github.com/bitsquare/bitsquare/blob/master/doc/build.md#7-enable-unlimited-strength-for-cryptographic-keys
    Thread checkCryptoThread = new Thread() {

        @Override
        public void run() {
            try {
                Thread.currentThread().setName("checkCryptoThread");
                log.trace("Run crypto test");
                // just use any simple dummy msg
                io.bitsquare.p2p.peers.keepalive.messages.Ping payload = new Ping(1, 1);
                SealedAndSigned sealedAndSigned = Encryption.encryptHybridWithSignature(payload, keyRing.getSignatureKeyPair(), keyRing.getPubKeyRing().getEncryptionPubKey());
                DecryptedDataTuple tuple = Encryption.decryptHybridWithSignature(sealedAndSigned, keyRing.getEncryptionKeyPair().getPrivate());
                if (tuple.payload instanceof Ping && ((Ping) tuple.payload).nonce == payload.nonce && ((Ping) tuple.payload).lastRoundTripTime == payload.lastRoundTripTime)
                    log.debug("Crypto test succeeded");
                else
                    throw new CryptoException("Payload not correct after decryption");
            } catch (CryptoException e) {
                e.printStackTrace();
                String msg = "Seems that you use a self compiled binary and have not following the build " + "instructions in https://github.com/bitsquare/bitsquare/blob/master/doc/build.md#7-enable-unlimited-strength-for-cryptographic-keys.\n\n" + "If that is not the case and you use the official Bitsquare binary, " + "please file a bug report to the Github page.\n" + "Error=" + e.getMessage();
                log.error(msg);
                UserThread.execute(() -> new Popup<>().warning(msg).actionButtonText("Shut down").onAction(BitsquareApp.shutDownHandler::run).closeButtonText("Report bug at Github issues").onClose(() -> GUIUtil.openWebPage("https://github.com/bitsquare/bitsquare/issues")).show());
            }
        }
    };
    checkCryptoThread.start();
    if (Security.getProvider("BC") == null) {
        new Popup<>().warning("There is a problem with the crypto libraries. BountyCastle is not available.").actionButtonText("Shut down").onAction(BitsquareApp.shutDownHandler::run).closeButtonText("Report bug at Github issues").onClose(() -> GUIUtil.openWebPage("https://github.com/bitsquare/bitsquare/issues")).show();
    }
    String remindPasswordAndBackupKey = "remindPasswordAndBackup";
    user.getPaymentAccountsAsObservable().addListener((SetChangeListener<PaymentAccount>) change -> {
        if (!walletService.getWallet().isEncrypted() && preferences.showAgain(remindPasswordAndBackupKey) && change.wasAdded()) {
            new Popup<>().headLine("Important security recommendation").information("We would like to remind you to consider using password protection for your wallet if you have not already enabled that.\n\n" + "It is also highly recommended to write down the wallet seed words. Those seed words are like a master password for recovering your Bitcoin wallet.\n" + "At the \"Wallet Seed\" section you find more information.\n\n" + "Additionally you can backup the complete application data folder at the \"Backup\" section.\n" + "Please note, that this backup is not encrypted!").dontShowAgainId(remindPasswordAndBackupKey, preferences).show();
        }
    });
    checkIfOpenOffersMatchTradeProtocolVersion();
}
Also used : Clock(io.bitsquare.common.Clock) OpenOffer(io.bitsquare.trade.offer.OpenOffer) PriceFeedService(io.bitsquare.btc.pricefeed.PriceFeedService) Popup(io.bitsquare.gui.main.overlays.popups.Popup) Transaction(org.bitcoinj.core.Transaction) MarketPrice(io.bitsquare.btc.pricefeed.MarketPrice) Coin(org.bitcoinj.core.Coin) Inject(com.google.inject.Inject) ViewModel(io.bitsquare.gui.common.model.ViewModel) LoggerFactory(org.slf4j.LoggerFactory) TradeCurrency(io.bitsquare.locale.TradeCurrency) Security(java.security.Security) TimeoutException(java.util.concurrent.TimeoutException) DisputeManager(io.bitsquare.arbitration.DisputeManager) BalanceWithConfirmationTextField(io.bitsquare.gui.components.BalanceWithConfirmationTextField) Trade(io.bitsquare.trade.Trade) GUIUtil(io.bitsquare.gui.util.GUIUtil) DevFlags(io.bitsquare.app.DevFlags) PaymentAccount(io.bitsquare.payment.PaymentAccount) NotificationCenter(io.bitsquare.gui.main.overlays.notifications.NotificationCenter) ListChangeListener(javafx.collections.ListChangeListener) Navigation(io.bitsquare.gui.Navigation) TradeWalletService(io.bitsquare.btc.TradeWalletService) BlockStoreException(org.bitcoinj.store.BlockStoreException) MonadicBinding(org.fxmisc.easybind.monadic.MonadicBinding) AddressEntry(io.bitsquare.btc.AddressEntry) WalletPasswordWindow(io.bitsquare.gui.main.overlays.windows.WalletPasswordWindow) FilterManager(io.bitsquare.filter.FilterManager) Subscription(org.fxmisc.easybind.Subscription) Collectors(java.util.stream.Collectors) PrivateNotificationManager(io.bitsquare.alert.PrivateNotificationManager) ConnectionListener(io.bitsquare.p2p.network.ConnectionListener) Preferences(io.bitsquare.user.Preferences) CryptoCurrencyAccount(io.bitsquare.payment.CryptoCurrencyAccount) Dispute(io.bitsquare.arbitration.Dispute) BalanceTextField(io.bitsquare.gui.components.BalanceTextField) Address(org.bitcoinj.core.Address) Ping(io.bitsquare.p2p.peers.keepalive.messages.Ping) ObservableList(javafx.collections.ObservableList) CurrencyUtil(io.bitsquare.locale.CurrencyUtil) io.bitsquare.common.crypto(io.bitsquare.common.crypto) PrivateNotification(io.bitsquare.alert.PrivateNotification) Version(io.bitsquare.app.Version) P2PServiceListener(io.bitsquare.p2p.P2PServiceListener) java.util(java.util) P2PService(io.bitsquare.p2p.P2PService) SetChangeListener(javafx.collections.SetChangeListener) FXCollections(javafx.collections.FXCollections) BitsquareApp(io.bitsquare.app.BitsquareApp) AddBitcoinNodesWindow(io.bitsquare.gui.main.overlays.windows.AddBitcoinNodesWindow) Connection(io.bitsquare.p2p.network.Connection) Timer(io.bitsquare.common.Timer) BalanceListener(io.bitsquare.btc.listeners.BalanceListener) OKPayAccount(io.bitsquare.payment.OKPayAccount) TradeManager(io.bitsquare.trade.TradeManager) User(io.bitsquare.user.User) WalletService(io.bitsquare.btc.WalletService) TacWindow(io.bitsquare.gui.main.overlays.windows.TacWindow) Alert(io.bitsquare.alert.Alert) DisplayAlertMessageWindow(io.bitsquare.gui.main.overlays.windows.DisplayAlertMessageWindow) Nullable(javax.annotation.Nullable) Log(io.bitsquare.app.Log) BSFormatter(io.bitsquare.gui.util.BSFormatter) javafx.beans.property(javafx.beans.property) Logger(org.slf4j.Logger) UserThread(io.bitsquare.common.UserThread) TxIdTextField(io.bitsquare.gui.components.TxIdTextField) Wallet(org.bitcoinj.core.Wallet) TimeUnit(java.util.concurrent.TimeUnit) EasyBind(org.fxmisc.easybind.EasyBind) OpenOfferManager(io.bitsquare.trade.offer.OpenOfferManager) ArbitratorManager(io.bitsquare.arbitration.ArbitratorManager) CloseConnectionReason(io.bitsquare.p2p.network.CloseConnectionReason) ChangeListener(javafx.beans.value.ChangeListener) AlertManager(io.bitsquare.alert.AlertManager) BalanceListener(io.bitsquare.btc.listeners.BalanceListener) PaymentAccount(io.bitsquare.payment.PaymentAccount) OpenOffer(io.bitsquare.trade.offer.OpenOffer) UserThread(io.bitsquare.common.UserThread) BitsquareApp(io.bitsquare.app.BitsquareApp) Trade(io.bitsquare.trade.Trade) Coin(org.bitcoinj.core.Coin) Transaction(org.bitcoinj.core.Transaction) Ping(io.bitsquare.p2p.peers.keepalive.messages.Ping) Popup(io.bitsquare.gui.main.overlays.popups.Popup) Dispute(io.bitsquare.arbitration.Dispute) Ping(io.bitsquare.p2p.peers.keepalive.messages.Ping)

Aggregations

Coin (org.bitcoinj.core.Coin)35 AddressEntry (io.bitsquare.btc.AddressEntry)13 WalletService (io.bitsquare.btc.WalletService)13 Transaction (org.bitcoinj.core.Transaction)11 Popup (io.bitsquare.gui.main.overlays.popups.Popup)9 BalanceListener (io.bitsquare.btc.listeners.BalanceListener)8 Offer (io.bitsquare.trade.offer.Offer)7 Address (org.bitcoinj.core.Address)6 BSFormatter (io.bitsquare.gui.util.BSFormatter)5 Trade (io.bitsquare.trade.Trade)5 Inject (com.google.inject.Inject)4 Log (io.bitsquare.app.Log)4 UserThread (io.bitsquare.common.UserThread)4 DevFlags (io.bitsquare.app.DevFlags)3 Dispute (io.bitsquare.arbitration.Dispute)3 DisputeManager (io.bitsquare.arbitration.DisputeManager)3 TradeWalletService (io.bitsquare.btc.TradeWalletService)3 MarketPrice (io.bitsquare.btc.pricefeed.MarketPrice)3 PriceFeedService (io.bitsquare.btc.pricefeed.PriceFeedService)3 CurrencyUtil (io.bitsquare.locale.CurrencyUtil)3