org.bitcoinj.crypto.DeterministicKey Java Examples

The following examples show how to use org.bitcoinj.crypto.DeterministicKey. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ElectrumMultiWalletTest.java    From java-stratum with Apache License 2.0 6 votes vote down vote up
@Test
public void markKeysAsUsedDisorder() throws Exception {
    control.replay();
    DeterministicKey key1 = wallet.currentReceiveKey();
    String a1 = "mfsh3sGu8SzxRZXDRPMbwdCykDfdiXLTVQ";
    String a2 = "mpkchvF3Twgpd5AEmrRZM3TENT8V7Ygi8T";

    Transaction tx1 = FakeTxBuilder.createFakeTx(params, Coin.CENT, new Address(params, a2));
    multiWallet.addPendingDownload(tx1.getHash());
    multiWallet.receive(tx1, 0);
    DeterministicKey key2 = wallet.currentReceiveKey();
    assertEquals(wallet.currentReceiveKey(), key1);

    Transaction tx2 = FakeTxBuilder.createFakeTx(params, Coin.CENT, new Address(params, a1));
    multiWallet.addPendingDownload(tx2.getHash());
    multiWallet.receive(tx2, 0);
    assertNotEquals(wallet.currentReceiveKey(), key2);
    assertNotEquals(wallet.currentReceiveKey().toAddress(params), a1);
    assertNotEquals(wallet.currentReceiveKey().toAddress(params), a2);
    control.verify();
}
 
Example #2
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Seller signs payout transaction, buyer has not signed yet.
 *
 * @param depositTx                 deposit transaction
 * @param buyerPayoutAmount         payout amount for buyer
 * @param sellerPayoutAmount        payout amount for seller
 * @param buyerPayoutAddressString  address for buyer
 * @param sellerPayoutAddressString address for seller
 * @param multiSigKeyPair           DeterministicKey for MultiSig from seller
 * @param buyerPubKey               the public key of the buyer
 * @param sellerPubKey              the public key of the seller
 * @return DER encoded canonical signature
 * @throws AddressFormatException if the buyer or seller base58 address doesn't parse or its checksum is invalid
 * @throws TransactionVerificationException if there was an unexpected problem with the payout tx or its signature
 */
public byte[] buyerSignsPayoutTx(Transaction depositTx,
                                 Coin buyerPayoutAmount,
                                 Coin sellerPayoutAmount,
                                 String buyerPayoutAddressString,
                                 String sellerPayoutAddressString,
                                 DeterministicKey multiSigKeyPair,
                                 byte[] buyerPubKey,
                                 byte[] sellerPubKey)
        throws AddressFormatException, TransactionVerificationException {
    Transaction preparedPayoutTx = createPayoutTx(depositTx, buyerPayoutAmount, sellerPayoutAmount,
            buyerPayoutAddressString, sellerPayoutAddressString);
    // MS redeemScript
    Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
    // MS output from prev. tx is index 0
    Sha256Hash sigHash = preparedPayoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);
    checkNotNull(multiSigKeyPair, "multiSigKeyPair must not be null");
    if (multiSigKeyPair.isEncrypted()) {
        checkNotNull(aesKey);
    }
    ECKey.ECDSASignature buyerSignature = multiSigKeyPair.sign(sigHash, aesKey).toCanonicalised();
    WalletService.printTx("prepared payoutTx", preparedPayoutTx);
    WalletService.verifyTransaction(preparedPayoutTx);
    return buyerSignature.encodeToDER();
}
 
Example #3
Source File: BtcWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public DeterministicKey getMultiSigKeyPair(String tradeId, byte[] pubKey) {
    Optional<AddressEntry> multiSigAddressEntryOptional = getAddressEntry(tradeId, AddressEntry.Context.MULTI_SIG);
    DeterministicKey multiSigKeyPair;
    if (multiSigAddressEntryOptional.isPresent()) {
        AddressEntry multiSigAddressEntry = multiSigAddressEntryOptional.get();
        multiSigKeyPair = multiSigAddressEntry.getKeyPair();
        if (!Arrays.equals(pubKey, multiSigAddressEntry.getPubKey())) {
            log.error("Pub Key from AddressEntry does not match key pair from trade data. Trade ID={}\n" +
                    "We try to find the keypair in the wallet with the pubKey we found in the trade data.", tradeId);
            multiSigKeyPair = findKeyFromPubKey(pubKey);
        }
    } else {
        log.error("multiSigAddressEntry not found for trade ID={}.\n" +
                "We try to find the keypair in the wallet with the pubKey we found in the trade data.", tradeId);
        multiSigKeyPair = findKeyFromPubKey(pubKey);
    }

    return multiSigKeyPair;
}
 
Example #4
Source File: MarriedKeyChain.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void maybeLookAheadScripts() {
    super.maybeLookAheadScripts();
    int numLeafKeys = getLeafKeys().size();

    checkState(marriedKeysRedeemData.size() <= numLeafKeys, "Number of scripts is greater than number of leaf keys");
    if (marriedKeysRedeemData.size() == numLeafKeys)
        return;

    maybeLookAhead();
    for (DeterministicKey followedKey : getLeafKeys()) {
        RedeemData redeemData = getRedeemData(followedKey);
        Script scriptPubKey = ScriptBuilder.createP2SHOutputScript(redeemData.redeemScript);
        marriedKeysRedeemData.put(ByteString.copyFrom(scriptPubKey.getPubKeyHash()), redeemData);
    }
}
 
Example #5
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public byte[] signDelayedPayoutTx(Transaction delayedPayoutTx,
                                  DeterministicKey myMultiSigKeyPair,
                                  byte[] buyerPubKey,
                                  byte[] sellerPubKey)
        throws AddressFormatException, TransactionVerificationException {

    Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
    Sha256Hash sigHash = delayedPayoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);
    checkNotNull(myMultiSigKeyPair, "myMultiSigKeyPair must not be null");
    if (myMultiSigKeyPair.isEncrypted()) {
        checkNotNull(aesKey);
    }

    ECKey.ECDSASignature mySignature = myMultiSigKeyPair.sign(sigHash, aesKey).toCanonicalised();
    WalletService.printTx("delayedPayoutTx for sig creation", delayedPayoutTx);
    WalletService.verifyTransaction(delayedPayoutTx);
    return mySignature.encodeToDER();
}
 
Example #6
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
public void createWallet2(String passphrase, Runnable callback) {

        wallet = new Wallet(params);
        DeterministicSeed seed = wallet.getKeyChainSeed();
        mnemonicKey = Joiner.on(" ").join(seed.getMnemonicCode());
        sharedManager.setLastSyncedBlock(Coders.encodeBase64(mnemonicKey));

        walletFriendlyAddress = wallet.currentReceiveAddress().toString();

        ChildNumber childNumber = new ChildNumber(ChildNumber.HARDENED_BIT);
        DeterministicKey de = wallet.getKeyByPath(ImmutableList.of(childNumber));
        xprvKey = de.serializePrivB58(params);

        wifKey = wallet.currentReceiveKey().getPrivateKeyAsWiF(params);

        callback.run();
    }
 
Example #7
Source File: WalletProtobufSerializerTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testRoundTripMarriedWallet() throws Exception {
    // create 2-of-2 married wallet
    myWallet = new Wallet(UNITTEST);
    final DeterministicKeyChain partnerChain = new DeterministicKeyChain(new SecureRandom());
    DeterministicKey partnerKey = DeterministicKey.deserializeB58(null, partnerChain.getWatchingKey().serializePubB58(UNITTEST), UNITTEST);
    MarriedKeyChain chain = MarriedKeyChain.builder()
            .random(new SecureRandom())
            .followingKeys(partnerKey)
            .threshold(2).build();
    myWallet.addAndActivateHDChain(chain);

    myAddress = myWallet.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);

    Wallet wallet1 = roundTrip(myWallet);
    assertEquals(0, wallet1.getTransactions(true).size());
    assertEquals(Coin.ZERO, wallet1.getBalance());
    assertEquals(2, wallet1.getActiveKeyChain().getSigsRequiredToSpend());
    assertEquals(myAddress, wallet1.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS));
}
 
Example #8
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
public String createTokenHexTx(String abiParams, String tokenAddress,
                               String fee, BigDecimal feePerKb, List<ContractUnspentOutput> unspentOutputs,
                               String description) throws Exception {

    final int gasLimit = 300000;
    final int gasPrice = 40;

    ContractBuilder contractBuilder = new ContractBuilder();
    Script script = contractBuilder.createMethodScript(abiParams, gasLimit, gasPrice, tokenAddress);

    DeterministicKey ownDeterKey = extractWalletDeterministicKey();

    return contractBuilder.createTransactionHash(script, unspentOutputs, gasLimit, gasPrice,
            feePerKb, fee,
            context, params, extractWalletFriendlyAddress(), wallet, description, ownDeterKey);
}
 
Example #9
Source File: BuyerSignsDelayedPayoutTx.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void run() {
    try {
        runInterceptHook();

        Transaction preparedDelayedPayoutTx = checkNotNull(processModel.getPreparedDelayedPayoutTx());
        BtcWalletService btcWalletService = processModel.getBtcWalletService();
        String id = processModel.getOffer().getId();

        byte[] buyerMultiSigPubKey = processModel.getMyMultiSigPubKey();
        DeterministicKey myMultiSigKeyPair = btcWalletService.getMultiSigKeyPair(id, buyerMultiSigPubKey);

        checkArgument(Arrays.equals(buyerMultiSigPubKey,
                btcWalletService.getOrCreateAddressEntry(id, AddressEntry.Context.MULTI_SIG).getPubKey()),
                "buyerMultiSigPubKey from AddressEntry must match the one from the trade data. trade id =" + id);
        byte[] sellerMultiSigPubKey = processModel.getTradingPeer().getMultiSigPubKey();
        byte[] delayedPayoutTxSignature = processModel.getTradeWalletService().signDelayedPayoutTx(preparedDelayedPayoutTx, myMultiSigKeyPair, buyerMultiSigPubKey, sellerMultiSigPubKey);
        processModel.setDelayedPayoutTxSignature(delayedPayoutTxSignature);

        complete();
    } catch (Throwable t) {
        failed(t);
    }
}
 
Example #10
Source File: BtcWalletService.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
public DeterministicKey getMultiSigKeyPair(String tradeId, byte[] pubKey) {
    Optional<AddressEntry> multiSigAddressEntryOptional = getAddressEntry(tradeId, AddressEntry.Context.MULTI_SIG);
    DeterministicKey multiSigKeyPair;
    if (multiSigAddressEntryOptional.isPresent()) {
        AddressEntry multiSigAddressEntry = multiSigAddressEntryOptional.get();
        multiSigKeyPair = multiSigAddressEntry.getKeyPair();
        if (!Arrays.equals(pubKey, multiSigAddressEntry.getPubKey())) {
            log.error("Pub Key from AddressEntry does not match key pair from trade data. Trade ID={}\n" +
                    "We try to find the keypair in the wallet with the pubKey we found in the trade data.", tradeId);
            multiSigKeyPair = findKeyFromPubKey(pubKey);
        }
    } else {
        log.error("multiSigAddressEntry not found for trade ID={}.\n" +
                "We try to find the keypair in the wallet with the pubKey we found in the trade data.", tradeId);
        multiSigKeyPair = findKeyFromPubKey(pubKey);
    }

    return multiSigKeyPair;
}
 
Example #11
Source File: WalletManager.java    From token-core-android with Apache License 2.0 6 votes vote down vote up
public static Wallet findWalletByMnemonic(String chainType, String network, String mnemonic, String path, String segWit) {
  List<String> mnemonicCodes = Arrays.asList(mnemonic.split(" "));
  MnemonicUtil.validateMnemonics(mnemonicCodes);
  DeterministicSeed seed = new DeterministicSeed(mnemonicCodes, null, "", 0L);
  DeterministicKeyChain keyChain = DeterministicKeyChain.builder().seed(seed).build();
  if (Strings.isNullOrEmpty(path)) {
    throw new TokenException(Messages.INVALID_MNEMONIC_PATH);
  }

  if (ChainType.BITCOIN.equalsIgnoreCase(chainType)) {
    path += "/0/0";
  }

  DeterministicKey key = keyChain.getKeyByPath(BIP44Util.generatePath(path), true);
  Network net = new Network(network);
  String address = AddressCreatorManager.getInstance(chainType, net.isMainnet(), segWit).fromPrivateKey(key.getPrivateKeyAsHex());
  return findWalletByAddress(chainType, address);
}
 
Example #12
Source File: MarriedKeyChain.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void maybeLookAheadScripts() {
    super.maybeLookAheadScripts();
    int numLeafKeys = getLeafKeys().size();

    checkState(marriedKeysRedeemData.size() <= numLeafKeys, "Number of scripts is greater than number of leaf keys");
    if (marriedKeysRedeemData.size() == numLeafKeys)
        return;

    maybeLookAhead();
    for (DeterministicKey followedKey : getLeafKeys()) {
        RedeemData redeemData = getRedeemData(followedKey);
        Script scriptPubKey = ScriptBuilder.createP2SHOutputScript(redeemData.redeemScript);
        marriedKeysRedeemData.put(ByteString.copyFrom(scriptPubKey.getPubKeyHash()), redeemData);
    }
}
 
Example #13
Source File: SeedTest.java    From snowblossom with Apache License 2.0 6 votes vote down vote up
private void testVector(String seed, String data, String pw, String xprv)
  throws Exception
{
  ByteString expected = HexUtil.hexStringToBytes(data);

  ByteString found = SeedUtil.decodeSeed(seed, pw);

  Assert.assertEquals( HexUtil.getHexString(expected), HexUtil.getHexString(found));

  DeterministicKey dk = HDKeyDerivation.createMasterPrivateKey(found.toByteArray());
  DeterministicHierarchy dh = new DeterministicHierarchy(dk);

  DeterministicKey dk_acct = dh.get( ImmutableList.of(
    new ChildNumber(44,true),
    new ChildNumber(0,true),
    new ChildNumber(0,true)),
    true, true);

  Assert.assertEquals(
    xprv,
    dk_acct.serializePrivB58(org.bitcoinj.params.MainNetParams.get()));
}
 
Example #14
Source File: BTChipHWWallet.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
private DeterministicKey internalGetPubKey() throws BTChipException {
    if (mCachedPubkey == null) {
        final BTChipDongle.BTChipPublicKey walletKey = mDongle.getWalletPublicKey(getPath());
        final byte[] compressedPubKey = KeyUtils.compressPublicKey(walletKey.getPublicKey());
        mCachedPubkey = HDKey.createMasterKey(walletKey.getChainCode(), compressedPubKey);
    }
    return mCachedPubkey;
}
 
Example #15
Source File: AddressEntry.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public AddressEntry(@NotNull DeterministicKey keyPair,
                    Context context,
                    @Nullable String offerId) {
    this.keyPair = keyPair;
    this.context = context;
    this.offerId = offerId;
    pubKey = keyPair.getPubKey();
    pubKeyHash = keyPair.getPubKeyHash();
}
 
Example #16
Source File: MarriedKeyChain.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
/** Create a new married key and return the matching output script */
@Override
public Script freshOutputScript(KeyPurpose purpose) {
    DeterministicKey followedKey = getKey(purpose);
    ImmutableList.Builder<ECKey> keys = ImmutableList.<ECKey>builder().add(followedKey);
    for (DeterministicKeyChain keyChain : followingKeyChains) {
        DeterministicKey followingKey = keyChain.getKey(purpose);
        checkState(followedKey.getChildNumber().equals(followingKey.getChildNumber()), "Following keychains should be in sync");
        keys.add(followingKey);
    }
    List<ECKey> marriedKeys = keys.build();
    Script redeemScript = ScriptBuilder.createRedeemScript(sigsRequiredToSpend, marriedKeys);
    return ScriptBuilder.createP2SHOutputScript(redeemScript);
}
 
Example #17
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlockByXPRV2(String xprv, Runnable callback) {
    xprv = xprv.trim();
    try {
        DeterministicKey dk01 = DeterministicKey.deserializeB58(xprv, params);
        String privhex = dk01.getPrivateKeyAsHex();
        ECKey ecKey001 = ECKey.fromPrivate(Hex.decode(privhex));
        KeyChainGroup kcg = new KeyChainGroup(params, dk01.dropPrivateBytes().dropParent());
        kcg.importKeys(ecKey001);
        wallet = new Wallet(params, kcg);
        sharedManager.setLastSyncedBlock(Coders.encodeBase64(xprv));
        walletFriendlyAddress = wallet.currentReceiveAddress().toString();
        xprvKey = xprv;
    } catch (IllegalArgumentException iae) {
        FirebaseCrash.report(iae);
        Log.e("psd", "restoreFromBlockByXPRV2: " + iae.toString());
        callback.run();
        return;
    }

    callback.run();

    RequestorBtc.getUTXOListBtgNew(wallet.currentReceiveAddress().toString(), new ApiMethods.RequestListener() {
        @Override
        public void onSuccess(Object response) {
            List<UTXOItem> utxos = (List<UTXOItem>)response;
            setUTXO(utxos);
        }

        @Override
        public void onFailure(String msg) {

        }
    });
}
 
Example #18
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlock2(String mnemonicCode, Runnable callback) {
    if (mnemonicCode.charAt(mnemonicCode.length() - 1) == ' ') {
        mnemonicCode = mnemonicCode.substring(0, mnemonicCode.length() - 1);
    }

    DeterministicSeed seed = new DeterministicSeed(Splitter.on(' ').splitToList(mnemonicCode), null, "", 0);

    wallet = Wallet.fromSeed(params, seed);
    mnemonicKey = Joiner.on(" ").join(seed.getMnemonicCode());
    sharedManager.setLastSyncedBlock(Coders.encodeBase64(mnemonicKey));
    walletFriendlyAddress = wallet.currentReceiveAddress().toString();

    ChildNumber childNumber = new ChildNumber(ChildNumber.HARDENED_BIT);
    DeterministicKey de = wallet.getKeyByPath(ImmutableList.of(childNumber));
    xprvKey = de.serializePrivB58(params);

    wifKey = wallet.currentReceiveKey().getPrivateKeyAsWiF(params);

    callback.run();

    RequestorBtc.getUTXOListLtcNew(wallet.currentReceiveAddress().toString(), new ApiMethods.RequestListener() {
        @Override
        public void onSuccess(Object response) {
            List<UTXOItem> utxos = (List<UTXOItem>)response;
            setUTXO(utxos);
        }

        @Override
        public void onFailure(String msg) {

        }
    });
}
 
Example #19
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlockByXPRV(String xprv, WalletCreationCallback callback) {
    xprv = xprv.trim();
    try {
        DeterministicKey dk01 = DeterministicKey.deserializeB58(xprv, params);
        String privhex = dk01.getPrivateKeyAsHex();
        ECKey ecKey001 = ECKey.fromPrivate(Hex.decode(privhex));
        KeyChainGroup kcg = new KeyChainGroup(params, dk01.dropPrivateBytes().dropParent());
        kcg.importKeys(ecKey001);
        wallet = new Wallet(params, kcg);
        walletFriendlyAddress = wallet.currentReceiveAddress().toString();
        xprvKey = xprv;
    } catch (IllegalArgumentException iae) {
        FirebaseCrash.report(iae);
        Log.e("psd", "restoreFromBlockByXPRV: " + iae.toString());
        callback.onWalletCreated(wallet);
        return;
    }

    callback.onWalletCreated(wallet);

    RequestorBtc.getUTXOListLtcNew(wallet.currentReceiveAddress().toString(), new ApiMethods.RequestListener() {
        @Override
        public void onSuccess(Object response) {
            List<UTXOItem> utxos = (List<UTXOItem>)response;
            setUTXO(utxos);
        }

        @Override
        public void onFailure(String msg) {

        }
    });
}
 
Example #20
Source File: KeycardTest.java    From status-keycard with Apache License 2.0 5 votes vote down vote up
private void verifyKeyDerivation(KeyPair keyPair, byte[] chainCode, int[] path) throws Exception {
  byte[] hash = sha256(new byte[8]);
  APDUResponse resp = cmdSet.sign(hash);
  assertEquals(0x9000, resp.getSw());
  byte[] sig = resp.getData();
  byte[] publicKey = extractPublicKeyFromSignature(sig);
  sig = extractSignature(sig);

  if (cmdSet.getApplicationInfo().hasKeyManagementCapability()) {
    DeterministicKey key = deriveKey(keyPair, chainCode, path);

    assertTrue(key.verify(hash, sig));
    assertArrayEquals(key.getPubKeyPoint().getEncoded(false), publicKey);
  } else {
    Signature signature = Signature.getInstance("SHA256withECDSA", "BC");

    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256k1");
    ECPublicKeySpec cardKeySpec = new ECPublicKeySpec(ecSpec.getCurve().decodePoint(publicKey), ecSpec);
    ECPublicKey cardKey = (ECPublicKey) KeyFactory.getInstance("ECDSA", "BC").generatePublic(cardKeySpec);

    signature.initVerify(cardKey);
    signature.update(new byte[8]);
    assertTrue(signature.verify(sig));
  }

  resp = cmdSet.getStatus(KeycardApplet.GET_STATUS_P1_KEY_PATH);
  assertEquals(0x9000, resp.getSw());
  byte[] rawPath = resp.getData();

  assertEquals(path.length * 4, rawPath.length);

  for (int i = 0; i < path.length; i++) {
    int k = path[i];
    int k1 = (rawPath[i * 4] << 24) | (rawPath[(i * 4) + 1] << 16) | (rawPath[(i * 4) + 2] << 8) | rawPath[(i * 4) + 3];
    assertEquals(k, k1);
  }
}
 
Example #21
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlock(String mnemonicCode, WalletCreationCallback callback) {
    mnemonicCode = mnemonicCode.trim();
    if (mnemonicCode.equals("")) {
        callback.onWalletCreated(null);
        return;
    }

    DeterministicSeed seed = new DeterministicSeed(Splitter.on(' ').splitToList(mnemonicCode), null, "", 0);

    wallet = Wallet.fromSeed(params, seed);
    mnemonicKey = Joiner.on(" ").join(seed.getMnemonicCode());
    //sharedManager.setLastSyncedBlock(Coders.encodeBase64(mnemonicKey));
    walletFriendlyAddress = wallet.currentReceiveAddress().toString();

    ChildNumber childNumber = new ChildNumber(ChildNumber.HARDENED_BIT);
    DeterministicKey de = wallet.getKeyByPath(ImmutableList.of(childNumber));
    xprvKey = de.serializePrivB58(params);

    wifKey = wallet.currentReceiveKey().getPrivateKeyAsWiF(params);

    callback.onWalletCreated(wallet);

    RequestorBtc.getUTXOListLtcNew(wallet.currentReceiveAddress().toString(), new ApiMethods.RequestListener() {
        @Override
        public void onSuccess(Object response) {
            List<UTXOItem> utxos = (List<UTXOItem>)response;
            setUTXO(utxos);
        }

        @Override
        public void onFailure(String msg) {

        }
    });
}
 
Example #22
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlockByXPRV2(String xprv, Runnable callback) {
    xprv = xprv.trim();
    try {
        DeterministicKey dk01 = DeterministicKey.deserializeB58(xprv, params);
        String privhex = dk01.getPrivateKeyAsHex();
        ECKey ecKey001 = ECKey.fromPrivate(Hex.decode(privhex));
        KeyChainGroup kcg = new KeyChainGroup(params, dk01.dropPrivateBytes().dropParent());
        kcg.importKeys(ecKey001);
        wallet = new Wallet(params, kcg);
        sharedManager.setLastSyncedBlock(Coders.encodeBase64(xprv));
        walletFriendlyAddress = wallet.currentReceiveAddress().toString();
        walletFriendlyAddress = testReadonlyAddress == null ? walletFriendlyAddress : testReadonlyAddress;
        xprvKey = xprv;
    } catch (IllegalArgumentException iae) {
        FirebaseCrash.report(iae);
        Log.e("psd", "restoreFromBlockByXPRV2: " + iae.toString());
        callback.run();
        return;
    }

    callback.run();

    RequestorBtc.getUTXOListKmdNew(walletFriendlyAddress, new ApiMethods.RequestListener() {
        @Override
        public void onSuccess(Object response) {
            List<UTXOItem> utxos = (List<UTXOItem>)response;
            setUTXO(utxos);
        }

        @Override
        public void onFailure(String msg) {

        }
    });
}
 
Example #23
Source File: BtcWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
void encryptWallet(KeyCrypterScrypt keyCrypterScrypt, KeyParameter key) {
    super.encryptWallet(keyCrypterScrypt, key);
    addressEntryList.stream().forEach(e -> {
        final DeterministicKey keyPair = e.getKeyPair();
        if (keyPair.isEncrypted())
            e.setDeterministicKey(keyPair.encrypt(keyCrypterScrypt, key));
    });
    addressEntryList.persist();
}
 
Example #24
Source File: MarriedKeyChain.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
/** Get the redeem data for a key in this married chain */
@Override
public RedeemData getRedeemData(DeterministicKey followedKey) {
    List<ECKey> marriedKeys = getMarriedKeysWithFollowed(followedKey);
    Script redeemScript = ScriptBuilder.createRedeemScript(sigsRequiredToSpend, marriedKeys);
    return RedeemData.of(marriedKeys, redeemScript);
}
 
Example #25
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlockByXPRV2(String xprv, Runnable callback) {
    xprv = xprv.trim();
    try {
        DeterministicKey dk01 = DeterministicKey.deserializeB58(xprv, params);
        String privhex = dk01.getPrivateKeyAsHex();
        ECKey ecKey001 = ECKey.fromPrivate(Hex.decode(privhex));
        KeyChainGroup kcg = new KeyChainGroup(params, dk01.dropPrivateBytes().dropParent());
        kcg.importKeys(ecKey001);
        wallet = new Wallet(params, kcg);
        sharedManager.setLastSyncedBlock(Coders.encodeBase64(xprv));
        walletFriendlyAddress = wallet.currentReceiveAddress().toString();
        xprvKey = xprv;
    } catch (IllegalArgumentException iae) {
        FirebaseCrash.report(iae);
        Log.e("psd", "restoreFromBlockByXPRV2: " + iae.toString());
        callback.run();
        return;
    }

    callback.run();

    RequestorBtc.getUTXOListSbtcNew(wallet.currentReceiveAddress().toString(), new ApiMethods.RequestListener() {
        @Override
        public void onSuccess(Object response) {
            List<UTXOItem> utxos = (List<UTXOItem>)response;
            setUTXO(utxos);
        }

        @Override
        public void onFailure(String msg) {

        }
    });
}
 
Example #26
Source File: MarriedKeyChain.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
/** Get the redeem data for a key in this married chain */
@Override
public RedeemData getRedeemData(DeterministicKey followedKey) {
    List<ECKey> marriedKeys = getMarriedKeysWithFollowed(followedKey);
    Script redeemScript = ScriptBuilder.createRedeemScript(sigsRequiredToSpend, marriedKeys);
    return RedeemData.of(marriedKeys, redeemScript);
}
 
Example #27
Source File: SeedUtil.java    From snowblossom with Apache License 2.0 5 votes vote down vote up
public static ByteString getSeedIdFromXpub(String xpub)
{
  DeterministicKey account_key = DeterministicKey.deserializeB58(xpub, org.bitcoinj.params.MainNetParams.get());

  ByteString seed_id = ByteString.copyFrom(account_key.getIdentifier());

  return seed_id;
}
 
Example #28
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlockByXPRV2(String xprv, Runnable callback) {
    xprv = xprv.trim();
    try {
        DeterministicKey dk01 = DeterministicKey.deserializeB58(xprv, params);
        String privhex = dk01.getPrivateKeyAsHex();
        ECKey ecKey001 = ECKey.fromPrivate(Hex.decode(privhex));
        KeyChainGroup kcg = new KeyChainGroup(params, dk01.dropPrivateBytes().dropParent());
        kcg.importKeys(ecKey001);
        wallet = new Wallet(params, kcg);
        sharedManager.setLastSyncedBlock(Coders.encodeBase64(xprv));
        walletFriendlyAddress = wallet.currentReceiveAddress().toString();
        xprvKey = xprv;
    } catch (IllegalArgumentException iae) {
        FirebaseCrash.report(iae);
        Log.e("psd", "restoreFromBlockByXPRV2: " + iae.toString());
        callback.run();
        return;
    }

    callback.run();

    RequestorBtc.getUTXOListDgbNew(wallet.currentReceiveAddress().toString(), new ApiMethods.RequestListener() {
        @Override
        public void onSuccess(Object response) {
            List<UTXOItemDgb> utxos = (List<UTXOItemDgb>)response;
            setUTXO(utxos);
        }

        @Override
        public void onFailure(String msg) {

        }
    });
}
 
Example #29
Source File: SWWallet.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Override
public byte[] signBitcoinMessageHash(final byte[] sha256d, final int[] path) {
    if (sha256d.length != Wally.SHA256_LEN)
        return null; // Dont sign anything but a message hash
    if (path.length < 2 || path[0] != 0x4741b11e || path[1] != HDKey.BRANCH_MESSAGES)
        return null; // Dont sign on any path except messages paths

    final byte[] sha256dHex = Wally.hex_from_bytes(sha256d).getBytes();
    final byte[] messageHash = Wally.format_bitcoin_message(sha256dHex,
                                                            Wally.BITCOIN_MESSAGE_FLAG_HASH);
    DeterministicKey key = mRootKey;
    for (int i : path)
        key = HDKey.deriveChildKey(key, i);
    return ECKey.fromPrivate(key.getPrivKey()).sign(Sha256Hash.wrap(messageHash)).encodeToDER();
}
 
Example #30
Source File: MarriedKeyChain.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
private List<ECKey> getMarriedKeysWithFollowed(DeterministicKey followedKey) {
    ImmutableList.Builder<ECKey> keys = ImmutableList.builder();
    for (DeterministicKeyChain keyChain : followingKeyChains) {
        keyChain.maybeLookAhead();
        keys.add(keyChain.getKeyByPath(followedKey.getPath()));
    }
    keys.add(followedKey);
    return keys.build();
}