Generating a New Derived Public Key Using XPub in Python
As of Ethereum 2.0, the xpub' format has been deprecated and replaced by the
xprv’ format. However, some older contracts still use xpub' to store their private keys. In this article, we will show you how to use Python to generate a new derived public key (
new_pub) from an existing xpub.
What is XPub?
XPub is a standard format for storing Ethereum private keys in the XRPDB (XRPL) database. Although it is no longer widely used, it can still be useful if you are working with older contracts that require this format.
Deriving a New Derived Public Key from XPub Using Python
We will use thecryptography’ library for the derivation. Here is an example code snippet:
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
def derive_new_pub(xpub, new_path):
"""
Derives a new derived public key (new_pub) from an existing xpub.
Args:
xpub (str): The xpub private key.
new_path (str): The path to the new derived public key in the XRPDB.
Returns:
bytes: The newly derived public key.
"""
Load the existing private keyopen(xpub, "rb") as f_in:
private_key = serialization.load_pem_private_key(
f_in.read(),
password=None,
backend=default_backend()
)
Create a new derived public key key (new_pub)new_priv = private_key.new_path(new_path)
Save the new private key to diskwith open("new_pub.pvt", "wb") as f_out:
f_out.write(new_priv.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
))
return new_priv.public_bytes(
encoding=serialization.Encoding.X962,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
This function has two arguments:
xpub
: The existing xpub private key as a string.
new_path
: The path to the new derived public key in the XRPDB.
The function loads the existing private key using “cryptography” and derives a new derived public key (new_pub) by calling “private_key.new_path(new_path)”. Finally, the new private key is saved to disk in PEM format.
Example use case
Assuming you have an xpub private key in a file named xpub.txt
, you can derive a new derived public key using the following code:
new_pub = derive_new_pub("xpub.txt", "new_derived.pub")
This generates a new derived public key (new_derived.pub
) that can be used to sign messages or verify transactions.
Note
While this library provides an easy way to derive a new derived public key, it is essential to ensure that the existing xpub private key is properly formatted and not compromised. Always be careful when handling confidential information, especially in a production environment.