Search in sources :

Example 11 with SegwitAddress

use of com.samourai.wallet.segwit.SegwitAddress in project samourai-wallet-android by Samourai-Wallet.

the class APIFactory method deleteXPUB.

public synchronized JSONObject deleteXPUB(String xpub, boolean bip49) {
    String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2;
    JSONObject jsonObject = null;
    try {
        String response = null;
        ECKey ecKey = null;
        if (AddressFactory.getInstance(context).xpub2account().get(xpub) != null || xpub.equals(BIP49Util.getInstance(context).getWallet().getAccount(0).ypubstr())) {
            HD_Address addr = null;
            if (bip49) {
                addr = BIP49Util.getInstance(context).getWallet().getAccountAt(0).getChange().getAddressAt(0);
            } else {
                addr = HD_WalletFactory.getInstance(context).get().getAccount(0).getChain(AddressFactory.CHANGE_CHAIN).getAddressAt(0);
            }
            ecKey = addr.getECKey();
            if (ecKey != null && ecKey.hasPrivKey()) {
                String sig = ecKey.signMessage(xpub);
                String address = null;
                if (bip49) {
                    SegwitAddress segwitAddress = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
                    address = segwitAddress.getAddressAsString();
                } else {
                    address = ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
                }
                if (!TorUtil.getInstance(context).statusFromBroadcast()) {
                    StringBuilder args = new StringBuilder();
                    args.append("message=");
                    args.append(xpub);
                    args.append("address=");
                    args.append(address);
                    args.append("&signature=");
                    args.append(Uri.encode(sig));
                    Log.i("APIFactory", "delete XPUB:" + args.toString());
                    response = WebUtil.getInstance(context).deleteURL(_url + "delete/" + xpub, args.toString());
                    Log.i("APIFactory", "delete XPUB response:" + response);
                } else {
                    HashMap<String, String> args = new HashMap<String, String>();
                    args.put("message", xpub);
                    args.put("address", address);
                    args.put("signature", Uri.encode(sig));
                    Log.i("APIFactory", "delete XPUB:" + args.toString());
                    response = WebUtil.getInstance(context).tor_deleteURL(_url + "delete", args);
                    Log.i("APIFactory", "delete XPUB response:" + response);
                }
                try {
                    jsonObject = new JSONObject(response);
                    if (jsonObject.has("status") && jsonObject.getString("status").equals("ok")) {
                        ;
                    }
                } catch (JSONException je) {
                    je.printStackTrace();
                    jsonObject = null;
                }
            }
        }
    } catch (Exception e) {
        jsonObject = null;
        e.printStackTrace();
    }
    return jsonObject;
}
Also used : JSONObject(org.json.JSONObject) HD_Address(com.samourai.wallet.hd.HD_Address) SegwitAddress(com.samourai.wallet.segwit.SegwitAddress) HashMap(java.util.HashMap) JSONException(org.json.JSONException) ECKey(org.bitcoinj.core.ECKey) JSONException(org.json.JSONException) AddressFormatException(org.bitcoinj.core.AddressFormatException) MnemonicException(org.bitcoinj.crypto.MnemonicException) IOException(java.io.IOException)

Example 12 with SegwitAddress

use of com.samourai.wallet.segwit.SegwitAddress in project samourai-wallet-android by Samourai-Wallet.

the class AddressFactory method getBIP84.

public SegwitAddress getBIP84(int chain) {
    int idx = 0;
    HD_Address addr = null;
    SegwitAddress p2wpkh = null;
    // try	{
    HD_Wallet hdw = BIP84Util.getInstance(context).getWallet();
    if (hdw != null) {
        idx = BIP84Util.getInstance(context).getWallet().getAccount(SamouraiWallet.SAMOURAI_ACCOUNT).getChain(chain).getAddrIdx();
        addr = BIP84Util.getInstance(context).getWallet().getAccount(SamouraiWallet.SAMOURAI_ACCOUNT).getChain(chain).getAddressAt(idx);
        p2wpkh = new SegwitAddress(addr.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
        if (chain == RECEIVE_CHAIN && canIncBIP84ReceiveAddress(idx)) {
            BIP84Util.getInstance(context).getWallet().getAccount(SamouraiWallet.SAMOURAI_ACCOUNT).getChain(chain).incAddrIdx();
        // PayloadUtil.getInstance(context).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(context).getGUID() + AccessFactory.getInstance(context).getPIN()));
        }
    }
    return p2wpkh;
}
Also used : HD_Wallet(com.samourai.wallet.hd.HD_Wallet) HD_Address(com.samourai.wallet.hd.HD_Address) SegwitAddress(com.samourai.wallet.segwit.SegwitAddress)

Example 13 with SegwitAddress

use of com.samourai.wallet.segwit.SegwitAddress in project samourai-wallet-android by Samourai-Wallet.

the class AddressCalcActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_address_calc);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    edIndex = (EditText) findViewById(R.id.index);
    spType = (Spinner) findViewById(R.id.address_type_spinner);
    spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            if (position == 3) {
                tvChain.setVisibility(View.INVISIBLE);
                rChain.setVisibility(View.INVISIBLE);
            } else {
                tvChain.setVisibility(View.VISIBLE);
                rChain.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            ;
        }
    });
    populateSpinner();
    tvChain = (TextView) findViewById(R.id.chain_label);
    rChain = (RadioGroup) findViewById(R.id.chain);
    btOK = (Button) findViewById(R.id.ok);
    btOK.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            try {
                HD_Address hd_addr = null;
                final SegwitAddress segwitAddress;
                String strIndex = edIndex.getText().toString();
                if (strIndex == null || strIndex.length() < 1) {
                    Toast.makeText(AddressCalcActivity.this, R.string.invalid_index, Toast.LENGTH_SHORT).show();
                    return;
                }
                int index = Integer.parseInt(strIndex);
                int chain = 0;
                int selectedId = rChain.getCheckedRadioButtonId();
                if (spType.getSelectedItemPosition() == 3) {
                    chain = 0;
                } else if (selectedId == R.id.change) {
                    chain = 1;
                } else {
                    chain = 0;
                }
                if (spType.getSelectedItemPosition() == 1) {
                    hd_addr = BIP84Util.getInstance(AddressCalcActivity.this).getWallet().getAccountAt(0).getChain(chain).getAddressAt(index);
                    segwitAddress = new SegwitAddress(hd_addr.getECKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
                } else if (spType.getSelectedItemPosition() == 2) {
                    segwitAddress = null;
                    hd_addr = HD_WalletFactory.getInstance(AddressCalcActivity.this).get().getAccount(0).getChain(chain).getAddressAt(index);
                } else if (spType.getSelectedItemPosition() == 3) {
                    hd_addr = BIP84Util.getInstance(AddressCalcActivity.this).getWallet().getAccountAt(RicochetMeta.getInstance(AddressCalcActivity.this).getRicochetAccount()).getChain(chain).getAddressAt(index);
                    segwitAddress = new SegwitAddress(hd_addr.getECKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
                } else if (spType.getSelectedItemPosition() == 4) {
                    hd_addr = BIP84Util.getInstance(AddressCalcActivity.this).getWallet().getAccountAt(WhirlpoolMeta.getInstance(AddressCalcActivity.this).getWhirlpoolPremixAccount()).getChain(chain).getAddressAt(index);
                    segwitAddress = new SegwitAddress(hd_addr.getECKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
                } else if (spType.getSelectedItemPosition() == 5) {
                    hd_addr = BIP84Util.getInstance(AddressCalcActivity.this).getWallet().getAccountAt(WhirlpoolMeta.getInstance(AddressCalcActivity.this).getWhirlpoolPostmix()).getChain(chain).getAddressAt(index);
                    segwitAddress = new SegwitAddress(hd_addr.getECKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
                } else if (spType.getSelectedItemPosition() == 6) {
                    hd_addr = BIP84Util.getInstance(AddressCalcActivity.this).getWallet().getAccountAt(WhirlpoolMeta.getInstance(AddressCalcActivity.this).getWhirlpoolBadBank()).getChain(chain).getAddressAt(index);
                    segwitAddress = new SegwitAddress(hd_addr.getECKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
                } else {
                    hd_addr = BIP49Util.getInstance(AddressCalcActivity.this).getWallet().getAccountAt(0).getChain(chain).getAddressAt(index);
                    segwitAddress = new SegwitAddress(hd_addr.getECKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
                }
                final ECKey ecKey;
                final String strAddress;
                if (spType.getSelectedItemPosition() == 2) {
                    ecKey = hd_addr.getECKey();
                    strAddress = hd_addr.getAddressString();
                } else {
                    ecKey = segwitAddress.getECKey();
                    if (spType.getSelectedItemPosition() == 0) {
                        strAddress = segwitAddress.getAddressAsString();
                    } else {
                        strAddress = segwitAddress.getBech32AsString();
                    }
                }
                String message = spType.getSelectedItem().toString();
                message += "\n";
                message += (chain == 1) ? AddressCalcActivity.this.getText(R.string.change_chain) : AddressCalcActivity.this.getText(R.string.receive_chain);
                message += "\n";
                message += index + ":";
                message += "\n";
                message += strAddress;
                final TextView tvText = new TextView(getApplicationContext());
                tvText.setText(message);
                tvText.setTextIsSelectable(true);
                tvText.setPadding(40, 10, 40, 10);
                tvText.setTextColor(0xffffffff);
                AlertDialog.Builder dlg = new AlertDialog.Builder(AddressCalcActivity.this).setTitle(R.string.app_name).setView(tvText).setCancelable(true).setNeutralButton(R.string.utxo_sign, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.dismiss();
                        String addr = strAddress;
                        String msg = null;
                        if (FormatsUtil.getInstance().isValidBech32(addr) || Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), addr).isP2SHAddress()) {
                            msg = AddressCalcActivity.this.getString(R.string.utxo_sign_text3);
                            try {
                                JSONObject obj = new JSONObject();
                                obj.put("pubkey", ecKey.getPublicKeyAsHex());
                                obj.put("address", addr);
                                msg += " " + obj.toString();
                            } catch (JSONException je) {
                                msg += ":";
                                msg += addr;
                                msg += ", ";
                                msg += "pubkey:";
                                msg += ecKey.getPublicKeyAsHex();
                            }
                        } else {
                            msg = AddressCalcActivity.this.getString(R.string.utxo_sign_text2);
                        }
                        if (ecKey != null) {
                            MessageSignUtil.getInstance(AddressCalcActivity.this).doSign(AddressCalcActivity.this.getString(R.string.utxo_sign), AddressCalcActivity.this.getString(R.string.utxo_sign_text1), msg, ecKey);
                        }
                    }
                }).setNegativeButton(R.string.options_display_privkey, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        String strPrivKey = ecKey.getPrivateKeyAsWiF(SamouraiWallet.getInstance().getCurrentNetworkParams());
                        ImageView showQR = new ImageView(AddressCalcActivity.this);
                        Bitmap bitmap = null;
                        QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(strPrivKey, null, Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), 500);
                        try {
                            bitmap = qrCodeEncoder.encodeAsBitmap();
                        } catch (WriterException e) {
                            e.printStackTrace();
                        }
                        showQR.setImageBitmap(bitmap);
                        TextView showText = new TextView(AddressCalcActivity.this);
                        showText.setText(strPrivKey);
                        showText.setTextIsSelectable(true);
                        showText.setPadding(40, 10, 40, 10);
                        showText.setTextSize(18.0f);
                        LinearLayout privkeyLayout = new LinearLayout(AddressCalcActivity.this);
                        privkeyLayout.setOrientation(LinearLayout.VERTICAL);
                        privkeyLayout.addView(showQR);
                        privkeyLayout.addView(showText);
                        new AlertDialog.Builder(AddressCalcActivity.this).setTitle(R.string.app_name).setView(privkeyLayout).setCancelable(false).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int whichButton) {
                                ;
                            }
                        }).show();
                    }
                });
                if (spType.getSelectedItemPosition() != 2) {
                    dlg.setPositiveButton(R.string.options_display_redeem_script, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {
                            String redeemScript = org.spongycastle.util.encoders.Hex.toHexString(segwitAddress.segWitRedeemScript().getProgram());
                            TextView showText = new TextView(AddressCalcActivity.this);
                            showText.setText(redeemScript);
                            showText.setTextIsSelectable(true);
                            showText.setPadding(40, 10, 40, 10);
                            showText.setTextSize(18.0f);
                            new AlertDialog.Builder(AddressCalcActivity.this).setTitle(R.string.app_name).setView(showText).setCancelable(false).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog, int whichButton) {
                                    dialog.dismiss();
                                }
                            }).show();
                        }
                    });
                }
                if (!isFinishing()) {
                    dlg.show();
                }
            } catch (Exception e) {
                Toast.makeText(AddressCalcActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    });
    btCancel = (Button) findViewById(R.id.cancel);
    btCancel.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            finish();
        }
    });
}
Also used : AlertDialog(android.app.AlertDialog) SegwitAddress(com.samourai.wallet.segwit.SegwitAddress) DialogInterface(android.content.DialogInterface) QRCodeEncoder(com.google.zxing.client.android.encode.QRCodeEncoder) ECKey(org.bitcoinj.core.ECKey) Bitmap(android.graphics.Bitmap) TextView(android.widget.TextView) ImageView(android.widget.ImageView) HD_Address(com.samourai.wallet.hd.HD_Address) JSONException(org.json.JSONException) ImageView(android.widget.ImageView) View(android.view.View) AdapterView(android.widget.AdapterView) TextView(android.widget.TextView) WriterException(com.google.zxing.WriterException) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) AdapterView(android.widget.AdapterView) WriterException(com.google.zxing.WriterException) LinearLayout(android.widget.LinearLayout)

Example 14 with SegwitAddress

use of com.samourai.wallet.segwit.SegwitAddress in project samourai-wallet-android by Samourai-Wallet.

the class RBFTask method signTx.

private Transaction signTx(Transaction tx) {
    HashMap<String, ECKey> keyBag = new HashMap<String, ECKey>();
    HashMap<String, ECKey> keyBag49 = new HashMap<String, ECKey>();
    HashMap<String, ECKey> keyBag84 = new HashMap<String, ECKey>();
    HashMap<String, String> keys = rbf.getKeyBag();
    for (String outpoint : keys.keySet()) {
        ECKey ecKey = null;
        String[] s = keys.get(outpoint).split("/");
        Log.i("RBF", "path length:" + s.length);
        if (s.length == 4) {
            if (s[3].equals("84")) {
                HD_Address addr = BIP84Util.getInstance(activity).getWallet().getAccount(0).getChain(Integer.parseInt(s[1])).getAddressAt(Integer.parseInt(s[2]));
                ecKey = addr.getECKey();
            } else {
                HD_Address addr = BIP49Util.getInstance(activity).getWallet().getAccount(0).getChain(Integer.parseInt(s[1])).getAddressAt(Integer.parseInt(s[2]));
                ecKey = addr.getECKey();
            }
        } else if (s.length == 3) {
            HD_Address hd_address = AddressFactory.getInstance(activity).get(0, Integer.parseInt(s[1]), Integer.parseInt(s[2]));
            String strPrivKey = hd_address.getPrivateKeyString();
            DumpedPrivateKey pk = new DumpedPrivateKey(SamouraiWallet.getInstance().getCurrentNetworkParams(), strPrivKey);
            ecKey = pk.getKey();
        } else if (s.length == 2) {
            try {
                PaymentAddress address = BIP47Util.getInstance(activity).getReceiveAddress(new PaymentCode(s[0]), Integer.parseInt(s[1]));
                ecKey = address.getReceiveECKey();
            } catch (Exception e) {
                ;
            }
        } else {
            ;
        }
        Log.i("RBF", "outpoint:" + outpoint);
        Log.i("RBF", "path:" + keys.get(outpoint));
        if (ecKey != null) {
            if (s.length == 4) {
                if (s[3].equals("84")) {
                    keyBag84.put(outpoint, ecKey);
                } else {
                    keyBag49.put(outpoint, ecKey);
                }
            } else {
                keyBag.put(outpoint, ecKey);
            }
        } else {
            throw new RuntimeException("ECKey error: cannot process private key");
        // Log.i("ECKey error", "cannot process private key");
        }
    }
    List<TransactionInput> inputs = tx.getInputs();
    for (int i = 0; i < inputs.size(); i++) {
        ECKey ecKey = null;
        String address = null;
        if (inputs.get(i).getValue() != null || keyBag49.containsKey(inputs.get(i).getOutpoint().toString()) || keyBag84.containsKey(inputs.get(i).getOutpoint().toString())) {
            if (keyBag84.containsKey(inputs.get(i).getOutpoint().toString())) {
                ecKey = keyBag84.get(inputs.get(i).getOutpoint().toString());
                SegwitAddress segwitAddress = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
                address = segwitAddress.getBech32AsString();
            } else {
                ecKey = keyBag49.get(inputs.get(i).getOutpoint().toString());
                SegwitAddress segwitAddress = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
                address = segwitAddress.getAddressAsString();
            }
        } else {
            ecKey = keyBag.get(inputs.get(i).getOutpoint().toString());
            address = ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
        }
        Log.d("RBF", "pubKey:" + Hex.toHexString(ecKey.getPubKey()));
        Log.d("RBF", "address:" + address);
        if (inputs.get(i).getValue() != null || keyBag49.containsKey(inputs.get(i).getOutpoint().toString()) || keyBag84.containsKey(inputs.get(i).getOutpoint().toString())) {
            final SegwitAddress segwitAddress = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
            Script scriptPubKey = segwitAddress.segWitOutputScript();
            final Script redeemScript = segwitAddress.segWitRedeemScript();
            System.out.println("redeem script:" + Hex.toHexString(redeemScript.getProgram()));
            final Script scriptCode = redeemScript.scriptCode();
            System.out.println("script code:" + Hex.toHexString(scriptCode.getProgram()));
            TransactionSignature sig = tx.calculateWitnessSignature(i, ecKey, scriptCode, Coin.valueOf(input_values.get(inputs.get(i).getOutpoint().toString())), Transaction.SigHash.ALL, false);
            final TransactionWitness witness = new TransactionWitness(2);
            witness.setPush(0, sig.encodeToBitcoin());
            witness.setPush(1, ecKey.getPubKey());
            tx.setWitness(i, witness);
            if (!FormatsUtil.getInstance().isValidBech32(address) && Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) {
                final ScriptBuilder sigScript = new ScriptBuilder();
                sigScript.data(redeemScript.getProgram());
                tx.getInput(i).setScriptSig(sigScript.build());
                tx.getInput(i).getScriptSig().correctlySpends(tx, i, scriptPubKey, Coin.valueOf(input_values.get(inputs.get(i).getOutpoint().toString())), Script.ALL_VERIFY_FLAGS);
            }
        } else {
            Log.i("RBF", "sign outpoint:" + inputs.get(i).getOutpoint().toString());
            Log.i("RBF", "ECKey address from keyBag:" + ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
            Log.i("RBF", "script:" + ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams())));
            Log.i("RBF", "script:" + Hex.toHexString(ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams())).getProgram()));
            TransactionSignature sig = tx.calculateSignature(i, ecKey, ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams())).getProgram(), Transaction.SigHash.ALL, false);
            tx.getInput(i).setScriptSig(ScriptBuilder.createInputScript(sig, ecKey));
        }
    }
    return tx;
}
Also used : Script(org.bitcoinj.script.Script) PaymentCode(com.samourai.wallet.bip47.rpc.PaymentCode) TransactionWitness(org.bitcoinj.core.TransactionWitness) HD_Address(com.samourai.wallet.hd.HD_Address) HashMap(java.util.HashMap) SegwitAddress(com.samourai.wallet.segwit.SegwitAddress) ECKey(org.bitcoinj.core.ECKey) TransactionSignature(org.bitcoinj.crypto.TransactionSignature) ScriptBuilder(org.bitcoinj.script.ScriptBuilder) PaymentAddress(com.samourai.wallet.bip47.rpc.PaymentAddress) JSONException(org.json.JSONException) DecoderException(org.bouncycastle.util.encoders.DecoderException) MnemonicException(org.bitcoinj.crypto.MnemonicException) IOException(java.io.IOException) MyTransactionInput(com.samourai.wallet.send.MyTransactionInput) TransactionInput(org.bitcoinj.core.TransactionInput) MyTransactionOutPoint(com.samourai.wallet.send.MyTransactionOutPoint) DumpedPrivateKey(org.bitcoinj.core.DumpedPrivateKey)

Example 15 with SegwitAddress

use of com.samourai.wallet.segwit.SegwitAddress in project samourai-wallet-android by Samourai-Wallet.

the class SendFactory method signTransaction.

private synchronized Transaction signTransaction(Transaction transaction, HashMap<String, ECKey> keyBag) throws ScriptException {
    List<TransactionInput> inputs = transaction.getInputs();
    TransactionInput input = null;
    TransactionOutput connectedOutput = null;
    byte[] connectedPubKeyScript = null;
    TransactionSignature sig = null;
    Script scriptPubKey = null;
    ECKey key = null;
    for (int i = 0; i < inputs.size(); i++) {
        input = inputs.get(i);
        key = keyBag.get(input.getOutpoint().toString());
        connectedPubKeyScript = input.getOutpoint().getConnectedPubKeyScript();
        connectedOutput = input.getOutpoint().getConnectedOutput();
        scriptPubKey = connectedOutput.getScriptPubKey();
        String script = Hex.toHexString(connectedPubKeyScript);
        String address = null;
        if (Bech32Util.getInstance().isBech32Script(script)) {
            try {
                address = Bech32Util.getInstance().getAddressFromScript(script);
            } catch (Exception e) {
                ;
            }
        } else {
            address = new Script(connectedPubKeyScript).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
        }
        if (FormatsUtil.getInstance().isValidBech32(address) || Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) {
            final SegwitAddress segwitAddress = new SegwitAddress(key.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
            // System.out.println("pubKey:" + Hex.toHexString(key.getPubKey()));
            // final Script scriptPubKey = p2shp2wpkh.segWitOutputScript();
            // System.out.println("scriptPubKey:" + Hex.toHexString(scriptPubKey.getProgram()));
            // System.out.println("to address from script:" + scriptPubKey.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
            final Script redeemScript = segwitAddress.segWitRedeemScript();
            // System.out.println("redeem script:" + Hex.toHexString(redeemScript.getProgram()));
            final Script scriptCode = redeemScript.scriptCode();
            // System.out.println("script code:" + Hex.toHexString(scriptCode.getProgram()));
            sig = transaction.calculateWitnessSignature(i, key, scriptCode, connectedOutput.getValue(), Transaction.SigHash.ALL, false);
            final TransactionWitness witness = new TransactionWitness(2);
            witness.setPush(0, sig.encodeToBitcoin());
            witness.setPush(1, key.getPubKey());
            transaction.setWitness(i, witness);
            if (!FormatsUtil.getInstance().isValidBech32(address) && Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) {
                final ScriptBuilder sigScript = new ScriptBuilder();
                sigScript.data(redeemScript.getProgram());
                transaction.getInput(i).setScriptSig(sigScript.build());
                transaction.getInput(i).getScriptSig().correctlySpends(transaction, i, scriptPubKey, connectedOutput.getValue(), Script.ALL_VERIFY_FLAGS);
            }
        } else {
            if (key != null && key.hasPrivKey() || key.isEncrypted()) {
                sig = transaction.calculateSignature(i, key, connectedPubKeyScript, Transaction.SigHash.ALL, false);
            } else {
                // watch only ?
                sig = TransactionSignature.dummy();
            }
            if (scriptPubKey.isSentToAddress()) {
                input.setScriptSig(ScriptBuilder.createInputScript(sig, key));
            } else if (scriptPubKey.isSentToRawPubKey()) {
                input.setScriptSig(ScriptBuilder.createInputScript(sig));
            } else {
                throw new RuntimeException("Unknown script type: " + scriptPubKey);
            }
        }
    }
    return transaction;
}
Also used : Script(org.bitcoinj.script.Script) TransactionOutput(org.bitcoinj.core.TransactionOutput) TransactionWitness(org.bitcoinj.core.TransactionWitness) SegwitAddress(com.samourai.wallet.segwit.SegwitAddress) TransactionSignature(org.bitcoinj.crypto.TransactionSignature) ECKey(org.bitcoinj.core.ECKey) ScriptBuilder(org.bitcoinj.script.ScriptBuilder) TransactionInput(org.bitcoinj.core.TransactionInput) ScriptException(org.bitcoinj.script.ScriptException) AddressFormatException(org.bitcoinj.core.AddressFormatException) MnemonicException(org.bitcoinj.crypto.MnemonicException) IOException(java.io.IOException)

Aggregations

SegwitAddress (com.samourai.wallet.segwit.SegwitAddress)30 ECKey (org.bitcoinj.core.ECKey)17 HashMap (java.util.HashMap)12 JSONException (org.json.JSONException)12 MyTransactionOutPoint (com.samourai.wallet.send.MyTransactionOutPoint)11 HD_Address (com.samourai.wallet.hd.HD_Address)10 IOException (java.io.IOException)10 MnemonicException (org.bitcoinj.crypto.MnemonicException)10 JSONObject (org.json.JSONObject)9 Triple (org.apache.commons.lang3.tuple.Triple)8 Script (org.bitcoinj.script.Script)8 ArrayList (java.util.ArrayList)7 TransactionOutPoint (org.bitcoinj.core.TransactionOutPoint)7 AlertDialog (android.app.AlertDialog)6 DialogInterface (android.content.DialogInterface)5 WriterException (com.google.zxing.WriterException)5 PaymentAddress (com.samourai.wallet.bip47.rpc.PaymentAddress)5 PaymentCode (com.samourai.wallet.bip47.rpc.PaymentCode)5 UTXO (com.samourai.wallet.send.UTXO)5 TransactionSignature (org.bitcoinj.crypto.TransactionSignature)5