Search in sources :

Example 1 with DecryptionException

use of com.samourai.wallet.crypto.DecryptionException in project samourai-wallet-android by Samourai-Wallet.

the class BalanceActivity method doBackup.

private void doBackup() {
    try {
        final String passphrase = HD_WalletFactory.getInstance(BalanceActivity.this).get().getPassphrase();
        final String[] export_methods = new String[2];
        export_methods[0] = getString(R.string.export_to_clipboard);
        export_methods[1] = getString(R.string.export_to_email);
        new AlertDialog.Builder(BalanceActivity.this).setTitle(R.string.options_export).setSingleChoiceItems(export_methods, 0, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                try {
                    PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN()));
                } catch (IOException ioe) {
                    ;
                } catch (JSONException je) {
                    ;
                } catch (DecryptionException de) {
                    ;
                } catch (MnemonicException.MnemonicLengthException mle) {
                    ;
                }
                String encrypted = null;
                try {
                    encrypted = AESUtil.encrypt(PayloadUtil.getInstance(BalanceActivity.this).getPayload().toString(), new CharSequenceX(passphrase), AESUtil.DefaultPBKDF2Iterations);
                } catch (Exception e) {
                    Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                } finally {
                    if (encrypted == null) {
                        Toast.makeText(BalanceActivity.this, R.string.encryption_error, Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                JSONObject obj = PayloadUtil.getInstance(BalanceActivity.this).putPayload(encrypted, true);
                if (which == 0) {
                    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(android.content.Context.CLIPBOARD_SERVICE);
                    android.content.ClipData clip = null;
                    clip = android.content.ClipData.newPlainText("Wallet backup", obj.toString());
                    clipboard.setPrimaryClip(clip);
                    Toast.makeText(BalanceActivity.this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show();
                } else {
                    Intent email = new Intent(Intent.ACTION_SEND);
                    email.putExtra(Intent.EXTRA_SUBJECT, "Samourai Wallet backup");
                    email.putExtra(Intent.EXTRA_TEXT, obj.toString());
                    email.setType("message/rfc822");
                    startActivity(Intent.createChooser(email, BalanceActivity.this.getText(R.string.choose_email_client)));
                }
                dialog.dismiss();
            }
        }).show();
    } catch (IOException ioe) {
        ioe.printStackTrace();
        Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show();
    } catch (MnemonicException.MnemonicLengthException mle) {
        mle.printStackTrace();
        Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show();
    }
}
Also used : AlertDialog(android.app.AlertDialog) CharSequenceX(com.samourai.wallet.util.CharSequenceX) DialogInterface(android.content.DialogInterface) JSONException(org.json.JSONException) Intent(android.content.Intent) IOException(java.io.IOException) JSONException(org.json.JSONException) AddressFormatException(org.bitcoinj.core.AddressFormatException) DecryptionException(com.samourai.wallet.crypto.DecryptionException) IOException(java.io.IOException) DecoderException(org.bouncycastle.util.encoders.DecoderException) MnemonicException(org.bitcoinj.crypto.MnemonicException) ClipData(android.content.ClipData) MnemonicException(org.bitcoinj.crypto.MnemonicException) JSONObject(org.json.JSONObject) OnClickListener(android.view.View.OnClickListener) DecryptionException(com.samourai.wallet.crypto.DecryptionException)

Example 2 with DecryptionException

use of com.samourai.wallet.crypto.DecryptionException in project samourai-wallet-android by Samourai-Wallet.

the class BIP47Activity method onActivityResult.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK && requestCode == SCAN_PCODE) {
        if (data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) {
            String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT);
            processScan(strResult);
        }
    } else if (resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_PCODE) {
        ;
    } else if (resultCode == Activity.RESULT_OK && requestCode == EDIT_PCODE) {
        if (data.hasExtra("pcode")) {
            String pcode = data.getStringExtra("pcode");
            if (BIP47Meta.getInstance().getOutgoingStatus(pcode) == BIP47Meta.STATUS_NOT_SENT) {
                doNotifTx(pcode);
            }
        }
    } else if (resultCode == Activity.RESULT_CANCELED && requestCode == EDIT_PCODE) {
        ;
    } else if (resultCode == Activity.RESULT_OK && requestCode == RECOMMENDED_PCODE) {
        if (data.hasExtra("pcode") && data.hasExtra("label")) {
            String pcode = data.getStringExtra("pcode");
            String label = data.getStringExtra("label");
            BIP47Meta.getInstance().setLabel(pcode, label);
            new Thread(new Runnable() {

                @Override
                public void run() {
                    Looper.prepare();
                    try {
                        PayloadUtil.getInstance(BIP47Activity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BIP47Activity.this).getGUID() + AccessFactory.getInstance().getPIN()));
                    } catch (MnemonicException.MnemonicLengthException mle) {
                        mle.printStackTrace();
                        Toast.makeText(BIP47Activity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
                    } catch (DecoderException de) {
                        de.printStackTrace();
                        Toast.makeText(BIP47Activity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
                    } catch (JSONException je) {
                        je.printStackTrace();
                        Toast.makeText(BIP47Activity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                        Toast.makeText(BIP47Activity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
                    } catch (java.lang.NullPointerException npe) {
                        npe.printStackTrace();
                        Toast.makeText(BIP47Activity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
                    } catch (DecryptionException de) {
                        de.printStackTrace();
                        Toast.makeText(BIP47Activity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
                    } finally {
                        ;
                    }
                    Looper.loop();
                }
            }).start();
            if (BIP47Meta.getInstance().getOutgoingStatus(pcode) == BIP47Meta.STATUS_NOT_SENT) {
                doNotifTx(pcode);
            }
        }
    } else if (resultCode == Activity.RESULT_CANCELED && requestCode == RECOMMENDED_PCODE) {
        ;
    } else {
        ;
    }
}
Also used : DecoderException(org.bouncycastle.util.encoders.DecoderException) MnemonicException(org.bitcoinj.crypto.MnemonicException) CharSequenceX(com.samourai.wallet.util.CharSequenceX) JSONException(org.json.JSONException) IOException(java.io.IOException) DecryptionException(com.samourai.wallet.crypto.DecryptionException)

Example 3 with DecryptionException

use of com.samourai.wallet.crypto.DecryptionException 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 4 with DecryptionException

use of com.samourai.wallet.crypto.DecryptionException in project samourai-wallet-android by Samourai-Wallet.

the class BIP47Add method onOptionsItemSelected.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        finish();
    } else if (id == R.id.action_add) {
        View view = BIP47Add.this.getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
        String label = edLabel.getText().toString();
        final String pcode = edPCode.getText().toString();
        if (pcode == null || pcode.length() < 1 || !FormatsUtil.getInstance().isValidPaymentCode(pcode)) {
            Toast.makeText(BIP47Add.this, R.string.invalid_payment_code, Toast.LENGTH_SHORT).show();
        } else if (label == null || label.length() < 1) {
            Toast.makeText(BIP47Add.this, R.string.bip47_no_label_error, Toast.LENGTH_SHORT).show();
        } else {
            BIP47Meta.getInstance().setLabel(pcode, label);
            new Thread(new Runnable() {

                @Override
                public void run() {
                    Looper.prepare();
                    try {
                        PayloadUtil.getInstance(BIP47Add.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BIP47Add.this).getGUID() + AccessFactory.getInstance().getPIN()));
                    } catch (MnemonicException.MnemonicLengthException mle) {
                        mle.printStackTrace();
                        Toast.makeText(BIP47Add.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
                    } catch (DecoderException de) {
                        de.printStackTrace();
                        Toast.makeText(BIP47Add.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
                    } catch (JSONException je) {
                        je.printStackTrace();
                        Toast.makeText(BIP47Add.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                        Toast.makeText(BIP47Add.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
                    } catch (java.lang.NullPointerException npe) {
                        npe.printStackTrace();
                        Toast.makeText(BIP47Add.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
                    } catch (DecryptionException de) {
                        de.printStackTrace();
                        Toast.makeText(BIP47Add.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
                    } finally {
                        ;
                    }
                    Looper.loop();
                }
            }).start();
            Intent resultIntent = new Intent();
            resultIntent.putExtra("pcode", pcode);
            setResult(Activity.RESULT_OK, resultIntent);
            finish();
        }
    } else {
        ;
    }
    return super.onOptionsItemSelected(item);
}
Also used : CharSequenceX(com.samourai.wallet.util.CharSequenceX) JSONException(org.json.JSONException) InputMethodManager(android.view.inputmethod.InputMethodManager) Intent(android.content.Intent) IOException(java.io.IOException) View(android.view.View) DecoderException(org.bouncycastle.util.encoders.DecoderException) MnemonicException(org.bitcoinj.crypto.MnemonicException) DecryptionException(com.samourai.wallet.crypto.DecryptionException)

Example 5 with DecryptionException

use of com.samourai.wallet.crypto.DecryptionException in project samourai-wallet-android by Samourai-Wallet.

the class CreateWalletActivity method initThread.

/**
 * Creates new wallet account
 *
 * @param create
 * @param pin
 * @param passphrase
 * @param seed
 */
private void initThread(final boolean create, final String pin, final String passphrase, final String seed) {
    toggleLoading();
    new Thread(new Runnable() {

        @Override
        public void run() {
            Looper.prepare();
            String guid = AccessFactory.getInstance(CreateWalletActivity.this).createGUID();
            String hash = AccessFactory.getInstance(CreateWalletActivity.this).getHash(guid, new CharSequenceX(pin), AESUtil.DefaultPBKDF2Iterations);
            PrefsUtil.getInstance(CreateWalletActivity.this).setValue(PrefsUtil.ACCESS_HASH, hash);
            PrefsUtil.getInstance(CreateWalletActivity.this).setValue(PrefsUtil.ACCESS_HASH2, hash);
            if (create) {
                try {
                    HD_WalletFactory.getInstance(CreateWalletActivity.this).newWallet(12, passphrase, SamouraiWallet.NB_ACCOUNTS);
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                } catch (MnemonicException.MnemonicLengthException mle) {
                    mle.printStackTrace();
                } finally {
                    ;
                }
            } else if (seed == null) {
                ;
            } else {
                try {
                    HD_WalletFactory.getInstance(CreateWalletActivity.this).restoreWallet(seed, passphrase, SamouraiWallet.NB_ACCOUNTS);
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                } catch (DecoderException de) {
                    de.printStackTrace();
                } catch (AddressFormatException afe) {
                    afe.printStackTrace();
                } catch (MnemonicException.MnemonicLengthException mle) {
                    mle.printStackTrace();
                } catch (MnemonicException.MnemonicChecksumException mce) {
                    mce.printStackTrace();
                } catch (MnemonicException.MnemonicWordException mwe) {
                    mwe.printStackTrace();
                } finally {
                    ;
                }
            }
            PrefsUtil.getInstance(CreateWalletActivity.this).setValue(PrefsUtil.SCRAMBLE_PIN, true);
            try {
                String msg = null;
                if (HD_WalletFactory.getInstance(CreateWalletActivity.this).get() != null) {
                    if (create) {
                        msg = getString(R.string.wallet_created_ok);
                    } else {
                        msg = getString(R.string.wallet_restored_ok);
                    }
                    try {
                        AccessFactory.getInstance(CreateWalletActivity.this).setPIN(pin);
                        PayloadUtil.getInstance(CreateWalletActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(CreateWalletActivity.this).getGUID() + pin));
                        if (create) {
                            PrefsUtil.getInstance(CreateWalletActivity.this).setValue(PrefsUtil.WALLET_ORIGIN, "new");
                            PrefsUtil.getInstance(CreateWalletActivity.this).setValue(PrefsUtil.FIRST_RUN, true);
                        } else {
                            PrefsUtil.getInstance(CreateWalletActivity.this).setValue(PrefsUtil.WALLET_ORIGIN, "restored");
                            PrefsUtil.getInstance(CreateWalletActivity.this).setValue(PrefsUtil.FIRST_RUN, true);
                        }
                    } catch (JSONException je) {
                        je.printStackTrace();
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    } catch (DecryptionException de) {
                        de.printStackTrace();
                    } finally {
                        ;
                    }
                    for (int i = 0; i < 2; i++) {
                        AddressFactory.getInstance().account2xpub().put(i, HD_WalletFactory.getInstance(CreateWalletActivity.this).get().getAccount(i).xpubstr());
                        AddressFactory.getInstance().xpub2account().put(HD_WalletFactory.getInstance(CreateWalletActivity.this).get().getAccount(i).xpubstr(), i);
                    }
                    // 
                    if (create) {
                        String seed = null;
                        try {
                            seed = HD_WalletFactory.getInstance(CreateWalletActivity.this).get().getMnemonic();
                        } catch (IOException ioe) {
                            ioe.printStackTrace();
                        } catch (MnemonicException.MnemonicLengthException mle) {
                            mle.printStackTrace();
                        }
                        Intent intent = new Intent(CreateWalletActivity.this, RecoveryWordsActivity.class);
                        intent.putExtra("BIP39_WORD_LIST", seed);
                        startActivity(intent);
                        finish();
                    } else {
                        AccessFactory.getInstance(CreateWalletActivity.this).setIsLoggedIn(true);
                        TimeOutUtil.getInstance().updatePin();
                        AppUtil.getInstance(CreateWalletActivity.this).restartApp();
                    }
                } else {
                    if (create) {
                        msg = getString(R.string.wallet_created_ko);
                    } else {
                        msg = getString(R.string.wallet_restored_ko);
                    }
                }
                Toast.makeText(CreateWalletActivity.this, msg, Toast.LENGTH_SHORT).show();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            } catch (MnemonicException.MnemonicLengthException mle) {
                mle.printStackTrace();
            } finally {
                ;
            }
            toggleLoading();
            Looper.loop();
        }
    }).start();
}
Also used : AddressFormatException(org.bitcoinj.core.AddressFormatException) CharSequenceX(com.samourai.wallet.util.CharSequenceX) JSONException(org.json.JSONException) Intent(android.content.Intent) IOException(java.io.IOException) DecoderException(org.apache.commons.codec.DecoderException) MnemonicException(org.bitcoinj.crypto.MnemonicException) DecryptionException(com.samourai.wallet.crypto.DecryptionException)

Aggregations

DecryptionException (com.samourai.wallet.crypto.DecryptionException)13 CharSequenceX (com.samourai.wallet.util.CharSequenceX)13 IOException (java.io.IOException)13 JSONException (org.json.JSONException)13 MnemonicException (org.bitcoinj.crypto.MnemonicException)12 Intent (android.content.Intent)10 DecoderException (org.apache.commons.codec.DecoderException)6 JSONObject (org.json.JSONObject)6 AlertDialog (android.app.AlertDialog)5 DialogInterface (android.content.DialogInterface)5 AddressFormatException (org.bitcoinj.core.AddressFormatException)5 DecoderException (org.bouncycastle.util.encoders.DecoderException)4 ProgressDialog (android.app.ProgressDialog)3 HD_Wallet (com.samourai.wallet.hd.HD_Wallet)3 MyTransactionOutPoint (com.samourai.wallet.send.MyTransactionOutPoint)3 Point (android.graphics.Point)2 OnClickListener (android.view.View.OnClickListener)2 EditText (android.widget.EditText)2 PaymentCode (com.samourai.wallet.bip47.rpc.PaymentCode)2 SecretPoint (com.samourai.wallet.bip47.rpc.SecretPoint)2