Generating a new derived public key using XPub in Python
As of Ethereum 2.0, the xpub
format has been deprecated and replaced by xprv
. However, some older contracts still use xpub
to store their private keys. In this article, we will show you how to generate a new derived public key (new_pub
) from an existing xpub
using Python.
What is XPub?
XPub is a standardized format for storing Ethereum private keys in the XRPDB (XRPL) database. While it is no longer widely used, it can still be useful when working with older contracts that require this format.
Deriving a new derived public key from XPub using Python
We will use the cryptography
library to perform 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.
Arguments:
xpub (str): The xpub private key.
new_path (str): The path to the new derived public key in the XRPDB.
Returns:
bytes: The new derived public key.
"""
Load the existing private keywith open(xpub, "rb") as f_in:
private_key = serialization.load_pem_private_key(
f_in.read(),
password=None,
backend=default_backend()
)
Derive a new derived public 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 takes 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, it saves the new private key to disk in PEM format.
Example Use Case
Assuming you have an xpub private key stored in a file called 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 will generate a new derived public key (new_derived.pub
) that can be used to sign messages or verify transactions.
Note
While this library provides a simple way to derive a new derived public key, it is essential to ensure that the existing xpub private key is properly formatted and has not been compromised. Always exercise caution when handling sensitive information, especially in production environments.