org.bitcoinj.core.Coin Java Examples

The following examples show how to use org.bitcoinj.core.Coin. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public void emptyWallet(String toAddress,
                        KeyParameter aesKey,
                        ResultHandler resultHandler,
                        ErrorMessageHandler errorMessageHandler)
        throws InsufficientMoneyException, AddressFormatException {
    SendRequest sendRequest = SendRequest.emptyWallet(Address.fromBase58(params, toAddress));
    sendRequest.fee = Coin.ZERO;
    sendRequest.feePerKb = getTxFeeForWithdrawalPerByte().multiply(1000);
    sendRequest.aesKey = aesKey;
    Wallet.SendResult sendResult = wallet.sendCoins(sendRequest);
    printTx("empty wallet", sendResult.tx);
    Futures.addCallback(sendResult.broadcastComplete, new FutureCallback<Transaction>() {
        @Override
        public void onSuccess(Transaction result) {
            log.info("emptyWallet onSuccess Transaction=" + result);
            resultHandler.handleResult();
        }

        @Override
        public void onFailure(@NotNull Throwable t) {
            log.error("emptyWallet onFailure " + t.toString());
            errorMessageHandler.handleErrorMessage(t.getMessage());
        }
    });
}
 
Example #2
Source File: ProposalsView.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
private void onVote() {
    Coin stake = ParsingUtils.parseToCoin(stakeInputTextField.getText(), bsqFormatter);
    try {
        // We create a dummy tx to get the miningFee for displaying it at the confirmation popup
        Tuple2<Coin, Integer> miningFeeAndTxSize = daoFacade.getBlindVoteMiningFeeAndTxSize(stake);
        Coin miningFee = miningFeeAndTxSize.first;
        int txSize = miningFeeAndTxSize.second;
        Coin blindVoteFee = daoFacade.getBlindVoteFeeForCycle();
        if (!DevEnv.isDevMode()) {
            GUIUtil.showBsqFeeInfoPopup(blindVoteFee, miningFee, txSize, bsqFormatter, btcFormatter,
                    Res.get("dao.blindVote"), () -> publishBlindVote(stake));
        } else {
            publishBlindVote(stake);
        }
    } catch (InsufficientMoneyException | WalletException | TransactionVerificationException exception) {
        new Popup().warning(exception.toString()).show();
    }
}
 
Example #3
Source File: OfferDataModel.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void updateBalance() {
    Coin tradeWalletBalance = btcWalletService.getBalanceForAddress(addressEntry.getAddress());
    if (useSavingsWallet) {
        Coin savingWalletBalance = btcWalletService.getSavingWalletBalance();
        totalAvailableBalance = savingWalletBalance.add(tradeWalletBalance);
        if (totalToPayAsCoin.get() != null) {
            if (totalAvailableBalance.compareTo(totalToPayAsCoin.get()) > 0)
                balance.set(totalToPayAsCoin.get());
            else
                balance.set(totalAvailableBalance);
        }
    } else {
        balance.set(tradeWalletBalance);
    }
    if (totalToPayAsCoin.get() != null) {
        Coin missing = totalToPayAsCoin.get().subtract(balance.get());
        if (missing.isNegative())
            missing = Coin.ZERO;
        missingCoin.set(missing);
    }

    isBtcWalletFunded.set(isBalanceSufficient(balance.get()));
    if (totalToPayAsCoin.get() != null && isBtcWalletFunded.get() && !showWalletFundedNotification.get()) {
        showWalletFundedNotification.set(true);
    }
}
 
Example #4
Source File: ProposalsView.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
private void publishBlindVote(Coin stake) {
    //TODO Starting voteButtonBusyAnimation here does not make sense if we stop it immediately below.
    // Check if voteButtonBusyAnimation should stay running until we hear back from publishing and only disable
    // button so that the user cannot click twice.
    voteButtonBusyAnimation.play();
    voteButtonInfoLabel.setText(Res.get("dao.blindVote.startPublishing"));
    daoFacade.publishBlindVote(stake,
            () -> {
                if (!DevEnv.isDevMode())
                    new Popup().feedback(Res.get("dao.blindVote.success")).show();
            }, exception -> {
                voteButtonBusyAnimation.stop();
                voteButtonInfoLabel.setText("");
                updateViews();
                new Popup().warning(exception.toString()).show();
            });

    // We reset UI without waiting for callback as callback might be slow and then the user could click
    // multiple times.
    voteButtonBusyAnimation.stop();
    voteButtonInfoLabel.setText("");
    updateViews();
}
 
Example #5
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void spendToSameWallet() throws Exception {
    // Test that a spend to the same wallet is dealt with correctly.
    // It should appear in the wallet and confirm.
    // This is a bit of a silly thing to do in the real world as all it does is burn a fee but it is perfectly valid.
    Coin coin1 = COIN;
    Coin coinHalf = valueOf(0, 50);
    // Start by giving us 1 coin.
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, coin1);
    // Send half to ourselves. We should then have a balance available to spend of zero.
    assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
    assertEquals(1, wallet.getTransactions(true).size());
    Transaction outbound1 = wallet.createSend(myAddress, coinHalf);
    wallet.commitTx(outbound1);
    // We should have a zero available balance before the next block.
    assertEquals(ZERO, wallet.getBalance());
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, outbound1);
    // We should have a balance of 1 BTC after the block is received.
    assertEquals(coin1, wallet.getBalance());
}
 
Example #6
Source File: ProposalDisplay.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public void applyBallotAndVoteWeight(@Nullable Ballot ballot, long merit, long stake, boolean ballotIncluded) {
    boolean ballotIsNotNull = ballot != null;
    boolean hasVoted = stake > 0;
    if (hasVoted) {
        String myVote = Res.get("dao.proposal.display.myVote.ignored");
        Vote vote = ballotIsNotNull ? ballot.getVote() : null;
        if (vote != null) {
            myVote = vote.isAccepted() ? Res.get("dao.proposal.display.myVote.accepted") :
                    Res.get("dao.proposal.display.myVote.rejected");
        }

        String voteIncluded = ballotIncluded ? "" : " - " + Res.get("dao.proposal.display.myVote.unCounted");
        String meritString = bsqFormatter.formatCoinWithCode(Coin.valueOf(merit));
        String stakeString = bsqFormatter.formatCoinWithCode(Coin.valueOf(stake));
        String weight = bsqFormatter.formatCoinWithCode(Coin.valueOf(merit + stake));
        String myVoteSummary = Res.get("dao.proposal.myVote.summary", myVote,
                weight, meritString, stakeString, voteIncluded);
        myVoteTextField.setText(myVoteSummary);

        GridPane.setRowSpan(myVoteTitledGroup, votingBoxRowSpan - 1);
    }

    boolean show = ballotIsNotNull && hasVoted;
    setMyVoteBoxVisibility(show);
}
 
Example #7
Source File: SellerTrade.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
SellerTrade(Offer offer,
            Coin txFee,
            Coin takeOfferFee,
            boolean isCurrencyForTakerFeeBtc,
            @Nullable NodeAddress arbitratorNodeAddress,
            @Nullable NodeAddress mediatorNodeAddress,
            @Nullable NodeAddress refundAgentNodeAddress,
            Storage<? extends TradableList> storage,
            BtcWalletService btcWalletService) {
    super(offer,
            txFee,
            takeOfferFee,
            isCurrencyForTakerFeeBtc,
            arbitratorNodeAddress,
            mediatorNodeAddress,
            refundAgentNodeAddress,
            storage,
            btcWalletService);
}
 
Example #8
Source File: BtcWalletService.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
public String sendFundsForMultipleAddresses(Set<String> fromAddresses,
                                            String toAddress,
                                            Coin receiverAmount,
                                            Coin fee,
                                            @Nullable String changeAddress,
                                            @Nullable KeyParameter aesKey,
                                            FutureCallback<Transaction> callback) throws AddressFormatException,
        AddressEntryException, InsufficientMoneyException {

    SendRequest request = getSendRequestForMultipleAddresses(fromAddresses, toAddress, receiverAmount, fee, changeAddress, aesKey);
    Wallet.SendResult sendResult = wallet.sendCoins(request);
    Futures.addCallback(sendResult.broadcastComplete, callback);

    printTx("sendFunds", sendResult.tx);
    return sendResult.tx.getHashAsString();
}
 
Example #9
Source File: MyReputationListItem.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
MyReputationListItem(MyBondedReputation myBondedReputation,
                     BsqFormatter bsqFormatter) {
    this.myBondedReputation = myBondedReputation;

    MyReputation myReputation = myBondedReputation.getBondedAsset();
    hash = Utilities.bytesAsHexString(myReputation.getHash());
    salt = Utilities.bytesAsHexString(myReputation.getSalt());
    txId = myBondedReputation.getLockupTxId();
    amount = bsqFormatter.formatCoin(Coin.valueOf(myBondedReputation.getAmount()));
    lockupDate = new Date(myBondedReputation.getLockupDate());
    lockupDateString = DisplayUtils.formatDateTime(lockupDate);
    lockTime = Integer.toString(myBondedReputation.getLockTime());
    lockupTxId = myBondedReputation.getLockupTxId();
    bondState = myBondedReputation.getBondState();
    bondStateString = Res.get("dao.bond.bondState." + myBondedReputation.getBondState().name());
    showButton = myBondedReputation.getBondState() == BondState.LOCKUP_TX_CONFIRMED;
    buttonText = Res.get("dao.bond.table.button.unlock");
}
 
Example #10
Source File: SendRequest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * <p>Creates a new SendRequest to the given address for the given value.</p>
 * <p>
 * <p>Be very careful when value is smaller than {@link Transaction#MIN_NONDUST_OUTPUT} as the transaction will
 * likely be rejected by the network in this case.</p>
 */
public static SendRequest to(Address destination, Coin value) {
    SendRequest req = new SendRequest();
    final NetworkParameters parameters = destination.getParameters();
    checkNotNull(parameters, "Address is for an unknown network");
    req.tx = new Transaction(parameters);
    req.tx.addOutput(value, destination);
    return req;
}
 
Example #11
Source File: TxOutInfo.java    From consensusj with Apache License 2.0 5 votes vote down vote up
@JsonCreator
public TxOutInfo(@JsonProperty("bestblock")     Sha256Hash  bestblock,
                 @JsonProperty("confirmations") int         confirmations,
                 @JsonProperty("value")         Coin        value,
                 @JsonProperty("scriptPubKey")  Map         scriptPubKey,
                 @JsonProperty("version")       int         version,
                 @JsonProperty("coinbase")      boolean     coinbase) {
    this.bestblock = bestblock;
    this.confirmations = confirmations;
    this.value = value;
    this.scriptPubKey = scriptPubKey;
    this.version = version;
    this.coinbase = coinbase;
}
 
Example #12
Source File: SendRequest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
/**
 * <p>Creates a new SendRequest to the given address for the given value.</p>
 *
 * <p>Be very careful when value is smaller than {@link Transaction#MIN_NONDUST_OUTPUT} as the transaction will
 * likely be rejected by the network in this case.</p>
 */
public static SendRequest to(Address destination, Coin value) {
    SendRequest req = new SendRequest();
    final NetworkParameters parameters = destination.getParameters();
    checkNotNull(parameters, "Address is for an unknown network");
    req.tx = new Transaction(parameters);
    req.tx.addOutput(value, destination);
    return req;
}
 
Example #13
Source File: PendingTradesViewModel.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getTxFee() {
    if (trade != null && trade.getTradeAmount() != null) {
        Coin txFee = dataModel.getTxFee();
        String percentage = GUIUtil.getPercentageOfTradeAmount(txFee, trade.getTradeAmount(),
                Coin.ZERO);
        return btcFormatter.formatCoinWithCode(txFee) + percentage;
    } else {
        return "";
    }
}
 
Example #14
Source File: BtcFormatTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void parse() throws Exception {
    BtcFormat coin = BtcFormat.getCoinInstance(Locale.US);
    assertEquals(Coin.COIN, coin.parseObject("1"));
    assertEquals(Coin.COIN, coin.parseObject("1."));
    assertEquals(Coin.COIN, coin.parseObject("1.0"));
    assertEquals(Coin.COIN, BtcFormat.getCoinInstance(Locale.GERMANY).parseObject("1,0"));
    assertEquals(Coin.COIN, coin.parseObject("01.0000000000"));
    // TODO work with express positive sign
    // assertEquals(Coin.COIN, coin.parseObject("+1.0"));
    assertEquals(Coin.COIN.negate(), coin.parseObject("-1"));
    assertEquals(Coin.COIN.negate(), coin.parseObject("-1.0"));

    assertEquals(Coin.CENT, coin.parseObject(".01"));

    BtcFormat milli = BtcFormat.getMilliInstance(Locale.US);
    assertEquals(Coin.MILLICOIN, milli.parseObject("1"));
    assertEquals(Coin.MILLICOIN, milli.parseObject("1.0"));
    assertEquals(Coin.MILLICOIN, milli.parseObject("01.0000000000"));
    // TODO work with express positive sign
    //assertEquals(Coin.MILLICOIN, milli.parseObject("+1.0"));
    assertEquals(Coin.MILLICOIN.negate(), milli.parseObject("-1"));
    assertEquals(Coin.MILLICOIN.negate(), milli.parseObject("-1.0"));

    BtcFormat micro = BtcFormat.getMicroInstance(Locale.US);
    assertEquals(Coin.MICROCOIN, micro.parseObject("1"));
    assertEquals(Coin.MICROCOIN, micro.parseObject("1.0"));
    assertEquals(Coin.MICROCOIN, micro.parseObject("01.0000000000"));
    // TODO work with express positive sign
    // assertEquals(Coin.MICROCOIN, micro.parseObject("+1.0"));
    assertEquals(Coin.MICROCOIN.negate(), micro.parseObject("-1"));
    assertEquals(Coin.MICROCOIN.negate(), micro.parseObject("-1.0"));
}
 
Example #15
Source File: PaymentChannelServerTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void shouldTruncateTooSmallTimeWindow() {
    final int minTimeWindow = 20000;
    final int timeWindow = minTimeWindow - 1;
    final TwoWayChannelMessage message = createClientVersionMessage(timeWindow);
    final Capture<TwoWayChannelMessage> initiateCapture = new Capture<>();
    connection.sendToClient(capture(initiateCapture));

    replay(connection);
    dut = new PaymentChannelServer(broadcaster, wallet, Coin.CENT, new PaymentChannelServer.DefaultServerChannelProperties() {
        @Override
        public long getMinTimeWindow() {
            return minTimeWindow;
        }
        @Override
        public long getMaxTimeWindow() {
            return 40000;
        }
    }, connection);

    dut.connectionOpen();
    dut.receiveMessage(message);

    long expectedExpire = Utils.currentTimeSeconds() + minTimeWindow;
    assertServerVersion();
    assertExpireTime(expectedExpire, initiateCapture);
}
 
Example #16
Source File: MutableOfferDataModel.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private Coin getSellerSecurityDepositAsCoin() {
    Coin amountAsCoin = this.amount.get();
    if (amountAsCoin == null)
        amountAsCoin = Coin.ZERO;

    Coin percentOfAmountAsCoin = CoinUtil.getPercentOfAmountAsCoin(createOfferService.getSellerSecurityDepositAsDouble(), amountAsCoin);
    return getBoundedSellerSecurityDepositAsCoin(percentOfAmountAsCoin);
}
 
Example #17
Source File: TransHistoryAdapter.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
@Override
    public void onBindViewHolder(TransHistoryItemHolder holder, final int position) {
        final TransactionItem item = getTxByPosition(position);
        Long txSum = item.getValue();
        holder.rootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.OnItemClick(position);
                }
            }
        });

        if (item.getConfirmations() < MIN_CONFIRMATIONS) {
//            enableLoader(holder);
            holder.tvTxStatus.setText(R.string.tx_status_wait);
        } else {
//            disableLoader(holder);
            holder.tvTxStatus.setVisibility(View.GONE);
            holder.viewIndicator.setBackground(view.getContext().getResources().getDrawable(R.drawable.transaction_indicator_green));
            holder.viewIndicator.setVisibility(View.VISIBLE);
        }

        Coin coin = Coin.valueOf(txSum);
        String sumStr = coin.toPlainString() + " " + sharedManager.getCurrentCurrency().toUpperCase();
        holder.tvTransactionSum.setText(item.isOut() ? "-" + sumStr : sumStr);
        holder.tvDate.setText(CalendarHelper.parseDateToddMMyyyy(item.getTime() * 1000));

//        if (!item.isOut()) {
//            holder.viewIndicator.setBackground(view.getContext().getResources().getDrawable(R.drawable.transaction_indicator_green));
//        } else {
//            holder.viewIndicator.setBackground(view.getContext().getResources().getDrawable(R.drawable.transaction_indicator_red));
//        }

    }
 
Example #18
Source File: TransactionDetailsActivity.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private void setBalanceDetails() {
    long balanceBefore = transactionsManager.getBalanceByTime(true, walletManager.getMyBalance().getValue(), transaction.getTime());
    long balanceAfter;
    if (balanceBefore == 0) {
        balanceAfter = getStartBalanceAfter(balanceBefore, transaction.getValue());
    } else {
        balanceAfter = transactionsManager.getBalanceByTime(false, walletManager.getMyBalance().getValue(), transaction.getTime());
    }
    etBalanceBefore.setText(String.format("%s %s", WalletManager.getFriendlyBalance(Coin.valueOf(balanceBefore)), Common.MAIN_CURRENCY.toUpperCase()));
    etBalanceAfter.setText(String.format("%s %s", WalletManager.getFriendlyBalance(Coin.valueOf(balanceAfter)), Common.MAIN_CURRENCY.toUpperCase()));
}
 
Example #19
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
private void receiveATransactionAmount(Wallet wallet, Address toAddress, Coin amount) {
    final ListenableFuture<Coin> availFuture = wallet.getBalanceFuture(amount, Wallet.BalanceType.AVAILABLE);
    final ListenableFuture<Coin> estimatedFuture = wallet.getBalanceFuture(amount, Wallet.BalanceType.ESTIMATED);
    assertFalse(availFuture.isDone());
    assertFalse(estimatedFuture.isDone());
    // Send some pending coins to the wallet.
    Transaction t1 = sendMoneyToWallet(wallet, null, amount, toAddress);
    Threading.waitForUserCode();
    final ListenableFuture<TransactionConfidence> depthFuture = t1.getConfidence().getDepthFuture(1);
    assertFalse(depthFuture.isDone());
    assertEquals(ZERO, wallet.getBalance());
    assertEquals(amount, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
    assertFalse(availFuture.isDone());
    // Our estimated balance has reached the requested level.
    assertTrue(estimatedFuture.isDone());
    assertEquals(1, wallet.getPoolSize(Pool.PENDING));
    assertEquals(0, wallet.getPoolSize(Pool.UNSPENT));
    // Confirm the coins.
    sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, t1);
    assertEquals("Incorrect confirmed tx balance", amount, wallet.getBalance());
    assertEquals("Incorrect confirmed tx PENDING pool size", 0, wallet.getPoolSize(Pool.PENDING));
    assertEquals("Incorrect confirmed tx UNSPENT pool size", 1, wallet.getPoolSize(Pool.UNSPENT));
    assertEquals("Incorrect confirmed tx ALL pool size", 1, wallet.getTransactions(true).size());
    Threading.waitForUserCode();
    assertTrue(availFuture.isDone());
    assertTrue(estimatedFuture.isDone());
    assertTrue(depthFuture.isDone());
}
 
Example #20
Source File: MyBlindVoteListService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public Tuple2<Coin, Integer> getMiningFeeAndTxSize(Coin stake)
        throws InsufficientMoneyException, WalletException, TransactionVerificationException {
    // We set dummy opReturn data
    Coin blindVoteFee = BlindVoteConsensus.getFee(daoStateService, daoStateService.getChainHeight());
    Transaction dummyTx = getBlindVoteTx(stake, blindVoteFee, new byte[22]);
    Coin miningFee = dummyTx.getFee();
    int txSize = dummyTx.bitcoinSerialize().length;
    return new Tuple2<>(miningFee, txSize);
}
 
Example #21
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testEmptyRandomWallet() throws Exception {
    // Add a random set of outputs
    StoredBlock block = new StoredBlock(makeSolvedTestBlock(blockStore, OTHER_ADDRESS), BigInteger.ONE, 1);
    Random rng = new Random();
    for (int i = 0; i < rng.nextInt(100) + 1; i++) {
        Transaction tx = createFakeTx(PARAMS, Coin.valueOf(rng.nextInt((int) COIN.value)), myAddress);
        wallet.receiveFromBlock(tx, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, i);
    }
    SendRequest request = SendRequest.emptyWallet(OTHER_ADDRESS);
    wallet.completeTx(request);
    wallet.commitTx(request.tx);
    assertEquals(ZERO, wallet.getBalance());
}
 
Example #22
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void transactionGetFeeTest() throws Exception {
    // Prepare wallet to spend
    StoredBlock block = new StoredBlock(makeSolvedTestBlock(blockStore, OTHER_ADDRESS), BigInteger.ONE, 1);
    Transaction tx = createFakeTx(UNITTEST, COIN, myAddress);
    wallet.receiveFromBlock(tx, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0);

    // Create a transaction
    SendRequest request = SendRequest.to(OTHER_ADDRESS, CENT);
    request.feePerKb = Transaction.DEFAULT_TX_FEE;
    wallet.completeTx(request);
    assertEquals(Coin.valueOf(22700), request.tx.getFee());
}
 
Example #23
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void opReturnMaxBytes() throws Exception {
    receiveATransaction(wallet, myAddress);
    Transaction tx = new Transaction(PARAMS);
    Script script = ScriptBuilder.createOpReturnScript(new byte[80]);
    tx.addOutput(Coin.ZERO, script);
    SendRequest request = SendRequest.forTx(tx);
    request.ensureMinRequiredFee = true;
    wallet.completeTx(request);
}
 
Example #24
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private void setUTXO(List<UTXOItem> utxoList) {
    if (wallet == null) {
        return;
    }

    Address a = wallet.getImportedKeys().get(0).toAddress(params);
    final List<UTXO> utxos = new ArrayList<>();

    for (UTXOItem utxo : utxoList) {
        Sha256Hash hash = Sha256Hash.wrap(utxo.getTxHash());
        utxos.add(new UTXO(hash, utxo.getTxOutputN(), Coin.valueOf(utxo.getSatoshiValue()),
                0, false, ScriptBuilder.createOutputScript(a)));
    }

    UTXOProvider utxoProvider = new UTXOProvider() {
        @Override
        public List<UTXO> getOpenTransactionOutputs(List<Address> addresses) throws UTXOProviderException {
            return utxos;
        }

        @Override
        public int getChainHeadHeight() throws UTXOProviderException {
            return Integer.MAX_VALUE;
        }

        @Override
        public NetworkParameters getParams() {
            return wallet.getParams();
        }
    };
    wallet.setUTXOProvider(utxoProvider);
}
 
Example #25
Source File: BsqWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Coin getValueSentToMeForTransaction(Transaction transaction) throws ScriptException {
    Coin result = Coin.ZERO;
    final String txId = transaction.getHashAsString();
    // We check if we have a matching BSQ tx. We do that call here to avoid repeated calls in the loop.
    Optional<Tx> txOptional = daoStateService.getTx(txId);
    // We check all the outputs of our tx
    for (int i = 0; i < transaction.getOutputs().size(); i++) {
        TransactionOutput output = transaction.getOutputs().get(i);
        final boolean isConfirmed = output.getParentTransaction() != null &&
                output.getParentTransaction().getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING;
        if (output.isMineOrWatched(wallet)) {
            if (isConfirmed) {
                if (txOptional.isPresent()) {
                    // The index of the BSQ tx outputs are the same like the bitcoinj tx outputs
                    TxOutput txOutput = txOptional.get().getTxOutputs().get(i);
                    if (daoStateService.isBsqTxOutputType(txOutput)) {
                        //TODO check why values are not the same
                        if (txOutput.getValue() != output.getValue().value) {
                            log.warn("getValueSentToMeForTransaction: Value of BSQ output do not match BitcoinJ tx output. " +
                                            "txOutput.getValue()={}, output.getValue().value={}, txId={}",
                                    txOutput.getValue(), output.getValue().value, txId);
                        }

                        // If it is a valid BSQ output we add it
                        result = result.add(Coin.valueOf(txOutput.getValue()));
                    }
                }
            } /*else {
                // TODO atm we don't display amounts of unconfirmed txs but that might change so we leave that code
                // if it will be required
                // If the tx is not confirmed yet we add the value and assume it is a valid BSQ output.
                result = result.add(output.getValue());
            }*/
        }
    }
    return result;
}
 
Example #26
Source File: SellerTrade.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
SellerTrade(Offer offer,
            Coin tradeAmount,
            Coin txFee,
            Coin takerFee,
            boolean isCurrencyForTakerFeeBtc,
            long tradePrice,
            NodeAddress tradingPeerNodeAddress,
            Storage<? extends TradableList> storage,
            BtcWalletService btcWalletService) {
    super(offer, tradeAmount, txFee, takerFee, isCurrencyForTakerFeeBtc, tradePrice,
            tradingPeerNodeAddress, storage, btcWalletService);
}
 
Example #27
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void opReturnOneOutputTest() throws Exception {
    // Tests basic send of transaction with one output that doesn't transfer any value but just writes OP_RETURN.
    receiveATransaction(wallet, myAddress);
    Transaction tx = new Transaction(PARAMS);
    Coin messagePrice = Coin.ZERO;
    Script script = ScriptBuilder.createOpReturnScript("hello world!".getBytes());
    tx.addOutput(messagePrice, script);
    SendRequest request = SendRequest.forTx(tx);
    request.ensureMinRequiredFee = true;
    wallet.completeTx(request);
}
 
Example #28
Source File: BsqFormatter.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public String formatMarketCap(MarketPrice bsqPriceMarketPrice, MarketPrice fiatMarketPrice, Coin issuedAmount) {
    if (bsqPriceMarketPrice != null && fiatMarketPrice != null) {
        double marketCap = bsqPriceMarketPrice.getPrice() * fiatMarketPrice.getPrice() * (MathUtils.scaleDownByPowerOf10(issuedAmount.value, 2));
        return marketCapFormat.format(MathUtils.doubleToLong(marketCap)) + " " + fiatMarketPrice.getCurrencyCode();
    } else {
        return "";
    }
}
 
Example #29
Source File: CreateOfferService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private Coin getSellerSecurityDeposit(Coin amount, double sellerSecurityDeposit) {
    Coin amountAsCoin = amount;
    if (amountAsCoin == null)
        amountAsCoin = Coin.ZERO;

    Coin percentOfAmountAsCoin = CoinUtil.getPercentOfAmountAsCoin(sellerSecurityDeposit, amountAsCoin);
    return getBoundedSellerSecurityDeposit(percentOfAmountAsCoin);
}
 
Example #30
Source File: TransHistoryAdapter.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
@Override
    public void onBindViewHolder(TransHistoryItemHolder holder, final int position) {
        final TransactionItem item = getTxByPosition(position);
        Long txSum = item.getValue();
        holder.rootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.OnItemClick(position);
                }
            }
        });

        if (item.getConfirmations() < MIN_CONFIRMATIONS) {
//            enableLoader(holder);
            holder.tvTxStatus.setText(R.string.tx_status_wait);
        } else {
//            disableLoader(holder);
            holder.tvTxStatus.setVisibility(View.GONE);
            holder.viewIndicator.setBackground(view.getContext().getResources().getDrawable(R.drawable.transaction_indicator_green));
            holder.viewIndicator.setVisibility(View.VISIBLE);
        }

        Coin coin = Coin.valueOf(txSum);
        String sumStr = coin.toPlainString() + " " + sharedManager.getCurrentCurrency().toUpperCase();
        holder.tvTransactionSum.setText(item.isOut() ? "-" + sumStr : sumStr);
        holder.tvDate.setText(CalendarHelper.parseDateToddMMyyyy(item.getTime() * 1000));

//        if (!item.isOut()) {
//            holder.viewIndicator.setBackground(view.getContext().getResources().getDrawable(R.drawable.transaction_indicator_green));
//        } else {
//            holder.viewIndicator.setBackground(view.getContext().getResources().getDrawable(R.drawable.transaction_indicator_red));
//        }

    }