private DeterministicKey encryptNonLeaf(
     KeyParameter aesKey,
     DeterministicKeyChain chain,
     DeterministicKey parent,
     ImmutableList<ChildNumber> path) {
   DeterministicKey key = chain.hierarchy.get(path, false, false);
   key = key.encrypt(checkNotNull(basicKeyChain.getKeyCrypter()), aesKey, parent);
   hierarchy.putKey(key);
   basicKeyChain.importKey(key);
   return key;
 }
  // For use in encryption.
  private DeterministicKeyChain(
      KeyCrypter crypter, KeyParameter aesKey, DeterministicKeyChain chain) {
    // Can't encrypt a watching chain.
    checkNotNull(chain.rootKey);
    checkNotNull(chain.seed);

    checkArgument(!chain.rootKey.isEncrypted(), "Chain already encrypted");

    this.issuedExternalKeys = chain.issuedExternalKeys;
    this.issuedInternalKeys = chain.issuedInternalKeys;

    this.lookaheadSize = chain.lookaheadSize;
    this.lookaheadThreshold = chain.lookaheadThreshold;

    this.seed = chain.seed.encrypt(crypter, aesKey);
    basicKeyChain = new BasicKeyChain(crypter);
    // The first number is the "account number" but we don't use that feature.
    rootKey = chain.rootKey.encrypt(crypter, aesKey, null);
    hierarchy = new DeterministicHierarchy(rootKey);
    basicKeyChain.importKey(rootKey);

    DeterministicKey account = encryptNonLeaf(aesKey, chain, rootKey, ACCOUNT_ZERO_PATH);
    externalKey = encryptNonLeaf(aesKey, chain, account, EXTERNAL_PATH);
    internalKey = encryptNonLeaf(aesKey, chain, account, INTERNAL_PATH);

    // Now copy the (pubkey only) leaf keys across to avoid rederiving them. The private key bytes
    // are missing
    // anyway so there's nothing to encrypt.
    for (ECKey eckey : chain.basicKeyChain.getKeys()) {
      DeterministicKey key = (DeterministicKey) eckey;
      if (key.getPath().size() != 3) continue; // Not a leaf key.
      DeterministicKey parent =
          hierarchy.get(checkNotNull(key.getParent()).getPath(), false, false);
      // Clone the key to the new encrypted hierarchy.
      key = new DeterministicKey(key.getPubOnly(), parent);
      hierarchy.putKey(key);
      basicKeyChain.importKey(key);
    }
  }