mnemonic seed – How to properly compute the BIP39 checksum bytes?

0
8


I’m trying to understand the logic of generating a valid BIP-39 seed phrase. I have read the BIP-39 and trying to implement the section Generating the mnemonic step by step. I have the following Crystal code that works very well for a 256-bit seed I found in the answer to: How to generate a valid hash for a bip39 seed phrase?

# First, an initial entropy of ENT bits is generated.
entropy = "87c1b129fbadd7b6e9abc0a9ef7695436d767aece042bec198a97e949fcbe14c"
# => "87c1b129fbadd7b6e9abc0a9ef7695436d767aece042bec198a97e949fcbe14c"

# A checksum is generated by taking the first ENT / 32 bits of its SHA256 hash.
sha2sum = OpenSSL::Digest.new("SHA256").update(entropy.hexbytes).final.hexstring
# => "0dc811788c7e02c32b9c4b3586baf58ca27f74330c92d661042b19faa6c7e9f2"

# the checksum length (CS): 2 (hex) := 8 (bits)
checksum_length_hex = 2
# => 2

checksum = sha2sum[0, checksum_length_hex]
# => "0d"

# This checksum is appended to the end of the initial entropy.
entropy_checksummed = entropy + checksum
# => "87c1b129fbadd7b6e9abc0a9ef7695436d767aece042bec198a97e949fcbe14c0d"

This works, as I said and my code is able to generate the correct indices for the words required, and the resulting phrase matches with the one provided in the other thread.

My problem is, however, how do we manage the checksum_length_hex for entropies of 160, 192, and 224 bits? As I said, my code works for 256 bit with checksum_length_hex of 2 and it also works for 128 bit with a length of 1.

But how do I deal with the cases in between? I cannot create a prefix of 1.2. I was thinking of taking the checksum prefix in pure bits (e.g., 5 bits for 160 entropy) and eventually got only gibberish results. The following table is taken directly from BIP-39:

# |  ENT  | CS | ENT+CS |  MS  |
# +-------+----+--------+------+
# |  128  |  4 |   132  |  12  "https://bitcoin.stackexchange.com/questions/110451/#"  160  |  5 |   165  |  15  "https://bitcoin.stackexchange.com/questions/110451/#"  192  |  6 |   198  |  18  "https://bitcoin.stackexchange.com/questions/110451/#"  224  |  7 |   231  |  21  "https://bitcoin.stackexchange.com/questions/110451/#"  256  |  8 |   264  |  24  |

How do I properly compute BIP-39 checksum bytes of sizes 5, 6, and 7 for entropies of 160, 192, and 224?



Source link

Leave a reply