Java Code Examples for org.bitcoinj.wallet.DeterministicKeyChain

The following examples show how to use org.bitcoinj.wallet.DeterministicKeyChain. 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
@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 2
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 3
Source Project: token-core-android   Source File: V3MnemonicKeystore.java    License: Apache License 2.0 6 votes vote down vote up
private V3MnemonicKeystore(Metadata metadata, String password, List<String> mnemonicCodes, String path, String id) {
  MnemonicUtil.validateMnemonics(mnemonicCodes);
  DeterministicSeed seed = new DeterministicSeed(mnemonicCodes, null, "", 0L);
  DeterministicKeyChain keyChain = DeterministicKeyChain.builder().seed(seed).build();

  this.mnemonicPath = path;
  List<ChildNumber> zeroPath = BIP44Util.generatePath(path);

  byte[] prvKeyBytes = keyChain.getKeyByPath(zeroPath, true).getPrivKeyBytes();
  this.crypto = Crypto.createPBKDF2CryptoWithKDFCached(password, prvKeyBytes);
  this.encMnemonic = crypto.deriveEncPair(password, Joiner.on(" ").join(mnemonicCodes).getBytes());
  this.crypto.clearCachedDerivedKey();

  this.address = AddressCreatorManager.getInstance(metadata.getChainType(), metadata.isMainNet(), metadata.getSegWit()).fromPrivateKey(prvKeyBytes);
  metadata.setTimestamp(DateUtil.getUTCTime());
  metadata.setWalletType(Metadata.V3);
  this.metadata = metadata;
  this.version = VERSION;
  this.id = Strings.isNullOrEmpty(id) ? UUID.randomUUID().toString() : id;
}
 
Example 4
@Test
public void testRoundTripMarriedWallet() throws Exception {
    // create 2-of-2 married wallet
    myWallet = new Wallet(PARAMS);
    final DeterministicKeyChain partnerChain = new DeterministicKeyChain(new SecureRandom());
    DeterministicKey partnerKey = DeterministicKey.deserializeB58(null, partnerChain.getWatchingKey().serializePubB58(PARAMS), PARAMS);
    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 5
Source Project: java-stratum   Source File: ElectrumMultiWalletTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    params = NetworkParameters.fromID(NetworkParameters.ID_UNITTESTNET);
    mapper = new ObjectMapper();

    DeterministicSeed seed = new DeterministicSeed("correct battery horse staple", null, "", 0);
    DeterministicKeyChain chain =
            DeterministicKeyChain.builder()
                    .seed(seed)
                    .build();
    KeyChainGroup group = new KeyChainGroup(params);
    group.addAndActivateHDChain(chain);
    wallet = new SmartWallet(params, group);
    wallet.setKeychainLookaheadSize(10);

    control = EasyMock.createStrictControl();
    client = control.createMock(StratumClient.class);
    expect(client.getConnectedAddresses()).andStubReturn(Lists.newArrayList(new InetSocketAddress(InetAddress.getLocalHost(), 0)));
    expect(client.getPeerVersion()).andStubReturn("1.0");
    store = control.createMock(HeadersStore.class);
    stratumChain = control.createMock(StratumChain.class);
    expect(stratumChain.getPeerHeight()).andStubReturn(100L);
    expect(store.get(340242)).andStubReturn(params.getGenesisBlock().cloneAsHeader());
    multiWallet = new ElectrumMultiWallet(wallet, BASE_DIRECTORY);
    multiWallet.start(client, stratumChain, store);
}
 
Example 6
@Test
public void testRoundTripMarriedWallet() throws Exception {
    // create 2-of-2 married wallet
    myWallet = new Wallet(PARAMS);
    final DeterministicKeyChain partnerChain = new DeterministicKeyChain(new SecureRandom());
    DeterministicKey partnerKey = DeterministicKey.deserializeB58(null, partnerChain.getWatchingKey().serializePubB58(PARAMS), PARAMS);
    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 7
@Override
public DeterministicKeyChain makeWatchingKeyChain(Protos.Key key, Protos.Key firstSubKey, DeterministicKey accountKey,
                                                  boolean isFollowingKey, boolean isMarried) throws UnreadableWalletException {
    ImmutableList<ChildNumber> accountPath = useBitcoinDeterministicKeyChain ? BtcDeterministicKeyChain.BIP44_BTC_ACCOUNT_PATH : BisqDeterministicKeyChain.BIP44_BSQ_ACCOUNT_PATH;
    if (!accountKey.getPath().equals(accountPath))
        throw new UnreadableWalletException("Expecting account key but found key with path: " +
                HDUtils.formatPath(accountKey.getPath()));
    return useBitcoinDeterministicKeyChain ? new BtcDeterministicKeyChain(accountKey, isFollowingKey) : new BisqDeterministicKeyChain(accountKey, isFollowingKey);
}
 
Example 8
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 9
Source Project: token-core-android   Source File: EOSKeystore.java    License: Apache License 2.0 5 votes vote down vote up
private List<KeyPath> calcAllDefaultKeys(List<String> mnemonics) {
  DeterministicSeed seed = new DeterministicSeed(mnemonics, null, "", 0L);
  DeterministicKeyChain rootKeyChain = DeterministicKeyChain.builder().seed(seed).build();

  List<KeyPath> defaultKeys = calcDefaultKeys(rootKeyChain, this.mnemonicPath);

  return defaultKeys;
}
 
Example 10
Source Project: token-core-android   Source File: EOSKeystore.java    License: Apache License 2.0 5 votes vote down vote up
private static List<KeyPath> calcDefaultKeys(DeterministicKeyChain rootKeyChain, String path) {

    String[] subpaths = path.split(",");
    List<KeyPath> result = new ArrayList<>(subpaths.length);
    for (String subpath : subpaths) {
      byte[] prvKeyBytes = rootKeyChain.getKeyByPath(BIP44Util.generatePath(subpath), true).getPrivKeyBytes();
      result.add(new KeyPath(prvKeyBytes, subpath));
    }
    return result;
  }
 
Example 11
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 12
Source Project: Android-Wallet-Token-ERC20   Source File: GetCredentials.java    License: Apache License 2.0 5 votes vote down vote up
public Credentials FromSeed(String seedCode,
                            String passwordWallet) throws UnreadableWalletException {
    DeterministicSeed seed = new DeterministicSeed(seedCode, null, passwordWallet, 1409478661L);
    DeterministicKeyChain chain = DeterministicKeyChain.builder().seed(seed).build();
    List<ChildNumber> keyPath = HDUtils.parsePath("M/44H/60H/0H/0/0");
    DeterministicKey key = chain.getKeyByPath(keyPath, true);
    BigInteger privKey = key.getPrivKey();
    return Credentials.create(ECKeyPair.create(privKey));
}
 
Example 13
@Override
public DeterministicKeyChain makeWatchingKeyChain(Protos.Key key, Protos.Key firstSubKey, DeterministicKey accountKey,
                                                  boolean isFollowingKey, boolean isMarried) throws UnreadableWalletException {
    ImmutableList<ChildNumber> accountPath = useBitcoinDeterministicKeyChain ? BtcDeterministicKeyChain.BIP44_BTC_ACCOUNT_PATH : BisqDeterministicKeyChain.BIP44_BSQ_ACCOUNT_PATH;
    if (!accountKey.getPath().equals(accountPath))
        throw new UnreadableWalletException("Expecting account key but found key with path: " +
                HDUtils.formatPath(accountKey.getPath()));
    return useBitcoinDeterministicKeyChain ? new BtcDeterministicKeyChain(accountKey, isFollowingKey) : new BisqDeterministicKeyChain(accountKey, isFollowingKey);
}
 
Example 14
public KeyChainTransactionSigner(DeterministicKeyChain keyChain) {
    this.keyChain = keyChain;
}
 
Example 15
@Override
public DeterministicKeyChain makeKeyChain(Protos.Key key, Protos.Key firstSubKey, DeterministicSeed seed, KeyCrypter crypter, boolean isMarried) {
    return useBitcoinDeterministicKeyChain ? new BtcDeterministicKeyChain(seed, crypter) : new BisqDeterministicKeyChain(seed, crypter);
}
 
Example 16
@Override
public DeterministicKeyChain toEncrypted(KeyCrypter keyCrypter, KeyParameter aesKey) {
    return new BisqDeterministicKeyChain(keyCrypter, aesKey, this);
}
 
Example 17
protected DeterministicKeyChain makeKeyChainFromSeed(DeterministicSeed seed) {
    return new BisqDeterministicKeyChain(seed);
}
 
Example 18
protected BisqDeterministicKeyChain(KeyCrypter crypter, KeyParameter aesKey, DeterministicKeyChain chain) {
    super(crypter, aesKey, chain);
}
 
Example 19
public BisqKeyChainGroup(NetworkParameters params, DeterministicKeyChain chain, boolean useBitcoinDeterministicKeyChain) {
    super(params, chain);

    this.useBitcoinDeterministicKeyChain = useBitcoinDeterministicKeyChain;
}
 
Example 20
@Override
public void createAndActivateNewHDChain() {
    DeterministicKeyChain chain = useBitcoinDeterministicKeyChain ? new BtcDeterministicKeyChain(new SecureRandom()) : new BisqDeterministicKeyChain(new SecureRandom());
    addAndActivateHDChain(chain);
}
 
Example 21
@Override
public DeterministicKeyChain toEncrypted(KeyCrypter keyCrypter, KeyParameter aesKey) {
    return new BtcDeterministicKeyChain(keyCrypter, aesKey, this);
}
 
Example 22
protected DeterministicKeyChain makeKeyChainFromSeed(DeterministicSeed seed) {
    return new BtcDeterministicKeyChain(seed);
}
 
Example 23
protected BtcDeterministicKeyChain(KeyCrypter crypter, KeyParameter aesKey, DeterministicKeyChain chain) {
    super(crypter, aesKey, chain);
}
 
Example 24
public WalletConfig(NetworkParameters params,
                    Socks5Proxy socks5Proxy,
                    File directory,
                    BisqEnvironment bisqEnvironment,
                    String userAgent,
                    int numConnectionForBtc,
                    @SuppressWarnings("SameParameterValue") String btcWalletFileName,
                    @SuppressWarnings("SameParameterValue") String bsqWalletFileName,
                    @SuppressWarnings("SameParameterValue") String spvChainFileName) {
    this.bisqEnvironment = bisqEnvironment;
    this.userAgent = userAgent;
    this.numConnectionForBtc = numConnectionForBtc;
    this.context = new Context(params);
    this.params = checkNotNull(context.getParams());
    this.directory = checkNotNull(directory);
    this.btcWalletFileName = checkNotNull(btcWalletFileName);
    this.bsqWalletFileName = bsqWalletFileName;
    this.spvChainFileName = spvChainFileName;
    this.socks5Proxy = socks5Proxy;

    walletFactory = new BisqWalletFactory() {
        @Override
        public Wallet create(NetworkParameters params, KeyChainGroup keyChainGroup) {
            // This is called when we load an existing wallet
            // We have already the chain here so we can use this to distinguish.
            List<DeterministicKeyChain> deterministicKeyChains = keyChainGroup.getDeterministicKeyChains();
            if (!deterministicKeyChains.isEmpty() && deterministicKeyChains.get(0) instanceof BisqDeterministicKeyChain) {
                checkArgument(BisqEnvironment.isBaseCurrencySupportingBsq(), "BisqEnvironment.isBaseCurrencySupportingBsq() is false but we get get " +
                        "called BisqWalletFactory.create with BisqDeterministicKeyChain");
                return new BsqWallet(params, keyChainGroup);
            } else {
                return new Wallet(params, keyChainGroup);
            }
        }

        @Override
        public Wallet create(NetworkParameters params, KeyChainGroup keyChainGroup, boolean isBsqWallet) {
            // This is called at first startup when we create the wallet
            if (isBsqWallet) {
                checkArgument(BisqEnvironment.isBaseCurrencySupportingBsq(), "BisqEnvironment.isBaseCurrencySupportingBsq() is false but we get get " +
                        "called BisqWalletFactory.create with isBsqWallet=true");
                return new BsqWallet(params, keyChainGroup);
            } else {
                return new Wallet(params, keyChainGroup);
            }
        }
    };

    String path = null;
    if (params.equals(MainNetParams.get())) {
        // Checkpoints are block headers that ship inside our app: for a new user, we pick the last header
        // in the checkpoints file and then download the rest from the network. It makes things much faster.
        // Checkpoint files are made using the BuildCheckpoints tool and usually we have to download the
        // last months worth or more (takes a few seconds).
        path = "/wallet/checkpoints";
    } else if (params.equals(TestNet3Params.get())) {
        path = "/wallet/checkpoints.testnet";
    }
    if (path != null) {
        try {
            setCheckpoints(getClass().getResourceAsStream(path));
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString());
        }
    }
}
 
Example 25
public KeyChainTransactionSigner(DeterministicKeyChain keyChain) {
    this.keyChain = keyChain;
}
 
Example 26
public KeyChainTransactionSigner(DeterministicKeyChain keyChain) {
    this.keyChain = keyChain;
}
 
Example 27
@Override
public DeterministicKeyChain makeKeyChain(Protos.Key key, Protos.Key firstSubKey, DeterministicSeed seed, KeyCrypter crypter, boolean isMarried) {
    return useBitcoinDeterministicKeyChain ? new BtcDeterministicKeyChain(seed, crypter) : new BisqDeterministicKeyChain(seed, crypter);
}
 
Example 28
@Override
public DeterministicKeyChain toEncrypted(KeyCrypter keyCrypter, KeyParameter aesKey) {
    return new BisqDeterministicKeyChain(keyCrypter, aesKey, this);
}
 
Example 29
protected DeterministicKeyChain makeKeyChainFromSeed(DeterministicSeed seed) {
    return new BisqDeterministicKeyChain(seed);
}
 
Example 30
protected BisqDeterministicKeyChain(KeyCrypter crypter, KeyParameter aesKey, DeterministicKeyChain chain) {
    super(crypter, aesKey, chain);
}