I'm working on a project which requires me to take an Electrum mnemonic, determine its type and derive the corresponding addresses for that wallet.
I found lots of information on how to determine the mnemonic type and covert it into the master seed, but I'm struggling to understand how addresses for the 2FA wallet are derived. To be more exact, I was able to derive both extended keypairs (x1/
and x2/
in the wallet file), but I can't seem to be able to derive the third xpub (x3/
in the wallet file).
I've looked through the source code and it seems this key is derived by combining both xpub keys (the keys should be ORDERED) that can be derived from the master seed (x1/
and x2/
), hashing them using SHA-256
and using that as the index when deriving the third xpub. A hard-coded xpub is used as the root.
I'm having trouble understanding / implementing this because the SHA-256
algorithm returns 32 bytes of data and the child index has to be 4 bytes long (as per the BIP32
specification).
Here's the code from Electrum that handles this.
def get_user_id(storage):
def make_long_id(xpub_hot, xpub_cold):
return bitcoin.sha256(''.join(sorted([xpub_hot, xpub_cold])))
xpub1 = storage.get('x1/')['xpub']
xpub2 = storage.get('x2/')['xpub']
long_id = make_long_id(xpub1, xpub2)
short_id = hashlib.sha256(long_id).hexdigest()
return long_id, short_id
def make_xpub(xpub, s):
version, _, _, _, c, cK = deserialize_xpub(xpub)
cK2, c2 = bitcoin._CKD_pub(cK, c, s)
return bitcoin.serialize_xpub(version, c2, cK2)
The functions are then called like this:
xpub1 = wizard.storage.get('x1/')['xpub']
xpub2 = wizard.storage.get('x2/')['xpub']
# Generate third key deterministically.
long_user_id, short_id = get_user_id(wizard.storage)
xpub3 = make_xpub(signing_xpub, long_user_id)
The long_user_id
is 32 bytes long since it's the result of the SHA-256
function and it's then being used to call the make_xpub()
function which is supposed to take in 4 bytes of data as the child index.
What am I missing here? Any input is appreciated.