Last active
July 1, 2023 19:52
-
-
Save pinhopro/0b510f95e168ca9ee2f9d9d146b98c82 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import bisect | |
import hashlib | |
def check_mnemonic(word_list: list[str], mnemonic_list: list[str]) -> bool: | |
if len(mnemonic_list) not in [12, 15, 18, 21, 24]: | |
return False | |
try: | |
idx = map(lambda x:bin(word_list.index(x))[2:].zfill(11), mnemonic_list) | |
b = "".join(idx) | |
except ValueError: | |
return False | |
l = len(b) | |
d = b[: l // 33 * 32] | |
h = b[-l // 33:] | |
nd = int(d, 2).to_bytes(l // 33 * 4, byteorder = "big") | |
nh = bin(int(hashlib.sha256(nd).hexdigest(), 16))[2:].zfill(256)[: l // 33] | |
return h == nh | |
def main(): | |
input_word_list = input("Enter 12, 15, 18, 21 or 24 words separated by spaces >").strip().lower().split(" ") | |
if len(input_word_list) not in [12, 15, 18, 21, 24]: | |
print( | |
"Number of words must be one of the following: [12, 15, 18, 21, 24], but it is not (%d)." % len(input_word_list)) | |
return | |
try: | |
with open("english.txt", 'r') as f: | |
word_list_lines = f.readlines() | |
word_list = [line.strip() for line in word_list_lines] | |
mnemonic_list = [] | |
for input_word in input_word_list[:-1]: | |
index = bisect.bisect_left(word_list, input_word) | |
mnemonic_list.append(word_list[index]) | |
valid_last_words = [] | |
for word in word_list: | |
if check_mnemonic(word_list, mnemonic_list + [word]): | |
valid_last_words.append(word) | |
last_word_index = bisect.bisect_left(valid_last_words, input_word_list[-1]) | |
mnemonic_list.append(valid_last_words[last_word_index]) | |
print(" ".join(mnemonic_list)) | |
except FileNotFoundError: | |
print("english.txt not found, please download it from " | |
"https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment