Exemple #1
0
  /**
   * @param params The network parameters or null
   * @param nameValuePairTokens The tokens representing the name value pairs (assumed to be
   *     separated by '=' e.g. 'amount=0.2')
   */
  private void parseParameters(
      @Nullable NetworkParameters params, String addressToken, String[] nameValuePairTokens)
      throws BitcoinURIParseException {
    // Attempt to decode the rest of the tokens into a parameter map.
    for (String nameValuePairToken : nameValuePairTokens) {
      final int sepIndex = nameValuePairToken.indexOf('=');
      if (sepIndex == -1)
        throw new BitcoinURIParseException(
            "Malformed Bitcoin URI - no separator in '" + nameValuePairToken + "'");
      if (sepIndex == 0)
        throw new BitcoinURIParseException(
            "Malformed Bitcoin URI - empty name '" + nameValuePairToken + "'");
      final String nameToken =
          nameValuePairToken.substring(0, sepIndex).toLowerCase(Locale.ENGLISH);
      final String valueToken = nameValuePairToken.substring(sepIndex + 1);

      // Parse the amount.
      if (FIELD_AMOUNT.equals(nameToken)) {
        // Decode the amount (contains an optional decimal component to 8dp).
        try {
          Coin amount = Coin.parseCoin(valueToken);
          if (params != null && amount.isGreaterThan(params.getMaxMoney()))
            throw new BitcoinURIParseException("Max number of coins exceeded");
          if (amount.signum() < 0) throw new ArithmeticException("Negative coins specified");
          putWithValidation(FIELD_AMOUNT, amount);
        } catch (IllegalArgumentException e) {
          throw new OptionalFieldValidationException(
              String.format(Locale.US, "'%s' is not a valid amount", valueToken), e);
        } catch (ArithmeticException e) {
          throw new OptionalFieldValidationException(
              String.format(Locale.US, "'%s' has too many decimal places", valueToken), e);
        }
      } else {
        if (nameToken.startsWith("req-")) {
          // A required parameter that we do not know about.
          throw new RequiredFieldValidationException(
              "'" + nameToken + "' is required but not known, this URI is not valid");
        } else {
          // Known fields and unknown parameters that are optional.
          try {
            if (valueToken.length() > 0)
              putWithValidation(nameToken, URLDecoder.decode(valueToken, "UTF-8"));
          } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e); // can't happen
          }
        }
      }
    }

    // Note to the future: when you want to implement 'req-expires' have a look at commit
    // 410a53791841
    // which had it in.
  }
  /**
   * function that updates debit/credit/balance/price in fiat and Transaction History table
   *
   * @param services
   */
  private void updateWalletsSummary(List<WalletService> services) {
    Coin totalDebit = Coin.ZERO;
    Coin totalCredit = Coin.ZERO;
    Coin totalBalance = Coin.ZERO;
    double priceInFiat = 0.00d;
    String confidence = "";
    // update debit/credit/balance and price in fiat
    List<TransactionWrapper> transactions = new ArrayList<>();
    for (WalletService service : services) {
      try {
        Wallet wallet = service.getWallet();
        totalBalance = totalBalance.add(wallet.getBalance());
        for (Transaction trx : wallet.getTransactionsByTime()) {
          if (trx.getConfidence().equals(TransactionConfidence.ConfidenceType.DEAD)) continue;
          Coin amount = trx.getValue(wallet);
          if (amount.isPositive()) {
            totalCredit = totalCredit.add(amount);
          } else {
            totalDebit = totalDebit.add(amount);
          }
          transactions.add(new TransactionWrapper(trx, wallet, amount));
        }
      } catch (Exception e) {
        logger.error("Unable to update wallet details");
      }
    }
    pnlDashboardStats.setTotalBalance(MonetaryFormat.BTC.noCode().format(totalBalance).toString());
    // pnlDashboardStats.setTotalDebit(MonetaryFormat.BTC.noCode().format(totalDebit).toString());
    // pnlDashboardStats.setTotalCredit(MonetaryFormat.BTC.noCode().format(totalCredit).toString());
    priceInFiat = Double.valueOf(MonetaryFormat.BTC.noCode().format(totalBalance).toString());
    priceInFiat *= BitcoinCurrencyRateApi.get().getCurrentRateValue();
    pnlDashboardStats.setPriceInFiat(
        String.format("%.2f", priceInFiat), "", ConfigManager.config().getSelectedCurrency());
    pnlDashboardStats.setExchangeRate(
        ConfigManager.config().getSelectedCurrency(),
        String.format("%.2f", BitcoinCurrencyRateApi.get().getCurrentRateValue()));
    Collections.sort(
        transactions,
        new Comparator<TransactionWrapper>() {
          @Override
          public int compare(TransactionWrapper o1, TransactionWrapper o2) {
            return o2.getTransaction()
                .getUpdateTime()
                .compareTo(o1.getTransaction().getUpdateTime());
          }
        });
    // update Transaction History table
    DefaultTableModel model = (DefaultTableModel) tblTransactions.getModel();
    model.setRowCount(0);
    for (TransactionWrapper wrapper : transactions) {
      Transaction transaction = wrapper.getTransaction();
      if (transaction.getConfidence().getDepthInBlocks() > 6)
        confidence = "<html>6<sup>+</sup></html>";
      else confidence = transaction.getConfidence().getDepthInBlocks() + "";
      Coin amount = wrapper.getAmount();
      Coin fee = transaction.getFee();
      String amountString = MonetaryFormat.BTC.noCode().format(amount).toString();
      String feeString = fee != null ? MonetaryFormat.BTC.noCode().format(fee).toString() : "0.00";
      Address from = transaction.getInput(0).getFromAddress();
      Address to =
          transaction
              .getOutput(0)
              .getAddressFromP2PKHScript(wrapper.getWallet().getNetworkParameters());
      boolean credit = amount.isPositive();

      model.addRow(
          new Object[] {
            Utils.formatTransactionDate(transaction.getUpdateTime()),
            from,
            to,
            credit ? "Credit" : "Debit",
            amountString,
            feeString,
            "",
            confidence
          });
    }
    Coin balanceAfter = Coin.ZERO;
    for (int index = transactions.size() - 1; index >= 0; index--) {
      balanceAfter = balanceAfter.add(Coin.parseCoin((String) model.getValueAt(index, 4)));
      model.setValueAt(MonetaryFormat.BTC.noCode().format(balanceAfter).toString(), index, 6);
    }
  }