Home Bitcoin javascript – Invalid checksum when producing BIP-39 Mnemonic

javascript – Invalid checksum when producing BIP-39 Mnemonic

0
javascript – Invalid checksum when producing BIP-39 Mnemonic

[ad_1]

There’s a few drawback in your code, within the hendecadsFromBits perform, you’ll want to use the numeric worth of bit and within the generateMnemonic perform, whenever you name hendecadsFromBits, you’ll want to go the end result to Array.from()

Right here is how you possibly can repair 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.delicate.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 phrases = [];
    for (let i = 0; i < chunks.size; i++) {
        phrases.push(wordlist[chunks[i]]);
    }
    return phrases.be a part of(' ');
};

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

perform* hendecadsFromBits(bits) {
    let i = 0;
    let val = 0;
    for (const little bit of bits) {
        if (i == 11) {
            yield val;
            i = val = 0;
        }
        val |= parseInt(bit, 10) << i++;
    }
    if (i > 0) yield val;
}

[ad_2]

LEAVE A REPLY

Please enter your comment!
Please enter your name here