nimiq / php-xpub

A simple class to derive BTC and ETH extended public keys and addresses without GMP.
10 stars 4 forks source link

How to convert xpub to zpub? #4

Closed c0dehunter closed 1 year ago

c0dehunter commented 1 year ago

I am looking to convert xpub to zpub, like on this site: https://jlopp.github.io/xpub-converter/

Can I do it with this library?

sisou commented 1 year ago

You should be able to just change the version on an XPub instance.

I am currently writing tests for it, and it doesn't always work. I am investigating, but it works sometimes. So treat with caution for now!


$xpub = XPub::fromString('xpub...');
$xpub->version = 'zpub';
$zpub = $xpub->toString();
c0dehunter commented 1 year ago

Thanks, that is amazing!

I noticed the resulting zpub is different than the one generated on the above linked website. However, it still works (I am fetching BTC balance from a node and if I provide xpub address it doesn't accept it, but after converting it to zpub with your library, it works; interestingly, it also works with the converted zpub from above website, so maybe one xpub can be converted to multiple zpubs and all of them are still valid?).

Example 1:

xpub6BhzbpuriJ8KTjVUAp7UFpMjk4eoi2R43FiLWxbRb3mMdem7XHEgd8QvL2vJJ4NgEYN9eWUrJHyoFZA3VrawPc5VPqKhdvSBer5fyiYw4j8

Your library: zpub6qNXDAFYfzgQcHThG8qt9NBqohHG4aX3MoKY8F732zKLdGCD7tVNEvNKKiAbWktSSku3SQapHJzafesw66G6TJkSwqggq8E6TF3N5f6E7SZ

https://jlopp.github.io/xpub-converter/: zpub6qNXDAFh1fDHAKshqXgifzYk5zwhbGQ3sUkn5kPCM4X7jrPa2bZosFjCNSqUHsgX3pbm9TfyDcgu28PAwFQxz5Sh8WiYok5ACJCxkqeKcw4

Example 2:

xpub6Cvnz2xtFQGS4jKWKCf9nokYnM5r8F7LgzbVEB4GFJNQjDPy6t9k6R6F2QrDHNZaQ9UwK1crfrVgTXif7utCZsYuzc4TS9tAu4sGgGxaaUJ

Your library: zpub6rbKbNJaD6pXDHHjQXPZgMaeqyiJUoDL1YCgqTZshEvPipq4hVQRiD3e266WW55LcN1q6uipesWTsdSYi9ZMdaDsYcRSdMg5hTpxnEnVS67

https://jlopp.github.io/xpub-converter/: zpub6rbKbNJiYmMPmKhjyvEQCywZ8HNk1V6LXDdvnxr31K8AqR2RcCUsLYQX4pmPHBsRDRiYoxoybBCnE6wnZJiEALv7jHTJbyX9SWzZTVHM5rV

sisou commented 1 year ago

Thanks for the feedback! I also noticed this library's generated ones are different than from the converter website, and thought that means they are wrong. But if they are still working for you, that's great!

I'll investigate in a bit what the actual difference between the zpubs are, and if they are relevant.

sisou commented 1 year ago

Fixed in version 1.4.0. As you can see from the commit message, the output from toString() had the wrong child index, which lead to a different xpub encoding. The relevant fields for address derivation in the xpub were correct though, that's why it worked for you. With this fix, the output of this library is now the same as from the xpub-converter website.

c0dehunter commented 1 year ago

Amazing, thank you for this!