Search in sources :

Example 1 with SuggestedFee

use of com.samourai.wallet.send.SuggestedFee in project samourai-wallet-android by Samourai-Wallet.

the class APIFactory method getDynamicFees.

public synchronized JSONObject getDynamicFees() {
    JSONObject jsonObject = null;
    try {
        int sel = PrefsUtil.getInstance(context).getValue(PrefsUtil.FEE_PROVIDER_SEL, 0);
        if (sel == 1) {
            int[] blocks = new int[] { 2, 6, 24 };
            List<SuggestedFee> suggestedFees = new ArrayList<SuggestedFee>();
            JSONRPC jsonrpc = new JSONRPC(TrustedNodeUtil.getInstance().getUser(), TrustedNodeUtil.getInstance().getPassword(), TrustedNodeUtil.getInstance().getNode(), TrustedNodeUtil.getInstance().getPort());
            for (int i = 0; i < blocks.length; i++) {
                JSONObject feeObj = jsonrpc.getFeeEstimate(blocks[i]);
                if (feeObj != null && feeObj.has("result")) {
                    double fee = feeObj.getDouble("result");
                    SuggestedFee suggestedFee = new SuggestedFee();
                    suggestedFee.setDefaultPerKB(BigInteger.valueOf((long) (fee * 1e8)));
                    suggestedFee.setStressed(false);
                    suggestedFee.setOK(true);
                    suggestedFees.add(suggestedFee);
                }
            }
            if (suggestedFees.size() > 0) {
                FeeUtil.getInstance().setEstimatedFees(suggestedFees);
            }
        } else {
            StringBuilder url = new StringBuilder(WebUtil.BITCOIND_FEE_URL);
            // Log.i("APIFactory", "Dynamic fees:" + url.toString());
            String response = WebUtil.getInstance(null).getURL(url.toString());
            // Log.i("APIFactory", "Dynamic fees response:" + response);
            try {
                jsonObject = new JSONObject(response);
                parseDynamicFees_bitcoind(jsonObject);
            } catch (JSONException je) {
                je.printStackTrace();
                jsonObject = null;
            }
        }
    } catch (Exception e) {
        jsonObject = null;
        e.printStackTrace();
    }
    return jsonObject;
}
Also used : JSONRPC(com.samourai.wallet.JSONRPC.JSONRPC) JSONObject(org.json.JSONObject) SuggestedFee(com.samourai.wallet.send.SuggestedFee) ArrayList(java.util.ArrayList) JSONException(org.json.JSONException) MyTransactionOutPoint(com.samourai.wallet.send.MyTransactionOutPoint) TransactionOutPoint(org.bitcoinj.core.TransactionOutPoint) JSONException(org.json.JSONException) AddressFormatException(org.bitcoinj.core.AddressFormatException) MnemonicException(org.bitcoinj.crypto.MnemonicException) IOException(java.io.IOException)

Example 2 with SuggestedFee

use of com.samourai.wallet.send.SuggestedFee in project samourai-wallet-android by Samourai-Wallet.

the class BIP47Activity method doNotifTx.

private void doNotifTx(final String pcode) {
    // 
    // get wallet balance
    // 
    long balance = 0L;
    try {
        balance = APIFactory.getInstance(BIP47Activity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BIP47Activity.this).get().getAccount(0).xpubstr());
    } catch (IOException ioe) {
        balance = 0L;
    } catch (MnemonicException.MnemonicLengthException mle) {
        balance = 0L;
    } catch (java.lang.NullPointerException npe) {
        balance = 0L;
    }
    final List<UTXO> selectedUTXO = new ArrayList<UTXO>();
    long totalValueSelected = 0L;
    // long change = 0L;
    BigInteger fee = null;
    // 
    // spend dust threshold amount to notification address
    // 
    long amount = SendNotifTxFactory._bNotifTxValue.longValue();
    // 
    // calc btc fee from USD Samourai fee
    // 
    double btc_fx = ExchangeRateFactory.getInstance(BIP47Activity.this).getBitfinexPrice("USD");
    BigInteger currentSWFee = BigInteger.valueOf((long) ((btc_fx / SendNotifTxFactory._dSWFeeUSD) * 1e8));
    if (currentSWFee.longValue() < SendNotifTxFactory._bSWFee.longValue() || currentSWFee.longValue() > SendNotifTxFactory._bSWCeilingFee.longValue()) {
        currentSWFee = SendNotifTxFactory._bSWFee;
    }
    // 
    // add Samourai Wallet fee to total amount
    // 
    amount += currentSWFee.longValue();
    // 
    // get unspents
    // 
    List<UTXO> utxos = null;
    if (UTXOFactory.getInstance().getTotalP2SH_P2WPKH() > amount + FeeUtil.getInstance().estimatedFeeSegwit(0, 1, 4).longValue()) {
        utxos = new ArrayList<UTXO>();
        utxos.addAll(UTXOFactory.getInstance().getP2SH_P2WPKH().values());
    } else {
        utxos = APIFactory.getInstance(BIP47Activity.this).getUtxos(true);
    }
    // sort in ascending order by value
    final List<UTXO> _utxos = utxos;
    Collections.sort(_utxos, new UTXO.UTXOComparator());
    Collections.reverse(_utxos);
    // 
    for (UTXO u : _utxos) {
        if (u.getValue() >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFee(1, 4).longValue())) {
            selectedUTXO.add(u);
            totalValueSelected += u.getValue();
            Log.d("BIP47Activity", "single output");
            Log.d("BIP47Activity", "value selected:" + u.getValue());
            Log.d("BIP47Activity", "total value selected:" + totalValueSelected);
            Log.d("BIP47Activity", "nb inputs:" + u.getOutpoints().size());
            break;
        }
    }
    // 
    // use low fee settings
    // 
    SuggestedFee suggestedFee = FeeUtil.getInstance().getSuggestedFee();
    FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getLowFee());
    if (selectedUTXO.size() == 0) {
        // sort in descending order by value
        Collections.sort(_utxos, new UTXO.UTXOComparator());
        int selected = 0;
        // get largest UTXOs > than spend + fee + dust
        for (UTXO u : _utxos) {
            selectedUTXO.add(u);
            totalValueSelected += u.getValue();
            selected += u.getOutpoints().size();
            if (totalValueSelected >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFee(selected, 4).longValue())) {
                Log.d("BIP47Activity", "multiple outputs");
                Log.d("BIP47Activity", "total value selected:" + totalValueSelected);
                Log.d("BIP47Activity", "nb inputs:" + u.getOutpoints().size());
                break;
            }
        }
        fee = FeeUtil.getInstance().estimatedFee(selected, 4);
    } else {
        fee = FeeUtil.getInstance().estimatedFee(1, 4);
    }
    // 
    // reset fee to previous setting
    // 
    FeeUtil.getInstance().setSuggestedFee(suggestedFee);
    // 
    if ((amount + fee.longValue()) >= balance) {
        String message = getText(R.string.bip47_notif_tx_insufficient_funds_1) + " ";
        BigInteger biAmount = SendNotifTxFactory._bSWFee.add(SendNotifTxFactory._bNotifTxValue.add(FeeUtil.getInstance().estimatedFee(1, 4, FeeUtil.getInstance().getLowFee().getDefaultPerKB())));
        String strAmount = MonetaryUtil.getInstance().getBTCFormat().format(((double) biAmount.longValue()) / 1e8) + " BTC ";
        message += strAmount;
        message += " " + getText(R.string.bip47_notif_tx_insufficient_funds_2);
        AlertDialog.Builder dlg = new AlertDialog.Builder(BIP47Activity.this).setTitle(R.string.app_name).setMessage(message).setCancelable(false).setPositiveButton(R.string.help, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://support.samourai.io/article/58-connecting-to-a-paynym-contact"));
                startActivity(browserIntent);
            }
        }).setNegativeButton(R.string.close, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.dismiss();
            }
        });
        if (!isFinishing()) {
            dlg.show();
        }
        return;
    }
    // 
    // payment code to be notified
    // 
    PaymentCode payment_code;
    try {
        payment_code = new PaymentCode(pcode);
    } catch (AddressFormatException afe) {
        payment_code = null;
    }
    if (payment_code == null) {
        return;
    }
    // 
    // create outpoints for spend later
    // 
    final List<MyTransactionOutPoint> outpoints = new ArrayList<MyTransactionOutPoint>();
    for (UTXO u : selectedUTXO) {
        outpoints.addAll(u.getOutpoints());
    }
    // 
    // create inputs from outpoints
    // 
    List<MyTransactionInput> inputs = new ArrayList<MyTransactionInput>();
    for (MyTransactionOutPoint o : outpoints) {
        Script script = new Script(o.getScriptBytes());
        if (script.getScriptType() == Script.ScriptType.NO_TYPE) {
            continue;
        }
        MyTransactionInput input = new MyTransactionInput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, new byte[0], o, o.getTxHash().toString(), o.getTxOutputN());
        inputs.add(input);
    }
    // 
    // sort inputs
    // 
    Collections.sort(inputs, new SendFactory.BIP69InputComparator());
    // 
    // find outpoint that corresponds to 0th input
    // 
    MyTransactionOutPoint outPoint = null;
    for (MyTransactionOutPoint o : outpoints) {
        if (o.getTxHash().toString().equals(inputs.get(0).getTxHash()) && o.getTxOutputN() == inputs.get(0).getTxPos()) {
            outPoint = o;
            break;
        }
    }
    if (outPoint == null) {
        Toast.makeText(BIP47Activity.this, R.string.bip47_cannot_identify_outpoint, Toast.LENGTH_SHORT).show();
        return;
    }
    byte[] op_return = null;
    // 
    try {
        Script inputScript = new Script(outPoint.getConnectedPubKeyScript());
        String address = inputScript.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
        ECKey ecKey = SendFactory.getPrivKey(address);
        if (ecKey == null || !ecKey.hasPrivKey()) {
            Toast.makeText(BIP47Activity.this, R.string.bip47_cannot_compose_notif_tx, Toast.LENGTH_SHORT).show();
            return;
        }
        // 
        // use outpoint for payload masking
        // 
        byte[] privkey = ecKey.getPrivKeyBytes();
        byte[] pubkey = payment_code.notificationAddress().getPubKey();
        byte[] outpoint = outPoint.bitcoinSerialize();
        // Log.i("BIP47Activity", "outpoint:" + Hex.toHexString(outpoint));
        // Log.i("BIP47Activity", "payer shared secret:" + Hex.toHexString(new SecretPoint(privkey, pubkey).ECDHSecretAsBytes()));
        byte[] mask = PaymentCode.getMask(new SecretPoint(privkey, pubkey).ECDHSecretAsBytes(), outpoint);
        // Log.i("BIP47Activity", "mask:" + Hex.toHexString(mask));
        // Log.i("BIP47Activity", "mask length:" + mask.length);
        // Log.i("BIP47Activity", "payload0:" + Hex.toHexString(BIP47Util.getInstance(context).getPaymentCode().getPayload()));
        op_return = PaymentCode.blind(BIP47Util.getInstance(BIP47Activity.this).getPaymentCode().getPayload(), mask);
    // Log.i("BIP47Activity", "payload1:" + Hex.toHexString(op_return));
    } catch (InvalidKeyException ike) {
        Toast.makeText(BIP47Activity.this, ike.getMessage(), Toast.LENGTH_SHORT).show();
        return;
    } catch (InvalidKeySpecException ikse) {
        Toast.makeText(BIP47Activity.this, ikse.getMessage(), Toast.LENGTH_SHORT).show();
        return;
    } catch (NoSuchAlgorithmException nsae) {
        Toast.makeText(BIP47Activity.this, nsae.getMessage(), Toast.LENGTH_SHORT).show();
        return;
    } catch (NoSuchProviderException nspe) {
        Toast.makeText(BIP47Activity.this, nspe.getMessage(), Toast.LENGTH_SHORT).show();
        return;
    }
    final HashMap<String, BigInteger> receivers = new HashMap<String, BigInteger>();
    receivers.put(Hex.toHexString(op_return), BigInteger.ZERO);
    receivers.put(payment_code.notificationAddress().getAddressString(), SendNotifTxFactory._bNotifTxValue);
    receivers.put(SamouraiWallet.getInstance().isTestNet() ? SendNotifTxFactory.TESTNET_SAMOURAI_NOTIF_TX_FEE_ADDRESS : SendNotifTxFactory.SAMOURAI_NOTIF_TX_FEE_ADDRESS, currentSWFee);
    final long change = totalValueSelected - (amount + fee.longValue());
    if (change > 0L) {
        String change_address = BIP49Util.getInstance(BIP47Activity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP49Util.getInstance(BIP47Activity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getAddressAsString();
        receivers.put(change_address, BigInteger.valueOf(change));
    }
    Log.d("BIP47Activity", "outpoints:" + outpoints.size());
    Log.d("BIP47Activity", "totalValueSelected:" + BigInteger.valueOf(totalValueSelected).toString());
    Log.d("BIP47Activity", "amount:" + BigInteger.valueOf(amount).toString());
    Log.d("BIP47Activity", "change:" + BigInteger.valueOf(change).toString());
    Log.d("BIP47Activity", "fee:" + fee.toString());
    if (change < 0L) {
        Toast.makeText(BIP47Activity.this, R.string.bip47_cannot_compose_notif_tx, Toast.LENGTH_SHORT).show();
        return;
    }
    final MyTransactionOutPoint _outPoint = outPoint;
    String strNotifTxMsg = getText(R.string.bip47_setup4_text1) + " ";
    long notifAmount = amount;
    String strAmount = MonetaryUtil.getInstance().getBTCFormat().format(((double) notifAmount + fee.longValue()) / 1e8) + " BTC ";
    strNotifTxMsg += strAmount + getText(R.string.bip47_setup4_text2);
    AlertDialog.Builder dlg = new AlertDialog.Builder(BIP47Activity.this).setTitle(R.string.bip47_setup4_title).setMessage(strNotifTxMsg).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int whichButton) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    Looper.prepare();
                    Transaction tx = SendFactory.getInstance(BIP47Activity.this).makeTransaction(0, outpoints, receivers);
                    if (tx != null) {
                        String input0hash = tx.getInput(0L).getOutpoint().getHash().toString();
                        Log.d("BIP47Activity", "input0 hash:" + input0hash);
                        Log.d("BIP47Activity", "_outPoint hash:" + _outPoint.getTxHash().toString());
                        int input0index = (int) tx.getInput(0L).getOutpoint().getIndex();
                        Log.d("BIP47Activity", "input0 index:" + input0index);
                        Log.d("BIP47Activity", "_outPoint index:" + _outPoint.getTxOutputN());
                        if (!input0hash.equals(_outPoint.getTxHash().toString()) || input0index != _outPoint.getTxOutputN()) {
                            Toast.makeText(BIP47Activity.this, R.string.bip47_cannot_compose_notif_tx, Toast.LENGTH_SHORT).show();
                            return;
                        }
                        tx = SendFactory.getInstance(BIP47Activity.this).signTransaction(tx);
                        final String hexTx = new String(org.bouncycastle.util.encoders.Hex.encode(tx.bitcoinSerialize()));
                        Log.d("SendActivity", tx.getHashAsString());
                        Log.d("SendActivity", hexTx);
                        boolean isOK = false;
                        String response = null;
                        try {
                            response = PushTx.getInstance(BIP47Activity.this).samourai(hexTx);
                            Log.d("SendActivity", "pushTx:" + response);
                            if (response != null) {
                                org.json.JSONObject jsonObject = new org.json.JSONObject(response);
                                if (jsonObject.has("status")) {
                                    if (jsonObject.getString("status").equals("ok")) {
                                        isOK = true;
                                    }
                                }
                            } else {
                                Toast.makeText(BIP47Activity.this, R.string.pushtx_returns_null, Toast.LENGTH_SHORT).show();
                                return;
                            }
                            if (isOK) {
                                Toast.makeText(BIP47Activity.this, R.string.payment_channel_init, Toast.LENGTH_SHORT).show();
                                // 
                                // set outgoing index for payment code to 0
                                // 
                                BIP47Meta.getInstance().setOutgoingIdx(pcode, 0);
                                // Log.i("SendNotifTxFactory", "tx hash:" + tx.getHashAsString());
                                // 
                                // status to NO_CFM
                                // 
                                BIP47Meta.getInstance().setOutgoingStatus(pcode, tx.getHashAsString(), BIP47Meta.STATUS_SENT_NO_CFM);
                                // 
                                if (change > 0L) {
                                    BIP49Util.getInstance(BIP47Activity.this).getWallet().getAccount(0).getChange().incAddrIdx();
                                }
                                PayloadUtil.getInstance(BIP47Activity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BIP47Activity.this).getGUID() + AccessFactory.getInstance(BIP47Activity.this).getPIN()));
                            } else {
                                Toast.makeText(BIP47Activity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException je) {
                            Toast.makeText(BIP47Activity.this, "pushTx:" + je.getMessage(), Toast.LENGTH_SHORT).show();
                            return;
                        } catch (MnemonicException.MnemonicLengthException mle) {
                            Toast.makeText(BIP47Activity.this, "pushTx:" + mle.getMessage(), Toast.LENGTH_SHORT).show();
                            return;
                        } catch (DecoderException de) {
                            Toast.makeText(BIP47Activity.this, "pushTx:" + de.getMessage(), Toast.LENGTH_SHORT).show();
                            return;
                        } catch (IOException ioe) {
                            Toast.makeText(BIP47Activity.this, "pushTx:" + ioe.getMessage(), Toast.LENGTH_SHORT).show();
                            return;
                        } catch (DecryptionException de) {
                            Toast.makeText(BIP47Activity.this, "pushTx:" + de.getMessage(), Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                    Looper.loop();
                }
            }).start();
        }
    }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int whichButton) {
            ;
        }
    });
    dlg.show();
}
Also used : AlertDialog(android.app.AlertDialog) CharSequenceX(com.samourai.wallet.util.CharSequenceX) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) MyTransactionOutPoint(com.samourai.wallet.send.MyTransactionOutPoint) ECKey(org.bitcoinj.core.ECKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JSONObject(org.json.JSONObject) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) SecretPoint(com.samourai.wallet.bip47.rpc.SecretPoint) AddressFormatException(org.bitcoinj.core.AddressFormatException) Script(org.bitcoinj.script.Script) SuggestedFee(com.samourai.wallet.send.SuggestedFee) Transaction(org.bitcoinj.core.Transaction) JSONObject(org.json.JSONObject) BigInteger(java.math.BigInteger) DialogInterface(android.content.DialogInterface) MnemonicException(org.bitcoinj.crypto.MnemonicException) PaymentCode(com.samourai.wallet.bip47.rpc.PaymentCode) SendFactory(com.samourai.wallet.send.SendFactory) JSONException(org.json.JSONException) Intent(android.content.Intent) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) MyTransactionOutPoint(com.samourai.wallet.send.MyTransactionOutPoint) SecretPoint(com.samourai.wallet.bip47.rpc.SecretPoint) Point(android.graphics.Point) UTXO(com.samourai.wallet.send.UTXO) DecoderException(org.bouncycastle.util.encoders.DecoderException) MyTransactionInput(com.samourai.wallet.send.MyTransactionInput) NoSuchProviderException(java.security.NoSuchProviderException) DecryptionException(com.samourai.wallet.crypto.DecryptionException)

Example 3 with SuggestedFee

use of com.samourai.wallet.send.SuggestedFee in project samourai-wallet-android by Samourai-Wallet.

the class FeeActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fee);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    FeeActivity.this.getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    btLowFee = (Button) findViewById(R.id.low_fee);
    btAutoFee = (Button) findViewById(R.id.auto_fee);
    btPriorityFee = (Button) findViewById(R.id.priority_fee);
    btCustomFee = (Button) findViewById(R.id.custom_fee);
    tvFeePrompt = (TextView) findViewById(R.id.current_fee_prompt);
    FEE_TYPE = PrefsUtil.getInstance(FeeActivity.this).getValue(PrefsUtil.CURRENT_FEE_TYPE, FEE_NORMAL);
    long lo = FeeUtil.getInstance().getLowFee().getDefaultPerKB().longValue() / 1000L;
    long mi = FeeUtil.getInstance().getNormalFee().getDefaultPerKB().longValue() / 1000L;
    long hi = FeeUtil.getInstance().getHighFee().getDefaultPerKB().longValue() / 1000L;
    if (lo == mi && mi == hi) {
        lo = (long) ((double) mi * 0.85);
        hi = (long) ((double) mi * 1.15);
        SuggestedFee lo_sf = new SuggestedFee();
        lo_sf.setDefaultPerKB(BigInteger.valueOf(lo * 1000L));
        FeeUtil.getInstance().setLowFee(lo_sf);
        SuggestedFee hi_sf = new SuggestedFee();
        hi_sf.setDefaultPerKB(BigInteger.valueOf(hi * 1000L));
        FeeUtil.getInstance().setHighFee(hi_sf);
    } else if (lo == mi || mi == hi) {
        mi = (lo + hi) / 2L;
        SuggestedFee mi_sf = new SuggestedFee();
        mi_sf.setDefaultPerKB(BigInteger.valueOf(mi * 1000L));
        FeeUtil.getInstance().setNormalFee(mi_sf);
    } else {
        ;
    }
    switch(FEE_TYPE) {
        case FEE_LOW:
            FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getLowFee());
            btLowFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.blue));
            btAutoFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
            btPriorityFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
            btCustomFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
            btLowFee.setTypeface(null, Typeface.BOLD);
            btAutoFee.setTypeface(null, Typeface.NORMAL);
            btPriorityFee.setTypeface(null, Typeface.NORMAL);
            btCustomFee.setTypeface(null, Typeface.NORMAL);
            tvFeePrompt.setText(getText(R.string.fee_low_priority) + " " + getText(R.string.blocks_to_cf));
            break;
        case FEE_PRIORITY:
            FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee());
            btLowFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
            btAutoFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
            btPriorityFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.blue));
            btCustomFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
            btLowFee.setTypeface(null, Typeface.NORMAL);
            btAutoFee.setTypeface(null, Typeface.NORMAL);
            btPriorityFee.setTypeface(null, Typeface.BOLD);
            btCustomFee.setTypeface(null, Typeface.NORMAL);
            tvFeePrompt.setText(getText(R.string.fee_high_priority) + " " + getText(R.string.blocks_to_cf));
            break;
        default:
            FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getNormalFee());
            btLowFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
            btAutoFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.blue));
            btPriorityFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
            btCustomFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
            btLowFee.setTypeface(null, Typeface.NORMAL);
            btAutoFee.setTypeface(null, Typeface.BOLD);
            btPriorityFee.setTypeface(null, Typeface.NORMAL);
            btCustomFee.setTypeface(null, Typeface.NORMAL);
            tvFeePrompt.setText(getText(R.string.fee_mid_priority) + " " + getText(R.string.blocks_to_cf));
            break;
    }
    btLowFee.setText((FeeUtil.getInstance().getLowFee().getDefaultPerKB().longValue() / 1000L) + "\n" + getString(R.string.sat_b));
    btPriorityFee.setText((FeeUtil.getInstance().getHighFee().getDefaultPerKB().longValue() / 1000L) + "\n" + getString(R.string.sat_b));
    btAutoFee.setText((FeeUtil.getInstance().getNormalFee().getDefaultPerKB().longValue() / 1000L) + "\n" + getString(R.string.sat_b));
    btLowFee.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getLowFee());
            PrefsUtil.getInstance(FeeActivity.this).setValue(PrefsUtil.CURRENT_FEE_TYPE, FEE_LOW);
            btLowFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.blue));
            btAutoFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
            btPriorityFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
            btCustomFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
            btLowFee.setTypeface(null, Typeface.BOLD);
            btAutoFee.setTypeface(null, Typeface.NORMAL);
            btPriorityFee.setTypeface(null, Typeface.NORMAL);
            btCustomFee.setTypeface(null, Typeface.NORMAL);
            btCustomFee.setText(R.string.custom_fee);
            tvFeePrompt.setText(getText(R.string.fee_low_priority) + " " + getText(R.string.blocks_to_cf));
        }
    });
    btAutoFee.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getNormalFee());
            PrefsUtil.getInstance(FeeActivity.this).setValue(PrefsUtil.CURRENT_FEE_TYPE, FEE_NORMAL);
            btLowFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
            btAutoFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.blue));
            btPriorityFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
            btCustomFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
            btLowFee.setTypeface(null, Typeface.NORMAL);
            btAutoFee.setTypeface(null, Typeface.BOLD);
            btPriorityFee.setTypeface(null, Typeface.NORMAL);
            btCustomFee.setTypeface(null, Typeface.NORMAL);
            btCustomFee.setText(R.string.custom_fee);
            tvFeePrompt.setText(getText(R.string.fee_mid_priority) + " " + getText(R.string.blocks_to_cf));
        }
    });
    btPriorityFee.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee());
            PrefsUtil.getInstance(FeeActivity.this).setValue(PrefsUtil.CURRENT_FEE_TYPE, FEE_PRIORITY);
            btLowFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
            btAutoFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
            btPriorityFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.blue));
            btCustomFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
            btLowFee.setTypeface(null, Typeface.NORMAL);
            btAutoFee.setTypeface(null, Typeface.NORMAL);
            btPriorityFee.setTypeface(null, Typeface.BOLD);
            btCustomFee.setTypeface(null, Typeface.NORMAL);
            btCustomFee.setText(R.string.custom_fee);
            tvFeePrompt.setText(getText(R.string.fee_high_priority) + " " + getText(R.string.blocks_to_cf));
        }
    });
    btCustomFee.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            doCustomFee();
        }
    });
    btOK = (Button) findViewById(R.id.ok);
    btOK.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Intent data = new Intent();
            setResult(RESULT_OK, data);
            finish();
        }
    });
    btCancel = (Button) findViewById(R.id.cancel);
    btCancel.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            finish();
        }
    });
}
Also used : SuggestedFee(com.samourai.wallet.send.SuggestedFee) Intent(android.content.Intent) ImageView(android.widget.ImageView) View(android.view.View) TextView(android.widget.TextView)

Example 4 with SuggestedFee

use of com.samourai.wallet.send.SuggestedFee in project samourai-wallet-android by Samourai-Wallet.

the class FeeActivity method doCustomFee.

private void doCustomFee() {
    double sanitySat = (double) FeeUtil.getInstance().getHighFee().getDefaultPerKB().doubleValue() / 1000.0;
    final long sanityValue = (long) (sanitySat * 1.5);
    final EditText etCustomFee = new EditText(FeeActivity.this);
    double d = FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().doubleValue() / 1000.0;
    NumberFormat decFormat = NumberFormat.getInstance(Locale.US);
    decFormat.setMaximumFractionDigits(3);
    decFormat.setMinimumFractionDigits(0);
    etCustomFee.setText(decFormat.format(d));
    InputFilter filter = new InputFilter() {

        String strCharset = "0123456789nollNOLL.";

        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            for (int i = start; i < end; i++) {
                if (strCharset.indexOf(source.charAt(i)) == -1) {
                    return "";
                }
            }
            return null;
        }
    };
    etCustomFee.setFilters(new InputFilter[] { filter });
    AlertDialog.Builder dlg = new AlertDialog.Builder(FeeActivity.this).setTitle(R.string.app_name).setMessage(R.string.set_sat).setView(etCustomFee).setCancelable(false).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int whichButton) {
            String strCustomFee = etCustomFee.getText().toString();
            double customValue = 0.0;
            if (strCustomFee.equalsIgnoreCase("noll") && PrefsUtil.getInstance(FeeActivity.this).getValue(PrefsUtil.USE_TRUSTED_NODE, false) == true) {
                customValue = 0.0;
            } else {
                try {
                    customValue = Double.valueOf(strCustomFee);
                } catch (Exception e) {
                    Toast.makeText(FeeActivity.this, R.string.custom_fee_too_low, Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            if (customValue < 1.0 && !strCustomFee.equalsIgnoreCase("noll")) {
                Toast.makeText(FeeActivity.this, R.string.custom_fee_too_low, Toast.LENGTH_SHORT).show();
            } else if (customValue > sanityValue) {
                Toast.makeText(FeeActivity.this, R.string.custom_fee_too_high, Toast.LENGTH_SHORT).show();
            } else {
                SuggestedFee suggestedFee = new SuggestedFee();
                suggestedFee.setStressed(false);
                suggestedFee.setOK(true);
                suggestedFee.setDefaultPerKB(BigInteger.valueOf((long) (customValue * 1000.0)));
                Log.d("FeeActivity", "custom fee:" + BigInteger.valueOf((long) (customValue * 1000.0)));
                FeeUtil.getInstance().setSuggestedFee(suggestedFee);
                btLowFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
                btAutoFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
                btPriorityFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.darkgrey));
                btCustomFee.setBackgroundColor(FeeActivity.this.getResources().getColor(R.color.blue));
                btCustomFee.setText((FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().doubleValue() / 1000L) + "\n" + getString(R.string.sat_b));
                btCustomFee.setTypeface(null, Typeface.BOLD);
                btLowFee.setTypeface(null, Typeface.NORMAL);
                btAutoFee.setTypeface(null, Typeface.NORMAL);
                btPriorityFee.setTypeface(null, Typeface.NORMAL);
                long lowFee = FeeUtil.getInstance().getLowFee().getDefaultPerKB().longValue() / 1000L;
                long normalFee = FeeUtil.getInstance().getNormalFee().getDefaultPerKB().longValue() / 1000L;
                long highFee = FeeUtil.getInstance().getHighFee().getDefaultPerKB().longValue() / 1000L;
                double pct = 0.0;
                int nbBlocks = 6;
                if (customValue == 0.0) {
                    customValue = 1.0;
                }
                if (customValue <= (double) lowFee) {
                    pct = ((double) lowFee / customValue);
                    nbBlocks = ((Double) Math.ceil(pct * 24.0)).intValue();
                } else if (customValue >= (double) highFee) {
                    pct = ((double) highFee / customValue);
                    nbBlocks = ((Double) Math.ceil(pct * 2.0)).intValue();
                    if (nbBlocks < 1) {
                        nbBlocks = 1;
                    }
                } else {
                    pct = ((double) normalFee / customValue);
                    nbBlocks = ((Double) Math.ceil(pct * 6.0)).intValue();
                }
                tvFeePrompt.setText(getText(R.string.fee_custom_priority) + " " + nbBlocks + " " + getText(R.string.blocks_to_cf));
            }
            dialog.dismiss();
        }
    }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.dismiss();
        }
    });
    if (!isFinishing()) {
        dlg.show();
    }
}
Also used : EditText(android.widget.EditText) AlertDialog(android.app.AlertDialog) InputFilter(android.text.InputFilter) DialogInterface(android.content.DialogInterface) SuggestedFee(com.samourai.wallet.send.SuggestedFee) Spanned(android.text.Spanned) MyTransactionOutPoint(com.samourai.wallet.send.MyTransactionOutPoint) Point(android.graphics.Point) JSONException(org.json.JSONException) IOException(java.io.IOException) WriterException(com.google.zxing.WriterException) ParseException(java.text.ParseException) DecoderException(org.bouncycastle.util.encoders.DecoderException) FileNotFoundException(java.io.FileNotFoundException) MnemonicException(org.bitcoinj.crypto.MnemonicException) NumberFormat(java.text.NumberFormat)

Example 5 with SuggestedFee

use of com.samourai.wallet.send.SuggestedFee in project samourai-wallet-android by Samourai-Wallet.

the class SendActivity method doFees.

private void doFees() {
    SuggestedFee highFee = FeeUtil.getInstance().getHighFee();
    SuggestedFee normalFee = FeeUtil.getInstance().getNormalFee();
    SuggestedFee lowFee = FeeUtil.getInstance().getLowFee();
    String message = getText(R.string.current_fee_selection) + " " + (FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat);
    message += "\n";
    message += getText(R.string.current_hi_fee_value) + " " + (highFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat);
    message += "\n";
    message += getText(R.string.current_mid_fee_value) + " " + (normalFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat);
    message += "\n";
    message += getText(R.string.current_lo_fee_value) + " " + (lowFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat);
    AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this).setTitle(R.string.app_name).setMessage(message).setCancelable(false).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.dismiss();
        }
    });
    if (!isFinishing()) {
        dlg.show();
    }
}
Also used : AlertDialog(android.app.AlertDialog) SuggestedFee(com.samourai.wallet.send.SuggestedFee) DialogInterface(android.content.DialogInterface) MyTransactionOutPoint(com.samourai.wallet.send.MyTransactionOutPoint) Point(android.graphics.Point)

Aggregations

SuggestedFee (com.samourai.wallet.send.SuggestedFee)9 MyTransactionOutPoint (com.samourai.wallet.send.MyTransactionOutPoint)7 AlertDialog (android.app.AlertDialog)5 DialogInterface (android.content.DialogInterface)5 Point (android.graphics.Point)5 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5 MnemonicException (org.bitcoinj.crypto.MnemonicException)5 JSONException (org.json.JSONException)5 DecoderException (org.bouncycastle.util.encoders.DecoderException)4 JSONObject (org.json.JSONObject)4 Intent (android.content.Intent)3 WriterException (com.google.zxing.WriterException)3 UTXO (com.samourai.wallet.send.UTXO)3 FileNotFoundException (java.io.FileNotFoundException)3 BigInteger (java.math.BigInteger)3 NumberFormat (java.text.NumberFormat)3 ParseException (java.text.ParseException)3 HashMap (java.util.HashMap)3 Transaction (org.bitcoinj.core.Transaction)3