Bitcoin

Incorrect checksum when creating BIP-39 mnemonic – Stack Overflow

There are some problems with your code. hendecadsFromBits The function must use the numeric value of the bits. generateMnemonic Function, when calling hendecadsFromBitsThe results must be passed to: Array.from()

Here’s how to fix your code:

export const generateMnemonic = async () => 
    const ent = window.crypto.getRandomValues(new Uint8Array(16));
    const entBits = toBinString(ent);
    const entHash = Array.from(new Uint8Array(
        await window.crypto.subtle.digest("SHA-256", ent)
    ));
    const entHashBits = toBinString(entHash)
    const checksum = entHashBits.slice(0, 4);
    const entCS = entBits + checksum;
    const chunks = Array.from(hendecadsFromBits(entCS));
    const words = ();
    for (let i = 0; i < chunks.length; i++) 
        words.push(wordlist(chunks(i)));
    
    return words.join(' ');
;

const toBinString = (bytes) => bytes.reduce((str, byte) => str + byte.toString(2).padStart(8, '0'), '')

function* hendecadsFromBits(bits) 
    let i = 0;
    let val = 0;
    for (const bit of bits) 
        if (i == 11) 
            yield val;
            i = val = 0;
        
        val 
    if (i > 0) yield val;

Related Articles

Back to top button