All files / ethers.js/src.ts/wordlists wordlist-owl.ts

100% Statements 77/77
100% Branches 10/10
100% Functions 7/7
100% Lines 77/77

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 781x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 4x 4x 6x 6x 6x 112991x 6x 6x 6x 6x 1x 1x 1x 1x 1x 6x 6x 6x 112991x 112991x 6x 6x 53738x 53738x 53738x 53738x 6x 6x 59253x 59253x 6x  
 
// Use the encode-latin.js script to create the necessary
// data files to be consumed by this class
 
import { id } from "../hash/index.js";
import { assertArgument } from "../utils/index.js";
 
import { decodeOwl } from "./decode-owl.js";
import { Wordlist } from "./wordlist.js";
 
/**
 *  An OWL format Wordlist is an encoding method that exploits
 *  the general locality of alphabetically sorted words to
 *  achieve a simple but effective means of compression.
 *
 *  This class is generally not useful to most developers as
 *  it is used mainly internally to keep Wordlists for languages
 *  based on ASCII-7 small.
 *
 *  If necessary, there are tools within the ``generation/`` folder
 *  to create the necessary data.
 */
export class WordlistOwl extends Wordlist {
    #data: string;
    #checksum: string;
 
    /**
     *  Creates a new Wordlist for %%locale%% using the OWL %%data%%
     *  and validated against the %%checksum%%.
     */
    constructor(locale: string, data: string, checksum: string) {
        super(locale);
        this.#data = data;
        this.#checksum = checksum;
        this.#words = null;
    }
 
    /**
     *  The OWL-encoded data.
     */
    get _data(): string { return this.#data; }
 
    /**
     *  Decode all the words for the wordlist.
     */
    _decodeWords(): Array<string> {
        return decodeOwl(this.#data);
    }
 
    #words: null | Array<string>;
    #loadWords(): Array<string> {
        if (this.#words == null) {
            const words = this._decodeWords();
 
            // Verify the computed list matches the official list
            const checksum = id(words.join("\n") + "\n");
            /* c8 ignore start */
            if (checksum !== this.#checksum) {
                throw new Error(`BIP39 Wordlist for ${ this.locale } FAILED`);
            }
            /* c8 ignore stop */
 
            this.#words = words;
        }
        return this.#words;
    }
 
    getWord(index: number): string {
        const words = this.#loadWords();
        assertArgument(index >= 0 && index < words.length, `invalid word index: ${ index }`, "index", index);
        return words[index];
    }
 
    getWordIndex(word: string): number {
        return this.#loadWords().indexOf(word);
    }
}