Search in sources :

Example 51 with Address

use of org.bitcoinj.core.Address in project bisq-desktop by bisq-network.

the class MainViewModel method updateReservedBalance.

private void updateReservedBalance() {
    Coin sum = Coin.valueOf(openOfferManager.getObservableList().stream().map(openOffer -> {
        final Optional<AddressEntry> addressEntryOptional = btcWalletService.getAddressEntry(openOffer.getId(), AddressEntry.Context.RESERVED_FOR_TRADE);
        if (addressEntryOptional.isPresent()) {
            Address address = addressEntryOptional.get().getAddress();
            return btcWalletService.getBalanceForAddress(address);
        } else {
            return null;
        }
    }).filter(e -> e != null).mapToLong(Coin::getValue).sum());
    reservedBalance.set(formatter.formatCoinWithCode(sum));
}
Also used : OpenOffer(bisq.core.offer.OpenOffer) User(bisq.core.user.User) ChainFileLockedException(org.bitcoinj.store.ChainFileLockedException) ListChangeListener(javafx.collections.ListChangeListener) BootstrapListener(bisq.network.p2p.BootstrapListener) SimpleIntegerProperty(javafx.beans.property.SimpleIntegerProperty) Map(java.util.Map) BlockStoreException(org.bitcoinj.store.BlockStoreException) MonadicBinding(org.fxmisc.easybind.monadic.MonadicBinding) P2PServiceListener(bisq.network.p2p.P2PServiceListener) ClosedTradableManager(bisq.core.trade.closed.ClosedTradableManager) FilterManager(bisq.core.filter.FilterManager) Set(java.util.Set) PaymentMethod(bisq.core.payment.payload.PaymentMethod) BooleanProperty(javafx.beans.property.BooleanProperty) Slf4j(lombok.extern.slf4j.Slf4j) TxIdTextField(bisq.desktop.components.TxIdTextField) Stream(java.util.stream.Stream) TorNetworkSettingsWindow(bisq.desktop.main.overlays.windows.TorNetworkSettingsWindow) AddressEntry(bisq.core.btc.AddressEntry) WalletsSetup(bisq.core.btc.wallet.WalletsSetup) TradeManager(bisq.core.trade.TradeManager) UserThread(bisq.common.UserThread) SimpleDoubleProperty(javafx.beans.property.SimpleDoubleProperty) FeeService(bisq.core.provider.fee.FeeService) ObservableList(javafx.collections.ObservableList) StringProperty(javafx.beans.property.StringProperty) CryptoException(bisq.common.crypto.CryptoException) AlertManager(bisq.core.alert.AlertManager) SetupUtils(bisq.core.app.SetupUtils) FXCollections(javafx.collections.FXCollections) Dispute(bisq.core.arbitration.Dispute) NotificationCenter(bisq.desktop.main.overlays.notifications.NotificationCenter) IntegerProperty(javafx.beans.property.IntegerProperty) ConnectionListener(bisq.network.p2p.network.ConnectionListener) Nullable(javax.annotation.Nullable) EncryptionService(bisq.network.crypto.EncryptionService) DontShowAgainLookup(bisq.core.user.DontShowAgainLookup) GlobalSettings(bisq.core.locale.GlobalSettings) IOException(java.io.IOException) BisqEnvironment(bisq.core.app.BisqEnvironment) OpenOfferManager(bisq.core.offer.OpenOfferManager) PriceFeedService(bisq.core.provider.price.PriceFeedService) SimpleObjectProperty(javafx.beans.property.SimpleObjectProperty) CloseConnectionReason(bisq.network.p2p.network.CloseConnectionReason) KeyRing(bisq.common.crypto.KeyRing) InetAddresses(com.google.common.net.InetAddresses) SealedAndSigned(bisq.common.crypto.SealedAndSigned) Transaction(org.bitcoinj.core.Transaction) DisplayAlertMessageWindow(bisq.desktop.main.overlays.windows.DisplayAlertMessageWindow) Coin(org.bitcoinj.core.Coin) Date(java.util.Date) DaoManager(bisq.core.dao.DaoManager) Clock(bisq.common.Clock) Inject(com.google.inject.Inject) PerfectMoneyAccount(bisq.core.payment.PerfectMoneyAccount) Security(java.security.Security) TimeoutException(java.util.concurrent.TimeoutException) Random(java.util.Random) DisputeManager(bisq.core.arbitration.DisputeManager) BSFormatter(bisq.desktop.util.BSFormatter) Alert(bisq.core.alert.Alert) Res(bisq.core.locale.Res) Popup(bisq.desktop.main.overlays.popups.Popup) WalletPasswordWindow(bisq.desktop.main.overlays.windows.WalletPasswordWindow) P2PService(bisq.network.p2p.P2PService) ArbitratorManager(bisq.core.arbitration.ArbitratorManager) Subscription(org.fxmisc.easybind.Subscription) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) AccountAgeWitnessService(bisq.core.payment.AccountAgeWitnessService) PaymentAccount(bisq.core.payment.PaymentAccount) List(java.util.List) TacWindow(bisq.desktop.main.overlays.windows.TacWindow) DevEnv(bisq.common.app.DevEnv) AppOptionKeys(bisq.core.app.AppOptionKeys) Preferences(bisq.core.user.Preferences) Optional(java.util.Optional) Address(org.bitcoinj.core.Address) BalanceWithConfirmationTextField(bisq.desktop.components.BalanceWithConfirmationTextField) Ping(bisq.network.p2p.peers.keepalive.messages.Ping) MarketPrice(bisq.core.provider.price.MarketPrice) DisplayUpdateDownloadWindow(bisq.desktop.main.overlays.windows.downloadupdate.DisplayUpdateDownloadWindow) GUIUtil(bisq.desktop.util.GUIUtil) BtcWalletService(bisq.core.btc.wallet.BtcWalletService) Socket(java.net.Socket) TradeCurrency(bisq.core.locale.TradeCurrency) SimpleStringProperty(javafx.beans.property.SimpleStringProperty) SetChangeListener(javafx.collections.SetChangeListener) Timer(bisq.common.Timer) DoubleProperty(javafx.beans.property.DoubleProperty) HashMap(java.util.HashMap) TradeStatisticsManager(bisq.core.trade.statistics.TradeStatisticsManager) BalanceListener(bisq.core.btc.listeners.BalanceListener) WalletsManager(bisq.core.btc.wallet.WalletsManager) CurrencyUtil(bisq.core.locale.CurrencyUtil) Connection(bisq.network.p2p.network.Connection) PrivateNotificationManager(bisq.core.alert.PrivateNotificationManager) Version(bisq.common.app.Version) ObjectProperty(javafx.beans.property.ObjectProperty) CryptoCurrencyAccount(bisq.core.payment.CryptoCurrencyAccount) PrivateNotificationPayload(bisq.core.alert.PrivateNotificationPayload) Trade(bisq.core.trade.Trade) FailedTradesManager(bisq.core.trade.failed.FailedTradesManager) ViewModel(bisq.desktop.common.model.ViewModel) TimeUnit(java.util.concurrent.TimeUnit) SimpleBooleanProperty(javafx.beans.property.SimpleBooleanProperty) EasyBind(org.fxmisc.easybind.EasyBind) DecryptedDataTuple(bisq.network.crypto.DecryptedDataTuple) ChangeListener(javafx.beans.value.ChangeListener) Coin(org.bitcoinj.core.Coin) InetSocketAddress(java.net.InetSocketAddress) Address(org.bitcoinj.core.Address) AddressEntry(bisq.core.btc.AddressEntry)

Example 52 with Address

use of org.bitcoinj.core.Address in project bisq-core by bisq-network.

the class CreateMakerFeeTx method run.

@Override
protected void run() {
    Offer offer = model.getOffer();
    try {
        runInterceptHook();
        String id = offer.getId();
        BtcWalletService walletService = model.getWalletService();
        NodeAddress selectedArbitratorNodeAddress = ArbitratorSelectionRule.select(model.getUser().getAcceptedArbitratorAddresses(), model.getOffer());
        log.debug("selectedArbitratorAddress " + selectedArbitratorNodeAddress);
        Arbitrator selectedArbitrator = model.getUser().getAcceptedArbitratorByAddress(selectedArbitratorNodeAddress);
        checkNotNull(selectedArbitrator, "selectedArbitrator must not be null at CreateOfferFeeTx");
        Address fundingAddress = walletService.getOrCreateAddressEntry(id, AddressEntry.Context.OFFER_FUNDING).getAddress();
        Address reservedForTradeAddress = walletService.getOrCreateAddressEntry(id, AddressEntry.Context.RESERVED_FOR_TRADE).getAddress();
        Address changeAddress = walletService.getOrCreateAddressEntry(AddressEntry.Context.AVAILABLE).getAddress();
        final TradeWalletService tradeWalletService = model.getTradeWalletService();
        if (offer.isCurrencyForMakerFeeBtc()) {
            tradeFeeTx = tradeWalletService.createBtcTradingFeeTx(fundingAddress, reservedForTradeAddress, changeAddress, model.getReservedFundsForOffer(), model.isUseSavingsWallet(), offer.getMakerFee(), offer.getTxFee(), selectedArbitrator.getBtcAddress(), new FutureCallback<Transaction>() {

                @Override
                public void onSuccess(Transaction transaction) {
                    // we delay one render frame to be sure we don't get called before the method call has
                    // returned (tradeFeeTx would be null in that case)
                    UserThread.execute(() -> {
                        if (!completed) {
                            offer.setOfferFeePaymentTxId(transaction.getHashAsString());
                            model.setTransaction(transaction);
                            walletService.swapTradeEntryToAvailableEntry(id, AddressEntry.Context.OFFER_FUNDING);
                            model.getOffer().setState(Offer.State.OFFER_FEE_PAID);
                            complete();
                        } else {
                            log.warn("We got the onSuccess callback called after the timeout has been triggered a complete().");
                        }
                    });
                }

                @Override
                public void onFailure(@NotNull Throwable t) {
                    if (!completed) {
                        failed(t);
                    } else {
                        log.warn("We got the onFailure callback called after the timeout has been triggered a complete().");
                    }
                }
            });
        } else {
            final BsqWalletService bsqWalletService = model.getBsqWalletService();
            Transaction preparedBurnFeeTx = model.getBsqWalletService().getPreparedBurnFeeTx(offer.getMakerFee());
            Transaction txWithBsqFee = tradeWalletService.completeBsqTradingFeeTx(preparedBurnFeeTx, fundingAddress, reservedForTradeAddress, changeAddress, model.getReservedFundsForOffer(), model.isUseSavingsWallet(), offer.getTxFee());
            Transaction signedTx = model.getBsqWalletService().signTx(txWithBsqFee);
            WalletService.checkAllScriptSignaturesForTx(signedTx);
            bsqWalletService.commitTx(signedTx);
            // We need to create another instance, otherwise the tx would trigger an invalid state exception
            // if it gets committed 2 times
            tradeWalletService.commitTx(tradeWalletService.getClonedTransaction(signedTx));
            bsqWalletService.broadcastTx(signedTx, new FutureCallback<Transaction>() {

                @Override
                public void onSuccess(@Nullable Transaction transaction) {
                    if (transaction != null) {
                        offer.setOfferFeePaymentTxId(transaction.getHashAsString());
                        model.setTransaction(transaction);
                        log.debug("onSuccess, offerId={}, OFFER_FUNDING", id);
                        walletService.swapTradeEntryToAvailableEntry(id, AddressEntry.Context.OFFER_FUNDING);
                        log.debug("Successfully sent tx with id " + transaction.getHashAsString());
                        model.getOffer().setState(Offer.State.OFFER_FEE_PAID);
                        complete();
                    }
                }

                @Override
                public void onFailure(@NotNull Throwable t) {
                    log.error(t.toString());
                    t.printStackTrace();
                    offer.setErrorMessage("An error occurred.\n" + "Error message:\n" + t.getMessage());
                    failed(t);
                }
            });
        }
    } catch (Throwable t) {
        offer.setErrorMessage("An error occurred.\n" + "Error message:\n" + t.getMessage());
        failed(t);
    }
}
Also used : NodeAddress(bisq.network.p2p.NodeAddress) Address(org.bitcoinj.core.Address) TradeWalletService(bisq.core.btc.wallet.TradeWalletService) Arbitrator(bisq.core.arbitration.Arbitrator) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) NotNull(org.jetbrains.annotations.NotNull) Transaction(org.bitcoinj.core.Transaction) Offer(bisq.core.offer.Offer) BtcWalletService(bisq.core.btc.wallet.BtcWalletService) BsqWalletService(bisq.core.btc.wallet.BsqWalletService) NodeAddress(bisq.network.p2p.NodeAddress) FutureCallback(com.google.common.util.concurrent.FutureCallback)

Example 53 with Address

use of org.bitcoinj.core.Address in project sentinel-android by Samourai-Wallet.

the class FormatsUtil method isValidBitcoinAddress.

public boolean isValidBitcoinAddress(final String address) {
    boolean ret = false;
    Address addr = null;
    if (address.toLowerCase().startsWith("bc")) {
        try {
            Pair<Byte, byte[]> pair = Bech32Segwit.decode(address.substring(0, 2), address);
            if (pair.getLeft() == null || pair.getRight() == null) {
                ;
            } else {
                ret = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        try {
            addr = new Address(MainNetParams.get(), address);
            if (addr != null) {
                ret = true;
            }
        } catch (WrongNetworkException wne) {
            ret = false;
        } catch (AddressFormatException afe) {
            ret = false;
        }
    }
    return ret;
}
Also used : AddressFormatException(org.bitcoinj.core.AddressFormatException) Address(org.bitcoinj.core.Address) AddressFormatException(org.bitcoinj.core.AddressFormatException) BitcoinURIParseException(org.bitcoinj.uri.BitcoinURIParseException) WrongNetworkException(org.bitcoinj.core.WrongNetworkException) WrongNetworkException(org.bitcoinj.core.WrongNetworkException)

Example 54 with Address

use of org.bitcoinj.core.Address in project catena-java by alinush.

the class SimpleWallet method getLastUtxo.

/**
 * Returns the last UTXO in the Catena chain used to fund and link the next TX
 * that commits the next statement.
 * If there is more than one UTXO, a warning is issued, since that case should never arise.
 */
public TransactionOutput getLastUtxo() {
    List<TransactionOutput> utxos = getUnspents();
    ArrayList<TransactionOutput> chainKeyUtxos = new ArrayList<TransactionOutput>();
    Address addr = getChainAddress();
    for (TransactionOutput o : utxos) {
        if (o.isMineOrWatched(this) && o.getAddressFromP2PKHScript(params).equals(addr)) {
            chainKeyUtxos.add(o);
        } else {
            log.trace("Ineligible UTXO (mine=" + o.isMineOrWatched(this) + ", to=" + o.getAddressFromP2PKHScript(params) + ", chainAddr=" + addr + "): " + o);
        }
    }
    // There should be exactly one Catena UTXO
    if (chainKeyUtxos.size() > 1) {
        log.warn("More than one UTXO spendable by '" + addr + "': " + chainKeyUtxos.size());
    }
    if (chainKeyUtxos.isEmpty()) {
        throw new RuntimeException("No UTXOs spendable by '" + addr + "'");
    }
    // Make sure the UTXO we found is from a Catena TX: does not check sigs,
    // checks the address in the TX's output is the right one, does not check the previous link
    TransactionOutput lastCatenaUtxo = chainKeyUtxos.get(0);
    if (CatenaUtils.maybeCatenaTx(lastCatenaUtxo.getParentTransaction(), addr) == false) {
        throw new RuntimeException("Expected to get an UTXO of a Catena TX.");
    }
    return lastCatenaUtxo;
}
Also used : TransactionOutput(org.bitcoinj.core.TransactionOutput) Address(org.bitcoinj.core.Address) ArrayList(java.util.ArrayList)

Example 55 with Address

use of org.bitcoinj.core.Address in project catena-java by alinush.

the class SimpleWallet method sendCatenaTxOffline.

/**
 * A modified sendCoinsOffline, for Catena TXs purposes.
 *
 * @param request
 * @param commit
 * @return
 * @throws InsufficientMoneyException
 */
public Transaction sendCatenaTxOffline(SendRequest request, boolean isRootOfTrustTxn, boolean commit) throws InsufficientMoneyException {
    // First we check a properly-structured Catena TX was given to us
    Address addr = request.tx.getOutput(0).getAddressFromP2PKHScript(request.tx.getParams());
    TransactionOutput utxo = request.tx.getInput(0).getConnectedOutput();
    // We don't have a signature yet (completeCatenaTx() call below will sign)
    if (!CatenaUtils.isCatenaTxNoSig(request.tx, addr, utxo, isRootOfTrustTxn == false)) {
        throw new RuntimeException("You must provide a Catena TX as input to this method, not: " + request.tx);
    }
    lock.lock();
    try {
        // Modified Wallet::completeTx and got rid of unnecessary complexities
        completeCatenaTx(request);
        // much when funding it and computing its tx fee.
        if (!CatenaUtils.isSignedCatenaTx(request.tx, addr, utxo, isRootOfTrustTxn == false)) {
            throw new RuntimeException("bitcoinj meddled with the Catena tx too much: " + request.tx);
        }
        // When generating lies, for testing code, we don't commit the lies because otherwise we can't double-spend.
        if (commit)
            commitTx(request.tx);
        return request.tx;
    } finally {
        lock.unlock();
    }
}
Also used : TransactionOutput(org.bitcoinj.core.TransactionOutput) Address(org.bitcoinj.core.Address)

Aggregations

Address (org.bitcoinj.core.Address)78 Transaction (org.bitcoinj.core.Transaction)32 Coin (org.bitcoinj.core.Coin)28 TransactionOutput (org.bitcoinj.core.TransactionOutput)15 TransactionInput (org.bitcoinj.core.TransactionInput)13 ArrayList (java.util.ArrayList)12 AddressEntry (bisq.core.btc.AddressEntry)11 Wallet (org.bitcoinj.wallet.Wallet)11 BtcWalletService (bisq.core.btc.wallet.BtcWalletService)10 AddressFormatException (org.bitcoinj.core.AddressFormatException)10 TransactionConfidence (org.bitcoinj.core.TransactionConfidence)10 IOException (java.io.IOException)9 SendRequest (org.bitcoinj.wallet.SendRequest)9 WalletService (io.bitsquare.btc.WalletService)8 List (java.util.List)8 Collectors (java.util.stream.Collectors)8 Nullable (javax.annotation.Nullable)8 TransactionOutPoint (org.bitcoinj.core.TransactionOutPoint)8 Script (org.bitcoinj.script.Script)8 Intent (android.content.Intent)7