Search in sources :

Example 1 with NetworkParameters

use of org.bitcoinj.core.NetworkParameters in project bisq-core by bisq-network.

the class MakerSetupDepositTxListener method run.

@Override
protected void run() {
    try {
        runInterceptHook();
        if (trade.getDepositTx() == null && processModel.getPreparedDepositTx() != null) {
            BtcWalletService walletService = processModel.getBtcWalletService();
            final NetworkParameters params = walletService.getParams();
            Transaction preparedDepositTx = new Transaction(params, processModel.getPreparedDepositTx());
            checkArgument(!preparedDepositTx.getOutputs().isEmpty(), "preparedDepositTx.getOutputs() must not be empty");
            Address depositTxAddress = preparedDepositTx.getOutput(0).getAddressFromP2SH(params);
            final TransactionConfidence confidence = walletService.getConfidenceForAddress(depositTxAddress);
            if (isInNetwork(confidence)) {
                applyConfidence(confidence);
            } else {
                confidenceListener = new AddressConfidenceListener(depositTxAddress) {

                    @Override
                    public void onTransactionConfidenceChanged(TransactionConfidence confidence) {
                        if (isInNetwork(confidence))
                            applyConfidence(confidence);
                    }
                };
                walletService.addAddressConfidenceListener(confidenceListener);
                tradeStateSubscription = EasyBind.subscribe(trade.stateProperty(), newValue -> {
                    if (trade.isDepositPublished()) {
                        swapReservedForTradeEntry();
                        // hack to remove tradeStateSubscription at callback
                        UserThread.execute(this::unSubscribe);
                    }
                });
            }
        }
        // we complete immediately, our object stays alive because the balanceListener is stored in the WalletService
        complete();
    } catch (Throwable t) {
        failed(t);
    }
}
Also used : BtcWalletService(bisq.core.btc.wallet.BtcWalletService) Transaction(org.bitcoinj.core.Transaction) TransactionConfidence(org.bitcoinj.core.TransactionConfidence) Trade(bisq.core.trade.Trade) Subscription(org.fxmisc.easybind.Subscription) NetworkParameters(org.bitcoinj.core.NetworkParameters) Slf4j(lombok.extern.slf4j.Slf4j) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) TaskRunner(bisq.common.taskrunner.TaskRunner) AddressEntry(bisq.core.btc.AddressEntry) EasyBind(org.fxmisc.easybind.EasyBind) UserThread(bisq.common.UserThread) Address(org.bitcoinj.core.Address) AddressConfidenceListener(bisq.core.btc.listeners.AddressConfidenceListener) TradeTask(bisq.core.trade.protocol.tasks.TradeTask) AddressConfidenceListener(bisq.core.btc.listeners.AddressConfidenceListener) Transaction(org.bitcoinj.core.Transaction) Address(org.bitcoinj.core.Address) BtcWalletService(bisq.core.btc.wallet.BtcWalletService) NetworkParameters(org.bitcoinj.core.NetworkParameters) TransactionConfidence(org.bitcoinj.core.TransactionConfidence)

Example 2 with NetworkParameters

use of org.bitcoinj.core.NetworkParameters in project samourai-wallet-android by Samourai-Wallet.

the class PayloadUtil method restoreWalletfromJSON.

public synchronized HD_Wallet restoreWalletfromJSON(JSONObject obj) throws DecoderException, MnemonicException.MnemonicLengthException {
    // Log.i("PayloadUtil", obj.toString());
    HD_Wallet hdw = null;
    NetworkParameters params = SamouraiWallet.getInstance().getCurrentNetworkParams();
    JSONObject wallet = null;
    JSONObject meta = null;
    try {
        if (obj.has("wallet")) {
            wallet = obj.getJSONObject("wallet");
        } else {
            wallet = obj;
        }
        if (obj.has("meta")) {
            meta = obj.getJSONObject("meta");
        } else {
            meta = obj;
        }
    } catch (JSONException je) {
        ;
    }
    try {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
        // Log.i("PayloadUtil", obj.toString());
        if (wallet != null) {
            if (wallet.has("testnet")) {
                SamouraiWallet.getInstance().setCurrentNetworkParams(wallet.getBoolean("testnet") ? TestNet3Params.get() : MainNetParams.get());
                PrefsUtil.getInstance(context).setValue(PrefsUtil.TESTNET, wallet.getBoolean("testnet"));
            } else {
                SamouraiWallet.getInstance().setCurrentNetworkParams(MainNetParams.get());
                PrefsUtil.getInstance(context).removeValue(PrefsUtil.TESTNET);
            }
            hdw = new HD_Wallet(context, 44, wallet, params);
            hdw.getAccount(SamouraiWallet.SAMOURAI_ACCOUNT).getReceive().setAddrIdx(wallet.has("receiveIdx") ? wallet.getInt("receiveIdx") : 0);
            hdw.getAccount(SamouraiWallet.SAMOURAI_ACCOUNT).getChange().setAddrIdx(wallet.has("changeIdx") ? wallet.getInt("changeIdx") : 0);
            if (wallet.has("accounts")) {
                JSONArray accounts = wallet.getJSONArray("accounts");
                // 
                for (int i = 0; i < 2; i++) {
                    JSONObject account = accounts.getJSONObject(i);
                    hdw.getAccount(i).getReceive().setAddrIdx(account.has("receiveIdx") ? account.getInt("receiveIdx") : 0);
                    hdw.getAccount(i).getChange().setAddrIdx(account.has("changeIdx") ? account.getInt("changeIdx") : 0);
                    AddressFactory.getInstance().account2xpub().put(i, hdw.getAccount(i).xpubstr());
                    AddressFactory.getInstance().xpub2account().put(hdw.getAccount(i).xpubstr(), i);
                }
            }
        }
        if (meta != null) {
            if (meta.has("prev_balance")) {
                APIFactory.getInstance(context).setXpubBalance(meta.getLong("prev_balance"));
            }
            if (meta.has("use_segwit")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.USE_SEGWIT, meta.getBoolean("use_segwit"));
                editor.putBoolean("segwit", meta.getBoolean("use_segwit"));
                editor.commit();
            }
            if (meta.has("use_like_typed_change")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.USE_LIKE_TYPED_CHANGE, meta.getBoolean("use_like_typed_change"));
                editor.putBoolean("likeTypedChange", meta.getBoolean("use_like_typed_change"));
                editor.commit();
            }
            if (meta.has("spend_type")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.SPEND_TYPE, meta.getInt("spend_type"));
                editor.putBoolean("bip126", meta.getInt("spend_type") == SendActivity.SPEND_BIP126 ? true : false);
                editor.commit();
            }
            if (meta.has("use_bip126")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.USE_BIP126, meta.getBoolean("use_bip126"));
                editor.putBoolean("bip126", meta.getBoolean("use_bip126"));
                editor.commit();
            }
            if (meta.has("rbf_opt_in")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.RBF_OPT_IN, meta.getBoolean("rbf_opt_in"));
                editor.putBoolean("rbf", meta.getBoolean("rbf_opt_in") ? true : false);
                editor.commit();
            }
            if (meta.has("sent_tos")) {
                SendAddressUtil.getInstance().fromJSON((JSONArray) meta.get("sent_tos"));
            }
            if (meta.has("batch_send")) {
                BatchSendUtil.getInstance().fromJSON((JSONArray) meta.get("batch_send"));
            }
            if (meta.has("bip47")) {
                try {
                    BIP47Meta.getInstance().fromJSON((JSONObject) meta.get("bip47"));
                } catch (ClassCastException cce) {
                    JSONArray _array = (JSONArray) meta.get("bip47");
                    JSONObject _obj = new JSONObject();
                    _obj.put("pcodes", _array);
                    BIP47Meta.getInstance().fromJSON(_obj);
                }
            }
            if (meta.has("pin")) {
                AccessFactory.getInstance().setPIN((String) meta.get("pin"));
            }
            if (meta.has("pin2")) {
                AccessFactory.getInstance().setPIN2((String) meta.get("pin2"));
            }
            if (meta.has("ricochet")) {
                RicochetMeta.getInstance(context).fromJSON((JSONObject) meta.get("ricochet"));
            }
            if (meta.has("trusted_node")) {
                TrustedNodeUtil.getInstance().fromJSON((JSONObject) meta.get("trusted_node"));
            }
            if (meta.has("rbfs")) {
                RBFUtil.getInstance().fromJSON((JSONArray) meta.get("rbfs"));
            }
            if (meta.has("tor")) {
                TorUtil.getInstance(context).fromJSON((JSONObject) meta.get("tor"));
            }
            if (meta.has("blocked_utxos")) {
                BlockedUTXO.getInstance().fromJSON((JSONObject) meta.get("blocked_utxos"));
            }
            if (meta.has("explorer")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.BLOCK_EXPLORER, meta.getInt("explorer"));
            }
            if (meta.has("trusted_no")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.ALERT_MOBILE_NO, (String) meta.get("trusted_no"));
                editor.putString("alertSMSNo", meta.getString("trusted_no"));
                editor.commit();
            }
            if (meta.has("scramble_pin")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.SCRAMBLE_PIN, meta.getBoolean("scramble_pin"));
                editor.putBoolean("scramblePin", meta.getBoolean("scramble_pin"));
                editor.commit();
            }
            if (meta.has("haptic_pin")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.HAPTIC_PIN, meta.getBoolean("haptic_pin"));
                editor.putBoolean("haptic", meta.getBoolean("haptic_pin"));
                editor.commit();
            }
            if (meta.has("auto_backup")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.AUTO_BACKUP, meta.getBoolean("auto_backup"));
                editor.putBoolean("auto_backup", meta.getBoolean("auto_backup"));
                editor.commit();
            }
            if (meta.has("remote")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.ACCEPT_REMOTE, meta.getBoolean("remote"));
                editor.putBoolean("stealthRemote", meta.getBoolean("remote"));
                editor.commit();
            }
            if (meta.has("use_trusted")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.TRUSTED_LOCK, meta.getBoolean("use_trusted"));
                editor.putBoolean("trustedLock", meta.getBoolean("use_trusted"));
                editor.commit();
            }
            if (meta.has("check_sim")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.CHECK_SIM, meta.getBoolean("check_sim"));
                editor.putBoolean("sim_switch", meta.getBoolean("check_sim"));
                editor.commit();
                if (meta.getBoolean("check_sim")) {
                    SIMUtil.getInstance(context).setStoredSIM();
                }
            }
            if (meta.has("fiat")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.CURRENT_FIAT, (String) meta.get("fiat"));
            }
            if (meta.has("fiat_sel")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.CURRENT_FIAT_SEL, meta.getInt("fiat_sel"));
            }
            if (meta.has("fx")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.CURRENT_EXCHANGE, (String) meta.get("fx"));
            }
            if (meta.has("fx_sel")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.CURRENT_EXCHANGE_SEL, meta.getInt("fx_sel"));
            }
            if (meta.has("use_trusted_node")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.USE_TRUSTED_NODE, meta.getBoolean("use_trusted_node"));
            }
            if (meta.has("fee_provider_sel")) {
                // PrefsUtil.getInstance(context).setValue(PrefsUtil.FEE_PROVIDER_SEL, meta.getInt("fee_provider_sel") > 0 ? 0 : meta.getInt("fee_provider_sel"));
                PrefsUtil.getInstance(context).setValue(PrefsUtil.FEE_PROVIDER_SEL, 0);
            }
            if (meta.has("broadcast_tx")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.BROADCAST_TX, meta.getBoolean("broadcast_tx"));
            }
            /*
                if(meta.has("xpubreg44")) {
                    PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB44REG, meta.getBoolean("xpubreg44"));
                }
                */
            if (meta.has("xpubreg49")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB49REG, meta.getBoolean("xpubreg49"));
            }
            if (meta.has("xpublock44")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB44LOCK, meta.getBoolean("xpublock44"));
            }
            if (meta.has("xpublock49")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB49LOCK, meta.getBoolean("xpublock49"));
            }
            if (meta.has("paynym_claimed")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.PAYNYM_CLAIMED, meta.getBoolean("paynym_claimed"));
            }
            if (meta.has("paynym_refused")) {
                PrefsUtil.getInstance(context).setValue(PrefsUtil.PAYNYM_REFUSED, meta.getBoolean("paynym_refused"));
            }
        /*
                if(obj.has("passphrase")) {
                    Log.i("PayloadUtil", (String)obj.get("passphrase"));
                    Toast.makeText(context, "'" + (String)obj.get("passphrase") + "'", Toast.LENGTH_SHORT).show();
                }
                Toast.makeText(context, "'" + hdw.getPassphrase() + "'", Toast.LENGTH_SHORT).show();
                */
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (JSONException je) {
        je.printStackTrace();
    }
    HD_WalletFactory.getInstance(context).getWallets().clear();
    HD_WalletFactory.getInstance(context).getWallets().add(hdw);
    return hdw;
}
Also used : HD_Wallet(com.samourai.wallet.hd.HD_Wallet) JSONObject(org.json.JSONObject) SharedPreferences(android.content.SharedPreferences) NetworkParameters(org.bitcoinj.core.NetworkParameters) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) IOException(java.io.IOException)

Example 3 with NetworkParameters

use of org.bitcoinj.core.NetworkParameters in project samourai-wallet-android by Samourai-Wallet.

the class HD_WalletFactory method newWallet.

public HD_Wallet newWallet(int nbWords, String passphrase, int nbAccounts) throws IOException, MnemonicException.MnemonicLengthException {
    HD_Wallet hdw = null;
    if ((nbWords % 3 != 0) || (nbWords < 12 || nbWords > 24)) {
        nbWords = 12;
    }
    // len == 16 (12 words), len == 24 (18 words), len == 32 (24 words)
    int len = (nbWords / 3) * 4;
    if (passphrase == null) {
        passphrase = "";
    }
    NetworkParameters params = SamouraiWallet.getInstance().getCurrentNetworkParams();
    AppUtil.getInstance(context).applyPRNGFixes();
    SecureRandom random = new SecureRandom();
    byte[] seed = new byte[len];
    random.nextBytes(seed);
    InputStream wis = context.getResources().getAssets().open("BIP39/en.txt");
    if (wis != null) {
        MnemonicCode mc = new MnemonicCode(wis, BIP39_ENGLISH_SHA256);
        hdw = new HD_Wallet(44, mc, params, seed, passphrase, nbAccounts);
        wis.close();
    }
    BIP47Util.getInstance(context).reset();
    BIP49Util.getInstance(context).reset();
    wallets.clear();
    wallets.add(hdw);
    return hdw;
}
Also used : NetworkParameters(org.bitcoinj.core.NetworkParameters) InputStream(java.io.InputStream) SecureRandom(java.security.SecureRandom) MnemonicCode(org.bitcoinj.crypto.MnemonicCode)

Example 4 with NetworkParameters

use of org.bitcoinj.core.NetworkParameters in project catena-java by alinush.

the class CatenaUtils method isCatenaTxHelper.

/**
 * Returns true if the specified tx is a valid Catena TX created from the
 * UTXO in prevLink and signed by chainAddr.
 * If prevLink is null, then the previous UTXO is not checked.
 * If chainAddr is null, then the chain's address is not checked.
 *
 * @param tx
 * @param chainAddr
 * @param prevLink
 * @return
 */
private static boolean isCatenaTxHelper(Transaction tx, boolean verifySig, Address chainAddr, TransactionOutput prevLink, boolean checkPrevLinkIndex) {
    checkNotNull(tx);
    log.trace("Inspecting TX " + tx);
    String txid = tx.getHashAsString();
    NetworkParameters params = tx.getParams();
    // Check if this TX is properly connected to the previous TX's (unique) UTXO
    if (prevLink != null) {
        // Check the prev TX's output is #0
        if (checkPrevLinkIndex && prevLink.getIndex() != 0) {
            log.warn("Index of UTXO '" + prevLink.getOutPointFor() + "' was '" + prevLink.getIndex() + "' but expected index 0 (w.r.t. to txid=" + txid + ")");
            return false;
        }
        if (checkConnectedTo(tx, prevLink) == false)
            return false;
        // Check that the address in the previous output matches the one provided to this call
        Address prevLinkAddr = prevLink.getAddressFromP2PKHScript(tx.getParams());
        if (chainAddr != null && prevLinkAddr.equals(chainAddr) == false) {
            log.warn("Address in UTXO '" + prevLink.getOutPointFor() + "' was '" + prevLinkAddr + "' but expected chain address '" + chainAddr + "' (w.r.t. to txid=" + txid + ")");
            return false;
        }
        // Verify the signature on the first input
        if (verifySig) {
            TransactionInput firstInput = tx.getInput(0);
            try {
                firstInput.verify();
            } catch (ScriptException e) {
                log.warn("TX '" + txid + "' has invalid signature: " + Throwables.getStackTraceAsString(e));
                return false;
            } catch (VerificationException e) {
                log.warn("TX '" + txid + "' has invalid format: " + Throwables.getStackTraceAsString(e));
                return false;
            } catch (Throwable e) {
                log.warn("TX '" + txid + "' unknown signature verification error: " + Throwables.getStackTraceAsString(e));
                return false;
            }
        }
    }
    // Make sure we have only one input
    if (tx.getInputs().size() != 1) {
        log.warn("expected only one input in tx '" + txid + "', got " + tx.getInputs().size());
        return false;
    }
    // Make sure we have only two outputs (data + next)
    if (tx.getOutputs().size() != 2) {
        log.warn("expected two outputs in tx '" + txid + "' (continuation and OP_RETURN), got " + tx.getOutputs().size());
        return false;
    }
    // Make sure chain's address is correct in first output
    Address firstOutputAddr = tx.getOutput(0).getAddressFromP2PKHScript(params);
    if (chainAddr != null && !firstOutputAddr.equals(chainAddr)) {
        log.warn("first output address of '" + txid + "' was '" + firstOutputAddr + "'; expected chain address '" + chainAddr + "'");
        return false;
    }
    // Make sure 2nd output is an OP_RETURN
    Script secondOutput = tx.getOutput(1).getScriptPubKey();
    if (!secondOutput.isOpReturn()) {
        log.warn("second output of '" + txid + "' was supposed to be an OP_RETURN, got '" + secondOutput + "'");
        return false;
    }
    // All is well.
    return true;
}
Also used : ScriptException(org.bitcoinj.core.ScriptException) Script(org.bitcoinj.script.Script) Address(org.bitcoinj.core.Address) NetworkParameters(org.bitcoinj.core.NetworkParameters) VerificationException(org.bitcoinj.core.VerificationException) TransactionInput(org.bitcoinj.core.TransactionInput)

Example 5 with NetworkParameters

use of org.bitcoinj.core.NetworkParameters in project bitcoin-wallet by bitcoin-wallet.

the class SampleActivity method handleRequest.

private void handleRequest() {
    try {
        final String[] addresses = donationAddresses();
        final NetworkParameters params = Address.getParametersFromAddress(addresses[0]);
        final Protos.Output.Builder output1 = Protos.Output.newBuilder();
        output1.setAmount(AMOUNT);
        output1.setScript(ByteString.copyFrom(ScriptBuilder.createOutputScript(new Address(params, addresses[0])).getProgram()));
        final Protos.Output.Builder output2 = Protos.Output.newBuilder();
        output2.setAmount(AMOUNT);
        output2.setScript(ByteString.copyFrom(ScriptBuilder.createOutputScript(new Address(params, addresses[1])).getProgram()));
        final Protos.PaymentDetails.Builder paymentDetails = Protos.PaymentDetails.newBuilder();
        paymentDetails.setNetwork(params.getPaymentProtocolId());
        paymentDetails.addOutputs(output1);
        paymentDetails.addOutputs(output2);
        paymentDetails.setMemo(MEMO);
        paymentDetails.setTime(System.currentTimeMillis());
        final Protos.PaymentRequest.Builder paymentRequest = Protos.PaymentRequest.newBuilder();
        paymentRequest.setSerializedPaymentDetails(paymentDetails.build().toByteString());
        BitcoinIntegration.requestForResult(SampleActivity.this, REQUEST_CODE, paymentRequest.build().toByteArray());
    } catch (final AddressFormatException x) {
        throw new RuntimeException(x);
    }
}
Also used : AddressFormatException(org.bitcoinj.core.AddressFormatException) Address(org.bitcoinj.core.Address) NetworkParameters(org.bitcoinj.core.NetworkParameters) ByteString(com.google.protobuf.ByteString)

Aggregations

NetworkParameters (org.bitcoinj.core.NetworkParameters)14 Address (org.bitcoinj.core.Address)5 ECKey (org.bitcoinj.core.ECKey)5 InputStream (java.io.InputStream)2 BigInteger (java.math.BigInteger)2 DumpedPrivateKey (org.bitcoinj.core.DumpedPrivateKey)2 Transaction (org.bitcoinj.core.Transaction)2 MnemonicCode (org.bitcoinj.crypto.MnemonicCode)2 SharedPreferences (android.content.SharedPreferences)1 UserThread (bisq.common.UserThread)1 TaskRunner (bisq.common.taskrunner.TaskRunner)1 AddressEntry (bisq.core.btc.AddressEntry)1 AddressConfidenceListener (bisq.core.btc.listeners.AddressConfidenceListener)1 BtcWalletService (bisq.core.btc.wallet.BtcWalletService)1 Trade (bisq.core.trade.Trade)1 TradeTask (bisq.core.trade.protocol.tasks.TradeTask)1 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 ByteString (com.google.protobuf.ByteString)1 HD_Wallet (com.samourai.wallet.hd.HD_Wallet)1