Java Code Examples for org.bitcoinj.core.Coin#valueOf()

The following examples show how to use org.bitcoinj.core.Coin#valueOf() . 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: SendFragment.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
Coin getFeeRate(final UI.FEE_TARGET feeTarget) throws GAException {
    GaService service=getGAService();
    if (!service.isElements() && feeTarget.equals(UI.FEE_TARGET.CUSTOM)) {
        // FIXME: Custom fees for elements
        final Double feeRate = Double.valueOf(UI.getText(mFeeTargetEdit));
        return Coin.valueOf(feeRate.longValue());
    }

    // 1 is not possible yet as we always get 2 as the fastest estimate,
    // but try it anyway in case that improves in the future.
    final int forBlock;
    if (service.isElements())
        forBlock = 6; // FIXME: feeTarget for elements
    else
        forBlock = feeTarget.getBlock();
    return GATx.getFeeEstimate(getGAService(), forBlock);
}
 
Example 2
Source File: RestrictionsTest.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testIsMinSpendableAmount() {
    Coin amount = null;
    Coin txFee = Coin.valueOf(20000);

    amount = Coin.ZERO;
    assertFalse(Restrictions.isAboveDust(amount.subtract(txFee)));

    amount = txFee;
    assertFalse(Restrictions.isAboveDust(amount.subtract(txFee)));

    amount = Restrictions.getMinNonDustOutput();
    assertFalse(Restrictions.isAboveDust(amount.subtract(txFee)));

    amount = txFee.add(Restrictions.getMinNonDustOutput());
    assertTrue(Restrictions.isAboveDust(amount.subtract(txFee)));

    amount = txFee.add(Restrictions.getMinNonDustOutput()).add(Coin.valueOf(1));
    assertTrue(Restrictions.isAboveDust(amount.subtract(txFee)));
}
 
Example 3
Source File: DisplayUtils.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Converts to a coin with max. 4 decimal places. Last place gets rounded.
 * <p>0.01234 -> 0.0123
 * <p>0.01235 -> 0.0124
 *
 * @param input         the decimal coin value to parse and round
 * @param coinFormatter the coin formatter instance
 * @return the converted coin
 */
public static Coin parseToCoinWith4Decimals(String input, CoinFormatter coinFormatter) {
    try {
        return Coin.valueOf(
                new BigDecimal(ParsingUtils.parseToCoin(ParsingUtils.cleanDoubleInput(input), coinFormatter).value)
                        .setScale(-SCALE - 1, RoundingMode.HALF_UP)
                        .setScale(SCALE + 1, RoundingMode.HALF_UP)
                        .toBigInteger().longValue()
        );
    } catch (Throwable t) {
        if (input != null && input.length() > 0)
            log.warn("Exception at parseToCoinWith4Decimals: " + t.toString());
        return Coin.ZERO;
    }
}
 
Example 4
Source File: BSFormatter.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Converts to a coin with max. 4 decimal places. Last place gets rounded.
 * 0.01234 -> 0.0123
 * 0.01235 -> 0.0124
 *
 * @param input
 * @return
 */
public Coin parseToCoinWith4Decimals(String input) {
    try {
        return Coin.valueOf(new BigDecimal(parseToCoin(cleanDoubleInput(input)).value).setScale(-scale - 1,
                BigDecimal.ROUND_HALF_UP).setScale(scale + 1, BigDecimal.ROUND_HALF_UP).toBigInteger().longValue());
    } catch (Throwable t) {
        if (input != null && input.length() > 0)
            log.warn("Exception at parseToCoinWith4Decimals: " + t.toString());
        return Coin.ZERO;
    }
}
 
Example 5
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 6
Source File: FakeTxBuilder.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a fake TX for unit tests, for use with unit tests that need greater control. One outputs, 2 random inputs,
 * split randomly to create randomness.
 */
public static Transaction createFakeTxWithoutChangeAddress(NetworkParameters params, Coin value, Address to) {
    Transaction t = new Transaction(params);
    TransactionOutput outputToMe = new TransactionOutput(params, t, value, to);
    t.addOutput(outputToMe);

    // Make a random split in the output value so we get a distinct hash when we call this multiple times with same args
    long split = new Random().nextLong();
    if (split < 0) {
        split *= -1;
    }
    if (split == 0) {
        split = 15;
    }
    while (split > value.getValue()) {
        split /= 2;
    }

    // Make a previous tx simply to send us sufficient coins. This prev tx is not really valid but it doesn't
    // matter for our purposes.
    Transaction prevTx1 = new Transaction(params);
    TransactionOutput prevOut1 = new TransactionOutput(params, prevTx1, Coin.valueOf(split), to);
    prevTx1.addOutput(prevOut1);
    // Connect it.
    t.addInput(prevOut1).setScriptSig(ScriptBuilder.createInputScript(TransactionSignature.dummy()));
    // Fake signature.

    // Do it again
    Transaction prevTx2 = new Transaction(params);
    TransactionOutput prevOut2 = new TransactionOutput(params, prevTx2, Coin.valueOf(value.getValue() - split), to);
    prevTx2.addOutput(prevOut2);
    t.addInput(prevOut2).setScriptSig(ScriptBuilder.createInputScript(TransactionSignature.dummy()));

    // Serialize/deserialize to ensure internal state is stripped, as if it had been read from the wire.
    return roundTripTransaction(params, t);
}
 
Example 7
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private TransactionInput getTransactionInput(Transaction depositTx,
                                             byte[] scriptProgram,
                                             RawTransactionInput rawTransactionInput) {
    return new TransactionInput(params, depositTx, scriptProgram, new TransactionOutPoint(params,
            rawTransactionInput.index, new Transaction(params, rawTransactionInput.parentTransaction)),
            Coin.valueOf(rawTransactionInput.value));
}
 
Example 8
Source File: BondingViewUtils.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public void lockupBondForBondedRole(Role role, Consumer<String> resultHandler) {
    Optional<RoleProposal> roleProposal = getAcceptedBondedRoleProposal(role);
    checkArgument(roleProposal.isPresent(), "roleProposal must be present");

    long requiredBond = daoFacade.getRequiredBond(roleProposal);
    Coin lockupAmount = Coin.valueOf(requiredBond);
    int lockupTime = roleProposal.get().getUnlockTime();
    if (!bondedRolesRepository.isBondedAssetAlreadyInBond(role)) {
        lockupBond(role.getHash(), lockupAmount, lockupTime, LockupReason.BONDED_ROLE, resultHandler);
    } else {
        handleError(new RuntimeException("The role has been used already for a lockup tx."));
    }
}
 
Example 9
Source File: TradeStatisticsForJson.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public Coin getTradeAmount() {
    return Coin.valueOf(tradeAmount);
}
 
Example 10
Source File: DisputeResult.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
public Coin getBuyerPayoutAmount() {
    return Coin.valueOf(buyerPayoutAmount);
}
 
Example 11
Source File: Verifier.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
static Coin verify(final GaService service,
                   final Map<TransactionOutPoint, Coin> countedUtxoValues, final PreparedTransaction ptx,
                   final Address recipient, final Coin amount, final List<Boolean> input) {
    final int changeIdx;
    if (input == null)
        changeIdx = -1;
    else if (input.get(0))
        changeIdx = 0;
    else if (input.get(1))
        changeIdx = 1;
    else
        throw new IllegalArgumentException("Verification: Change output missing.");

    if (input != null && input.get(0) && input.get(1)) {
        // Shouldn't happen really. In theory user can send money to a new change address
        // of themselves which they've generated manually, but it's unlikely, so for
        // simplicity we don't handle it.
        throw new IllegalArgumentException("Verification: Cannot send to a change address.");
    }
    final TransactionOutput output = ptx.mDecoded.getOutputs().get(1 - Math.abs(changeIdx));
    if (recipient != null) {
        final Address gotAddress = output.getScriptPubKey().getToAddress(service.getNetworkParameters());
        if (!gotAddress.equals(recipient))
            throw new IllegalArgumentException("Verification: Invalid recipient address.");
    }
    if (amount != null && !output.getValue().equals(amount))
        throw new IllegalArgumentException("Verification: Invalid output amount.");

    // 3. Verify fee value
    Coin fee = Coin.ZERO;
    for (final TransactionInput in : ptx.mDecoded.getInputs()) {
        if (countedUtxoValues.get(in.getOutpoint()) != null) {
            fee = fee.add(countedUtxoValues.get(in.getOutpoint()));
            continue;
        }

        final Transaction prevTx = ptx.mPrevoutRawTxs.get(in.getOutpoint().getHash().toString());
        if (!prevTx.getHash().equals(in.getOutpoint().getHash()))
            throw new IllegalArgumentException("Verification: Prev tx hash invalid");
        fee = fee.add(prevTx.getOutput((int) in.getOutpoint().getIndex()).getValue());
    }
    for (final TransactionOutput out : ptx.mDecoded.getOutputs())
        fee = fee.subtract(out.getValue());

    final double messageSize = ptx.mDecoded.getMessageSize();
    final double satoshiPerByte = fee.value / messageSize;
    final double satoshiPerKiloByte = satoshiPerByte * 1000.0;
    final Coin feeRate = Coin.valueOf((int) satoshiPerKiloByte);

    final Coin minFeeRate = service.getMinFeeRate();
    if (feeRate.isLessThan(minFeeRate) && service.getNetworkParameters() != RegTestParams.get())
        feeError("small", feeRate, minFeeRate);

    final Coin maxFeeRate = Coin.valueOf(15000 * 1000); // FIXME: Get max fee rate from server
    if (feeRate.isGreaterThan(maxFeeRate))
        feeError("large", feeRate, maxFeeRate);

    return amount == null ? output.getValue() : fee;
}
 
Example 12
Source File: FeeService.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Coin getMakerFeePerBtc(boolean currencyForMakerFeeBtc) {
    return currencyForMakerFeeBtc ? Coin.valueOf(DEFAULT_MAKER_FEE_IN_BASE_CUR) : Coin.valueOf(DEFAULT_MAKER_FEE_IN_BSQ);
}
 
Example 13
Source File: Contract.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public Coin getTradeAmount() {
    return Coin.valueOf(tradeAmount);
}
 
Example 14
Source File: SellerAsTakerSignsDepositTx.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected void run() {
    try {
        runInterceptHook();
        log.debug("\n\n------------------------------------------------------------\n"
                + "Contract as json\n"
                + trade.getContractAsJson()
                + "\n------------------------------------------------------------\n");

        byte[] contractHash = Hash.getSha256Hash(checkNotNull(trade.getContractAsJson()));
        trade.setContractHash(contractHash);

        List<RawTransactionInput> sellerInputs = checkNotNull(processModel.getRawTransactionInputs(), "sellerInputs must not be null");
        BtcWalletService walletService = processModel.getBtcWalletService();
        String id = processModel.getOffer().getId();

        Optional<AddressEntry> addressEntryOptional = walletService.getAddressEntry(id, AddressEntry.Context.MULTI_SIG);
        checkArgument(addressEntryOptional.isPresent(), "addressEntryOptional must be present");
        AddressEntry sellerMultiSigAddressEntry = addressEntryOptional.get();
        byte[] sellerMultiSigPubKey = processModel.getMyMultiSigPubKey();
        checkArgument(Arrays.equals(sellerMultiSigPubKey,
                sellerMultiSigAddressEntry.getPubKey()),
                "sellerMultiSigPubKey from AddressEntry must match the one from the trade data. trade id =" + id);

        Coin sellerInput = Coin.valueOf(sellerInputs.stream().mapToLong(input -> input.value).sum());

        sellerMultiSigAddressEntry.setCoinLockedInMultiSig(sellerInput.subtract(trade.getTxFee().multiply(2)));
        walletService.saveAddressEntryList();

        TradingPeer tradingPeer = processModel.getTradingPeer();

        Transaction depositTx = processModel.getTradeWalletService().takerSignsDepositTx(
                true,
                contractHash,
                processModel.getPreparedDepositTx(),
                checkNotNull(tradingPeer.getRawTransactionInputs()),
                sellerInputs,
                tradingPeer.getMultiSigPubKey(),
                sellerMultiSigPubKey);

        trade.applyDepositTx(depositTx);

        complete();
    } catch (Throwable t) {
        Contract contract = trade.getContract();
        if (contract != null)
            contract.printDiff(processModel.getTradingPeer().getContractAsJson());
        failed(t);
    }
}
 
Example 15
Source File: MutableOfferDataModel.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
private Coin getBoundedSellerSecurityDepositAsCoin(Coin value) {
    // We need to ensure that for small amount values we don't get a too low BTC amount. We limit it with using the
    // MinSellerSecurityDepositAsCoin from Restrictions.
    return Coin.valueOf(Math.max(Restrictions.getMinSellerSecurityDepositAsCoin().value, value.value));
}
 
Example 16
Source File: WalletTest.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
@Test
@Ignore("disabled for now as this test is not maintainable")
public void basicCategoryStepTest() throws Exception {
    // Creates spends that step through the possible fee solver categories

    // Generate a ton of small outputs
    StoredBlock block = new StoredBlock(makeSolvedTestBlock(blockStore, OTHER_ADDRESS), BigInteger.ONE, 1);
    int i = 0;
    Coin tenThousand = Coin.valueOf(10000);
    while (i <= 100) {
        Transaction tx = createFakeTxWithChangeAddress(PARAMS, tenThousand, myAddress, OTHER_ADDRESS);
        tx.getInput(0).setSequenceNumber(i++); // Keep every transaction unique
        wallet.receiveFromBlock(tx, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, i);
    }
    Coin balance = wallet.getBalance();

    // Create a spend that will throw away change (category 3 type 2 in which the change causes fee which is worth more than change)
    SendRequest request1 = SendRequest.to(OTHER_ADDRESS, balance.subtract(SATOSHI));
    request1.ensureMinRequiredFee = true;
    wallet.completeTx(request1);
    assertEquals(SATOSHI, request1.tx.getFee());
    assertEquals(request1.tx.getInputs().size(), i); // We should have spent all inputs

    // Give us one more input...
    Transaction tx1 = createFakeTxWithChangeAddress(PARAMS, tenThousand, myAddress, OTHER_ADDRESS);
    tx1.getInput(0).setSequenceNumber(i++); // Keep every transaction unique
    wallet.receiveFromBlock(tx1, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, i);

    // ... and create a spend that will throw away change (category 3 type 1 in which the change causes dust output)
    SendRequest request2 = SendRequest.to(OTHER_ADDRESS, balance.subtract(SATOSHI));
    request2.ensureMinRequiredFee = true;
    wallet.completeTx(request2);
    assertEquals(SATOSHI, request2.tx.getFee());
    assertEquals(request2.tx.getInputs().size(), i - 1); // We should have spent all inputs - 1

    // Give us one more input...
    Transaction tx2 = createFakeTxWithChangeAddress(PARAMS, tenThousand, myAddress, OTHER_ADDRESS);
    tx2.getInput(0).setSequenceNumber(i++); // Keep every transaction unique
    wallet.receiveFromBlock(tx2, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, i);

    // ... and create a spend that will throw away change (category 3 type 1 in which the change causes dust output)
    // but that also could have been category 2 if it wanted
    SendRequest request3 = SendRequest.to(OTHER_ADDRESS, CENT.add(tenThousand).subtract(SATOSHI));
    request3.ensureMinRequiredFee = true;
    wallet.completeTx(request3);
    assertEquals(SATOSHI, request3.tx.getFee());
    assertEquals(request3.tx.getInputs().size(), i - 2); // We should have spent all inputs - 2

    //
    SendRequest request4 = SendRequest.to(OTHER_ADDRESS, balance.subtract(SATOSHI));
    request4.feePerKb = Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.divide(request3.tx.unsafeBitcoinSerialize().length);
    request4.ensureMinRequiredFee = true;
    wallet.completeTx(request4);
    assertEquals(SATOSHI, request4.tx.getFee());
    assertEquals(request4.tx.getInputs().size(), i - 2); // We should have spent all inputs - 2

    // Give us a few more inputs...
    while (wallet.getBalance().compareTo(CENT.multiply(2)) < 0) {
        Transaction tx3 = createFakeTxWithChangeAddress(PARAMS, tenThousand, myAddress, OTHER_ADDRESS);
        tx3.getInput(0).setSequenceNumber(i++); // Keep every transaction unique
        wallet.receiveFromBlock(tx3, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, i);
    }

    // ...that is just slightly less than is needed for category 1
    SendRequest request5 = SendRequest.to(OTHER_ADDRESS, CENT.add(tenThousand).subtract(SATOSHI));
    request5.ensureMinRequiredFee = true;
    wallet.completeTx(request5);
    assertEquals(SATOSHI, request5.tx.getFee());
    assertEquals(1, request5.tx.getOutputs().size()); // We should have no change output

    // Give us one more input...
    Transaction tx4 = createFakeTxWithChangeAddress(PARAMS, tenThousand, myAddress, OTHER_ADDRESS);
    tx4.getInput(0).setSequenceNumber(i); // Keep every transaction unique
    wallet.receiveFromBlock(tx4, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, i);

    // ... that puts us in category 1 (no fee!)
    SendRequest request6 = SendRequest.to(OTHER_ADDRESS, CENT.add(tenThousand).subtract(SATOSHI));
    request6.ensureMinRequiredFee = true;
    wallet.completeTx(request6);
    assertEquals(ZERO, request6.tx.getFee());
    assertEquals(2, request6.tx.getOutputs().size()); // We should have a change output
}
 
Example 17
Source File: MonetaryFormatTest.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void mBtcRounding() throws Exception {
    assertEquals("0", format(ZERO, 3, 0));
    assertEquals("0.00", format(ZERO, 3, 2));

    assertEquals("1000", format(COIN, 3, 0));
    assertEquals("1000.0", format(COIN, 3, 1));
    assertEquals("1000.00", format(COIN, 3, 2));
    assertEquals("1000.00", format(COIN, 3, 2, 2));
    assertEquals("1000.000", format(COIN, 3, 3));
    assertEquals("1000.0000", format(COIN, 3, 4));

    final Coin justNot = COIN.subtract(SATOSHI.multiply(10));
    assertEquals("1000", format(justNot, 3, 0));
    assertEquals("1000.0", format(justNot, 3, 1));
    assertEquals("1000.00", format(justNot, 3, 2));
    assertEquals("999.9999", format(justNot, 3, 2, 2));
    assertEquals("1000.000", format(justNot, 3, 3));
    assertEquals("999.9999", format(justNot, 3, 4));

    final Coin slightlyMore = COIN.add(SATOSHI.multiply(10));
    assertEquals("1000", format(slightlyMore, 3, 0));
    assertEquals("1000.0", format(slightlyMore, 3, 1));
    assertEquals("1000.00", format(slightlyMore, 3, 2));
    assertEquals("1000.000", format(slightlyMore, 3, 3));
    assertEquals("1000.0001", format(slightlyMore, 3, 2, 2));
    assertEquals("1000.0001", format(slightlyMore, 3, 4));

    final Coin pivot = COIN.add(SATOSHI.multiply(50));
    assertEquals("1000.0005", format(pivot, 3, 4));
    assertEquals("1000.0005", format(pivot, 3, 3, 1));
    assertEquals("1000.001", format(pivot, 3, 3));

    final Coin value = Coin.valueOf(1122334455667788l);
    assertEquals("11223344557", format(value, 3, 0));
    assertEquals("11223344556.7", format(value, 3, 1));
    assertEquals("11223344556.68", format(value, 3, 2));
    assertEquals("11223344556.6779", format(value, 3, 2, 2));
    assertEquals("11223344556.678", format(value, 3, 3));
    assertEquals("11223344556.6779", format(value, 3, 4));
}
 
Example 18
Source File: LNPaymentLogicImpl.java    From thundernetwork with GNU Affero General Public License v3.0 4 votes vote down vote up
private List<Transaction> getPaymentTransactions (Sha256Hash parentTransactionHash, ChannelStatus channelStatus, RevocationHash
        revocationHash, ECKey keyServer, ECKey keyClient) {

    List<PaymentData> allPayments = new ArrayList<>(channelStatus.remainingPayments);
    allPayments.addAll(channelStatus.newPayments);

    List<Transaction> transactions = new ArrayList<>(allPayments.size());

    int index = 2;

    for (PaymentData payment : allPayments) {

        Transaction transaction = new Transaction(Constants.getNetwork());
        transaction.addInput(parentTransactionHash, index, Tools.getDummyScript());

        Coin value = Coin.valueOf(payment.amount);
        Script script = ScriptTools.getPaymentTxOutput(keyServer, keyClient, revocationHash, payment.csvDelay);
        transaction.addOutput(value, script);

        transactions.add(transaction);

        index++;
    }

    return transactions;
}
 
Example 19
Source File: Offer.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
public Coin getAmount() {
    return Coin.valueOf(offerPayload.getAmount());
}
 
Example 20
Source File: MonetaryFormat.java    From GreenBits with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Parse a human readable coin value to a {@link org.bitcoinj.core.Coin} instance.
 * 
 * @throws NumberFormatException
 *             if the string cannot be parsed for some reason
 */
public Coin parse(String str) throws NumberFormatException {
    return Coin.valueOf(parseValue(str, Coin.SMALLEST_UNIT_EXPONENT));
}