diff --git a/core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java b/core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java index 2d8afea8..5eb21983 100644 --- a/core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java +++ b/core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java @@ -668,7 +668,6 @@ public class KeyChainGroup implements KeyBag { checkNotNull(keyCrypter); checkNotNull(aesKey); checkState((chains != null && !chains.isEmpty()) || basic.numKeys() != 0, "can't encrypt entirely empty wallet"); - // This code must be exception safe. BasicKeyChain newBasic = basic.toEncrypted(keyCrypter, aesKey); List newChains = new ArrayList<>(); @@ -676,6 +675,8 @@ public class KeyChainGroup implements KeyBag { for (DeterministicKeyChain chain : chains) newChains.add(chain.toEncrypted(keyCrypter, aesKey)); } + + // Code below this point must be exception safe. this.keyCrypter = keyCrypter; this.basic = newBasic; if (chains != null) { @@ -691,18 +692,20 @@ public class KeyChainGroup implements KeyBag { * @throws org.bitcoinj.crypto.KeyCrypterException Thrown if the wallet decryption fails for some reason, leaving the group unchanged. */ public void decrypt(KeyParameter aesKey) { - // This code must be exception safe. checkNotNull(aesKey); + BasicKeyChain newBasic = basic.toDecrypted(aesKey); - List newChains = new ArrayList<>(chains.size()); - if (chains != null) + if (chains != null) { + List newChains = new ArrayList<>(chains.size()); for (DeterministicKeyChain chain : chains) newChains.add(chain.toDecrypted(aesKey)); + // Code below this point must be exception safe. + this.chains.clear(); + this.chains.addAll(newChains); + } + this.basic = newBasic; this.keyCrypter = null; - basic = newBasic; - chains.clear(); - chains.addAll(newChains); } /** Returns true if the group is encrypted. */ diff --git a/core/src/test/java/org/bitcoinj/wallet/KeyChainGroupTest.java b/core/src/test/java/org/bitcoinj/wallet/KeyChainGroupTest.java index fb162f27..0c08533b 100644 --- a/core/src/test/java/org/bitcoinj/wallet/KeyChainGroupTest.java +++ b/core/src/test/java/org/bitcoinj/wallet/KeyChainGroupTest.java @@ -707,10 +707,11 @@ public class KeyChainGroupTest { } @Test - public void onlyBasicKeyEncryption() { + public void onlyBasicKeyEncryptionAndDecryption() { group = KeyChainGroup.createBasic(MAINNET); final ECKey key = ECKey.fromPrivate(BigInteger.TEN); group.importKeys(key); group.encrypt(KEY_CRYPTER, AES_KEY); + group.decrypt(AES_KEY); } }