Java Code Examples for org.bitcoinj.crypto.DeterministicKey

The following examples show how to use org.bitcoinj.crypto.DeterministicKey. These examples are extracted from open source projects. 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 Project: bcm-android   Source File: MarriedKeyChain.java    License: 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 2
/**
 * 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
@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 4
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 5
Source Project: token-core-android   Source File: WalletManager.java    License: 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 6
Source Project: java-stratum   Source File: ElectrumMultiWalletTest.java    License: 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 7
Source Project: snowblossom   Source File: SeedTest.java    License: 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 8
Source Project: GreenBits   Source File: MarriedKeyChain.java    License: 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 9
@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
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 11
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 12
Source Project: bisq   Source File: BtcWalletService.java    License: 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 13
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 14
Source Project: status-keycard   Source File: KeycardTest.java    License: Apache License 2.0 5 votes vote down vote up
private DeterministicKey deriveKey(KeyPair keyPair, byte[] chainCode, int[] path) {
  DeterministicKey key = HDKeyDerivation.createMasterPrivKeyFromBytes(((org.bouncycastle.jce.interfaces.ECPrivateKey) keyPair.getPrivate()).getD().toByteArray(), chainCode);

  for (int i : path) {
    key = HDKeyDerivation.deriveChildKey(key, new ChildNumber(i));
  }

  return key;
}
 
Example 15
Source Project: bcm-android   Source File: MarriedKeyChain.java    License: 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();
}
 
Example 16
Source Project: bcm-android   Source File: MarriedKeyChain.java    License: 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 17
Source Project: GreenBits   Source File: HDKey.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static DeterministicKey[] getGAPublicKeys(final int subAccount, final Integer pointer, final Network network) {
    final DeterministicKey[] ret = new DeterministicKey[2];
    synchronized (mServerKeys) {
        // Fetch the parent key. This is expensive so we cache it
        if ((ret[0] = mServerKeys.get(subAccount)) == null)
            mServerKeys.put(subAccount, ret[0] = getServerKeyImpl(subAccount, network));
    }
    // Compute the child key if we were asked for it
    if (pointer != null)
        ret[1] = deriveChildKey(ret[0], pointer); // Child
    return ret;
}
 
Example 18
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 19
@Override
void decryptWallet(@NotNull KeyParameter key) {
    super.decryptWallet(key);

    addressEntryList.stream().forEach(e -> {
        final DeterministicKey keyPair = e.getKeyPair();
        if (keyPair.isEncrypted())
            e.setDeterministicKey(keyPair.decrypt(key));
    });
    addressEntryList.persist();
}
 
Example 20
Source Project: bisq   Source File: AddressEntryList.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private void updateList(Transaction tx) {
    tx.getOutputs().stream()
            .filter(output -> output.isMine(wallet))
            .map(output -> output.getAddressFromP2PKHScript(wallet.getNetworkParameters()))
            .filter(Objects::nonNull)
            .filter(address -> !listContainsEntryWithAddress(address.toBase58()))
            .map(address -> (DeterministicKey) wallet.findKeyFromPubHash(address.getHash160()))
            .filter(Objects::nonNull)
            .map(deterministicKey -> new AddressEntry(deterministicKey, AddressEntry.Context.AVAILABLE))
            .forEach(addressEntry -> list.add(addressEntry));
}
 
Example 21
public void onWalletReady(Wallet wallet) {
    this.wallet = wallet;

    if (list != null) {
        list.forEach(addressEntry -> {
            DeterministicKey keyFromPubHash = (DeterministicKey) wallet.findKeyFromPubHash(addressEntry.getPubKeyHash());
            if (keyFromPubHash != null) {
                addressEntry.setDeterministicKey(keyFromPubHash);
            } else {
                log.error("Key from addressEntry not found in that wallet " + addressEntry.toString());
            }
        });
    } else {
        list = new ArrayList<>();
        add(new AddressEntry(wallet.freshReceiveKey(), AddressEntry.Context.ARBITRATOR));

        // In case we restore from seed words and have balance we need to add the relevant addresses to our list:
        if (wallet.getBalance().isPositive()) {
            wallet.getIssuedReceiveAddresses().forEach(address -> {
                log.info("Create AddressEntry for address={}", address);
                add(new AddressEntry((DeterministicKey) wallet.findKeyFromPubHash(address.getHash160()), AddressEntry.Context.AVAILABLE));
            });
        }

        persist();
    }
}
 
Example 22
Source Project: java-stratum   Source File: ElectrumMultiWallet.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
void subscribeToKeys() {
    final NetworkParameters params = wallet.getParams();
    List<DeterministicKeyChain> chains = wallet.getKeychain().getDeterministicKeyChains();
    Set<Address> addresses = Sets.newHashSet();
    for (DeterministicKeyChain chain : chains) {
        chain.maybeLookAhead();
        if (chain instanceof AddressableKeyChain) {
            for (ByteString bytes : ((AddressableKeyChain) chain).getP2SHHashes()) {
                addresses.add(Address.fromP2SHHash(params, bytes.toByteArray()));
            }
        } else {
            for (ECKey ecKey : chain.getLeafKeys()) {
                DeterministicKey key = (DeterministicKey) ecKey;
                addresses.add(key.toAddress(params));
            }
        }
    }

    for (final Address address : addresses) {
        final String addressString = address.toString();
        downloadFutures.put(addressString, SettableFuture.<Integer>create());
        client.subscribe(address);
    }

    downloadFuture = Futures.allAsList(downloadFutures.values());
    Futures.addCallback(downloadFuture, new FutureCallback<List<Integer>>() {
        @Override
        public void onSuccess(List<Integer> result) {
            isHistorySynced = true;
            notifyHeight(store.getHeight());
        }

        @Override
        public void onFailure(Throwable t) {
            log.error("failed to sync history", t);
        }
    });
}
 
Example 23
Source Project: token-core-android   Source File: HDMnemonicKeystore.java    License: Apache License 2.0 5 votes vote down vote up
public HDMnemonicKeystore(Metadata metadata, String password, List<String> mnemonics, String path, String id) {
  MnemonicUtil.validateMnemonics(mnemonics);
  DeterministicSeed seed = new DeterministicSeed(mnemonics, null, "", 0L);
  DeterministicKeyChain keyChain = DeterministicKeyChain.builder().seed(seed).build();
  this.mnemonicPath = path;

  DeterministicKey parent = keyChain.getKeyByPath(BIP44Util.generatePath(path), true);
  NetworkParameters networkParameters = metadata.isMainNet() ? MainNetParams.get() : TestNet3Params.get();
  this.xpub = parent.serializePubB58(networkParameters);
  String xprv = parent.serializePrivB58(networkParameters);
  DeterministicKey mainAddressKey = keyChain.getKeyByPath(BIP44Util.generatePath(path + "/0/0"), true);
  if (Metadata.P2WPKH.equals(metadata.getSegWit())) {
    this.address = new SegWitBitcoinAddressCreator(networkParameters).fromPrivateKey(mainAddressKey.getPrivateKeyAsHex());
  } else {
    this.address = mainAddressKey.toAddress(networkParameters).toBase58();
  }
  if (metadata.getTimestamp() == 0) {
    metadata.setTimestamp(DateUtil.getUTCTime());
  }
  metadata.setWalletType(Metadata.HD);

  this.crypto = Crypto.createPBKDF2CryptoWithKDFCached(password, xprv.getBytes(Charset.forName("UTF-8")));
  this.metadata = metadata;
  this.encMnemonic = crypto.deriveEncPair(password, Joiner.on(" ").join(mnemonics).getBytes());
  this.crypto.clearCachedDerivedKey();

  this.version = VERSION;
  this.info = new Info();
  this.id = Strings.isNullOrEmpty(id) ? UUID.randomUUID().toString() : id;
}
 
Example 24
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();
}
 
Example 25
Source Project: token-core-android   Source File: ValidatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testImportingValidationPrivateKey() {
  Metadata metadata = new Metadata();
  metadata.setSource(Metadata.FROM_PRIVATE);
  metadata.setChainType(ChainType.ETHEREUM);
  DeterministicSeed seed = new DeterministicSeed(Arrays.asList(SampleKey.MNEMONIC.split(" ")), null, "", 0L);
  DeterministicKeyChain keyChain = DeterministicKeyChain.builder().seed(seed).build();
  for (int i=0; i< 100; i++) {
    String path = String.format("m/44'/60'/0'/0/%d", i);
    DeterministicKey key = keyChain.getKeyByPath(BIP44Util.generatePath(path), true);
    new PrivateKeyValidator(key.getPrivateKeyAsHex()).validate();
  }

}
 
Example 26
Source Project: GreenBits   Source File: SWWallet.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public String[] signChallenge(final String challengeString, final String[] challengePath) {

    // Generate a path for the challenge. This is really a nonce so we aren't
    // tricked into signing the same challenge (and thus revealing our key)
    // by a compromised server.
    final byte[] path = CryptoHelper.randomBytes(8);

    // Return the path to the caller for them to pass in the server RPC call
    challengePath[0] = Wally.hex_from_bytes(path);

    // Derive the private key for signing the challenge from the path
    DeterministicKey key = mRootKey;
    for (int i = 0; i < path.length / 2; ++i) {
        final int step = u8(path[i * 2]) * 256 + u8(path[i * 2 + 1]);
        key = HDKey.deriveChildKey(key, step);
    }

    // Get rid of initial 0 byte if challenge > 2^31
    // FIXME: The server should not send us challenges that we have to munge!
    byte[] challenge = new BigInteger(challengeString).toByteArray();
    if (challenge.length == 33 && challenge[0] == 0)
        challenge = Arrays.copyOfRange(challenge, 1, 33);

    // Compute and return the challenge signatures
    final ECKey.ECDSASignature sig;
    sig = ECKey.fromPrivate(key.getPrivKey()).sign(Sha256Hash.wrap(challenge));
    return new String[]{ sig.r.toString(), sig.s.toString() };
}
 
Example 27
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 28
Source Project: GreenBits   Source File: MarriedKeyChain.java    License: 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 29
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 30
Source Project: bisq   Source File: BtcWalletService.java    License: 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();
}