Skip to content

DeterministicKey: fix depth can overflow byte in serialize() - #3693

Closed
schildbach wants to merge 1 commit into
bitcoinj:masterfrom
schildbach:deterministickey-fix-depth-overflow
Closed

schildbach wants to merge 1 commit into
bitcoinj:masterfrom
schildbach:deterministickey-fix-depth-overflow

Conversation

@schildbach

Copy link
Copy Markdown
Member

Also use Byte.toUnsignedInt() when deserializing.

Fixes #3683.

Also use `Byte.toUnsignedInt()` when deserializing depth.
@schildbach
schildbach force-pushed the deterministickey-fix-depth-overflow branch from 4b8ac29 to 5dfaa7d Compare April 1, 2025 15:22
@schildbach

Copy link
Copy Markdown
Member Author

This is a candidate for backporting to 0.17.

@msgilligan msgilligan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. I've requested 2 minor changes. I also think it is worth considering catching the depth > 256 issue earlier with checks in the DeterministicKey constructor and/or in HDPath.

@quapka

quapka commented Apr 1, 2025 •

Copy link
Copy Markdown

This is not a serialization problem in itself. The point of BIP32 is to have deterministically derived keys across different implementation, requiring the user only to store the seed value. Due to the serialization format, the depth is limited to the range [0, 255].

Thus, overflowing keys must not be created. Yet, I suspect this and this to potentially overflow.

If I got the proposal right, the serialize() method would just wrap the, potentially already overflowed, method. Which seems possible even worse, hiding the problem and creating orphaned keys. I am still getting familiar with bitcoinj BIP32 API, so can be wrong.

Also, I strongly recommend adding tests for this!

@msgilligan

Copy link
Copy Markdown
Member

@quapka Is there a valid use-case for paths of length > 255?

Changing the serialization format is a backward-incompatible change for any existing wallets, so it's something we definitely want to avoid if at all possible.

Detecting and enforcing the limit earlier makes sense if there are no real-world use cases for length > 255.

@quapka

quapka commented Apr 1, 2025

Copy link
Copy Markdown

Similarly, I don't see any length checks when extending HDPath objects. I am trying to understand similar possible code paths in HDKeyDerivation. As I suspect issues could be there as well.

@msgilligan

Copy link
Copy Markdown
Member

I don't see any length checks when extending HDPath objects.

PR #3694 is a worthwhile PR as a standalone, but is also a step towards catching length > 256 earlier, by encouraging the use of HDPath.

I can make a separate PR to add the checks to HDPath.

@quapka

quapka commented Apr 1, 2025 •

Copy link
Copy Markdown

@quapka Is there a valid use-case for paths of length > 255?

I have no idea. Without much thinking, I don't see a particular reason to limit the depth at all. But, in BIP32 this limitation is indirectly done so by using only a single byte for serialization.

Seeing this from the perspective of interoperability of BIP32 implementation across languages, and wallets, I think that the worst case is lost coins (due to depth overflow and creation of some invalid keys), or just sending to xpubs that will overflow and live at different places in the trees than expected, thus ending up hidden (even if the corresponding correct xprv could in principal be derived).

Changing the serialization format is a backward-incompatible change for any existing wallets, so it's something we definitely want to avoid if at all possible.

Detecting and enforcing the limit earlier makes sense if there are no real-world use cases for length > 255.

I am not sure what you mean. Your serialization format for xpub/xprv does not respect the single BIP32 format to store the depth as the single, fifth byte?

@quapka

quapka commented Apr 1, 2025

Copy link
Copy Markdown

PR #3694 is a worthwhile PR as a standalone, but is also a step towards catching length > 256 earlier, by encouraging the use of HDPath.

I am not sure about your API specifics, but see that master node sits already on the 0th level. Thus path of length 256 (those off by one errors) would overflow already.

@msgilligan

msgilligan commented Apr 1, 2025 •

Copy link
Copy Markdown
Member

But, in BIP32 this limitation is indirectly done so by using only a single byte for serialization.

OK, there is some precedent for limiting the length to ~256 in BIP-32 itself. So, bitcoinj won't be the only implementation imposing a limit.

Changing the serialization format is a backward-incompatible change for any existing wallets, so it's something we definitely want to avoid if at all possible.

I am not sure what you mean.

I'm talking about existing bitcoinj wallets and that we generally try to avoid changing the serialization format used by bitcoinj.

@msgilligan

Copy link
Copy Markdown
Member

PR #3694 is a worthwhile PR as a standalone, but is also a step towards catching length > 256 earlier, by encouraging the use of HDPath.

I am not sure about your API specifics, but see that master node sits already on the 0th level. Thus path of length 256 (those off by one errors) would overflow already.

OK, I'll double-check for off-by-one in PR #3696 -- thanks for the warning! If @schildbach approves everything else about the PR, I'll make that change.

@quapka

quapka commented Apr 1, 2025

Copy link
Copy Markdown

I'm talking about existing bitcoinj wallets and that we generally try to avoid changing the serialization format used by bitcoinj.

I understand the sentiment to try to avoid changing serialization of xpubs and xprvs. What I don't understand is what serialization format are thinking of. I've stitched together the following test (see patch below), where 1000 keys are derived from a master private key. Then serialized using Base58 and then deserialized back and compared. When the loop goes only to 255, the test passes, but as soon as it is 255, the deserialized keys has the wrapped depth, starting again from 0.

I can imagine that within one system that uses bitcoinj and passes the keys as objects (with a path that is longer then 255), things might work out. But when serialized to Base58 the depth information will get stored modulo 256.

diff --git a/core/src/test/java/org/bitcoinj/crypto/ChildKeyDerivationTest.java b/core/src/test/java/org/bitcoinj/crypto/ChildKeyDerivationTest.java
index b1f81a34a..39efdac5b 100644
--- a/core/src/test/java/org/bitcoinj/crypto/ChildKeyDerivationTest.java
+++ b/core/src/test/java/org/bitcoinj/crypto/ChildKeyDerivationTest.java
@@ -230,6 +230,29 @@ public class ChildKeyDerivationTest {
         assertEquals("tprv8ZgxMBicQKsPdSvtfhyEXbdp95qPWmMK9ukkDHfU8vTGQWrvtnZxe7TEg48Ui7HMsZKMj7CcQRg8YF1ydtFPZBxha5oLa3qeN3iwpYhHPVZ", priv58);
     }

+    @Test
+    public void depthShouldNotOverflow() {
+        DeterministicKey key1 = HDKeyDerivation.createMasterPrivateKey("satoshi lives!".getBytes());
+
+
+        for (int i = 0; i < 1000; i++ ){
+            key1 = HDKeyDerivation.deriveChildKey(key1, ChildNumber.ZERO);
+
+            String serializedB58 = key1.serializePrivB58(MAINNET);
+
+            // serialized to Base58 does not go over 111
+            assertEquals(serializedB58.length(), 111);
+
+            DeterministicKey tmp = DeterministicKey.deserializeB58(serializedB58, MAINNET);
+            assertEquals(key1.getDepth(), tmp.getDepth());
+
+            assertEquals(serializedB58, tmp.serializePrivB58(MAINNET));
+
+            // serialized for network does go over 78 bytes
+            assertEquals(key1.serialize(MAINNET, true).length, 78);
+        }
+    }
+
     @Test
     public void serializeToTextAndBytes() {
         DeterministicKey key1 = HDKeyDerivation.createMasterPrivateKey("satoshi lives!".getBytes());

To be honest, I am not familiar with how the depth is then later used elsewhere in the wallets. It seems to me that parent key is identifiable via the fingerprint and the index of the key can then be used to derive the correct key. In that case the depth is not crucial, but I would not put my bets on it never causing any problems.

@quapka

quapka commented Apr 1, 2025

Copy link
Copy Markdown

See bitcoin for example test.

@msgilligan

msgilligan commented Apr 2, 2025 •

Copy link
Copy Markdown
Member

What I don't understand is what serialization format [you] are thinking of.

I was mistakenly thinking that this serialization was used in the ProtoBuf serialization of the wallet. Sorry for the confusion.

@schildbach

Copy link
Copy Markdown
Member Author

I changed the test to 2 tests and merged to master and 0.17.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Deriving extended key over 255 silently overflows the key depth

3 participants